Main.cpp 1.6 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700
  1. #include <juce_gui_basics/juce_gui_basics.h>
  2. #include "engine/FileSort.h"
  3. #include "platform/Paths.h"
  4. #include "core/EditorScale.h"
  5. #include "core/SimplePads.h"
  6. #include "core/ClipEnvelope.h"
  7. #include "core/ClipWarp.h"
  8. #include "core/KeyGuess.h"
  9. #include "core/EditorPolish.h"
  10. #include "core/FlpExport.h"
  11. #include "core/Groove.h"
  12. #include "core/DrawMode.h"
  13. #include "core/SessionOps.h"
  14. #include "ui/ClipGridComponent.h"
  15. #include "ui/ExternalDrag.h"
  16. #include "ui/SessionMixer.h"
  17. #include "core/FlSamplers.h"
  18. #include "core/ArrangeOps.h"
  19. #include "core/ClipSample.h"
  20. #include "core/WarpModes.h"
  21. #include "ui/ClipAudioPanel.h"
  22. #include "core/DetailChain.h"
  23. #include "core/SessionMixer.h"
  24. #include "core/PlaylistOps.h"
  25. #include "core/LastTweaked.h"
  26. #include "core/ClipOps.h"
  27. #include "core/SamplerPage.h"
  28. #include "core/FlTrackMenus.h"
  29. #include "core/FlClipMenu.h"
  30. #include "core/OneClickRec.h"
  31. #include "core/WarpTools.h"
  32. #include "core/Comping.h"
  33. #include "core/Drumaxx.h"
  34. #include "core/PatternBlocks.h"
  35. #include "core/LoadTrace.h"
  36. #include "core/ProjectSafety.h"
  37. #include "core/Patcher.h"
  38. #include "core/Rack.h"
  39. #include "ui/RackEditor.h"
  40. #include "ui/DrumRackShot.h"
  41. #include "ui/GroovePoolComponent.h"
  42. #include "core/Patcherize.h"
  43. #include "core/Performance.h"
  44. #include "core/VideoPlayer.h"
  45. #include "core/Effects.h"
  46. #include "core/MixSuite.h"
  47. #include "core/HardwareInsert.h"
  48. #include "core/EchoSuite.h"
  49. #include "core/LynxTune.h"
  50. #include "core/FlEffects.h"
  51. #include "core/FlpImport.h"
  52. #include "core/NoteEdit.h"
  53. #include "core/MaximusFx.h"
  54. #include "core/ChainPresets.h"
  55. #include "core/GoalKnobs.h"
  56. #include "core/MasterLooks.h"
  57. #include "core/Harmor.h"
  58. #include "flp/Flp.h"
  59. #include "core/DemoSongs.h"
  60. #include "core/FirstSongTour.h"
  61. #include "core/ShowcaseSong.h"
  62. #include "core/RenderAhead.h"
  63. #include "core/SynthPresets.h"
  64. #include "core/FlWrapper.h"
  65. #include "engine/AudioEngine.h"
  66. #include "engine/RemoteControl.h"
  67. #include "engine/RemoteError.h"
  68. #include "ui/RemoteControlSettings.h"
  69. #include "engine/PreviewPlayer.h"
  70. #include "engine/Metronome.h"
  71. #include "engine/AudioLogger.h"
  72. #include "engine/DllAsioDevice.h"
  73. #include "engine/PipeWireDevice.h"
  74. #include "platform/LinuxRealtime.h"
  75. #include "engine/PowerHints.h"
  76. #include "engine/Exporter.h"
  77. #include "engine/FlStudioExport.h"
  78. #include "engine/MidiFileIo.h"
  79. #include "engine/PluginHost.h"
  80. #include "engine/Vst3NoteTuning.h"
  81. #include "engine/PluginSandbox.h"
  82. #include "engine/Bridge32Test.h"
  83. #include "engine/ClapFormat.h"
  84. #include "engine/ClapTeardownTest.h"
  85. #include "core/EdisonFx.h"
  86. #include "engine/ProjectFile.h"
  87. #include "ui/RemoteControl.h"
  88. #include "core/FlControlMenus.h"
  89. #include "core/PlaylistOps.h"
  90. #include "core/Sha256.h"
  91. #include "engine/SessionPack.h"
  92. #include "engine/LiveTest.h"
  93. #include "engine/ShortExportTest.h"
  94. #include "core/SessionIds.h"
  95. #include "core/SessionParts.h"
  96. #include "engine/SampleLibrary.h"
  97. #include "engine/Text.h"
  98. #include "platform/FileTypes.h"
  99. #include "platform/Package.h"
  100. #include "core/AlsImport.h"
  101. #include "core/PianoRollScript.h"
  102. #include "ui/ScriptPanel.h"
  103. #include "ui/AlsExportDialog.h"
  104. #include "ui/LiveRemoteUi.h"
  105. #include "ui/GamepadInput.h"
  106. #include "ui/SettingsPages.h"
  107. #include "ui/OtherAppsExport.h"
  108. #include "ui/TimerWhileShowing.h"
  109. #include "ui/MixerBasicsCheck.h"
  110. #include "ui/VideoPlayerView.h"
  111. #include "ui/VideoMedia.h"
  112. #include "ui/VideoTracks.h"
  113. #include "ui/AdrWindow.h"
  114. #include "ui/PlaylistComponent.h"
  115. #include "ui/PictureCheck.h"
  116. #include "ui/PatternBlocksView.h"
  117. #include "ui/PaintAB.h"
  118. #include <typeinfo>
  119. #include "ui/PatcherEditor.h"
  120. #include "ui/VisualEditors.h"
  121. #include "ui/FlExtraEditors.h"
  122. #include "ui/VisualGl.h"
  123. #include "ui/DanceView.h"
  124. #include "ui/PluginPresetMenu.h"
  125. #include "ui/GeneratorPresetMenu.h"
  126. #include "core/GeneratorPresets.h"
  127. #include "ui/PluginWindow.h"
  128. #include "ui/Motion.h"
  129. #include "ui/NativeChild.h"
  130. #include "ui/Workspace.h"
  131. #include "ui/PluginThumbs.h"
  132. #include "ui/ClipProperties.h"
  133. #include "ui/NewProjectDialog.h"
  134. #include "ui/PluginMonitorWindow.h"
  135. #include "ui/TouchKeyboard.h"
  136. #include "ui/AutomationUi.h"
  137. #include "ui/PluginSkin.h"
  138. #include "ui/ChannelSettings.h"
  139. #include "ui/TempoDetectionDialog.h"
  140. #include "ui/AudioClipboard.h"
  141. #include "ui/FlVoicePanel.h"
  142. #include "ui/SlicexEditor.h"
  143. #include "ui/FruitySlicerEditor.h"
  144. #include "core/GrossBeat.h"
  145. #include "core/LynxBanks.h"
  146. #include "core/NativeEngines.h"
  147. #include "ui/ControllerEditors.h"
  148. #include "ui/NewtoneEditor.h"
  149. #include "core/NewtoneFx.h"
  150. #include "core/FormulaController.h"
  151. #include "core/MidiControls.h"
  152. #include "core/FlSynths.h"
  153. #include "core/SoundFont.h"
  154. #include "core/Sfz.h"
  155. #include "core/Slicex.h"
  156. #include "ui/Dialogs.h"
  157. #include "ui/FileChoosers.h"
  158. #include "ui/TrackIcons.h"
  159. #include "core/RackOps.h"
  160. #include "core/Layer.h"
  161. #include "core/XyController.h"
  162. #include "core/FlCurve.h"
  163. #include "core/ControlSurface.h"
  164. #include "core/VoltageController.h"
  165. #include "ui/Controllers164.h"
  166. #include "core/StandIns.h"
  167. #include "ui/ExportDialog.h"
  168. #include "ui/QuickAddPalette.h"
  169. #include "ui/I18n.h"
  170. #include "ui/MainComponent.h"
  171. #include "ui/SimpleDock.h"
  172. #include "core/ScaleKeys.h"
  173. #include "core/KeyFollow.h"
  174. #include "core/SoundLibrary.h"
  175. #include "ui/MidiToolsPanel.h"
  176. #include "ui/FrameProbe.h"
  177. #include "ui/UiTrace.h"
  178. #include "core/MixerOps.h"
  179. #include "ui/QuickPick.h"
  180. #include "core/NoteTools.h"
  181. #include "engine/ProjectPackage.h"
  182. #include "ui/SetupWizard.h"
  183. #include "engine/FlStudio.h"
  184. #include "ui/HistoryPanel.h"
  185. #include "ui/VersionsPanel.h"
  186. #include "ui/CleanVoiceMenu.h"
  187. #include "ui/LyricsPanel.h"
  188. #include "ui/ReferenceMatchPanel.h"
  189. #include "ui/StartFromPanel.h"
  190. #include "ui/FirstSongTour.h"
  191. #include "ui/PluginsOffPanel.h"
  192. #include "ui/MissingFilesDialog.h"
  193. #include "ui/SettingsDialog.h"
  194. #include "ui/PluginManager.h"
  195. #include "ui/ShortcutManager.h"
  196. #include "ui/NoteToolDialogs.h"
  197. #include "ui/EventEditor.h"
  198. #include "ui/AudioEditor.h"
  199. #include "ui/TempoTapper.h"
  200. #include "core/EventEdit.h"
  201. #include "core/FacetEq.h"
  202. #include "ui/FacetEqEditor.h"
  203. #include "core/RackRenderer.h"
  204. #include "ui/ProEditors.h"
  205. #include "ui/ParametricEqEditor.h"
  206. #include "ui/PluginEditors.h"
  207. #include "core/PluginLayout.h"
  208. #include "core/EffectPresets.h"
  209. #include "ui/PluginHeader.h"
  210. #include "core/Vfx.h"
  211. #include "core/TransistorBass.h"
  212. #include "ui/Splash.h"
  213. #include "ui/Theme.h"
  214. #include "ui/ThemeSettings.h"
  215. #include "ui/WaveformView.h"
  216. #include "ui/WindowOwner.h"
  217. #include "ui/PluginKeysTest.h"
  218. #include "ui/Toolbar.h"
  219. #include "ui/ToolWindow.h"
  220. #include "platform/CrashGuard.h"
  221. #include "ui/CrashReporter.h"
  222. #include "ui/Updater.h"
  223. #include "ui/AudioCheck.h"
  224. #include "ui/StemExtract.h"
  225. #include "ui/AudioToMidi.h"
  226. #include "ui/ShotScale.h"
  227. #include "core/Links.h"
  228. #include <algorithm>
  229. #include <atomic>
  230. #include <exception>
  231. #include <chrono>
  232. #include <cstdio>
  233. #include <ctime>
  234. #include <cstdlib>
  235. #include <future>
  236. #include <mutex>
  237. #include <thread>
  238. namespace
  239. {
  240. lynx::AudioEngine* crashEngine = nullptr;
  241. // Startup trace (REA round 116): with LYNX_TRACE_STARTUP set, the time of each startup step since the C++ runtime
  242. // started is written to %APPDATA%\LYNX\startup.log (the loader's own time before that is not included).
  243. struct StartupTrace
  244. {
  245. using clock = std::chrono::steady_clock;
  246. const clock::time_point t0 = clock::now(); // static initialisation: no JUCE yet, standard library only
  247. const std::chrono::system_clock::time_point t0System = std::chrono::system_clock::now(); // (round 190hd: vs the process's creation)
  248. // (round 190go: always kept, as a field-readable start-up timeline; written to startup.log 5 s and 15 s after the
  249. // window — with LYNX_TRACE_STARTUP set, at every step as before, so a start that hangs still leaves its last step)
  250. const bool on = true;
  251. const bool eachStep = std::getenv ("LYNX_TRACE_STARTUP") != nullptr;
  252. juce::String text;
  253. clock::time_point last = t0;
  254. std::int64_t lastPrivate = 0;
  255. double seconds() const { return std::chrono::duration<double> (clock::now() - t0).count(); } // since the process started
  256. void mark (const char* step)
  257. {
  258. if (! on)
  259. return;
  260. const auto now = clock::now();
  261. const auto ms = [] (clock::duration d) { return std::chrono::duration<double, std::milli> (d).count(); };
  262. // (round 190gd: the process's memory after each step too, so the log says where the megabytes of a start go)
  263. const auto mb = [] (std::int64_t bytes) { return juce::String ((double) bytes / 1048576.0, 1).paddedLeft (' ', 7); };
  264. const auto priv = lynx::toolbar::PerformanceMeter::processPrivateBytes();
  265. const auto ws = lynx::toolbar::PerformanceMeter::processMemoryBytes();
  266. text << juce::String (ms (now - t0), 1).paddedLeft (' ', 8) << " ms +" << juce::String (ms (now - last), 1).paddedLeft (' ', 7)
  267. << " private " << mb (priv) << " MB (+" << mb (priv - lastPrivate).trim() << ") ws " << mb (ws) << " MB " << step << "\n";
  268. lastPrivate = priv;
  269. last = now;
  270. if (eachStep)
  271. write();
  272. }
  273. void write() const { lynx::platform::settingsFile ("startup.log").replaceWithText (text); }
  274. };
  275. StartupTrace startupTrace;
  276. void startupMarkHook (const char* step) { startupTrace.mark (step); }
  277. juce::File crashFolderForTest; // --faulttest: where the crash file goes instead of the settings' autosave folder
  278. // Crashed: try to save the project and write the backtrace (like FL's "emergency save").
  279. void onCrash (void* exceptionPointers)
  280. {
  281. // (round 190ci: once. The hook for stacks Windows cannot walk, crashguard::setUnwalkableFaultHandler, may have run
  282. // this before the top-level filter does)
  283. static std::atomic<bool> reported { false };
  284. if (reported.exchange (true))
  285. return;
  286. const auto folder = crashFolderForTest != juce::File() ? crashFolderForTest : lynx::platform::settingsFile ("autosave");
  287. folder.createDirectory();
  288. const auto stamp = juce::Time::getCurrentTime().formatted ("%Y-%m-%d %H-%M-%S");
  289. // JUCE's backtrace (named frames only), then every frame of the faulting thread as module+offset (round 157a: a
  290. // release LYNX.exe has no symbols, so its own frames were missing from the file)
  291. folder.getChildFile ("crash " + stamp + ".txt").replaceWithText (juce::SystemStats::getStackBacktrace() + "\n--- frames (module+offset)\n"
  292. + juce::String::fromUTF8 (lynx::crashguard::exceptionBacktrace (exceptionPointers).c_str()));
  293. lynx::crashguard::note (("crashed: backtrace in autosave\\crash " + stamp + ".txt").toStdString());
  294. if (crashEngine != nullptr)
  295. {
  296. juce::String error;
  297. lynx::ProjectFile::save (crashEngine->getSong(), folder.getChildFile ("recovered " + stamp + lynx::ProjectFile::extension), error);
  298. }
  299. }
  300. juce::File sessionsFolder()
  301. {
  302. return lynx::PluginHost::settingsFolder().getChildFile ("sessions");
  303. }
  304. // Sessions of earlier runs whose process is gone without closing (a fail-fast, a crash, a forced end): each is appended
  305. // to %APPDATA%\LYNX\crash-history.log and its file removed. Returns the last step of the newest one ("" when none).
  306. juce::StringArray uncleanSteps; // the newest unclean session's steps (without their times)
  307. juce::String uncleanSessionText; // the newest unclean session's whole file (round 159: the crash report reads it)
  308. // What the newest unclean session tells (round 157a): the plugin whose editor was opening / shown when it ended, and
  309. // whether its crash file blames a graphics driver
  310. struct UncleanCause
  311. {
  312. juce::String editorPlugin; // the last steps were that plugin's editor
  313. bool gpuDriver = false; // the crash file's top frames are in a GPU driver / Direct3D / Direct2D module
  314. juce::String driverModule;
  315. };
  316. UncleanCause uncleanCause()
  317. {
  318. UncleanCause cause;
  319. juce::File crashFile;
  320. for (int i = uncleanSteps.size(); --i >= 0 && i >= uncleanSteps.size() - 4;)
  321. {
  322. const auto& step = uncleanSteps[i];
  323. if (step.startsWith ("crashed: backtrace in "))
  324. crashFile = lynx::platform::settingsFolder().getChildFile (step.fromFirstOccurrenceOf ("backtrace in ", false, false).replaceCharacter ('\\', '/'));
  325. for (const auto* prefix : { "opening the editor of ", "editor open: ", "editor shown: " })
  326. if (cause.editorPlugin.isEmpty() && step.startsWith (prefix))
  327. cause.editorPlugin = step.fromFirstOccurrenceOf (prefix, false, false).trim();
  328. if (step.startsWith ("closing the editor of ") || step.startsWith ("loaded plugin") || step.startsWith ("opening project"))
  329. break; // older steps than these did not end the session
  330. }
  331. // issue #32 (round 174a): a plugin whose editor already faulted in this session (caught, LYNX went on) is the
  332. // likely cause when the session then ended without a word: offer it a separate process too
  333. for (int i = uncleanSteps.size(); --i >= 0 && cause.editorPlugin.isEmpty();)
  334. if (const auto editor = lynx::crashreport::parseEditorCrashStep (uncleanSteps[i].toStdString()); ! editor.plugin.empty())
  335. cause.editorPlugin = juce::String::fromUTF8 (editor.plugin.c_str());
  336. if (crashFile.existsAsFile())
  337. {
  338. // the first frames after the crash handler's own (the "--- frames" part lists the faulting thread)
  339. auto text = crashFile.loadFileAsString();
  340. if (text.contains ("--- frames"))
  341. text = text.fromFirstOccurrenceOf ("--- frames", false, false);
  342. auto lines = juce::StringArray::fromLines (text);
  343. int looked = 0;
  344. for (const auto& line : lines)
  345. {
  346. const auto module = line.fromFirstOccurrenceOf (": ", false, false).upToFirstOccurrenceOf ("+", false, false).trim().toLowerCase();
  347. if (module.isEmpty() || ! module.endsWith (".dll"))
  348. continue;
  349. if (++looked > 12)
  350. break;
  351. for (const auto* driver : { "igd", "ig9icd", "ig7icd", "igxelp", "nvwgf2um", "nvoglv", "nvd3dum", "atidxx", "atio6axx", "amdxx", "aticfx",
  352. "d3d11.dll", "d3d10warp", "dxgi.dll", "d2d1.dll", "opengl32.dll", "dcomp.dll" })
  353. if (module.startsWith (driver))
  354. {
  355. cause.gpuDriver = true;
  356. cause.driverModule = module;
  357. break;
  358. }
  359. if (cause.gpuDriver)
  360. break;
  361. }
  362. }
  363. return cause;
  364. }
  365. juce::String collectUncleanSessions()
  366. {
  367. juce::String lastStep;
  368. juce::Time newest;
  369. for (const auto& file : sessionsFolder().findChildFiles (juce::File::findFiles, false, "session-*.txt"))
  370. {
  371. const auto text = file.loadFileAsString();
  372. juce::StringPairArray values;
  373. juce::StringArray steps;
  374. for (const auto& line : juce::StringArray::fromLines (text))
  375. {
  376. if (line.startsWith ("step="))
  377. steps.add (line.fromFirstOccurrenceOf ("=", false, false));
  378. else if (line.contains ("="))
  379. values.set (line.upToFirstOccurrenceOf ("=", false, false), line.fromFirstOccurrenceOf ("=", false, false));
  380. }
  381. const auto pid = (std::uint32_t) values["pid"].getLargeIntValue();
  382. const auto start = (std::uint64_t) values["start"].getLargeIntValue();
  383. if (pid == lynx::crashguard::processId() || lynx::crashguard::processRunning (pid, start))
  384. continue; // this run, or another LYNX window still open
  385. lynx::PluginHost::settingsFolder().getChildFile ("crash-history.log")
  386. .appendText (juce::Time::getCurrentTime().toISO8601 (true) + " previous session ended without closing\n" + text + "\n");
  387. file.deleteFile();
  388. if (const auto modified = file.getLastModificationTime(); lastStep.isEmpty() || modified > newest)
  389. {
  390. newest = modified;
  391. lastStep = steps.isEmpty() ? juce::String ("start-up") : steps[steps.size() - 1].fromFirstOccurrenceOf (" ", false, false);
  392. uncleanSessionText = text;
  393. uncleanSteps.clear();
  394. for (const auto& step : steps)
  395. uncleanSteps.add (step.fromFirstOccurrenceOf (" ", false, false));
  396. }
  397. }
  398. return lastStep;
  399. }
  400. } // namespace
  401. // --uiperf (round 173f, discussion #10): a mixer fader dragged up and down with the mouse while the pattern plays. A
  402. // high-resolution timer delivers 125 moves a second to the message thread through the window's own mouse path
  403. // (ComponentPeer::handleMouseEvent), at most one waiting at a time as Windows does with WM_MOUSEMOVE; every frame the
  404. // window paints tells whether it covered the fader. Measured: how long a move waited for the message thread, the time
  405. // from a move to the first frame that shows the fader after it (input → paint), and whether the value stays put when
  406. // the mouse is released.
  407. struct UiPerfDrag final : public std::enable_shared_from_this<UiPerfDrag>,
  408. private juce::HighResolutionTimer
  409. {
  410. ~UiPerfDrag() override { stopTimer(); }
  411. void start (juce::Component& windowIn, juce::Component& strips, juce::Rectangle<int> rail, lynx::AudioEngine* engineIn, int trackIn)
  412. {
  413. window = &windowIn;
  414. engine = engineIn;
  415. track = trackIn;
  416. railInWindow = window->getLocalArea (&strips, rail);
  417. watch = railInWindow.expanded (6, 40); // the cap, its tip above and the dB read-out below
  418. visible = strips.isShowing() && window->getLocalArea (&strips, strips.getLocalBounds()).contains (railInWindow.getCentre());
  419. const auto volume = engine->getSong().mixer[(std::size_t) track].volume;
  420. x = (float) railInWindow.getCentreX();
  421. startY = (float) railInWindow.getBottom() - volume * (float) railInWindow.getHeight(); // on the cap: no jump
  422. amplitude = 0.4f * (float) railInWindow.getHeight();
  423. centreY = juce::jlimit ((float) railInWindow.getY() + amplitude, (float) railInWindow.getBottom() - amplitude, startY);
  424. t0 = juce::Time::getMillisecondCounterHiRes();
  425. inject (x, startY, false);
  426. juce::ModifierKeys::currentModifiers = juce::ModifierKeys (juce::ModifierKeys::leftButtonModifier);
  427. inject (x, startY, true);
  428. active = true;
  429. startTimer (8);
  430. }
  431. // message thread
  432. void framePainted (double now, juce::Rectangle<int> area)
  433. {
  434. if (pending.empty() || ! area.intersects (watch))
  435. return;
  436. for (const auto t : pending)
  437. latencies.push_back (now - t);
  438. pending.clear();
  439. ++framesOverFader;
  440. }
  441. // the moves end; as in the reporter's clip, the song is stopped while the button is still down
  442. juce::String stop()
  443. {
  444. stopTimer();
  445. active = false;
  446. valueAtRelease = engine->getSong().mixer[(std::size_t) track].volume;
  447. engine->stop();
  448. juce::String text;
  449. text << " drag of insert " << track << "'s fader" << (visible ? "" : " (NOT VISIBLE)") << ": " << moves << " moves handled, " << dropped
  450. << " folded into the next (the message thread still busy with the previous one)\n"
  451. << " move waited for the message thread: " << describe (queueDelays) << "\n"
  452. << " input -> paint (move to the first frame over the fader): " << describe (latencies) << ", " << framesOverFader
  453. << " frames over the fader\n";
  454. return text;
  455. }
  456. juce::String release()
  457. {
  458. const auto now = engine->getSong().mixer[(std::size_t) track].volume;
  459. juce::ModifierKeys::currentModifiers = {};
  460. inject (x, lastY, false);
  461. return " song stopped, button still down: fader " + juce::String (now, 4) + " (" + juce::String (valueAtRelease, 4) + " at the last move) "
  462. + (std::abs (now - valueAtRelease) < 1.0e-4f ? "kept" : "CHANGED") + "\n";
  463. }
  464. juce::String released() const
  465. {
  466. const auto now = engine->getSong().mixer[(std::size_t) track].volume;
  467. return " after the release: fader " + juce::String (now, 4) + " (" + juce::String (valueAtRelease, 4) + " when released) "
  468. + (std::abs (now - valueAtRelease) < 1.0e-4f ? "kept" : "CHANGED") + "\n";
  469. }
  470. private:
  471. juce::Component* window = nullptr;
  472. lynx::AudioEngine* engine = nullptr;
  473. int track = 1;
  474. juce::Rectangle<int> railInWindow, watch;
  475. bool visible = false;
  476. float x = 0.0f, startY = 0.0f, centreY = 0.0f, amplitude = 0.0f, lastY = 0.0f;
  477. double t0 = 0.0;
  478. std::atomic<bool> active { false }, posted { false };
  479. std::atomic<int> dropped { 0 };
  480. int moves = 0, framesOverFader = 0;
  481. float valueAtRelease = 0.0f;
  482. std::vector<double> pending, latencies, queueDelays;
  483. static juce::String describe (std::vector<double> v)
  484. {
  485. if (v.empty())
  486. return "none";
  487. std::sort (v.begin(), v.end());
  488. const auto at = [&v] (double q) { return v[std::min (v.size() - 1, (std::size_t) (q * (double) v.size()))]; };
  489. return "p50 " + juce::String (at (0.5), 1) + " / p95 " + juce::String (at (0.95), 1) + " / p99 " + juce::String (at (0.99), 1) + " / max "
  490. + juce::String (v.back(), 1) + " ms";
  491. }
  492. void inject (float px, float py, bool down)
  493. {
  494. lastY = py;
  495. if (auto* peer = window != nullptr ? window->getPeer() : nullptr)
  496. {
  497. const auto local = peer->globalToLocal (window->localPointToGlobal (juce::Point<float> (px, py)));
  498. peer->handleMouseEvent (juce::MouseInputSource::InputSourceType::mouse, local,
  499. down ? juce::ModifierKeys (juce::ModifierKeys::leftButtonModifier) : juce::ModifierKeys(),
  500. juce::MouseInputSource::defaultPressure, juce::MouseInputSource::defaultOrientation,
  501. juce::Time::currentTimeMillis());
  502. }
  503. }
  504. void hiResTimerCallback() override
  505. {
  506. if (! active.load())
  507. return;
  508. if (posted.exchange (true))
  509. {
  510. ++dropped;
  511. return;
  512. }
  513. const auto postedAt = juce::Time::getMillisecondCounterHiRes();
  514. juce::MessageManager::callAsync ([self = shared_from_this(), postedAt] {
  515. self->posted = false;
  516. if (! self->active.load())
  517. return;
  518. const auto now = juce::Time::getMillisecondCounterHiRes();
  519. self->queueDelays.push_back (now - postedAt);
  520. // up and down ~1.3 times a second, like the reporter's hand
  521. const auto y = self->centreY + self->amplitude * (float) std::sin (2.0 * juce::MathConstants<double>::pi * 1.3 * (now - self->t0) / 1000.0);
  522. self->inject (self->x, y, true);
  523. self->pending.push_back (postedAt);
  524. ++self->moves;
  525. });
  526. }
  527. };
  528. class LynxApplication final : public juce::JUCEApplication
  529. {
  530. public:
  531. const juce::String getApplicationName() override { return JUCE_APPLICATION_NAME_STRING; }
  532. const juce::String getApplicationVersion() override { return JUCE_APPLICATION_VERSION_STRING; }
  533. // the plugin scan runs copies of LYNX as child processes
  534. bool moreThanOneInstanceAllowed() override { return true; }
  535. // A file handed to the running application. macOS does this for every Finder double-click, "Open With" and Dock drop,
  536. // also the one that starts LYNX (its argv has no file). On Windows and Linux a second start is a second process
  537. // (moreThanOneInstanceAllowed) with the file as an argument, so this is not called there. Only the first file of a
  538. // multiple selection opens: a project replaces the one before it. (D#92, round 180a)
  539. void anotherInstanceStarted (const juce::String& commandLine) override
  540. {
  541. const auto files = lynx::safety::filesInCommandLine (commandLine.toStdString());
  542. if (files.empty())
  543. return;
  544. const auto file = juce::File::getCurrentWorkingDirectory().getChildFile (juce::String::fromUTF8 (files.front().c_str()));
  545. if (! startupFileHandled) // still starting: openStartupFile takes it, nothing to ask about yet
  546. {
  547. fileToOpen = file;
  548. return;
  549. }
  550. if (mainWindow != nullptr)
  551. {
  552. mainWindow->toFront (true);
  553. mainWindow->getContent().openFileRequest (file);
  554. }
  555. }
  556. void initialise (const juce::String& commandLine) override
  557. {
  558. // round 166b: the copy of LYNX.exe that installs an update (ui/Updater.h) waits, installs, starts LYNX again
  559. if (commandLine.contains ("--apply-update") && lynx::updater::runApplyHelper (juce::StringArray::fromTokens (commandLine, true)))
  560. {
  561. updateHelper = true;
  562. quit();
  563. return;
  564. }
  565. // Windows, LYNX.exe in a folder with accents: run again from its ASCII short path (Waves editors crash otherwise)
  566. if (int code = 0; lynx::platform::relaunchFromAsciiPath (code))
  567. {
  568. relaunched = true;
  569. setApplicationReturnValue (code);
  570. quit();
  571. return;
  572. }
  573. // a crash in any mode (UI, command line) writes its backtrace to %APPDATA%\LYNX\autosave
  574. juce::SystemStats::setApplicationCrashHandler (onCrash);
  575. // rollup 0.1.28 (REA 190hb action 4, FL's "Init DWM"): the compositor on MMCSS, steadier frames under CPU load
  576. // (Windows; LYNX_DWM_MMCSS=0 leaves it off)
  577. lynx::powerhints::enableCompositorMmcss();
  578. // round 190ci: also for a fault on a stack Windows cannot walk, which never reaches that handler (Windows)
  579. lynx::crashguard::setUnwalkableFaultHandler (onCrash);
  580. if (const auto args = juce::StringArray::fromTokens (commandLine, true); args.contains ("--faulttest"))
  581. {
  582. // LYNX.exe --faulttest plain|unwalkable <folder> (round 190ci): ends by an access violation on purpose,
  583. // before any window, so that --selftest can check that the crash file gets written (into <folder>)
  584. const auto i = args.indexOf ("--faulttest");
  585. crashFolderForTest = juce::File (args[i + 2].unquoted());
  586. lynx::crashguard::quietCrashReports();
  587. // round 190dt: guarded / guarded-libc = LYNX's own fault inside a guarded plugin call (Linux / macOS): it must
  588. // reach the crash handler like any other; a return means the guard swallowed it
  589. // round 190gg: thread / thread-libc = a fault on a thread of LYNX's own, with LYNX's executable watched as
  590. // a plugin's module: it must not be parked as a plugin's thread
  591. if (args[i + 1].startsWith ("thread"))
  592. {
  593. lynx::crashguard::faultOnOwnThreadForTest (args[i + 1] == "thread-libc");
  594. crashFolderForTest.getChildFile ("swallowed.txt").replaceWithText ("parked");
  595. lynx::crashguard::exitNow (4);
  596. }
  597. if (args[i + 1].startsWith ("guarded"))
  598. {
  599. const auto code = lynx::crashguard::faultInGuardedCallForTest (args[i + 1] == "guarded-libc");
  600. crashFolderForTest.getChildFile ("swallowed.txt").replaceWithText (lynx::crashguard::describe (code));
  601. lynx::crashguard::exitNow (4);
  602. }
  603. lynx::crashguard::faultForTest (args[i + 1] == "unwalkable");
  604. }
  605. lynx::crashguard::hardenSignals(); // issue #115: stack overflows and SIGTERM / SIGHUP leave a trace (Linux / macOS)
  606. // SFZ instruments (round 167o): their FLAC / OGG / AIFF / MP3 samples through JUCE's readers
  607. lynx::sfz::setDecoder ([] (const std::string& path, lynx::sfz::Audio& out) {
  608. juce::AudioFormatManager formats;
  609. formats.registerBasicFormats();
  610. std::unique_ptr<juce::AudioFormatReader> reader (formats.createReaderFor (juce::File (juce::String::fromUTF8 (path.c_str()))));
  611. if (reader == nullptr || reader->lengthInSamples <= 0 || reader->lengthInSamples > (1 << 28) || reader->numChannels == 0)
  612. return false;
  613. const auto frames = (int) reader->lengthInSamples;
  614. juce::AudioBuffer<float> buffer ((int) std::min (2u, reader->numChannels), frames);
  615. if (! reader->read (&buffer, 0, frames, 0, true, buffer.getNumChannels() > 1))
  616. return false;
  617. out.channels.clear();
  618. for (int ch = 0; ch < buffer.getNumChannels(); ++ch)
  619. out.channels.emplace_back (buffer.getReadPointer (ch), buffer.getReadPointer (ch) + frames);
  620. out.sampleRate = reader->sampleRate;
  621. out.loopStart = out.loopEnd = -1;
  622. return true;
  623. });
  624. // child process of a sandboxed plugin: no window or audio of its own
  625. if (lynx::runPluginSandboxWorker (commandLine))
  626. {
  627. lynx::crashguard::quietCrashReports();
  628. sandboxChild = true;
  629. return;
  630. }
  631. // --shot-scale <v> / --shot-suffix <text> (round 190bi, ui/ShotScale.h): the pixel scale and file-name suffix of every
  632. // picture route, taken out here so the routes' own arguments keep their places
  633. const auto args = lynx::shot::takeArguments (juce::StringArray::fromTokens (commandLine, true));
  634. // interface language: saved in %APPDATA%\LYNX\language.txt; --lang pt-BR overrides it for this run
  635. lynx::i18n::initialise (args);
  636. // interface font: saved in Settings › General; --uifont "Name" overrides it for this run
  637. const auto uiFontArg = args.indexOf ("--uifont");
  638. lookAndFeel.applyInterfaceFont (lynx::i18n::current(), uiFontArg >= 0 ? args[uiFontArg + 1].unquoted() : juce::String());
  639. if (args.contains ("--showcase"))
  640. {
  641. // LYNX's own demo project (README screenshots): --showcase output.lynx [pattern]
  642. const auto i = args.indexOf ("--showcase");
  643. runShowcase (args[i + 1].unquoted(), args[i + 2].getIntValue());
  644. return;
  645. }
  646. if (args.contains ("--demosongs"))
  647. {
  648. // round 190dv: LYNX's two short genre demos (core/DemoSongs.h) as .lynx files: --demosongs <folder>
  649. // (resources/demos/ in the repository)
  650. const auto i = args.indexOf ("--demosongs");
  651. runDemoSongs (args[i + 1].unquoted());
  652. return;
  653. }
  654. if (args.contains ("--sandboxtest"))
  655. {
  656. const auto i = args.indexOf ("--sandboxtest");
  657. runSandboxTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  658. return;
  659. }
  660. if (args.contains ("--bridge32test"))
  661. {
  662. // LYNX.exe --bridge32test "LYNX Test Synth 32.dll" report.txt [--compare "LYNX Test Synth.dll"] (round 176a):
  663. // the 32-bit plugin bridge (engine/Bridge32Test.cpp)
  664. const auto i = args.indexOf ("--bridge32test");
  665. const auto compare = args.contains ("--compare") ? args[args.indexOf ("--compare") + 1].unquoted() : juce::String();
  666. setApplicationReturnValue (lynx::runBridge32Test (args[i + 1].unquoted(), args[i + 2].unquoted(), compare));
  667. quit();
  668. return;
  669. }
  670. if (args.contains ("--rtstress"))
  671. {
  672. // LYNX.exe --rtstress project.(flp|lynx) report.txt [seconds] [--buffer N] [--type "driver type"] [--device "output"]
  673. // [--no-window] [--record take.wav]: the real app (window, audio device) plays the project and reports the callbacks
  674. // that missed their deadline (REA round 87); --type/--device pick another driver for this run only (round 97);
  675. // --record also records the input during the run, like Rec + Play, and moves the take to take.wav (round 106)
  676. const auto i = args.indexOf ("--rtstress");
  677. const auto seconds = args[i + 3].getDoubleValue();
  678. const auto buffer = args.contains ("--buffer") ? args[args.indexOf ("--buffer") + 1].getIntValue() : 0;
  679. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  680. const auto option = [&args] (const char* name) { return args.contains (name) ? args[args.indexOf (name) + 1].unquoted() : juce::String(); };
  681. runRealtimeStress (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()), seconds > 0.0 ? seconds : 30.0, buffer,
  682. option ("--type"), option ("--device"), option ("--record"));
  683. return;
  684. }
  685. if (args.contains ("--renderaheadtest"))
  686. {
  687. // LYNX --renderaheadtest report.txt [project.flp|.lynx ...] [--buffer N] [--seconds S] (round 190gq): the engine's
  688. // own device callback (a stand-in device driven block by block, as --cliplooptest) plays the showcase song (from
  689. // the start, round a loop region that wraps mid-block, in Pattern mode) and each project with Options › Audio
  690. // settings › "Render ahead" off, then on. The two outputs must be the same to the bit, nothing rendered ahead
  691. // may be dropped, and most blocks must come from the ring. No window, no audio device.
  692. const auto i = args.indexOf ("--renderaheadtest");
  693. juce::StringArray projects;
  694. for (int k = i + 2; k < args.size() && ! args[k].startsWith ("--"); ++k)
  695. projects.add (args[k].unquoted());
  696. const auto buffer = args.contains ("--buffer") ? args[args.indexOf ("--buffer") + 1].getIntValue() : 128;
  697. const auto seconds = args.contains ("--seconds") ? args[args.indexOf ("--seconds") + 1].getDoubleValue() : 12.0;
  698. runRenderAheadTest (juce::File (args[i + 1].unquoted()), projects, juce::jlimit (16, 2048, buffer), seconds > 0.0 ? seconds : 12.0);
  699. return;
  700. }
  701. if (args.contains ("--cliplooptest"))
  702. {
  703. // LYNX --cliplooptest report.txt [export.wav] (round 167q, issue #25: 0.1.21 drew the repeats of a stretched
  704. // pattern clip but played the pattern once). The real engine's device callback (a stand-in device, driven
  705. // block by block) plays a synth's 1-bar pattern in a 4-bar clip: every repeat must sound as bar 1, also
  706. // starting inside a repeat, after a jump mid-clip and in a loop region; the WAV export (written to
  707. // export.wav and read back) the same. With the LYNX extra off, bars 2-4 must be silent (FL's behaviour).
  708. const auto i = args.indexOf ("--cliplooptest");
  709. runClipLoopTest (juce::File (args[i + 1].unquoted()), args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? juce::File (args[i + 2].unquoted()) : juce::File());
  710. return;
  711. }
  712. if (args.contains ("--devicechangetest"))
  713. {
  714. // LYNX --devicechangetest report.txt [switches] [--plugin file]... (round 190c, issue #134: changing the
  715. // output device with a project open crashed LYNX). The engine plays a project of every instrument and effect
  716. // it can make here on stand-in devices with real callback threads, while the output device, its sample
  717. // rate and its buffer size change the way Settings > Audio changes them (8 kHz mono to 192 kHz, buffers of
  718. // 32 to 16384 samples, a device plugged in, the open one unplugged, one that refuses to open). After every
  719. // change the song must sound, finite, at the new rate. No window, no real audio or MIDI device.
  720. const auto i = args.indexOf ("--devicechangetest");
  721. const juce::File report (args[i + 1].unquoted());
  722. const auto switches = args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? args[i + 2].getIntValue() : 0;
  723. juce::StringArray plugins;
  724. for (int k = 0; k + 1 < args.size(); ++k)
  725. if (args[k] == "--plugin")
  726. plugins.add (args[k + 1].unquoted());
  727. auto text = std::make_shared<juce::String>();
  728. // --quick: the selftest's handful of instruments and effects instead of every one
  729. const auto result = lynx::AudioEngine::deviceChangeSelfTest (switches > 0 ? switches : 40, ! args.contains ("--quick"), plugins, [report, text] (const juce::String& line) {
  730. *text << line << "\n";
  731. report.replaceWithText (*text + "(running)\n"); // what was reached, if it crashes
  732. });
  733. *text << "device_change=" << result << "\nresult=" << (result.startsWith ("OK") ? "OK" : "FAILED") << "\n";
  734. report.replaceWithText (*text);
  735. setApplicationReturnValue (result.startsWith ("OK") ? 0 : 1);
  736. quit();
  737. return;
  738. }
  739. if (args.contains ("--exportparitytest") || args.contains ("--midihotplugtest"))
  740. {
  741. // LYNX --exportparitytest report.txt (round 190gh, B7): the export against playback through a stand-in audio
  742. // device, stems adding up to the mix with one length, the PDC trim. LYNX --midihotplugtest report.txt (B8):
  743. // MIDI devices plugged in and out (stand-in device lists) while messages arrive. No window.
  744. const auto parity = args.contains ("--exportparitytest");
  745. const auto i = args.indexOf (parity ? "--exportparitytest" : "--midihotplugtest");
  746. const juce::File report (args[i + 1].unquoted());
  747. juce::String text;
  748. const auto result = parity ? lynx::AudioEngine::exportParitySelfTest ([&text] (const juce::String& line) { text << line << "\n"; })
  749. : lynx::AudioEngine::midiHotplugSelfTest();
  750. text << (parity ? "export_parity=" : "midi_hotplug=") << result << "\nresult=" << (result.startsWith ("OK") ? "OK" : "FAILED") << "\n";
  751. report.replaceWithText (text);
  752. setApplicationReturnValue (result.startsWith ("OK") ? 0 : 1);
  753. quit();
  754. return;
  755. }
  756. if (args.contains ("--shortexporttest"))
  757. {
  758. // LYNX --shortexporttest report.txt [repeats] [--plugin file]... (round 190c, issue #138: a short note at
  759. // the very start of the Playlist exported quiet). Every instrument LYNX can make here, and a synth with
  760. // effects, tail modes, normalising and other rates, exported through the Export window's path (the job
  761. // made on the message thread, run on its own thread, the message loop running) with a 2-second note at
  762. // tick 0 and again with it at bar 2: the note must come out the same. No window.
  763. const auto i = args.indexOf ("--shortexporttest");
  764. const juce::File report (args[i + 1].unquoted());
  765. const auto repeats = args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? args[i + 2].getIntValue() : 0;
  766. juce::StringArray plugins;
  767. for (int k = 0; k + 1 < args.size(); ++k)
  768. if (args[k] == "--plugin")
  769. plugins.add (args[k + 1].unquoted());
  770. auto text = std::make_shared<juce::String>();
  771. lynx::shortexport::run (true, repeats > 0 ? repeats : 3, plugins,
  772. [report, text] (const juce::String& line) {
  773. *text << line << "\n";
  774. report.replaceWithText (*text + "(running)\n");
  775. },
  776. [this, report, text] (juce::String result) {
  777. *text << "short_export=" << result << "\nresult=" << (result.startsWith ("OK") ? "OK" : "FAILED") << "\n";
  778. report.replaceWithText (*text);
  779. setApplicationReturnValue (result.startsWith ("OK") ? 0 : 1);
  780. quit();
  781. });
  782. return;
  783. }
  784. if (args.contains ("--slicexedittest"))
  785. {
  786. // LYNX --slicexedittest project script.txt report.txt [png-prefix] (round 190aj): the Slicex editor of the
  787. // project's first Slicex channel, off screen, driven by the script's commands (ui/SlicexEditor.h; mouse
  788. // gestures at fractions of the deck's width, the menu entries, shortcuts). The report holds each command
  789. // and what the state held after it; "shot <name>" writes <png-prefix><name>.png.
  790. const auto i = args.indexOf ("--slicexedittest");
  791. runSlicexEditTest (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()), juce::File (args[i + 3].unquoted()),
  792. args.size() > i + 4 ? args[i + 4].unquoted() : juce::String());
  793. return;
  794. }
  795. if (args.contains ("--slicexkeytest"))
  796. {
  797. // LYNX --slicexkeytest report.txt (round 190ac): what a click on the Slicex editor's keyboard sends
  798. // (AudioEngine::sendLiveNote on the channel, velocity 100/128) through the real engine's device callback
  799. // (a stand-in device, driven block by block): the key's region must sound, on the channel's mixer meter
  800. // too, another key must play another region, and the note-off must end it.
  801. runSlicexKeyTest (juce::File (args[args.indexOf ("--slicexkeytest") + 1].unquoted()));
  802. return;
  803. }
  804. if (args.contains ("--countinrectest"))
  805. {
  806. // LYNX --countinrectest report.txt (round 170d, the Busy Works video: the chord on the downbeat after the
  807. // pre-count was lost). The real engine's device callback (a stand-in device: 48 kHz, blocks of 512, 256
  808. // samples of output latency) records a Song-mode take from bar 3 with a 1-bar count-in. Pass 1 finds where
  809. // the metronome's bar-3 click is heard; pass 2 plays MIDI notes stamped at the times they are heard around
  810. // 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
  811. // LYNX's MIDI input. Every note must land on the tick it was heard at (the chord on bar 3).
  812. const auto i = args.indexOf ("--countinrectest");
  813. runCountInRecordTest (juce::File (args[i + 1].unquoted()));
  814. return;
  815. }
  816. if (args.contains ("--bendrectest"))
  817. {
  818. // LYNX --bendrectest report.txt [song|pattern] (round 167a, issue #12): pitch bend recording end to end. A
  819. // controller's pitch wheel is injected into LYNX's MIDI input (as a device would send it) while recording
  820. // plays: a held note and a wheel sweep 0 → full up → full down → centre. The recorded lane (pattern mode) or
  821. // automation clip (song mode) of the channel's pitch bend must follow the sweep.
  822. const auto i = args.indexOf ("--bendrectest");
  823. const auto songMode = args.size() > i + 2 && args[i + 2] == "song";
  824. runBendRecordTest (juce::File (args[i + 1].unquoted()), songMode);
  825. return;
  826. }
  827. if (args.contains ("--rectest"))
  828. {
  829. // LYNX --rectest report.txt [seconds] [--type T] [--device D] [--input I] [--loop] [--buffer N]
  830. // (round 163): records a click track through a loopback (cable, interface loopback or PipeWire's
  831. // pw-loopback): pings the round trip, plays a click on every beat from an audio clip, records it on Insert 1,
  832. // stops, and checks every recorded click's song position on the Playlist against its beat (samples).
  833. // --loop: loop recording over bars 2-4 (take lanes). --punch: punch in/out on bars 3-4 with 1 bar of pre-roll
  834. // and 1 of post-roll (playback stops by itself after the post-roll).
  835. const auto i = args.indexOf ("--rectest");
  836. const auto option = [&args] (const char* name) { return args.contains (name) ? args[args.indexOf (name) + 1].unquoted() : juce::String(); };
  837. const auto seconds = args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? args[i + 2].getDoubleValue() : 20.0;
  838. runRecordTest (juce::File (args[i + 1].unquoted()), seconds > 0.0 ? seconds : 20.0, option ("--type"), option ("--device"), option ("--input"),
  839. args.contains ("--loop") ? 1 : args.contains ("--punch") ? 2 : 0, option ("--pdc").getIntValue(), option ("--buffer").getIntValue());
  840. return;
  841. }
  842. if (args.contains ("--hwinserttest"))
  843. {
  844. // LYNX --hwinserttest report.txt [seconds] [--type T] [--device D] [--input I] [--buffer N] (round 164d): a
  845. // hardware insert through a loopback cable (output pair 1-2 -> input pair 1-2; the Master plays nowhere, so
  846. // the cable carries the send only). The same click track plays on two inserts: Insert 1 through the
  847. // hardware insert (panned left), Insert 2 dry (panned right). The insert's own ping measures the round
  848. // trip, PDC delays the dry path by it, and every click of the Master's left side must sit on the same
  849. // sample as the right side's.
  850. const auto i = args.indexOf ("--hwinserttest");
  851. const auto option = [&args] (const char* name) { return args.contains (name) ? args[args.indexOf (name) + 1].unquoted() : juce::String(); };
  852. const auto seconds = args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? args[i + 2].getDoubleValue() : 10.0;
  853. // round 165c: --patcher puts the insert inside a Patcher on Insert 1; --bounce file.wav then exports the song in real
  854. // time through the device (Export › "Render through the hardware in real time") and offline, and compares them
  855. runHwInsertTest (juce::File (args[i + 1].unquoted()), seconds > 0.0 ? seconds : 10.0, option ("--type"), option ("--device"), option ("--input"),
  856. option ("--buffer").getIntValue(), args.contains ("--patcher"),
  857. args.contains ("--bounce") ? juce::File (option ("--bounce")) : juce::File());
  858. return;
  859. }
  860. if (args.contains ("--uiperf"))
  861. {
  862. // LYNX --uiperf project.(flp|lynx) report.txt: the heavy UI cases in the real window, every frame timed (round 161)
  863. const auto i = args.indexOf ("--uiperf");
  864. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  865. runUiPerf (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()));
  866. return;
  867. }
  868. if (args.contains ("--cachetest"))
  869. {
  870. // LYNX --cachetest project.(flp|lynx) report.txt (round 174f): the Playlist's cached picture against exact
  871. // paints after zooms, scrolls and repaints, off screen (no window)
  872. const auto i = args.indexOf ("--cachetest");
  873. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  874. runCacheTest (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()));
  875. return;
  876. }
  877. if (args.contains ("--picturetest"))
  878. {
  879. // LYNX --picturetest report.txt [project.(flp|lynx)] (round 190bm): the Playlist and the Mixer drawn through
  880. // their cached pictures at 100-300 %, into native and software targets, against straight paints; off
  881. // screen (no window)
  882. const auto i = args.indexOf ("--picturetest");
  883. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  884. runPictureTest (juce::File (args[i + 1].unquoted()), i + 2 < args.size() ? juce::File (args[i + 2].unquoted()) : juce::File());
  885. return;
  886. }
  887. if (args.contains ("--timertest"))
  888. {
  889. // LYNX --timertest report.txt (round 174f): ui::TimerWhileShowing through hide / show / minimise (opens a small window)
  890. runTimerTest (juce::File (args[args.indexOf ("--timertest") + 1].unquoted()));
  891. return;
  892. }
  893. if (args.contains ("--livepeer"))
  894. {
  895. // LYNX --livepeer host|guest|rejoin <folder> [--relay URL] [--code CODE|@file]: one computer's side of a live
  896. // session between two real computers, no window (round 190ah)
  897. setApplicationReturnValue (lynx::livetest::runPeer (args));
  898. quit();
  899. return;
  900. }
  901. if (args.contains ("--livetest"))
  902. {
  903. // LYNX --livetest report.txt [--relay URL]: a live session of four peers over the relay (round 169b)
  904. setApplicationReturnValue (lynx::livetest::run (args));
  905. quit();
  906. return;
  907. }
  908. if (args.contains ("--selftest"))
  909. {
  910. const auto i = args.indexOf ("--selftest");
  911. runSelfTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  912. return;
  913. }
  914. if (args.contains ("--scan-one"))
  915. {
  916. // child process of the plugin scan (see PluginHost::scan)
  917. const auto i = args.indexOf ("--scan-one");
  918. // no crash dialogs from the plugin being examined; and once the result is written, the process ends without
  919. // unloading it: a Waves shell crashed in its own teardown at exit (Intel GPU driver fail-fast, 0xC0000409),
  920. // which showed Windows' crash dialog and made the scan reject the whole shell (round 111)
  921. lynx::crashguard::quietCrashReports();
  922. lynx::PluginHost::scanOneFile (args[i + 1].unquoted(), args[i + 2].unquoted(), juce::File (args[i + 3].unquoted()));
  923. lynx::crashguard::exitNow (0);
  924. }
  925. if (args.contains ("--splashshot"))
  926. {
  927. // LYNX --splashshot <folder> (round 190hd): the splash card drawn as the JUCE card is and as the card on its own
  928. // thread is (ui/Splash.h), side by side; no window
  929. const auto shots = lynx::writeSplashShots (juce::File (args[args.indexOf ("--splashshot") + 1].unquoted()));
  930. setApplicationReturnValue (shots.size() == 20 ? 0 : 1);
  931. quit();
  932. return;
  933. }
  934. if (args.contains ("--browser-indexer"))
  935. {
  936. // round 190hd: the Browser's indexer, a low-priority child of the LYNX window (BrowserComponent.h): no window,
  937. // no session, no audio; it ends with its parent
  938. lynx::crashguard::quietCrashReports();
  939. lynx::crashguard::exitNow (lynx::BrowserComponent::runIndexerProcess (args));
  940. }
  941. if (args.contains ("--packageinfo"))
  942. {
  943. // round 165n: the Microsoft Store (MSIX) build's identity and folders (platform/Package.h); the release
  944. // workflow runs it inside the installed test package
  945. juce::File (args[args.indexOf ("--packageinfo") + 1].unquoted()).replaceWithText (lynx::platform::packageReport());
  946. quit();
  947. return;
  948. }
  949. if (args.contains ("--paths"))
  950. {
  951. // diagnostics: folders LYNX searches
  952. const auto programs = juce::File::getSpecialLocation (juce::File::globalApplicationsDirectory);
  953. juce::String report;
  954. report << "programs=" << programs.getFullPathName() << "\n";
  955. for (const auto& dir : programs.getChildFile ("Image-Line").findChildFiles (juce::File::findDirectories, false, "FL Studio*"))
  956. report << "fl=" << dir.getFullPathName() << " packs=" << (int) dir.getChildFile ("Data").getChildFile ("Patches").getChildFile ("Packs").isDirectory() << "\n";
  957. juce::File (args[args.indexOf ("--paths") + 1].unquoted()).replaceWithText (report);
  958. quit();
  959. return;
  960. }
  961. if (args.contains ("--fldb"))
  962. {
  963. // diagnostics: LYNX.exe --fldb report.txt [project.flp]: the FL Studio installation, its plugin database,
  964. // the suggested plugin folders and, for a project, how each of its plugins resolves (read-only)
  965. const auto i = args.indexOf ("--fldb");
  966. const auto fl = lynx::findFlStudio();
  967. lynx::PluginHost host (false);
  968. juce::String report;
  969. report << "install=" << fl.installDir.getFullPathName() << "\nuserdata=" << fl.userData.getFullPathName() << "\n";
  970. for (const auto& f : fl.vstFolders)
  971. report << "flvstfolder=" << f << "\n";
  972. report << "dbfiles=" << host.flPluginDatabaseFiles() << " entries=" << (int) host.flPluginDatabase().entries().size() << "\n";
  973. for (const auto& e : host.flPluginDatabase().entries())
  974. report << " entry: " << juce::String::fromUTF8 (e.name.c_str()) << " | " << juce::String::fromUTF8 (e.path.c_str()) << " | role=" << e.role << "\n";
  975. const auto suggested = host.suggestedFolders();
  976. for (int k = 0; k < suggested.getNumPaths(); ++k)
  977. report << "folder=" << suggested[k].getFullPathName() << "\n";
  978. if (const juce::File project (args[i + 2].unquoted()); project.existsAsFile())
  979. {
  980. juce::MemoryBlock data;
  981. project.loadFileAsData (data);
  982. try
  983. {
  984. for (const auto& use : lynx::flpForeignPlugins (flp::parseProject ({ static_cast<const std::uint8_t*> (data.getData()), data.getSize() })))
  985. {
  986. juce::String how;
  987. const auto d = host.findForeign (use.plugin, use.instrument, &how);
  988. const auto* entry = host.flPluginDatabase().match (use.plugin, use.instrument);
  989. report << "plugin: " << juce::String::fromUTF8 (use.plugin.name.c_str()) << " -> "
  990. << (d ? d->fileOrIdentifier + " (" + how + ")" : juce::String ("not known"))
  991. << (entry != nullptr ? " | fl db: " + juce::String::fromUTF8 (entry->path.c_str()) : juce::String()) << "\n";
  992. }
  993. const auto uses = lynx::flpForeignPlugins (flp::parseProject ({ static_cast<const std::uint8_t*> (data.getData()), data.getSize() }));
  994. const auto candidates = host.filesToScanFor (uses);
  995. report << "scan_candidates=" << candidates.joinIntoString (";") << "\n";
  996. if (args.contains ("--scan"))
  997. {
  998. // the targeted scan an open would run (child processes; the user's plugin list is not touched)
  999. report << "scanned_new=" << host.scanFiles (candidates, {}) << "\n";
  1000. for (const auto& use : uses)
  1001. {
  1002. juce::String how;
  1003. const auto d = host.findForeign (use.plugin, use.instrument, &how);
  1004. report << "after_scan: " << juce::String::fromUTF8 (use.plugin.name.c_str()) << " -> "
  1005. << (d ? d->fileOrIdentifier + " (" + how + ")" : juce::String ("not known")) << "\n";
  1006. }
  1007. }
  1008. }
  1009. catch (const flp::Error& e)
  1010. {
  1011. report << "error=" << e.what() << "\n";
  1012. }
  1013. }
  1014. juce::File (args[i + 1].unquoted()).replaceWithText (report);
  1015. quit();
  1016. return;
  1017. }
  1018. if (args.contains ("--midisync-test"))
  1019. {
  1020. // LYNX --midisync-test report.txt ["output device"] ["input device"] (round 165f): MIDI clock timing
  1021. const auto i = args.indexOf ("--midisync-test");
  1022. const auto out = args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  1023. const auto in = args.size() > i + 3 && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  1024. juce::File (args[i + 1].unquoted()).replaceWithText (lynx::MidiSyncIo::selfTest (out, in));
  1025. quit();
  1026. return;
  1027. }
  1028. if (args.contains ("--linktest"))
  1029. {
  1030. // LYNX --linktest report.txt [seconds] [peer] (round 190gl): Ableton Link with simulated audio callbacks; with
  1031. // "peer" a second Link peer in this process, else a peer on the network (Ableton's LinkHut) is expected
  1032. const auto i = args.indexOf ("--linktest");
  1033. const auto seconds = args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? args[i + 2].getDoubleValue() : 20.0;
  1034. const auto ownPeer = args.contains ("peer");
  1035. juce::File (args[i + 1].unquoted()).replaceWithText (juce::String (lynx::AbletonLink::selfTest (seconds > 0.0 ? seconds : 20.0, ownPeer)));
  1036. quit();
  1037. return;
  1038. }
  1039. if (args.contains ("--devices") || args.contains ("--dispositivos")) // --dispositivos: legacy alias
  1040. {
  1041. // diagnostics: driver types and output devices JUCE offers (without opening any)
  1042. juce::AudioDeviceManager manager;
  1043. juce::String report;
  1044. manager.getAvailableDeviceTypes();
  1045. if (auto pipeWire = lynx::makePipeWireDeviceType()) // Linux: LYNX's own PipeWire client (round 161)
  1046. manager.addAudioDeviceType (std::move (pipeWire));
  1047. #if JUCE_LINUX
  1048. report << lynx::describePipeWire() << "\n";
  1049. #endif
  1050. for (auto* type : manager.getAvailableDeviceTypes())
  1051. {
  1052. type->scanForDevices();
  1053. report << "type=" << type->getTypeName() << "\n";
  1054. for (const auto& name : type->getDeviceNames (false))
  1055. report << " output=" << name << "\n";
  1056. for (const auto& name : type->getDeviceNames (true))
  1057. report << " input=" << name << "\n";
  1058. }
  1059. for (const auto& d : juce::MidiInput::getAvailableDevices())
  1060. report << "midi-in=" << d.name << "\n";
  1061. for (const auto& d : juce::MidiOutput::getAvailableDevices())
  1062. report << "midi-out=" << d.name << "\n";
  1063. const auto flag = args.contains ("--devices") ? args.indexOf ("--devices") : args.indexOf ("--dispositivos");
  1064. juce::File (args[flag + 1].unquoted()).replaceWithText (report);
  1065. quit();
  1066. return;
  1067. }
  1068. if (args.contains ("--devicetest"))
  1069. {
  1070. // LYNX.exe --devicetest "type" "device" report.txt ["input device"] [--buffer N] [--roundtrip]: opens that output device (and, with the
  1071. // 4th argument, an input: "*" = the same device / the driver's default input), receives 1 s of callbacks
  1072. // writing silence, closes it and reports rate, block size, latency, callbacks and the input channels with
  1073. // their peak level (driver check, no sound). --roundtrip: clicks out, found again on input 1 through a loopback
  1074. // cable / PipeWire link: the round-trip latency (3 s)
  1075. const auto i = args.indexOf ("--devicetest");
  1076. const auto typeName = args[i + 1].unquoted(), deviceName = args[i + 2].unquoted();
  1077. auto inputName = args.size() > i + 4 && ! args[i + 4].startsWith ("--") ? args[i + 4].unquoted() : juce::String();
  1078. const auto wantInput = inputName.isNotEmpty();
  1079. juce::String report;
  1080. const juce::File reportFile (args[i + 3].unquoted());
  1081. auto step = [&] (const juce::String& line) { report << line << "\n"; reportFile.replaceWithText (report); }; // progress survives a driver that ends the process
  1082. step ("step=start");
  1083. juce::AudioDeviceManager manager;
  1084. manager.getAvailableDeviceTypes();
  1085. if (auto pipeWire = lynx::makePipeWireDeviceType())
  1086. manager.addAudioDeviceType (std::move (pipeWire));
  1087. std::unique_ptr<juce::AudioIODevice> device;
  1088. for (auto* type : manager.getAvailableDeviceTypes())
  1089. if (type->getTypeName() == typeName)
  1090. {
  1091. type->scanForDevices();
  1092. if (wantInput && type->hasSeparateInputsAndOutputs())
  1093. {
  1094. const auto inputs = type->getDeviceNames (true);
  1095. if (inputName == "*" || ! inputs.contains (inputName))
  1096. {
  1097. const auto index = type->getDefaultDeviceIndex (true);
  1098. inputName = juce::isPositiveAndBelow (index, inputs.size()) ? inputs[index] : juce::String();
  1099. }
  1100. for (const auto& n : inputs)
  1101. step ("input_device=" + n);
  1102. step ("input_chosen=" + inputName);
  1103. }
  1104. else if (wantInput)
  1105. inputName = deviceName;
  1106. step ("step=create");
  1107. device.reset (type->createDevice (deviceName, type->hasSeparateInputsAndOutputs() ? inputName : juce::String()));
  1108. step ("step=created");
  1109. }
  1110. struct Silence final : juce::AudioIODeviceCallback
  1111. {
  1112. std::atomic<int> calls { 0 }, inputs { 0 };
  1113. std::array<std::atomic<float>, 64> peaks {};
  1114. // --roundtrip (round 161): a click every quarter second on the outputs, found again on input 1 through a
  1115. // loopback; the delays in samples
  1116. bool roundtrip = false;
  1117. int period = 12000;
  1118. std::int64_t position = 0, lastClick = -1;
  1119. std::vector<int> delays;
  1120. void audioDeviceIOCallbackWithContext (const float* const* in, int numIn, float* const* out, int channels, int n,
  1121. const juce::AudioIODeviceCallbackContext&) override
  1122. {
  1123. for (int c = 0; c < channels; ++c)
  1124. if (out[c] != nullptr)
  1125. juce::FloatVectorOperations::clear (out[c], n);
  1126. if (roundtrip)
  1127. {
  1128. for (int i = 0; i < n; ++i)
  1129. {
  1130. if (numIn > 0 && in[0] != nullptr && lastClick >= 0 && std::abs (in[0][i]) > 0.5f)
  1131. {
  1132. if (delays.size() < delays.capacity())
  1133. delays.push_back ((int) (position + i - lastClick));
  1134. lastClick = -1;
  1135. }
  1136. if ((position + i) % period == 0 && position + i > 0)
  1137. {
  1138. for (int c = 0; c < channels; ++c)
  1139. if (out[c] != nullptr)
  1140. out[c][i] = 0.9f;
  1141. lastClick = position + i;
  1142. }
  1143. }
  1144. position += n;
  1145. }
  1146. inputs.store (numIn);
  1147. for (int c = 0; c < juce::jmin (numIn, 64); ++c)
  1148. if (in[c] != nullptr)
  1149. {
  1150. const auto range = juce::FloatVectorOperations::findMinAndMax (in[c], n);
  1151. const auto peak = juce::jmax (std::abs (range.getStart()), std::abs (range.getEnd()));
  1152. if (peak > peaks[(std::size_t) c].load())
  1153. peaks[(std::size_t) c].store (peak);
  1154. }
  1155. ++calls;
  1156. }
  1157. void audioDeviceAboutToStart (juce::AudioIODevice*) override {}
  1158. void audioDeviceStopped() override {}
  1159. } silence;
  1160. bool ok = false;
  1161. if (device == nullptr)
  1162. step ("error=device not found");
  1163. else
  1164. {
  1165. step ("step=open");
  1166. juce::BigInteger outputs;
  1167. outputs.setRange (0, 2, true);
  1168. const auto rates = device->getAvailableSampleRates();
  1169. const auto rate = device->getCurrentSampleRate() > 0 ? device->getCurrentSampleRate()
  1170. : rates.contains (48000.0) ? 48000.0 : rates.isEmpty() ? 44100.0 : rates[0];
  1171. step ("rates=" + juce::String (rates.size()) + " chosen=" + juce::String (rate) + " default_block=" + juce::String (device->getDefaultBufferSize()));
  1172. juce::BigInteger inputs;
  1173. if (wantInput)
  1174. {
  1175. const auto names = device->getInputChannelNames();
  1176. step ("input_channels=" + juce::String (names.size()));
  1177. for (int c = 0; c < names.size(); ++c)
  1178. step (" in" + juce::String (c + 1) + "=" + names[c]);
  1179. inputs.setRange (0, juce::jmin (64, names.size()), true);
  1180. }
  1181. // --buffer N: ask for that block size (REA round 97 latency survey); default: the driver's default
  1182. const auto wantedBlock = args.contains ("--buffer") ? args[args.indexOf ("--buffer") + 1].getIntValue() : 0;
  1183. const auto error = device->open (inputs, outputs, rate, wantedBlock > 0 ? wantedBlock : device->getDefaultBufferSize());
  1184. if (error.isNotEmpty())
  1185. step ("error=" + error);
  1186. else
  1187. {
  1188. step ("step=start_callbacks");
  1189. silence.roundtrip = args.contains ("--roundtrip");
  1190. silence.period = juce::jmax (1, (int) (rate / 4));
  1191. silence.delays.reserve (64);
  1192. device->start (&silence);
  1193. juce::Thread::sleep (silence.roundtrip ? 3000 : 1000);
  1194. device->stop();
  1195. if (silence.roundtrip)
  1196. {
  1197. auto d = silence.delays;
  1198. std::sort (d.begin(), d.end());
  1199. report << "roundtrip_clicks=" << (int) d.size() << "\n";
  1200. if (! d.empty())
  1201. report << "roundtrip_samples=min " << d.front() << " median " << d[d.size() / 2] << " max " << d.back() << "\n"
  1202. << "roundtrip_ms=" << juce::String (1000.0 * d[d.size() / 2] / device->getCurrentSampleRate(), 2) << "\n";
  1203. }
  1204. report << "rate=" << device->getCurrentSampleRate() << "\n"
  1205. << "block=" << device->getCurrentBufferSizeSamples() << "\n"
  1206. << "output_latency=" << device->getOutputLatencyInSamples() << "\n"
  1207. << "callbacks=" << silence.calls.load() << "\n";
  1208. if (wantInput)
  1209. {
  1210. report << "input_latency=" << device->getInputLatencyInSamples() << "\n"
  1211. << "active_inputs=" << device->getActiveInputChannels().countNumberOfSetBits() << "\n"
  1212. << "callback_inputs=" << silence.inputs.load() << "\n";
  1213. for (int c = 0; c < juce::jmin (64, silence.inputs.load()); ++c)
  1214. report << " peak_in" << (c + 1) << "=" << juce::Decibels::gainToDecibels (silence.peaks[(std::size_t) c].load(), -150.0f) << " dB\n";
  1215. }
  1216. ok = silence.calls.load() > 0 && (! wantInput || silence.inputs.load() > 0);
  1217. device->close();
  1218. }
  1219. }
  1220. step (juce::String ("result=") + (ok ? "OK" : "FAILED"));
  1221. setApplicationReturnValue (ok ? 0 : 1);
  1222. quit();
  1223. return;
  1224. }
  1225. if (args.contains ("--scantest"))
  1226. {
  1227. // LYNX.exe --scantest folder report.txt: scan (in child processes) without touching the user's list
  1228. const auto i = args.indexOf ("--scantest");
  1229. lynx::PluginHost host (false);
  1230. const auto found = host.scan (juce::FileSearchPath (args[i + 1].unquoted()), {});
  1231. juce::String report;
  1232. report << "found=" << found << "\n";
  1233. for (const auto& t : host.getKnownPlugins().getTypes())
  1234. report << " " << (t.isInstrument ? "instrument: " : "effect: ") << t.name << "\n";
  1235. for (const auto& f : host.getKnownPlugins().getBlacklistedFiles())
  1236. report << " blacklisted: " << f << "\n";
  1237. juce::File (args[i + 2].unquoted()).replaceWithText (report);
  1238. setApplicationReturnValue (found > 0 ? 0 : 1);
  1239. quit();
  1240. return;
  1241. }
  1242. if (args.contains ("--wrappermiditest"))
  1243. {
  1244. // LYNX.exe --wrappermiditest plugin.dll report.txt (round 181c), with LYNX_TEST_VST2_MIDILOG set: what a
  1245. // hosted plugin receives after a wrapper MIDI option changes while it runs
  1246. const auto i = args.indexOf ("--wrappermiditest");
  1247. runWrapperMidiTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  1248. return;
  1249. }
  1250. if (args.contains ("--wrappershot"))
  1251. {
  1252. const auto i = args.indexOf ("--wrappershot");
  1253. runWrapperShot (args[i + 1].unquoted(), args[i + 2].unquoted());
  1254. return;
  1255. }
  1256. if (args.contains ("--multiouttest"))
  1257. {
  1258. const auto i = args.indexOf ("--multiouttest");
  1259. runMultiOutTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  1260. return;
  1261. }
  1262. if (args.contains ("--vstitest"))
  1263. {
  1264. // LYNX --vstitest plugin folder [project.lynx] (round 190fw, issue #162): an instrument plugin (Image-Line's
  1265. // "FL Studio VSTi") on a channel: notes in, audio out, its state through a saved project, its outputs and
  1266. // the host tempo it follows. See runVstiTest.
  1267. const auto i = args.indexOf ("--vstitest");
  1268. const auto project = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  1269. runVstiTest (args[i + 1].unquoted(), args[i + 2].unquoted(), project);
  1270. return;
  1271. }
  1272. if (args.contains ("--vst2test"))
  1273. {
  1274. const auto i = args.indexOf ("--vst2test");
  1275. runVst2Test (args[i + 1].unquoted(), args[i + 2].unquoted());
  1276. return;
  1277. }
  1278. if (args.contains ("--vst3noteidtest"))
  1279. {
  1280. const auto i = args.indexOf ("--vst3noteidtest");
  1281. runVst3NoteIdTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  1282. return;
  1283. }
  1284. if (args.contains ("--lv2scantest"))
  1285. {
  1286. runLv2ScanTest (args[args.indexOf ("--lv2scantest") + 1].unquoted());
  1287. return;
  1288. }
  1289. if (args.contains ("--wrappertest"))
  1290. {
  1291. const auto i = args.indexOf ("--wrappertest");
  1292. runWrapperTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  1293. return;
  1294. }
  1295. if (args.contains ("--plugintest"))
  1296. {
  1297. const auto i = args.indexOf ("--plugintest");
  1298. // optional 3rd argument: the plugin's name inside a shell (e.g. "CLA-2A Stereo" in a WaveShell)
  1299. const auto only = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  1300. runPluginTest (args[i + 1].unquoted(), args[i + 2].unquoted(), only);
  1301. return;
  1302. }
  1303. if (args.contains ("--crashguardtest"))
  1304. {
  1305. // LYNX --crashguardtest "LYNX Test Crash.vst3|.clap" report.txt [process|memcpy] (round 190dt,
  1306. // tools/testplugin/lynx_test_crash*.{c,cpp}): the plugin crashes in its 40th block on insert 1; LYNX must
  1307. // catch it, mark the slot, keep playing the other inserts, save the project, reload the plugin; then the
  1308. // saved project opens with the plugin crashing on its state; and LYNX's own faults are still crashes
  1309. const auto i = args.indexOf ("--crashguardtest");
  1310. runCrashGuardTest (args[i + 1].unquoted(), args[i + 2].unquoted(),
  1311. i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String ("process"));
  1312. return;
  1313. }
  1314. if (args.contains ("--claprestarttest"))
  1315. {
  1316. // LYNX.exe --claprestarttest "LYNX Test Restart.clap" report.txt (tools/testplugin/lynx_test_restart.c)
  1317. const auto i = args.indexOf ("--claprestarttest");
  1318. runClapRestartTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  1319. return;
  1320. }
  1321. if (args.contains ("--clapteardowntest"))
  1322. {
  1323. // LYNX.exe --clapteardowntest "LYNX Test Restart.clap" report.txt (round 190az, engine/ClapTeardownTest.cpp)
  1324. const auto i = args.indexOf ("--clapteardowntest");
  1325. lynx::runClapTeardownTest (args[i + 1].unquoted(), args[i + 2].unquoted(), [this] (int code) {
  1326. setApplicationReturnValue (code);
  1327. quit();
  1328. });
  1329. return;
  1330. }
  1331. if (args.contains ("--mpetest"))
  1332. {
  1333. // LYNX.exe --mpetest "LYNX Test MPE.clap" report.txt (tools/testplugin/lynx_test_mpe.c, issue #108)
  1334. const auto i = args.indexOf ("--mpetest");
  1335. runMpeTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  1336. return;
  1337. }
  1338. if (args.contains ("--editortest"))
  1339. {
  1340. // LYNX.exe --editortest plugin.vst3 report.txt ["name"]: opens the plugin's own editor in a window for a few
  1341. // seconds, then closes it (a plugin whose UI crashes the host ends the process before the report says OK)
  1342. const auto i = args.indexOf ("--editortest");
  1343. const auto only = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  1344. runEditorTest (args[i + 1].unquoted(), args[i + 2].unquoted(), only);
  1345. return;
  1346. }
  1347. if (args.contains ("--editorcrashtest"))
  1348. {
  1349. // LYNX.exe --editorcrashtest "LYNX Test Crash.clap" report.txt (issue #32, round 174a; Windows): the test
  1350. // plugin's editor faults in its own window procedure (LYNX_TEST_CRASH=editor). LYNX must catch it, close
  1351. // that editor, record the trace and keep running its message loop.
  1352. const auto i = args.indexOf ("--editorcrashtest");
  1353. runEditorCrashTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  1354. return;
  1355. }
  1356. if (args.contains ("--reloadtest"))
  1357. {
  1358. // LYNX --reloadtest plugin report.txt [shots folder] [--wait-kill]: round 190ao (reload a crashed plugin).
  1359. // Hosts the plugin in a separate process (a channel for an instrument, insert 1 for an effect) in an offline
  1360. // engine, crashes its process (--wait-kill: writes <report>.pid and waits for the process to be killed
  1361. // from outside), checks that nothing reloads by itself, reloads it on request and checks the new process,
  1362. // the state captured last, the untouched song and undo history; twice. With a shots folder: PNGs of the
  1363. // plugin window's crash notice and of the prompt.
  1364. const auto i = args.indexOf ("--reloadtest");
  1365. runReloadTest (args[i + 1].unquoted(), args[i + 2].unquoted(),
  1366. i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String(), args.contains ("--wait-kill"));
  1367. return;
  1368. }
  1369. if (args.contains ("--pluginoptionstest"))
  1370. {
  1371. // LYNX --pluginoptionstest plugin report.txt [shots folder]: round 190ao. Hosts the plugin inside LYNX (a
  1372. // channel for an instrument, insert 1 for an effect) in an offline engine, opens its window and checks
  1373. // LYNX's own plugin-window options: Pin on top (set, kept above another window, saved with the plugin,
  1374. // back when the window opens again). With a shots folder: PNGs of each state. The window is on screen.
  1375. const auto i = args.indexOf ("--pluginoptionstest");
  1376. runPluginOptionsTest (args[i + 1].unquoted(), args[i + 2].unquoted(),
  1377. i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String());
  1378. return;
  1379. }
  1380. if (args.contains ("--plugwintest"))
  1381. {
  1382. // LYNX --plugwintest plugin report.txt ["name"] [seconds]: round 162d. Puts the plugin in a channel (an
  1383. // instrument) or on insert 1 (an effect) of an offline engine, opens its plugin window (wrapper header,
  1384. // presets), checks a preset round trip, keeps the window `seconds` on screen (default 15: time for xdotool /
  1385. // screenshots), then removes the plugin from the song and reports whether its window closed by itself.
  1386. const auto i = args.indexOf ("--plugwintest");
  1387. const auto only = i + 3 < args.size() && ! args[i + 3].startsWith ("--") && ! args[i + 3].containsOnly ("0123456789") ? args[i + 3].unquoted() : juce::String();
  1388. auto seconds = 15;
  1389. for (int k = i + 3; k < juce::jmin (args.size(), i + 5); ++k)
  1390. if (args[k].containsOnly ("0123456789"))
  1391. seconds = args[k].getIntValue();
  1392. runPlugWinTest (args[i + 1].unquoted(), args[i + 2].unquoted(), only, seconds);
  1393. return;
  1394. }
  1395. if (args.contains ("--fittest"))
  1396. {
  1397. // LYNX.exe --fittest report.txt [percent]: round 163 — at that UI zoom (default 150) a window taller than
  1398. // the screen and a big resizable window that grows with a zoom change keep their title bar and close
  1399. // button on the screen. The windows show for about two seconds.
  1400. const auto i = args.indexOf ("--fittest");
  1401. runFitTest (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].getIntValue() : 150);
  1402. return;
  1403. }
  1404. if (args.contains ("--windowtest"))
  1405. {
  1406. // LYNX.exe --windowtest report.txt: opens the Quick-add palette, the Audio editor, a plugin-like window and a name dialog
  1407. // over the main window and checks that each one stays in front, owned by the main window, with the
  1408. // keyboard focus (issue #4). The windows appear on screen for a few seconds.
  1409. runWindowTest (args[args.indexOf ("--windowtest") + 1].unquoted());
  1410. return;
  1411. }
  1412. if (args.contains ("--focustest"))
  1413. {
  1414. // LYNX --focustest report.txt (issue #161): the main window with the Playlist and the Piano roll (native
  1415. // child windows with docking on). For each: LYNX goes to the background (the main window loses the focus),
  1416. // the user comes back with a click in the panel, then presses Space: playback must start. Also: a text
  1417. // field's focus comes back with the window, and inside the active window the click's answer is unchanged.
  1418. // Shows a window (takes the foreground on Windows: GUI lock); exit code 0 = OK.
  1419. runFocusTest (args[args.indexOf ("--focustest") + 1].unquoted());
  1420. return;
  1421. }
  1422. if (args.contains ("--simplekeytest"))
  1423. {
  1424. // LYNX --simplekeytest report.txt (round 190fc, 0.1.27 RC H2): the main window in the Simple layout; after a
  1425. // demo opened from Welcome › Start from and after clicks in the dock, its tabs, the Lyrics button, a track
  1426. // header and the grid, Space must start playback (a text field clicked into keeps its typing keys). Shows a
  1427. // window (takes the foreground on Windows: GUI lock); exit code 0 = OK.
  1428. runSimpleKeyTest (args[args.indexOf ("--simplekeytest") + 1].unquoted());
  1429. return;
  1430. }
  1431. if (args.contains ("--pluginstyle")) // round 126: force one style for this run (glow, neon, hardware, vivid; auto = per plugin)
  1432. {
  1433. const auto i = args.indexOf ("--pluginstyle");
  1434. if (i + 1 < args.size())
  1435. {
  1436. const auto name = args[i + 1].unquoted();
  1437. lynx::skin::setForcedStyle (name.equalsIgnoreCase ("auto") ? -1 : (int) lynx::skin::styleFromName (name));
  1438. }
  1439. }
  1440. if (args.contains ("--gfxprobe"))
  1441. {
  1442. // LYNX.exe --gfxprobe report.txt (round 170c, issue #11): renderer checks on this platform's native images —
  1443. // text drawn with a gradient fill (a word with a space in it) and an empty path filled with a gradient must
  1444. // stay inside their shapes. JUCE 8.0.4's CoreGraphics renderer (macOS) clipped to an empty glyph or path as
  1445. // "no clip" and flooded the whole component (Facet EQ's blank pink window).
  1446. const auto i = args.indexOf ("--gfxprobe");
  1447. juce::File (args[i + 1].unquoted()).replaceWithText (lynx::skin::rendererProbeReport());
  1448. quit();
  1449. return;
  1450. }
  1451. if (args.contains ("--steppertest"))
  1452. {
  1453. // LYNX.exe --steppertest <report.txt>: round 170c (#14) — every value stepper of every generated effect editor
  1454. // driven by synthetic input (arrows, click on the value, drag, wheel, trackpad); ends with result=OK / FAIL
  1455. const auto i = args.indexOf ("--steppertest");
  1456. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1457. juce::String report;
  1458. int fails = 0, count = 0, skips = 0;
  1459. {
  1460. lynx::AudioEngine offline (false);
  1461. auto kinds = lynx::plugui::flLayoutKinds();
  1462. for (const auto own : lynx::plugui::ownLayoutKinds())
  1463. kinds.push_back (own);
  1464. // FL's Default preset when the installation has one (the state-backed controls need FL's state)
  1465. const auto roots = lynx::findFlStudioRoots();
  1466. const auto presets = juce::File (juce::String::fromUTF8 (roots.data.c_str())).getChildFile ("Patches/Plugin presets/Effects");
  1467. for (const auto kind : kinds)
  1468. {
  1469. auto fx = lynx::makeEffectSlot (kind);
  1470. for (const auto& plugin : lynx::flPluginsForEffect (kind))
  1471. {
  1472. juce::MemoryBlock data;
  1473. const auto file = presets.getChildFile (juce::String::fromUTF8 (plugin.c_str())).getChildFile ("Default.fst");
  1474. if (file.existsAsFile() && file.loadFileAsData (data))
  1475. {
  1476. const auto* bytes = static_cast<const std::uint8_t*> (data.getData());
  1477. 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)
  1478. fx = *loaded;
  1479. }
  1480. break;
  1481. }
  1482. lynx::Song song;
  1483. song.mixer.resize (2);
  1484. song.mixer[0].name = "Master";
  1485. song.mixer[1].name = "Insert 1";
  1486. song.mixer[1].effects.push_back (fx);
  1487. offline.setSong (std::move (song));
  1488. offline.dispatchPendingMessages();
  1489. const auto lines = lynx::stepperSelfTest (offline, 1, 0, (int) lynx::plugui::layoutFor (kind).pages.size());
  1490. for (const auto& line : juce::StringArray::fromLines (lines))
  1491. if (line.isNotEmpty())
  1492. {
  1493. ++count;
  1494. fails += line.contains (": FAIL") ? 1 : 0;
  1495. skips += line.contains (": SKIP") ? 1 : 0;
  1496. }
  1497. report << lines;
  1498. juce::PopupMenu::dismissAllActiveMenus();
  1499. offline.dispatchPendingMessages();
  1500. }
  1501. }
  1502. report << "steppers=" << count << " failures=" << fails << " skipped=" << skips << "\nresult=" << (fails == 0 && count > 0 ? "OK" : "FAIL") << "\n";
  1503. juce::File (args[i + 1].unquoted()).replaceWithText (report);
  1504. quit();
  1505. return;
  1506. }
  1507. if (args.contains ("--plugui"))
  1508. {
  1509. // LYNX.exe --plugui <folder>: the native effect editors at FL's size (one PNG per editor and page), each
  1510. // loaded with the FL plugin's Default preset when the FL installation has one
  1511. const auto i = args.indexOf ("--plugui");
  1512. runPluginEditorSnapshots (args[i + 1].unquoted());
  1513. return;
  1514. }
  1515. if (args.contains ("--parityshot"))
  1516. {
  1517. // LYNX.exe --parityshot <out.png> <effect name> [<params file>]: one built-in effect's editor with the given
  1518. // parameters ("index value" lines, tools/fxrender --dump), its displays fed by the demo song — the LYNX side
  1519. // of the third-party parity pictures (round tp172b)
  1520. const auto i = args.indexOf ("--parityshot");
  1521. runParityShot (args[i + 1].unquoted(), args[i + 2].unquoted(), i + 3 < args.size() ? args[i + 3].unquoted() : juce::String());
  1522. if (parityShotFailed)
  1523. setApplicationReturnValue (2);
  1524. if (parityShow == nullptr)
  1525. quit();
  1526. return;
  1527. }
  1528. if (args.contains ("--design168rshot"))
  1529. {
  1530. // LYNX.exe --design168rshot <folder>: round 168r's editors (FL effects that had a generated page and LYNX's own
  1531. // simple built-ins) at 100 % and 200 %, with their default settings and, when they have one, the first
  1532. // preset of LYNX's own bank. "--design168rshot <folder> generated": the generated pages they had before
  1533. const auto i = args.indexOf ("--design168rshot");
  1534. if (i + 2 < args.size() && args[i + 2] == "generated")
  1535. lynx::plugui::showGeneratedLayoutsOnly (true);
  1536. runDesign168rShots (args[i + 1].unquoted());
  1537. quit();
  1538. return;
  1539. }
  1540. if (args.contains ("--eq166fshot"))
  1541. {
  1542. // LYNX.exe --eq166fshot <folder>: round 166f's pictures (issue #16) — Parametric EQ 2's spectrum and heatmap
  1543. // (flat, a +12 dB band, a -12 dB band, Top position) and Facet EQ's comparative EQ (listening to the target,
  1544. // its spectrum over the source's), each fed by the demo song rendered offline
  1545. const auto i = args.indexOf ("--eq166fshot");
  1546. runEq166fShots (args[i + 1].unquoted());
  1547. quit();
  1548. return;
  1549. }
  1550. if (args.contains ("--editorcpu"))
  1551. {
  1552. // LYNX.exe --editorcpu report.txt: opens built-in plugin editors one at a time in a small window (no audio
  1553. // device: a silent, idle editor) and writes the process CPU each costs while idle and while its display
  1554. // animates (demo signal) — round 122's check that an idle editor burns no CPU
  1555. const auto i = args.indexOf ("--editorcpu");
  1556. runEditorCpu (args[i + 1].unquoted());
  1557. return;
  1558. }
  1559. if (args.contains ("--precomputeshot"))
  1560. {
  1561. // LYNX.exe --precomputeshot project.(flp|lynx) <prefix>: round 167h — <prefix>-precompute.png (channel 1's
  1562. // Precomputed effects panel) and <prefix>-project.png (Options › Project with "Fast declick for cut groups")
  1563. const auto i = args.indexOf ("--precomputeshot");
  1564. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1565. lynx::AudioEngine shotEngine (false);
  1566. const juce::File input (args[i + 1].unquoted());
  1567. const auto prefix = args[i + 2].unquoted();
  1568. juce::String error;
  1569. bool ok = false;
  1570. if (input.hasFileExtension ("flp"))
  1571. ok = shotEngine.importFlpFile (input, error);
  1572. else if (auto song = lynx::ProjectFile::load (input, error))
  1573. shotEngine.setSong (std::move (*song)), ok = true;
  1574. shotEngine.dispatchPendingMessages();
  1575. auto shoot = [&] (std::unique_ptr<juce::Component> c, const juce::String& name) {
  1576. if (c == nullptr)
  1577. return false;
  1578. if (c->getWidth() <= 0)
  1579. c->setSize (520, 600);
  1580. savePng (lynx::shot::snapshot (*c), prefix + name);
  1581. return true;
  1582. };
  1583. ok = ok && shoot (lynx::makeChannelPrecomputePanel (shotEngine, 0), "-precompute.png");
  1584. ok = ok && shoot (lynx::makeSettingsPanel (shotEngine, lynx::SettingsPage::project), "-project.png");
  1585. setApplicationReturnValue (ok ? 0 : 1);
  1586. quit();
  1587. return;
  1588. }
  1589. if (args.contains ("--pluginthumbs"))
  1590. {
  1591. // LYNX.exe --pluginthumbs <folder> [key,key...]: the Plugin picker's pictures of LYNX's own plugins (round 171c,
  1592. // ui/PluginThumbs.h), each editor drawn off-screen and kept as <folder>/<name>.png; the picker starts this in
  1593. // the background when pictures are missing. One line per plugin on stdout.
  1594. const auto i = args.indexOf ("--pluginthumbs");
  1595. lynx::crashguard::quietCrashReports();
  1596. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1597. juce::StringArray only;
  1598. if (i + 2 < args.size() && ! args[i + 2].startsWith ("--"))
  1599. only.addTokens (args[i + 2].unquoted(), ",", "");
  1600. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  1601. // round 190bi: with --shot-scale / LYNX_SHOT_SCALE each plugin's whole editor at that scale, not the picker's
  1602. // small thumbnail (never for the picker's own cache folder, whatever the environment says)
  1603. const juce::File folder (args[i + 1].unquoted());
  1604. const auto full = lynx::shot::given() && folder != lynx::pluginthumbs::nativeFolder() ? lynx::shot::scale() : 0.0f;
  1605. const auto drawn = lynx::pluginthumbs::renderNative (folder, only, [] (const juce::String& line) {
  1606. std::printf ("%s\n", line.toRawUTF8());
  1607. std::fflush (stdout);
  1608. }, full);
  1609. std::printf ("drawn %d in %.0f ms\n", drawn, juce::Time::getMillisecondCounterHiRes() - t0);
  1610. setApplicationReturnValue (0);
  1611. quit();
  1612. return;
  1613. }
  1614. if (args.contains ("--jsonroundtrip"))
  1615. {
  1616. // LYNX.exe --jsonroundtrip <folder>: round 183c's finding — a project saved, loaded and saved again: both texts
  1617. // (a.json, b.json) and the first lines that differ (diff.txt) for the default song, with and without a Patcher
  1618. const auto i = args.indexOf ("--jsonroundtrip");
  1619. const juce::File out (args[i + 1].unquoted());
  1620. out.createDirectory();
  1621. juce::String report;
  1622. auto check = [&] (const lynx::Song& song, const juce::String& name) {
  1623. const auto a = lynx::ProjectFile::toJson (song);
  1624. juce::String error;
  1625. const auto back = lynx::ProjectFile::fromJson (a, error);
  1626. const auto b = back ? lynx::ProjectFile::toJson (*back) : juce::String ("(not loaded: " + error + ")");
  1627. out.getChildFile (name + "-a.json").replaceWithText (a);
  1628. out.getChildFile (name + "-b.json").replaceWithText (b);
  1629. juce::StringArray la, lb;
  1630. la.addLines (a);
  1631. lb.addLines (b);
  1632. report << name << ": " << (a == b ? "stable" : "DIFFERS") << " (" << la.size() << " / " << lb.size() << " lines)\n";
  1633. int shown = 0;
  1634. for (int k = 0; k < juce::jmax (la.size(), lb.size()) && shown < 12; ++k)
  1635. if (la[k] != lb[k])
  1636. {
  1637. report << " line " << (k + 1) << "\n a: " << la[k].trim().substring (0, 200) << "\n b: " << lb[k].trim().substring (0, 200) << "\n";
  1638. ++shown;
  1639. }
  1640. };
  1641. auto song = lynx::Song::makeDefault();
  1642. check (song, "default");
  1643. song.mixer.resize (3);
  1644. song.mixer[1].effects = { lynx::makeEffectSlot (lynx::EffectKind::patcher) };
  1645. check (song, "patcher");
  1646. song.mixer[1].effects = { lynx::rack::makeRackSlot (lynx::RackDoc::Kind::audioEffect) };
  1647. check (song, "rack");
  1648. out.getChildFile ("diff.txt").replaceWithText (report);
  1649. setApplicationReturnValue (0);
  1650. quit();
  1651. return;
  1652. }
  1653. if (args.contains ("--rackshot"))
  1654. {
  1655. // LYNX.exe --rackshot <folder>: round 183c's Rack view drawn off-screen (no window), for the LYNX | Live pairs:
  1656. // rack-deviceview.png (an Audio Effect Rack laid out as in Live's reference shot), rack-mapmode.png (Map mode
  1657. // with the mapping list), rack-instrument.png (an Instrument Rack with its key zones)
  1658. const auto i = args.indexOf ("--rackshot");
  1659. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1660. const auto set = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  1661. setApplicationReturnValue (runRackShots (juce::File (args[i + 1].unquoted()), set) ? 0 : 1);
  1662. quit();
  1663. return;
  1664. }
  1665. if (args.contains ("--artshot"))
  1666. {
  1667. // LYNX.exe --artshot <folder> [before|after] [name,name...]: every editor with art of its own (round 170j/170k: the
  1668. // Themed style; or only the named ones, e.g. "sakura,facet-eq") drawn off-screen at 100 % and 200 % as
  1669. // <folder>/<plugin>-<before|after>-<scale>.png. "before" draws each in the style it had before the Themed style
  1670. const auto i = args.indexOf ("--artshot");
  1671. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1672. const auto mode = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String ("after");
  1673. if (i + 3 < args.size() && ! args[i + 3].startsWith ("--")) // [name,name...]: only these arts
  1674. artOnly().addTokens (args[i + 3].unquoted(), ",", "");
  1675. setApplicationReturnValue (runArtShots (juce::File (args[i + 1].unquoted()), mode == "before") ? 0 : 1);
  1676. quit();
  1677. return;
  1678. }
  1679. if (args.contains ("--artgui"))
  1680. {
  1681. // LYNX.exe --artgui <folder> [before|after|still] [name,name...]: the same editors in REAL windows on the desktop, one at a
  1682. // time (always on top, no focus taken), each held while an outside script screenshots it (it writes
  1683. // <folder>/<plugin>.ready with the window's bounds and waits up to 10 s for <folder>/<plugin>.done), then the
  1684. // process CPU it costs over 6 s is written to <folder>/cpu-<mode>.txt. "still": Themed with the motion off
  1685. const auto i = args.indexOf ("--artgui");
  1686. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1687. const auto mode = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String ("after");
  1688. if (i + 3 < args.size() && ! args[i + 3].startsWith ("--")) // [name,name...]: only these arts
  1689. artOnly().addTokens (args[i + 3].unquoted(), ",", "");
  1690. runArtGui (juce::File (args[i + 1].unquoted()), mode);
  1691. return;
  1692. }
  1693. if (args.contains ("--instrumentshot"))
  1694. {
  1695. // LYNX.exe --instrumentshot <folder> <engine,engine...|banks> [lynx|fl]: round 168n — the channel window of
  1696. // each engine (its Plugin tab) at 100 %, 150 % and 200 %, as <folder>/<engine>-<source>-<scale>.png. Source
  1697. // "lynx" starts from the engine's LYNX bank (what a PC without FL gets), "fl" from FL's Default preset.
  1698. const auto i = args.indexOf ("--instrumentshot");
  1699. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1700. const auto source = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String ("lynx");
  1701. setApplicationReturnValue (runInstrumentShots (juce::File (args[i + 1].unquoted()), args[i + 2].unquoted(), source) ? 0 : 1);
  1702. quit();
  1703. return;
  1704. }
  1705. if (args.contains ("--flextrashot"))
  1706. {
  1707. // LYNX.exe --flextrashot <folder>: pictures of the editors of round 165g (Big Clock, Tuner, HTML NoteBook, Mute 2, Scratcher, Transmitter) + round 167n Transporter
  1708. const auto i = args.indexOf ("--flextrashot");
  1709. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1710. lynx::AudioEngine shotEngine (false);
  1711. const auto ok = lynx::runFlExtraShots (shotEngine, juce::File (args[i + 1].unquoted()));
  1712. setApplicationReturnValue (ok ? 0 : 1);
  1713. quit();
  1714. return;
  1715. }
  1716. if (args.contains ("--visualtest"))
  1717. {
  1718. // LYNX.exe --visualtest <folder> [project.flp]: the visual plugins (round 164c) — the audio path's CPU, every
  1719. // Wave Candy mode and Visualizer scene drawn from a test signal (PNG + the editor's CPU each), and the video
  1720. // export of a project (default: FL's first ZGameEditor demo) with ffmpeg and as images. Writes report.txt.
  1721. const auto i = args.indexOf ("--visualtest");
  1722. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1723. const auto project = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? juce::File (args[i + 2].unquoted()) : juce::File();
  1724. lynx::runVisualTest (juce::File (args[i + 1].unquoted()), project, [this] (bool ok) {
  1725. setApplicationReturnValue (ok ? 0 : 1);
  1726. quit();
  1727. });
  1728. return;
  1729. }
  1730. if (args.contains ("--menu-entry"))
  1731. {
  1732. // LYNX.AppImage --menu-entry on|off: puts the AppImage in the applications menu (and .lynx files on it) or
  1733. // takes it out again, without opening a window; the same as the switch in Options › General (round 161)
  1734. const auto i = args.indexOf ("--menu-entry");
  1735. const auto on = args[i + 1].unquoted() != "off";
  1736. const auto ok = lynx::runningAsAppImage() && lynx::setAppImageMenuEntry (on);
  1737. std::fprintf (ok ? stdout : stderr, "%s\n", ok ? (on ? "LYNX SHARE added to the applications menu" : "LYNX SHARE removed from the applications menu")
  1738. : "only the LYNX SHARE AppImage on Linux can do this");
  1739. setApplicationReturnValue (ok ? 0 : 1);
  1740. quit();
  1741. return;
  1742. }
  1743. if (args.contains ("--send-test-report"))
  1744. {
  1745. // LYNX.exe --send-test-report out.txt [--dry]: builds a crash report marked "test" from the newest crash /
  1746. // hang file and this computer's facts, writes its JSON to out.txt.json and (without --dry) sends it to
  1747. // lynx-share.com (LYNX_CRASH_ENDPOINT overrides); out.txt gets "id=…" and "result=OK" or the error (round 159)
  1748. const auto i = args.indexOf ("--send-test-report");
  1749. const juce::File out (args[i + 1].unquoted());
  1750. lynx::crashreporter::Session session;
  1751. session.version = getApplicationVersion();
  1752. for (const auto* pattern : { "crash *.txt", "hang *.txt" })
  1753. {
  1754. auto files = lynx::platform::settingsFile ("autosave").findChildFiles (juce::File::findFiles, false, pattern);
  1755. lynx::filesort::byTime (files, lynx::filesort::By::modificationTime, true);
  1756. if (! files.isEmpty())
  1757. (juce::String (pattern).startsWith ("crash") ? session.crashFile : session.hangFile) = files[0];
  1758. }
  1759. session.steps = { "00:00:01 test report (LYNX.exe --send-test-report)", "00:00:02 opening project " + out.getFileName() };
  1760. auto input = lynx::crashreporter::makeInput (session, session.crashFile.existsAsFile() ? "crash" : "manual", nullptr);
  1761. input.test = true;
  1762. const auto json = lynx::crashreporter::buildJson (input, false);
  1763. out.withFileExtension (out.getFileExtension() + ".json").replaceWithText (json);
  1764. const auto error = args.contains ("--dry") ? juce::String() : lynx::crashreporter::sendNow (json);
  1765. out.replaceWithText ("id=" + juce::String::fromUTF8 (input.id.c_str()) + "\nendpoint=" + lynx::crashreporter::endpoint() + "\nbytes="
  1766. + juce::String (json.getNumBytesAsUTF8()) + "\nresult=" + (error.isEmpty() ? juce::String ("OK") : error) + "\n");
  1767. setApplicationReturnValue (error.isEmpty() ? 0 : 1);
  1768. quit();
  1769. return;
  1770. }
  1771. if (args.contains ("--symbolize"))
  1772. {
  1773. // LYNX.exe --symbolize "crash … .txt" out.txt: names the LYNX.exe+offset frames of a user's crash / hang file
  1774. // (needs this build's LYNX.pdb next to LYNX.exe — the release's "LYNX-symbols" CI artifact; round 157a)
  1775. const auto i = args.indexOf ("--symbolize");
  1776. const auto text = juce::File (args[i + 1].unquoted()).loadFileAsString();
  1777. juce::File (args[i + 2].unquoted()).replaceWithText (juce::String::fromUTF8 (lynx::crashguard::symbolizeOwnFrames (text.toStdString()).c_str()));
  1778. quit();
  1779. return;
  1780. }
  1781. if (args.contains ("--opentest"))
  1782. {
  1783. // LYNX.exe --opentest report.txt [--visible]: every built-in effect and instrument window opened as the mixer /
  1784. // Channel rack open them, with default, extreme, random and old-project states; a watchdog fails the test on
  1785. // a hang (round 157a: opening the Parametric EQ froze LYNX). Windows stay off-screen without --visible.
  1786. const auto i = args.indexOf ("--opentest");
  1787. runOpenTest (args[i + 1].unquoted(), args.contains ("--visible"), [this] (bool ok) {
  1788. setApplicationReturnValue (ok ? 0 : 1);
  1789. quit();
  1790. });
  1791. return;
  1792. }
  1793. if (args.contains ("--fxfuzz"))
  1794. {
  1795. // LYNX.exe --fxfuzz report.txt [rounds] [--drags]: every built-in effect in its editor, parameters swept (and
  1796. // dragged with the mouse), audio rendered at several rates; a crash ends the process (round 111)
  1797. const auto i = args.indexOf ("--fxfuzz");
  1798. const auto rounds = args.size() > i + 2 ? juce::jmax (1, args[i + 2].getIntValue()) : 6;
  1799. // --drags: also mouse drags over the editors (their menus may flash on screen: not for the selftest)
  1800. const auto ok = runEffectFuzz (rounds, args[i + 1].unquoted(), args.contains ("--drags"));
  1801. setApplicationReturnValue (ok ? 0 : 1);
  1802. quit();
  1803. return;
  1804. }
  1805. if (args.contains ("--controllershot"))
  1806. {
  1807. // LYNX.exe --controllershot prefix: the built-in controllers' editors (round 133) as PNGs
  1808. const auto i = args.indexOf ("--controllershot");
  1809. runControllerShot (args[i + 1].unquoted());
  1810. quit();
  1811. return;
  1812. }
  1813. if (args.contains ("--edisonshot"))
  1814. {
  1815. // LYNX.exe --edisonshot prefix [audio.wav]: the audio editor's Edison tool windows (round 165l) and the
  1816. // editor before / after some of them, as PNGs (a synthetic drum loop without a file)
  1817. const auto i = args.indexOf ("--edisonshot");
  1818. runEdisonShot (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String());
  1819. quit();
  1820. return;
  1821. }
  1822. if (args.contains ("--edisonslottest"))
  1823. {
  1824. // LYNX.exe --edisonslottest folder [project.flp]: round 190cd — the audio editor as a mixer-slot plugin through
  1825. // the engine and the project file (report.txt: one "name=ok|FAIL" per check), its window as slot-*.png, and
  1826. // the Edison slots of an FL project (what was read of each)
  1827. const auto i = args.indexOf ("--edisonslottest");
  1828. const auto ok = runEdisonSlotTest (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String());
  1829. setApplicationReturnValue (ok ? 0 : 1);
  1830. quit();
  1831. return;
  1832. }
  1833. if (args.contains ("--danceshot"))
  1834. {
  1835. // LYNX.exe --danceshot prefix: LYNX Dance (round 165e) — every move as a contact sheet, the channel's editor,
  1836. // and a demo project with two dance channels (for --snapshot)
  1837. const auto i = args.indexOf ("--danceshot");
  1838. runDanceShot (args[i + 1].unquoted());
  1839. quit();
  1840. return;
  1841. }
  1842. if (args.contains ("--videoshot") && args.indexOf ("--videoshot") + 2 < args.size())
  1843. {
  1844. // LYNX.exe --videoshot prefix video: the Video Player's editor (round 165g) at a few song positions, with
  1845. // the user's ffmpeg, as PNGs + report.txt (frames decoded, the sound track)
  1846. const auto i = args.indexOf ("--videoshot");
  1847. runVideoShot (args[i + 1].unquoted(), args[i + 2].unquoted());
  1848. return;
  1849. }
  1850. if (args.contains ("--videotrackshot") && args.indexOf ("--videotrackshot") + 2 < args.size())
  1851. {
  1852. // LYNX.exe --videotrackshot prefix video [video2]: round 174d — the Playlist with video tracks (filmstrips,
  1853. // timecode row) and the video window at a few song positions, as PNGs + report.txt (the decoder, the
  1854. // frame shown for each wanted time: frame accuracy, frames dropped)
  1855. const auto i = args.indexOf ("--videotrackshot");
  1856. runVideoTrackShot (args[i + 1].unquoted(), args[i + 2].unquoted(), i + 3 < args.size() ? args[i + 3].unquoted() : juce::String());
  1857. return;
  1858. }
  1859. if (args.contains ("--vfxshot"))
  1860. {
  1861. // LYNX.exe --vfxshot prefix: the VFX note effects' editors (round 164b), on channels and in a Patcher, as PNGs
  1862. const auto i = args.indexOf ("--vfxshot");
  1863. runVfxShot (args[i + 1].unquoted());
  1864. quit();
  1865. return;
  1866. }
  1867. if (args.contains ("--patchershot"))
  1868. {
  1869. // LYNX.exe --patchershot prefix [project]: every Patcher's editor (round 141) as PNGs (a demo one without a project)
  1870. const auto i = args.indexOf ("--patchershot");
  1871. runPatcherShot (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String());
  1872. quit();
  1873. return;
  1874. }
  1875. if (args.contains ("--audioxshot"))
  1876. {
  1877. // LYNX.exe --audioxshot prefix (round 190aq): the pre-fader send, the "Low latency while recording" mark on a
  1878. // bypassed slot and the Browser's "Preview in time", drawn off-screen
  1879. runAudioXShot (args[args.indexOf ("--audioxshot") + 1].unquoted());
  1880. quit();
  1881. return;
  1882. }
  1883. if (args.contains ("--comp177shot"))
  1884. {
  1885. // LYNX.exe --comp177shot prefix project (round 177c): a project of loop takes in the maximised
  1886. // Playlist as it opened; every group after "Comp these takes", with a swipe on the first; the track and record menus
  1887. const auto i = args.indexOf ("--comp177shot");
  1888. runComp177Shot (args[i + 1].unquoted(), args[i + 2].unquoted());
  1889. quit();
  1890. return;
  1891. }
  1892. if (args.contains ("--evpaneshot"))
  1893. {
  1894. // LYNX --evpaneshot prefix [project] (round 190fz): the Piano roll's event editor divider driven with the mouse
  1895. // handlers (drag, right-click = alternate size and back, middle-click = default, a drag into the snap zone),
  1896. // a picture of each state and prefix-report.txt with the heights and the remembered settings file
  1897. const auto i = args.indexOf ("--evpaneshot");
  1898. setApplicationReturnValue (runEvPaneShot (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String()) ? 0 : 1);
  1899. quit();
  1900. return;
  1901. }
  1902. if (args.contains ("--feat166shot"))
  1903. {
  1904. // LYNX.exe --feat166shot prefix [project]: round 166d (issue #14) — the Piano Roll with a scale, folded to
  1905. // it, with one ghost channel, the ghost channels menu, and the Mixer filled to 500 inserts (its start and
  1906. // its end, and the time a full repaint takes)
  1907. const auto i = args.indexOf ("--feat166shot");
  1908. runFeat166Shot (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String());
  1909. quit();
  1910. return;
  1911. }
  1912. if (args.contains ("--trackmodeshot"))
  1913. {
  1914. // LYNX --trackmodeshot prefix: rollup 190cv (UI gate of PR #151) — Playlist track header › Track mode › Audio
  1915. // track, off-screen, in three states of FL's live check 190cu (q1-01 fresh, q1-02 one insert linked
  1916. // elsewhere and one renamed, q1-07 the full state), plus a report that compares each list with FL's
  1917. setApplicationReturnValue (runTrackModeShot (args[args.indexOf ("--trackmodeshot") + 1].unquoted()) ? 0 : 1);
  1918. quit();
  1919. return;
  1920. }
  1921. if (args.contains ("--curveshot"))
  1922. {
  1923. // LYNX.exe --curveshot prefix: round 190bw — an automation clip with one segment per FL curve mode in the
  1924. // point editor and in the Playlist, and FL's point menu, off-screen
  1925. runCurveShot (args[args.indexOf ("--curveshot") + 1].unquoted());
  1926. quit();
  1927. return;
  1928. }
  1929. if (args.contains ("--remoteshot"))
  1930. {
  1931. // LYNX.exe --remoteshot prefix: Online Sessions P5-A1 (round 190ai) — the host's "Share plugins with guests"
  1932. // list and a guest's parameter editor of a plugin the host plays, off-screen with sample data
  1933. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1934. lynx::liveui::saveRemoteShots (args[args.indexOf ("--remoteshot") + 1].unquoted());
  1935. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  1936. quit();
  1937. return;
  1938. }
  1939. if (args.contains ("--settingsshot") && ! args.contains ("--rtstress")) // (--rtstress has its own --settingsshot file.png option, round 161)
  1940. {
  1941. // LYNX.exe --settingsshot prefix: round 190bx — every Settings page off-screen at the window's size, in a
  1942. // small window (390 x 390) and, for the long pages, whole (see runSettingsShot)
  1943. runSettingsShot (args[args.indexOf ("--settingsshot") + 1].unquoted());
  1944. quit();
  1945. return;
  1946. }
  1947. if (args.contains ("--perfshot"))
  1948. {
  1949. // LYNX.exe --perfshot prefix project: the Playlist in Performance mode with a few clips launched and waiting,
  1950. // then the project patcherized (every insert's effects, the first channels) saved as prefix-patcherized.lynx
  1951. // for --patchershot (round 165m)
  1952. const auto i = args.indexOf ("--perfshot");
  1953. runPerfShot (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String());
  1954. quit();
  1955. return;
  1956. }
  1957. if (args.contains ("--freezetest"))
  1958. {
  1959. // LYNX.exe --freezetest prefix [project]: round 190ay's Freeze end to end, off-screen (see runFreezeTest)
  1960. const auto i = args.indexOf ("--freezetest");
  1961. const auto project = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  1962. // a word after the project: "keep" = freeze, save prefix-frozen.lynx and stop (the audio stays);
  1963. // "measure" = only load and render the project, for the memory and time of a process of its own
  1964. const auto mode = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  1965. setApplicationReturnValue (runFreezeTest (args[i + 1].unquoted(), project, mode) ? 0 : 1);
  1966. quit();
  1967. return;
  1968. }
  1969. if (args.contains ("--trackfreezetest"))
  1970. {
  1971. // LYNX --trackfreezetest prefix: round 190ff's Freeze Track, Flatten / Bounce Track in Place, Bounce to New
  1972. // Track and Consolidate end to end in the Clip-launch workflow, off-screen (see runTrackFreezeTest)
  1973. const auto i = args.indexOf ("--trackfreezetest");
  1974. setApplicationReturnValue (runTrackFreezeTest (args[i + 1].unquoted()) ? 0 : 1);
  1975. quit();
  1976. return;
  1977. }
  1978. if (args.contains ("--paintbench"))
  1979. {
  1980. // LYNX --paintbench project.(flp|lynx|als) report.txt (round 190ge): each main view drawn off screen, whole, many
  1981. // times (the message thread's CPU per frame), with the playhead mid-song; no window, no audio device
  1982. const auto i = args.indexOf ("--paintbench");
  1983. runPaintBench (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()));
  1984. quit();
  1985. return;
  1986. }
  1987. if (args.contains ("--gridshot"))
  1988. {
  1989. // LYNX.exe --gridshot prefix [project]: the Clip-launch workflow's layout off-screen, with a grid of sample
  1990. // clips, some playing and waiting, at the size of LYNX_SNAPSHOT_SIZE (round 181a); with a project (.lynx,
  1991. // .flp, .als), that project's grid instead (round 181c: a Live set's Session view as LYNX imports it)
  1992. const auto i = args.indexOf ("--gridshot");
  1993. const auto project = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  1994. runGridShot (args[i + 1].unquoted(), project);
  1995. quit();
  1996. return;
  1997. }
  1998. if (args.contains ("--tour190dvshot"))
  1999. {
  2000. // LYNX.exe --tour190dvshot prefix: round 190dv off-screen — the Simple workflow's Welcome screen, every step of
  2001. // the first-song tour done with its "Do it for me" (a loop dropped for the loop step), the end card, Back /
  2002. // Next / close, the Help menu, the chooser's tour button, Start from with the three demo songs, a demo
  2003. // opened in Simple — and a text report of the checks (incl. resources/demos/*.lynx = the generated songs)
  2004. const auto i = args.indexOf ("--tour190dvshot");
  2005. runTour190dvShot (args[i + 1].unquoted());
  2006. quit();
  2007. return;
  2008. }
  2009. if (args.contains ("--donateshot"))
  2010. {
  2011. // LYNX --donateshot prefix: round 190fq off-screen (no window) — Help › Support LYNX SHARE... in the three
  2012. // layouts, the Support window, the About window's Support button, the start-up support note in the main
  2013. // window, and the note's rules end to end on its saved state (run it with LYNX_PROFILE_DIR: it writes
  2014. // support-note.txt there, and puts the old one back at the end); report prefix-report.txt, exit 0 = OK
  2015. const auto i = args.indexOf ("--donateshot");
  2016. setApplicationReturnValue (runDonateShot (args[i + 1].unquoted()) ? 0 : 1);
  2017. quit();
  2018. return;
  2019. }
  2020. if (args.contains ("--simpleclosetest"))
  2021. {
  2022. // LYNX --simpleclosetest <report.txt>: round 190fc off-screen (no window) — the main window in the Simple
  2023. // layout with Welcome, the tour, Start from, a demo, the dock's tabs, Finish and Lyrics open, then closed as at
  2024. // shutdown (the 0.1.27 RC crashed on every such close); exit code 0 = OK
  2025. const auto i = args.indexOf ("--simpleclosetest");
  2026. setApplicationReturnValue (runSimpleCloseTest (args[i + 1].unquoted()) ? 0 : 1);
  2027. quit();
  2028. return;
  2029. }
  2030. if (args.contains ("--patterns190ea"))
  2031. {
  2032. // LYNX --patterns190ea <report.txt>: round 190ea off-screen (no window) — a song with no pattern at all
  2033. // reaching the engine in every layout (the Simple dock's Editor tab, the Piano roll panel of the Pattern
  2034. // layout, the Clip-launch layout), the last pattern deleted, all patterns cleared by an edit, undo / redo,
  2035. // a live session's remote song and an out-of-range current pattern; each must leave one pattern and not crash
  2036. const auto i = args.indexOf ("--patterns190ea");
  2037. setApplicationReturnValue (runPatterns190ea (args[i + 1].unquoted()) ? 0 : 1);
  2038. quit();
  2039. return;
  2040. }
  2041. if (args.contains ("--reabl190foshot"))
  2042. {
  2043. // LYNX --reabl190foshot prefix: round 190fo off-screen — the Simple Sampler track's 16 pads in the dock, its
  2044. // menus and kits, the typing keys, the .lynx round trip, a folder of stems and MIDI files — and a report
  2045. const auto i = args.indexOf ("--reabl190foshot");
  2046. runReabl190foShot (args[i + 1].unquoted());
  2047. quit();
  2048. return;
  2049. }
  2050. if (args.contains ("--simple190dsshot"))
  2051. {
  2052. // LYNX.exe --simple190dsshot prefix: round 190ds off-screen, at 1x and 2x — loops dropped in the Simple
  2053. // workflow following the project key (the dock's switch, the clip menu), the docked Piano roll in the Editor
  2054. // tab, the keyboard's modes Keys / Scale keys / Chord pad with the scale selector — and a text report
  2055. const auto i = args.indexOf ("--simple190dsshot");
  2056. runSimple190dsShot (args[i + 1].unquoted());
  2057. quit();
  2058. return;
  2059. }
  2060. if (args.contains ("--simple190dgshot"))
  2061. {
  2062. // LYNX.exe --simple190dgshot prefix: round 190dg's additions to the Simple dock off-screen, at 1x and 2x —
  2063. // the Effects tab with all eight one-knob cards and each card alone, a chain preset with Blend, the
  2064. // favourites in the Preset menu, the sound picker (a search, My plugins with a made-up plugin list) — and a
  2065. // text report of the checks
  2066. const auto i = args.indexOf ("--simple190dgshot");
  2067. runSimple190dgShot (args[i + 1].unquoted());
  2068. quit();
  2069. return;
  2070. }
  2071. if (args.contains ("--simplefxshot"))
  2072. {
  2073. // LYNX.exe --simplefxshot prefix: round 190bu's track dock of the Simple workflow off-screen, at 1x and 2x —
  2074. // the Instrument tab (LYNX sounds, My SoundFonts), the Effects tab (empty, a preset, its menus), and a text
  2075. // report: the dock's edits, a user preset saved and loaded, the same slots in the Pattern workflow's Mixer
  2076. const auto i = args.indexOf ("--simplefxshot");
  2077. runSimpleFxShot (args[i + 1].unquoted());
  2078. quit();
  2079. return;
  2080. }
  2081. if (args.contains ("--simpleshot"))
  2082. {
  2083. // LYNX.exe --simpleshot prefix: round 184a's Simple workflow off-screen — View › Layout style with each style
  2084. // chosen, Settings › General (Pattern, then Simple selected) with its style list, the window in Pattern, then
  2085. // Simple, then Pattern again, and how many Simple workflow objects existed before and after (0 before)
  2086. const auto i = args.indexOf ("--simpleshot");
  2087. runSimpleShot (args[i + 1].unquoted());
  2088. quit();
  2089. return;
  2090. }
  2091. // --versionsshot <prefix> (round 190ap): the Versions panel, File's new items, a project opened without its
  2092. // third-party plugins (window, list, File menu) and the Export window's additions, offscreen
  2093. if (args.contains ("--versionsshot"))
  2094. {
  2095. runVersionsShot (args[args.indexOf ("--versionsshot") + 1].unquoted());
  2096. quit();
  2097. return;
  2098. }
  2099. // --linkshot <prefix> (round 190bt): FL's Remote control settings / Global link settings windows, the control
  2100. // menu with "Link to controller...", the formula presets and controller menus and the Multilink items,
  2101. // offscreen; prefix-checks.txt holds the round's checks of the engine, the project file and the settings
  2102. if (args.contains ("--linkshot"))
  2103. {
  2104. setApplicationReturnValue (runLinkShot (args[args.indexOf ("--linkshot") + 1].unquoted()) ? 0 : 1);
  2105. quit();
  2106. return;
  2107. }
  2108. // --flctlshot <prefix> (round 190df): FL's multilink menu (on / off), the plugin menu's A/B and "Link all
  2109. // parameters...", the sampler's File row with its Sample history, and the Envelope / instrument page of a sampler
  2110. // running FL's voice with its envelope presets, offscreen; prefix-checks.txt holds the checks
  2111. if (args.contains ("--flctlshot"))
  2112. {
  2113. setApplicationReturnValue (runFlCtlShot (args[args.indexOf ("--flctlshot") + 1].unquoted()) ? 0 : 1);
  2114. quit();
  2115. return;
  2116. }
  2117. // --samplerpageshot <prefix> (round 190dh): FL's Sampler page offscreen (shots and checks in prefix-checks.txt)
  2118. if (args.contains ("--samplerpageshot"))
  2119. {
  2120. setApplicationReturnValue (runSamplerPageShot (args[args.indexOf ("--samplerpageshot") + 1].unquoted()) ? 0 : 1);
  2121. quit();
  2122. return;
  2123. }
  2124. // --flplshot <prefix> (round 190dx): the audio clip menu (Preview, Automate › Panning / Volume), the Playlist's "+"
  2125. // and its menu, Track mode › Instrument track, the Channel rack's "Assign to new instrument track", Tools › One-click
  2126. // audio recording and Mixer › Disk recording › Latency compensation, offscreen; prefix-checks.txt holds the checks
  2127. // --hdrshot190ft <prefix> (round 190ft, issues #163 / #164): FL's track-header selection and resize rules driven
  2128. // with synthetic mouse events on the Playlist headers and the mixer strips, offscreen; prefix-checks.txt
  2129. if (args.contains ("--hdrshot190ft"))
  2130. {
  2131. setApplicationReturnValue (runHdrShot190ft (args[args.indexOf ("--hdrshot190ft") + 1].unquoted()) ? 0 : 1);
  2132. quit();
  2133. return;
  2134. }
  2135. // --userfixshot190ib <prefix> (round 190ib): issue #182's type-to-jump in a real popup menu (the Playlist's Edit menu
  2136. // of the issue's screenshot, typed into), #183's Piano roll item, #181's Ctrl+, through the main window's keys;
  2137. // prefix-checks.txt
  2138. if (args.contains ("--userfixshot190ib"))
  2139. {
  2140. setApplicationReturnValue (runUserFixShot190ib (args[args.indexOf ("--userfixshot190ib") + 1].unquoted()) ? 0 : 1);
  2141. quit();
  2142. return;
  2143. }
  2144. // --trackautoshot190gz <prefix> (round 190gz, issue #170): LYNX's "Link Playlist tracks to mixer tracks" — the
  2145. // switch, the linked headers' M / S / volume / pan driven with synthetic mouse events, row sizes, undo and the
  2146. // .lynx round trip, offscreen; prefix-checks.txt
  2147. if (args.contains ("--trackautoshot190gz"))
  2148. {
  2149. setApplicationReturnValue (runTrackAutoShot190gz (args[args.indexOf ("--trackautoshot190gz") + 1].unquoted()) ? 0 : 1);
  2150. quit();
  2151. return;
  2152. }
  2153. if (args.contains ("--flplshot"))
  2154. {
  2155. setApplicationReturnValue (runFlPlShot (args[args.indexOf ("--flplshot") + 1].unquoted()) ? 0 : 1);
  2156. quit();
  2157. return;
  2158. }
  2159. // --genpresetshot <prefix> (round 190fs): the channel window's preset box with the user's own presets (Save
  2160. // preset..., Your presets, Delete preset, Show the presets folder) for Fruity DX10, 3x Osc and LYNX's synth, the
  2161. // name box, a load (one undo step) and the Browser's new channel, offscreen; prefix-checks.txt holds the checks
  2162. if (args.contains ("--genpresetshot"))
  2163. {
  2164. setApplicationReturnValue (runGenPresetShot (args[args.indexOf ("--genpresetshot") + 1].unquoted()) ? 0 : 1);
  2165. quit();
  2166. return;
  2167. }
  2168. // --flfixshot <prefix> (round 190ey): what the live FL session 190ew found different (the Sampler page, the
  2169. // Multilink menu, the Playlist, issue #152's question), offscreen; prefix-checks.txt holds the checks
  2170. if (args.contains ("--flfixshot"))
  2171. {
  2172. setApplicationReturnValue (runFlFixShot (args[args.indexOf ("--flfixshot") + 1].unquoted()) ? 0 : 1);
  2173. quit();
  2174. return;
  2175. }
  2176. // --flclipshot <prefix> (round 190dz): FL's audio clip menu layout (two columns, FL's sections, LYNX's own items at
  2177. // the end) and the channel's Misc › Levels adjustment, offscreen; prefix-checks.txt holds the checks
  2178. if (args.contains ("--flclipshot"))
  2179. {
  2180. setApplicationReturnValue (runFlClipShot (args[args.indexOf ("--flclipshot") + 1].unquoted()) ? 0 : 1);
  2181. quit();
  2182. return;
  2183. }
  2184. if (args.contains ("--warpshot"))
  2185. {
  2186. // LYNX.exe --warpshot prefix: round 190cg's pictures (warp commands in the audio editor, the Clip page's
  2187. // Audio panel, the arrangement with the loop switched off, a folded track, signature changes), off-screen
  2188. const auto i = args.indexOf ("--warpshot");
  2189. runWarpShot (args[i + 1].unquoted());
  2190. quit();
  2191. return;
  2192. }
  2193. // --bandlabshot <prefix> (round 190ch): Lyrics / Notes, Reference match, Start from and Clean voice, offscreen
  2194. if (args.contains ("--bandlabshot"))
  2195. {
  2196. runBandlabShot (args[args.indexOf ("--bandlabshot") + 1].unquoted());
  2197. quit();
  2198. return;
  2199. }
  2200. if (args.contains ("--detailshot"))
  2201. {
  2202. // LYNX.exe --detailshot prefix: the Clip-launch workflow's detail view off-screen (round 183a): a track's chain
  2203. // (instrument, effects, one off, one folded), its clip page, and Pattern workflow before / after, at
  2204. // LYNX_SNAPSHOT_SIZE. Writes prefix-counts.txt with what the chain shows.
  2205. const auto i = args.indexOf ("--detailshot");
  2206. runDetailShot (args[i + 1].unquoted());
  2207. quit();
  2208. return;
  2209. }
  2210. if (args.contains ("--liveshot190ce"))
  2211. {
  2212. // LYNX.exe --liveshot190ce prefix: round 190ce off-screen, in the Ableton-style layout: the Device View's cards
  2213. // with their hot-swap and save buttons, a device's menu, hot-swap on (the Browser's bar, the lit button), a
  2214. // swap and its undo, a duplicate, and the Browser's collections (STARRED tab, the Collections menu, a search
  2215. // by a collection's name). Writes prefix-checks.txt.
  2216. runLiveShot190ce (args[args.indexOf ("--liveshot190ce") + 1].unquoted());
  2217. quit();
  2218. return;
  2219. }
  2220. if (args.contains ("--missingsearchshot190eo"))
  2221. {
  2222. // LYNX --missingsearchshot190eo prefix folder...: round 190eo (integration of issue #159's fix) off-screen: the
  2223. // Missing files window's Samples page while a real search of the folders runs (matches streamed in, Stop
  2224. // shown, Apply usable). Writes prefix-searching.png and prefix-checks.txt; the search is let go at the end.
  2225. const auto i = args.indexOf ("--missingsearchshot190eo");
  2226. const auto prefix = args[i + 1].unquoted();
  2227. juce::StringArray folders;
  2228. for (int k = i + 2; k < args.size(); ++k)
  2229. folders.add (args[k].unquoted());
  2230. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  2231. std::shared_ptr<juce::Component> panel = lynx::makeMissingFilesPanelSearching (lynx::missingFilesSnapshotInfo(), folders);
  2232. juce::Timer::callAfterDelay (700, [this, panel, prefix] {
  2233. juce::String status;
  2234. bool stopShown = false, applyEnabled = false;
  2235. const auto searching = lynx::missingFilesSearchState (*panel, status, stopShown, applyEnabled);
  2236. auto image = lynx::shot::paint (*panel, lynx::theme::panel);
  2237. const auto file = juce::File (prefix + "-searching.png");
  2238. file.deleteFile();
  2239. if (auto out = file.createOutputStream())
  2240. juce::PNGImageFormat().writeImageToStream (image, *out);
  2241. juce::String checks;
  2242. auto check = [&checks] (const char* name, bool ok, const juce::String& detail) {
  2243. checks << name << "=" << (ok ? "OK" : "FAIL") << " " << detail << "\n";
  2244. };
  2245. check ("still_searching_at_the_shot", searching, {});
  2246. check ("status_shows_the_walk", status.contains (lynx::tr ("Searching {0}... {1} files looked at").upToFirstOccurrenceOf ("{0}", false, false)), status);
  2247. check ("stop_shown", stopShown, {});
  2248. check ("apply_usable_during_the_search", applyEnabled, {});
  2249. lynx::stopMissingFilesSearch (*panel);
  2250. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  2251. quit();
  2252. });
  2253. return;
  2254. }
  2255. // --grooveshot190fm <prefix> (round 190fm): a Playlist pattern clip's menu with its Groove items (the chooser, Commit,
  2256. // Extract) and the "Classic swing" folder, and a Groove Pool holding classic swing grooves, offscreen;
  2257. // prefix-checks.txt holds the checks (also the .lynx round trip of a Playlist clip's groove)
  2258. if (args.contains ("--grooveshot190fm"))
  2259. {
  2260. setApplicationReturnValue (runGrooveShot190fm (args[args.indexOf ("--grooveshot190fm") + 1].unquoted()) ? 0 : 1);
  2261. quit();
  2262. return;
  2263. }
  2264. if (args.contains ("--mtshot190fm"))
  2265. {
  2266. // LYNX --mtshot190fm prefix: round 190fm off-screen: the MIDI Tools panel's Generate tab with each generator
  2267. // (prefix-generate-rhythm.png … -euclidean.png), the five side by side as Live's picture shows them
  2268. // (prefix-generate-panels.png; Live's: ableton190o/shots/live-04-generate-panels.png), then each generator
  2269. // written into a one-bar pattern and undone again: prefix-checks.txt.
  2270. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  2271. runMtShot190fm (args[args.indexOf ("--mtshot190fm") + 1].unquoted());
  2272. quit();
  2273. return;
  2274. }
  2275. if (args.contains ("--drumshot190ec"))
  2276. {
  2277. // LYNX.exe --drumshot190ec prefix: round 190ec off-screen: a demo Drum Rack's pad view (default and scrolled), its
  2278. // chain list with I-O, sends and return chains, a new empty Drum Rack and the Piano roll's pad names. Writes
  2279. // prefix-checks.txt (hit tests: C1 bottom-left, overview scroll, a pad dragged onto another swaps them).
  2280. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  2281. lynx::drumshot::run (args[args.indexOf ("--drumshot190ec") + 1].unquoted());
  2282. quit();
  2283. return;
  2284. }
  2285. if (args.contains ("--linkshot190gl"))
  2286. {
  2287. // LYNX --linkshot190gl prefix (round 190gl): Ableton Link off-screen with a second Link peer in this process —
  2288. // the toolbar in FL's Pattern layout (hidden by default, then shown, off and on) and in the Clip-launch layout
  2289. // ("1 Link", the position display's progress bar, Play waiting), Settings › Ableton Link, the toggle's
  2290. // drop-down and the Options menu. Writes prefix-checks.txt.
  2291. runLinkShot190gl (args[args.indexOf ("--linkshot190gl") + 1].unquoted());
  2292. quit();
  2293. return;
  2294. }
  2295. if (args.contains ("--mapshot190ef"))
  2296. {
  2297. // LYNX.exe --mapshot190ef prefix: round 190ef's map modes off-screen, in the Clip-launch workflow: MIDI Map Mode
  2298. // (the overlay over the grid, the Session mixer, the Device View and the transport; the Mapping Browser with
  2299. // Min / Max), Key Map Mode, the row menu, the title bar's Draw / Key / MIDI switches, Ctrl+M / Ctrl+K and the
  2300. // Pattern layout keeping Ctrl+M. Writes prefix-checks.txt.
  2301. runMapShot190ef (args[args.indexOf ("--mapshot190ef") + 1].unquoted());
  2302. quit();
  2303. return;
  2304. }
  2305. if (args.contains ("--sceneshot190ef"))
  2306. {
  2307. // LYNX.exe --sceneshot190ef prefix: round 190ef's scene work off-screen, in the Clip-launch workflow: the scene
  2308. // column with its tempo / time signature fields, the scene menu, a scene field's menu, the column title's menu
  2309. // (Rename, colours), a duplicated scene and a captured scene. Writes prefix-checks.txt.
  2310. runSceneShot190ef (args[args.indexOf ("--sceneshot190ef") + 1].unquoted());
  2311. quit();
  2312. return;
  2313. }
  2314. if (args.contains ("--drawshot190ef"))
  2315. {
  2316. // LYNX.exe --drawshot190ef prefix: round 190ef off-screen, in the Clip-launch workflow: Draw Mode in an
  2317. // automation lane, steps at the grid width and an Alt (no grid) freehand stroke drawn through the Playlist's
  2318. // own mouse handlers, and the Options menu with "Draw Mode". Writes prefix-checks.txt.
  2319. runDrawShot190ef (args[args.indexOf ("--drawshot190ef") + 1].unquoted());
  2320. quit();
  2321. return;
  2322. }
  2323. if (args.contains ("--clipenvshot190gi"))
  2324. {
  2325. // LYNX.exe --clipenvshot190gi prefix: round 190gi off-screen: audio clip envelopes on the Playlist (volume and
  2326. // pan lanes, edited through the Playlist's own mouse handlers), the clip menu's LYNX extras (Clip envelope ›,
  2327. // Auto-warp, Quantize audio, run from the menu), warp flags added on the flag strip and moved with Alt + drag,
  2328. // and the Clip-launch Clip View's Envelopes tab (Clip › Gain, Mixer › Track Panning). Writes prefix-checks.txt.
  2329. runClipEnvShot190gi (args[args.indexOf ("--clipenvshot190gi") + 1].unquoted());
  2330. quit();
  2331. return;
  2332. }
  2333. if (args.contains ("--livefactsshot190gx"))
  2334. {
  2335. // LYNX.exe --livefactsshot190gx prefix: round 190gx off-screen: the Clip page's Audio panel in Live's 190gu
  2336. // layout (Beats: Preserve label + chooser, the loop-mode icon chooser beside the Transient Envelope box;
  2337. // Tones / Texture: Grain Size [+ Flux]; Complex [Pro]), the Envelopes tab with a Clip Gain staircase on Live's
  2338. // axis, choosers at the bottom left, and an unwarped clip without the Envelopes tab. Writes prefix-checks.txt.
  2339. runLiveFactsShot190gx (args[args.indexOf ("--livefactsshot190gx") + 1].unquoted());
  2340. quit();
  2341. return;
  2342. }
  2343. if (args.contains ("--warpshot190fm"))
  2344. {
  2345. // LYNX.exe --warpshot190fm prefix: round 190fm off-screen: the Clip page's Audio panel of a grid audio clip in
  2346. // Beats (Preserve, Transient Loop Mode, Envelope), Tones and Texture (Grain Size), Complex (none), and the clip
  2347. // made unique by a mode change while another clip shares its channel (O16). Writes prefix-checks.txt.
  2348. runWarpShot190fm (args[args.indexOf ("--warpshot190fm") + 1].unquoted());
  2349. quit();
  2350. return;
  2351. }
  2352. if (args.contains ("--liveshot190dr"))
  2353. {
  2354. // LYNX.exe --liveshot190dr prefix: round 190dr off-screen, in the Clip-launch workflow: the Session mixer
  2355. // under the clip grid (default sections, Track Options, Volume only, hidden, its View menu), the Clip page's
  2356. // Sample panel of an audio clip (Warp on / off, the Set buttons while it plays, the sample's title) and a
  2357. // device dragged from one track's Device View to another track. Writes prefix-checks.txt.
  2358. runLiveShot190dr (args[args.indexOf ("--liveshot190dr") + 1].unquoted());
  2359. quit();
  2360. return;
  2361. }
  2362. if (args.contains ("--typeaheadtest"))
  2363. {
  2364. // LYNX.exe --typeaheadtest out.txt: issue #64 — a real popup menu (headings, a submenu) driven by key presses
  2365. // through its window's peer, as the OS delivers them; writes what got the highlight and what was picked
  2366. const auto i = args.indexOf ("--typeaheadtest");
  2367. runTypeAheadTest (juce::File (args[i + 1].unquoted()));
  2368. return;
  2369. }
  2370. if (args.contains ("--choosertest"))
  2371. {
  2372. // LYNX --choosertest out.txt file: issue #72 — opens LYNX's file chooser as the UI does (makeFileChooser +
  2373. // launchChooser) and reports which dialog came up and what reached the callback. A built-in dialog is shot
  2374. // (out.txt.png), `file` typed into it and confirmed; a native one (zenity / kdialog) is left to answer.
  2375. const auto i = args.indexOf ("--choosertest");
  2376. runChooserTest (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()));
  2377. return;
  2378. }
  2379. if (args.contains ("--stabilityshot"))
  2380. {
  2381. // LYNX --stabilityshot <folder> (round 190gg): offscreen PNGs of the crash prompt, the plugin window's crash
  2382. // notice, the Plugin manager's "Separate process" column and the monitor's dropout line (no window opens)
  2383. const auto i = args.indexOf ("--stabilityshot");
  2384. runStabilityShot (args[i + 1].unquoted());
  2385. return;
  2386. }
  2387. if (args.contains ("--snapshot"))
  2388. {
  2389. const auto i = args.indexOf ("--snapshot");
  2390. runSnapshot (args[i + 1].unquoted(), args[i + 2].unquoted());
  2391. return;
  2392. }
  2393. if (args.contains ("--stemsplit"))
  2394. {
  2395. // LYNX.exe --stemsplit input.wav folder: the stem separation of the clip menu, without the window
  2396. const auto i = args.indexOf ("--stemsplit");
  2397. lynx::AudioEngine loader (false);
  2398. const auto error = lynx::extractStemsToFolder (loader, juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()));
  2399. juce::File (args[i + 2].unquoted()).getSiblingFile ("stemsplit.txt").replaceWithText (error.isEmpty() ? "result=OK\n" : "result=FAIL " + error + "\n");
  2400. setApplicationReturnValue (error.isEmpty() ? 0 : 1);
  2401. quit();
  2402. return;
  2403. }
  2404. if (args.contains ("--audio2midi"))
  2405. {
  2406. // LYNX.exe --audio2midi input.wav melody|harmony|drums notes.csv: the clip menu's Convert to MIDI, without the
  2407. // window (round a2m189b's measurements)
  2408. const auto i = args.indexOf ("--audio2midi");
  2409. const auto mode = args[i + 2] == "drums" ? lynx::a2m::Mode::drums : args[i + 2] == "harmony" ? lynx::a2m::Mode::harmony : lynx::a2m::Mode::melody;
  2410. lynx::AudioEngine loader (false);
  2411. const juce::File csv (args[i + 3].unquoted());
  2412. const auto error = lynx::convertFileToMidiCsv (loader, juce::File (args[i + 1].unquoted()), mode, csv);
  2413. csv.getSiblingFile ("audio2midi.txt").replaceWithText (error.isEmpty() ? "result=OK\n" : "result=FAIL " + error + "\n");
  2414. setApplicationReturnValue (error.isEmpty() ? 0 : 1);
  2415. quit();
  2416. return;
  2417. }
  2418. if (args.contains ("--stems") || args.contains ("--stemexport"))
  2419. {
  2420. // LYNX.exe --stems project.(flp|als|lynx) base.wav [--separate]: one WAV per insert that has sound (like
  2421. // "Export stems"), in one render of the song (round 190gj; --separate: one render per insert, as before).
  2422. // LYNX.exe --stemexport project base.ext options.txt [--separate]: what the Export window writes with these
  2423. // options (exportopts::toText lines: stems, sections, the full mix, formats...), the same code.
  2424. // Both write <base>.txt: the files with their peaks, the renders, the wall and CPU time.
  2425. const auto full = args.contains ("--stemexport");
  2426. const auto i = args.indexOf (full ? "--stemexport" : "--stems");
  2427. const auto separate = args.contains ("--separate");
  2428. juce::String error, report;
  2429. int written = 0;
  2430. {
  2431. lynx::AudioEngine loader (false);
  2432. const juce::File input (args[i + 1].unquoted()), base (args[i + 2].unquoted());
  2433. // an .flp or a Live set (.als) opens through the import, as File › Open does (round 182b)
  2434. auto ok = input.hasFileExtension ("flp;als") ? loader.importFlpFile (input, error) : false;
  2435. if (! input.hasFileExtension ("flp;als"))
  2436. if (auto song = lynx::ProjectFile::load (input, error))
  2437. {
  2438. loader.setSong (std::move (*song));
  2439. ok = true;
  2440. }
  2441. const auto& song = loader.getSong();
  2442. lynx::StemPlan plan;
  2443. if (full && ok)
  2444. plan = lynx::planStemExport (song, lynx::exportopts::fromText (juce::File (args[i + 3].unquoted()).loadFileAsString().toStdString()), base);
  2445. else if (ok)
  2446. {
  2447. // every insert a channel goes to, as "<base> - <insert>.wav", 24-bit, 6 s of tail at most
  2448. lynx::ExportSettings settings;
  2449. plan.sets.push_back ({ song, settings.toOptions() });
  2450. for (int t = 1; t < (int) song.mixer.size(); ++t)
  2451. if (std::any_of (song.channels.begin(), song.channels.end(), [t] (const lynx::ChannelDef& c) { return c.mixerTrack == t; }))
  2452. plan.items.push_back ({ juce::String (t), base.getSiblingFile (base.getFileNameWithoutExtension() + " - " + juce::String (t) + ".wav"), 0, t,
  2453. lynx::makeBounceSong (song, t), settings.toOptions() });
  2454. }
  2455. const auto wallStart = juce::Time::getMillisecondCounterHiRes();
  2456. const auto cpuStart = std::clock();
  2457. lynx::StemRunStats stats;
  2458. std::vector<juce::String> lines (plan.items.size());
  2459. auto previous = wallStart; // (one render per file: the time since the file before is its render's)
  2460. written = lynx::runStemExport (
  2461. plan, [] (std::function<void()> f) { f(); }, {}, {}, {},
  2462. [&] (std::size_t k, bool done, float peak) {
  2463. const auto now = juce::Time::getMillisecondCounterHiRes();
  2464. if (done)
  2465. lines[k] = plan.items[k].file.getFileName() + " peak=" + juce::String (peak) + " ms=" + juce::String (now - previous, 0) + "\n";
  2466. previous = now;
  2467. },
  2468. separate, full, &stats);
  2469. const auto wallMs = juce::Time::getMillisecondCounterHiRes() - wallStart;
  2470. const auto cpuMs = 1000.0 * (double) (std::clock() - cpuStart) / (double) CLOCKS_PER_SEC;
  2471. for (const auto& line : lines)
  2472. report << line;
  2473. report << "renders=" << (stats.passes + stats.alone) << " shared=" << stats.passes << " inshared=" << stats.inPass
  2474. << " alone=" << stats.alone << "\n";
  2475. for (const auto& why : stats.why)
  2476. report << "alone: " << why << "\n";
  2477. report << "wall_ms=" << juce::String (wallMs, 0) << " cpu_ms=" << juce::String (cpuMs, 0) << " make_ms=" << juce::String (stats.makeMs, 0)
  2478. << " render_ms=" << juce::String (stats.renderMs, 0) << "\n";
  2479. }
  2480. report << "stems=" << written << "\n";
  2481. juce::File (args[i + 2].unquoted() + ".txt").replaceWithText (report);
  2482. setApplicationReturnValue (written > 0 ? 0 : 1);
  2483. quit();
  2484. return;
  2485. }
  2486. // --export-als <in.lynx|.flp|.als> <folder> [--live11] [--reference] [--scan]: "<folder>/<name> Project/<name>.als" (round 175a)
  2487. if (args.contains ("--export-als"))
  2488. {
  2489. const auto i = args.indexOf ("--export-als");
  2490. runAlsExport (args[i + 1].unquoted(), args[i + 2].unquoted(), args.contains ("--live11"), args.contains ("--reference"));
  2491. return;
  2492. }
  2493. // --gamepadshot <prefix> (round 184a, S16): the game controller's hints overlay and the MIDI settings page with
  2494. // the option on, offscreen, plus the poller fed fake pad states ("<prefix>-gamepad.txt")
  2495. if (args.contains ("--gamepadshot"))
  2496. {
  2497. runGamepadShot (args[args.indexOf ("--gamepadshot") + 1].unquoted());
  2498. return;
  2499. }
  2500. // --export-bundle <in.lynx|.flp|.als> <folder> [--zip] [--no-mixdown] [--shot <prefix>] (round 184a, S9): File ›
  2501. // Export › "For other apps..." without the window; the report goes to "<folder>/export-bundle.txt"
  2502. if (args.contains ("--export-bundle"))
  2503. {
  2504. const auto i = args.indexOf ("--export-bundle");
  2505. runBundleExport (args[i + 1].unquoted(), args[i + 2].unquoted(), args.contains ("--zip"), ! args.contains ("--no-mixdown"),
  2506. args.contains ("--shot") ? args[args.indexOf ("--shot") + 1].unquoted() : juce::String());
  2507. return;
  2508. }
  2509. if (args.contains ("--export-flp"))
  2510. {
  2511. const auto i = args.indexOf ("--export-flp");
  2512. runFlExport (args[i + 1].unquoted(), args[i + 2].unquoted(), args.contains ("--substitute"));
  2513. return;
  2514. }
  2515. if (args.contains ("--export"))
  2516. {
  2517. const auto i = args.indexOf ("--export");
  2518. const auto insert = args.contains ("--insert") ? args[args.indexOf ("--insert") + 1].getIntValue() : 0;
  2519. runExport (args[i + 1].unquoted(), args[i + 2].unquoted(), args.contains ("--pattern"), insert);
  2520. return;
  2521. }
  2522. if (args.contains ("--render"))
  2523. {
  2524. const auto i = args.indexOf ("--render");
  2525. runRender (args[i + 1].unquoted(), args[i + 2].unquoted(), args[i + 3].getDoubleValue());
  2526. return;
  2527. }
  2528. // session breadcrumb: a fail-fast (no crash handler runs) still leaves the last steps behind (round 111)
  2529. uncleanLastStep = collectUncleanSessions();
  2530. sessionsFolder().createDirectory();
  2531. lynx::crashguard::beginSession (
  2532. sessionsFolder().getChildFile ("session-" + juce::String (lynx::crashguard::processId()) + ".txt").getFullPathName().toStdString(),
  2533. ("LYNX session\nversion=" + getApplicationVersion() + "\npid=" + juce::String (lynx::crashguard::processId())
  2534. + "\nstart=" + juce::String ((juce::int64) lynx::crashguard::processStartTime())
  2535. + "\nstarted=" + juce::Time::getCurrentTime().toISO8601 (true) + "\n").toStdString());
  2536. startHangWatch();
  2537. // LYNX_PROFILE_MAIN=<file> (round 174f): the message thread sampled every millisecond, 5-second windows
  2538. if (const auto profile = juce::SystemStats::getEnvironmentVariable ("LYNX_PROFILE_MAIN", {}); profile.isNotEmpty())
  2539. lynx::crashguard::startMainProfiler (profile.toStdString());
  2540. startupTrace.mark ("initialise (normal start)");
  2541. // (round 190hd, Windows) how long before the trace's 0 the process was made: the loader (the exe, its DLLs,
  2542. // relocations) and the static initialisers that ran before this file's
  2543. if (const auto created = lynx::crashguard::processStartTime(); created != 0)
  2544. {
  2545. const auto t0 = (std::uint64_t) std::chrono::duration_cast<std::chrono::microseconds> (startupTrace.t0System.time_since_epoch()).count() * 10u
  2546. + 116444736000000000ull; // (FILETIME: 100 ns since 1601)
  2547. if (t0 > created)
  2548. startupTrace.mark ((" (the process was made " + juce::String ((double) (t0 - created) / 10000.0, 1)
  2549. + " ms before this trace's 0: the loader, the DLLs, the first static initialisers)").toRawUTF8());
  2550. }
  2551. prepareGraphicsDevice();
  2552. if (startupTrace.on)
  2553. lynx::startupMark = startupMarkHook;
  2554. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  2555. lynx::themeui::loadSaved(); // the user's theme (Options › Theme, round 162d)
  2556. startupOptions = lynx::StartupOptions::load();
  2557. lynx::registerFileTypes();
  2558. startupTrace.mark ("options + file types");
  2559. // Double-clicking a .lynx/.flp opens LYNX with the file as an argument; a path typed in a terminal may be relative
  2560. // (D#92, round 180a: it was ignored, leaving the blank project with no message). A missing file gets "Could not open".
  2561. if (args.size() > 0 && lynx::safety::isFileArgument (args[0].unquoted().toStdString()))
  2562. fileToOpen = juce::File::getCurrentWorkingDirectory().getChildFile (args[0].unquoted());
  2563. // LYNX --no-plugins project.lynx (round 190ap): File › "Open without third-party plugins..." from the command
  2564. // line, for a project a plugin keeps from opening — no hosted plugin is created, each keeps its settings
  2565. if (const auto i = args.indexOf ("--no-plugins"); i >= 0)
  2566. {
  2567. if (i + 1 < args.size() && lynx::safety::isFileArgument (args[i + 1].unquoted().toStdString()))
  2568. fileToOpen = juce::File::getCurrentWorkingDirectory().getChildFile (args[i + 1].unquoted());
  2569. startWithoutPlugins = fileToOpen.hasFileExtension ("lynx");
  2570. }
  2571. // LYNX_TEST_MODE=1 LYNX --open-event-test <ms> <file>: the file arrives the way macOS's Finder delivers it (a Linux
  2572. // or Windows run can exercise that path): 0 ms = at once, before the window exists
  2573. if (lynx::platform::testMode() && args[0] == "--open-event-test" && args.size() > 2)
  2574. {
  2575. const auto file = args[2].unquoted().quoted();
  2576. if (args[1].getIntValue() == 0)
  2577. anotherInstanceStarted (file);
  2578. else
  2579. juce::Timer::callAfterDelay (args[1].getIntValue(), [this, file] { anotherInstanceStarted (file); });
  2580. }
  2581. // LYNX --opentime project.(flp|lynx)|- report.txt [idle seconds] (round 165i): the normal start-up (splash, audio
  2582. // device, window) opens the project, waits until it is loaded and LYNX has gone quiet, measures the idle CPU and
  2583. // memory, writes the times and quits normally (a benchmark that killed LYNX left "closed unexpectedly" behind)
  2584. if (args.contains ("--opentime"))
  2585. {
  2586. const auto i = args.indexOf ("--opentime");
  2587. const auto project = args[i + 1].unquoted();
  2588. fileToOpen = project != "-" && juce::File::isAbsolutePath (project) ? juce::File (project) : juce::File();
  2589. openTimeReport = juce::File (args[i + 2].unquoted());
  2590. if (args.size() > i + 3 && ! args[i + 3].startsWith ("--"))
  2591. openTimeIdleSeconds = juce::jlimit (1, 120, args[i + 3].getIntValue());
  2592. }
  2593. // round 190go: the ASIO device of the last session is made and opened from now on, while the splash and the
  2594. // window come up (see below)
  2595. lynx::AudioEngine::prewarmAudioDevice();
  2596. // round 190go: the built-in start-up sound is made while the splash and the window come up (pure maths)
  2597. if (startupOptions.sound && lynx::themeui::current().startupSound.empty())
  2598. startupSampleJob = std::async (std::launch::async, [] { return lynx::makeStartupSample(); });
  2599. // Round 190go (start-up faster than FL Studio): the main window is built first, with the engine ready but no
  2600. // audio device open; the device opens after it. An ASIO device of the last session was made and opened ahead,
  2601. // on a worker, while the window was built (AudioEngine::prewarmAudioDevice; the driver itself only ever runs on
  2602. // JUCE's ASIO thread, as COM wants). Play pressed before the device is open starts with it.
  2603. if (! startupOptions.splash)
  2604. {
  2605. startEngine();
  2606. createMainWindow();
  2607. mainWindow->reveal();
  2608. startupTrace.mark ("window revealed");
  2609. // the device (and the start-up sound) once the window's first frame is on screen
  2610. mainWindow->whenPainted ([this] {
  2611. openAudioDevice();
  2612. openMidiDevices();
  2613. startAfterWindow (false);
  2614. });
  2615. return;
  2616. }
  2617. // the splash first; the main window is built behind its card (still: the logo has not started to drop; building
  2618. // it during the drop would stop the animation, both run on the message thread), then the audio device opens
  2619. // (the start-up sound needs it), and the drop starts with its sound. The window shows the moment the logo has
  2620. // landed (round 190go, A4: before, the window was built only after the drop: the drop, then ~0.6 s of build).
  2621. // Round 190hd (Windows): the card draws on a thread of its own, so the main window is built DURING the drop
  2622. // (startOnItsOwnThread below).
  2623. splash = lynx::makeStartupSplash();
  2624. startupTrace.mark ("splash made");
  2625. splash->showOnDesktop();
  2626. startupTrace.mark ("splash on the desktop");
  2627. if (splash->drawsOnItsOwnThread())
  2628. {
  2629. startWithThreadedSplash();
  2630. return;
  2631. }
  2632. // the rest once the card's first frame is on the screen (round 190go: before, a fixed 40 ms), at the latest
  2633. // after 40 ms
  2634. const auto goOn = [this, started = std::make_shared<bool> (false)] {
  2635. if (std::exchange (*started, true) || splash == nullptr) // (once; or quit meanwhile)
  2636. return;
  2637. startEngine();
  2638. if (splash == nullptr) // quit meanwhile
  2639. return;
  2640. createMainWindow();
  2641. if (splash == nullptr || mainWindow == nullptr)
  2642. return;
  2643. if (startupOptions.sound)
  2644. openAudioDevice (false); // (else after the splash: nothing waits for it)
  2645. // one turn of the message loop before the drop: what fell due while the window was built (JUCE's timers,
  2646. // the window's own async work) runs now, on the still card, not in the drop's first frames
  2647. juce::MessageManager::callAsync ([this] { startDrop(); });
  2648. };
  2649. splash->onFirstFrame = goOn;
  2650. juce::Timer::callAfterDelay (40, goOn);
  2651. }
  2652. // Round 190hd (start-up faster than FL Studio, Windows): the card draws on a thread of its own (ui/Splash.cpp), so
  2653. // nothing the message thread does stops the drop. The card shows at once (no Direct2D device is made for it); the
  2654. // engine starts and the audio device opens behind the still card (an ASIO device of the last session was made and
  2655. // opened ahead on its own thread meanwhile), the drop starts with its sound, and the main window is built while
  2656. // the logo drops and shown as soon as it is built, behind the card (the drop and its sound go on above it); the card
  2657. // fades the moment the logo has landed. The card stays for the drop only (the JUCE card's
  2658. // 2.1 s from the process start was there to keep a fast start from flashing; the drop alone is 1.05 s).
  2659. void startWithThreadedSplash()
  2660. {
  2661. splash->onFirstFrame = [this] {
  2662. if (splash != nullptr && startupTrace.on)
  2663. startupTrace.mark ((" splash: first frame on the screen at "
  2664. + juce::String (std::chrono::duration<double, std::milli> (splash->getFirstFrameTime() - startupTrace.t0).count(), 1) + " ms (its own thread)")
  2665. .toRawUTF8());
  2666. };
  2667. juce::MessageManager::callAsync ([this] {
  2668. if (splash == nullptr) // (quit meanwhile)
  2669. return;
  2670. startEngine();
  2671. if (splash == nullptr)
  2672. return;
  2673. if (startupOptions.sound)
  2674. openAudioDevice (false); // (else after the splash: nothing waits for it)
  2675. startDrop();
  2676. // the main window while the logo drops (one more message, so the drop's start is not held by it)
  2677. juce::MessageManager::callAsync ([this] {
  2678. if (splash == nullptr || mainWindow != nullptr || engine == nullptr)
  2679. return;
  2680. createMainWindow();
  2681. // shown as soon as it is built, behind the card: the logo goes on dropping above it and the card fades at
  2682. // the landing as before (LYNX_REVEAL_AT_LANDING=1: the window shows at the landing, as in round 190go)
  2683. if (mainWindow != nullptr && splash != nullptr
  2684. && juce::SystemStats::getEnvironmentVariable ("LYNX_REVEAL_AT_LANDING", {}) != "1")
  2685. {
  2686. mainWindow->reveal();
  2687. windowRevealed = true;
  2688. startupTrace.mark ("window revealed (behind the card, while the logo drops)");
  2689. splash->raise();
  2690. }
  2691. });
  2692. });
  2693. }
  2694. // the logo's drop and the start-up sound together; the window shows the moment the logo has landed
  2695. void startDrop()
  2696. {
  2697. const auto ownThread = splash != nullptr && splash->drawsOnItsOwnThread(); // (the window is built during the drop)
  2698. if (splash == nullptr || (mainWindow == nullptr && ! ownThread) || engine == nullptr)
  2699. return;
  2700. if (startupOptions.sound)
  2701. playStartupSound();
  2702. splash->setStatus (lynx::tr ("Loading the workspace..."));
  2703. splash->startClock();
  2704. // the minimum counts from the process start (the window and the audio device took part of it already); a card
  2705. // on its own thread stays for the drop (round 190hd)
  2706. splashDuration = ownThread ? landingSeconds : lynx::SplashScreen::remainingDuration (startupTrace.seconds());
  2707. splash->setBarDuration (splashDuration);
  2708. splash->whenLanded (splashDuration, [this] {
  2709. if (splash == nullptr || mainWindow == nullptr)
  2710. return;
  2711. if (startupTrace.on)
  2712. startupTrace.mark (("splash: the drop in " + juce::String (splash->getDropFrames()) + " frames, longest gap "
  2713. + juce::String (splash->getLongestDropGapMs(), 1) + " ms"
  2714. + (splash->getLongestDropGapAt() >= 0.0 ? " (at " + juce::String (splash->getLongestDropGapAt(), 3) + " s of its clock; the frame before: "
  2715. + splash->getLongestDropGapDetail() + ")"
  2716. : juce::String()))
  2717. .toRawUTF8());
  2718. if (! std::exchange (windowRevealed, true))
  2719. {
  2720. mainWindow->reveal();
  2721. startupTrace.mark ("window revealed (after the splash)");
  2722. }
  2723. splash->raise();
  2724. const auto deviceOpen = ! engine->isAudioDeviceOpenPending();
  2725. splash->finish ([this, deviceOpen] {
  2726. splash = nullptr;
  2727. // without the start-up sound the device opens now, once the card has faded (the window is up)
  2728. if (! deviceOpen)
  2729. openAudioDevice();
  2730. openMidiDevices();
  2731. if (! deviceOpen)
  2732. startAfterWindow (true);
  2733. });
  2734. if (deviceOpen)
  2735. mainWindow->whenPainted ([this] { startAfterWindow (true); });
  2736. });
  2737. }
  2738. // what follows the window's first frame (the audio device is open): the notice of an unclean end, the start-up
  2739. // project, the probes and the update check; on a first run (with the splash) the setup wizard
  2740. void startAfterWindow (bool offerSetupWizard)
  2741. {
  2742. if (std::exchange (startedAfterWindow, true) || mainWindow == nullptr)
  2743. return;
  2744. // (round 190go) each step after the window is a timed line of the start-up trace
  2745. showUncleanNotice();
  2746. startupTrace.mark ("after the window: unclean-session notice");
  2747. openStartupFile();
  2748. startupTrace.mark ("startup file opened");
  2749. startOpenTimeProbe();
  2750. startUpdateCheck();
  2751. startSupportNote(); // (round 190fq)
  2752. startupTrace.mark ("after the window: probes, update check scheduled");
  2753. juce::MessageManager::callAsync ([] { startupTrace.mark ("first message loop turn"); });
  2754. markSettled(); // (round 190gd)
  2755. // first run: language, audio, plugin folders (FL Studio's included) and a background scan
  2756. if (! offerSetupWizard)
  2757. return;
  2758. if (! lynx::setupWizardDone() && lynx::platform::testMode())
  2759. lynx::platform::testModeLog ("setup wizard");
  2760. else if (! lynx::setupWizardDone())
  2761. {
  2762. mainWindow->showSetupWizard();
  2763. startupTrace.mark ("after the window: setup wizard shown");
  2764. }
  2765. }
  2766. // round 190fq: the start-up support note (ui/SupportLynx.h) counts this start and, from the 10th on, may show its
  2767. // card once at a quiet moment. Only here, on the normal start path (the command-line modes returned earlier); test
  2768. // mode and CI machines neither count nor show it.
  2769. void startSupportNote()
  2770. {
  2771. if (mainWindow == nullptr)
  2772. return;
  2773. const auto env = [] (const char* name) { return juce::SystemStats::getEnvironmentVariable (name, {}).toStdString(); };
  2774. const auto quiet = lynx::supportnote::quietEnvironment (lynx::platform::testMode(), env ("CI"), env ("GITHUB_ACTIONS"), env ("LYNX_NO_SUPPORT_NOTE"));
  2775. if (quiet && lynx::platform::testMode())
  2776. lynx::platform::testModeLog ("support note: not counted (test mode)");
  2777. mainWindow->getContent().startSupportNote (quiet);
  2778. }
  2779. // the start-up trace's last lines: what the first seconds after the window add (lazy work, caches, the first paints)
  2780. static void markSettled()
  2781. {
  2782. if (! startupTrace.on)
  2783. return;
  2784. juce::Timer::callAfterDelay (5000, [] { startupTrace.mark ("5 s after the window"); startupTrace.write(); });
  2785. juce::Timer::callAfterDelay (15000, [] { startupTrace.mark ("15 s after the window"); startupTrace.write(); });
  2786. }
  2787. // Round 190hd (Windows): the Direct3D 11 + Direct2D device (~0.35 s: the graphics driver loads) is made once, on a
  2788. // worker, while the splash card, the engine and the audio device come up, and kept until LYNX closes: a 1 x 1
  2789. // Direct2D image holds JUCE's shared DirectX object (its devices), so the main window finds them made and nothing
  2790. // makes them again (before, every holder going away -- the splash's logo, a temporary one -- could mean a new device
  2791. // at its next use). Other systems: nothing to do.
  2792. void prepareGraphicsDevice()
  2793. {
  2794. #if JUCE_WINDOWS
  2795. if (juce::SystemStats::getEnvironmentVariable ("LYNX_GPU_PREWARM", {}) == "0")
  2796. return;
  2797. graphicsDeviceJob = std::async (std::launch::async, [] {
  2798. const auto from = std::chrono::steady_clock::now();
  2799. juce::Image holder (juce::Image::ARGB, 1, 1, false); // (NativeImageType: Direct2D, the shared device)
  2800. return std::make_pair (holder, std::chrono::duration<double, std::milli> (std::chrono::steady_clock::now() - from).count());
  2801. });
  2802. #endif
  2803. }
  2804. void markGraphicsDevice()
  2805. {
  2806. if (! graphicsDeviceJob.valid() || ! startupTrace.on || std::exchange (graphicsDeviceMarked, true))
  2807. return;
  2808. const auto ready = graphicsDeviceJob.wait_for (std::chrono::seconds (0)) == std::future_status::ready;
  2809. startupTrace.mark (ready ? (" graphics device made on a worker in " + juce::String (graphicsDeviceJob.get().second, 1) + " ms").toRawUTF8()
  2810. : " graphics device: still being made on its worker");
  2811. }
  2812. void startEngine()
  2813. {
  2814. startupTrace.mark ("before the audio engine");
  2815. lynx::BrowserComponent::allowIndexerProcess = true; // (round 190hd: the normal window only)
  2816. // (round 190go) ready to play, no device open yet: see openAudioDevice
  2817. engine = std::make_unique<lynx::AudioEngine> (true, -1, true, true);
  2818. lynx::videoview::install (*engine); // (Fruity Video Player channels: their sound tracks)
  2819. startupTrace.mark ("audio engine (no device yet)");
  2820. crashEngine = engine.get();
  2821. lynx::crashreporter::watchAudioDevice (engine->getDeviceManager()); // (the session file names the device: crash reports)
  2822. // a project given on the command line: its slow plugin modules (a Waves shell) start now, on their own
  2823. // thread, while the splash and the main window come up (round 121)
  2824. if (fileToOpen.hasFileExtension ("flp"))
  2825. if (juce::MemoryBlock data; fileToOpen.loadFileAsData (data))
  2826. try
  2827. {
  2828. engine->getPluginHost().startModulesFor (lynx::flpForeignPlugins (flp::parseProject ({ static_cast<const std::uint8_t*> (data.getData()), data.getSize() })));
  2829. startupTrace.mark ("plugin modules started ahead");
  2830. }
  2831. catch (const flp::Error&)
  2832. {
  2833. }
  2834. }
  2835. // The audio device of the last session, then (withSound) the start-up sound on it (once; message thread)
  2836. void openAudioDevice (bool withSound = true)
  2837. {
  2838. if (engine == nullptr || ! engine->isAudioDeviceOpenPending())
  2839. return;
  2840. engine->openAudioDevice();
  2841. if (const auto prewarmed = lynx::asioPrewarmReport(); prewarmed.isNotEmpty() && startupTrace.on)
  2842. startupTrace.mark ((" " + prewarmed).toRawUTF8());
  2843. startupTrace.mark ("audio device opened");
  2844. addDriverFileDeviceType();
  2845. if (withSound)
  2846. playStartupSound();
  2847. }
  2848. void playStartupSound()
  2849. {
  2850. if (startupOptions.sound && ! std::exchange (startupSoundPlayed, true) && engine != nullptr)
  2851. {
  2852. // Options › Theme › Startup sound (issue #12): the user's file, else (or when it can't be read) LYNX's own
  2853. std::shared_ptr<const lynx::SampleData> sound;
  2854. if (const auto& own = lynx::themeui::current().startupSound; ! own.empty() && juce::File (juce::String::fromUTF8 (own.c_str())).existsAsFile())
  2855. sound = engine->getSampleLibrary().load (juce::String::fromUTF8 (own.c_str()));
  2856. if (sound == nullptr && startupSampleJob.valid())
  2857. sound = startupSampleJob.get();
  2858. engine->previewSample (sound != nullptr ? sound : lynx::makeStartupSample());
  2859. }
  2860. startupTrace.mark ("startup sound");
  2861. }
  2862. void openMidiDevices()
  2863. {
  2864. if (engine != nullptr)
  2865. engine->openMidiDevices(); // (its own line in the start-up trace: "engine: MIDI inputs")
  2866. }
  2867. void createMainWindow()
  2868. {
  2869. mainWindow = std::make_unique<MainWindow> ("LYNX SHARE", *engine); // the brand; getApplicationName() stays "LYNX" (an id: instance lock, X11 WM_CLASS, ALSA client)
  2870. lynx::setMainWindowForOwnership (mainWindow.get());
  2871. lynx::applyRenderingChoice (*mainWindow); // (GPU rendering off: GDI; round 157a)
  2872. lynx::startRenderingWatch();
  2873. startupTrace.mark ("main window built");
  2874. lynx::remoteui::install ([this] (bool enabled) {
  2875. remoteControl = nullptr;
  2876. if (enabled)
  2877. remoteControl = lynx::RemoteControl::create (*engine, true, [this] {
  2878. const auto title = mainWindow != nullptr ? mainWindow->getName() : juce::String ("Untitled");
  2879. const auto separator = title.indexOf (" - ");
  2880. return separator >= 0 ? title.substring (separator + 3) : title;
  2881. }, [this] {
  2882. const auto file = mainWindow != nullptr ? mainWindow->getContent().getCurrentProjectFile() : juce::File();
  2883. return file == juce::File() ? juce::String() : file.getFullPathName();
  2884. });
  2885. lynx::remoteui::setRuntimeStatus (remoteControl != nullptr && remoteControl->active());
  2886. });
  2887. markGraphicsDevice();
  2888. }
  2889. // the previous run ended without closing (see collectUncleanSessions): say so once, with its last step — and, as
  2890. // Settings › General › "Crash reports" says (round 159), ask whether to send a report, send it unasked, or not
  2891. void showUncleanNotice()
  2892. {
  2893. if (lynx::platform::testMode()) // LYNX_TEST_MODE: no prompt, no report sent (written to test-mode.log)
  2894. {
  2895. if (uncleanLastStep.isNotEmpty())
  2896. lynx::platform::testModeLog ("\"closed unexpectedly\" notice (last step: " + uncleanLastStep + ")");
  2897. return;
  2898. }
  2899. if (uncleanLastStep.isEmpty())
  2900. {
  2901. lynx::crashreporter::retryPending(); // (reports an earlier run could not send: once more)
  2902. return;
  2903. }
  2904. auto message = lynx::tr ("The last session ended without closing normally. Last step: {0}. Backup copies of your project are in "
  2905. "LYNX SHARE's autosave folder; details in crash-history.log.",
  2906. { uncleanLastStep });
  2907. uncleanLastStep.clear();
  2908. const auto cause = uncleanCause();
  2909. // round 157a: a plugin's editor was opening — it crashed (often in the graphics driver, inside the plugin's own
  2910. // OpenGL window): offer to keep that plugin in its own process, where a crash takes only the plugin down
  2911. juce::String separatePlugin;
  2912. if (cause.editorPlugin.isNotEmpty() && ! lynx::pluginSandboxEnabled() && ! lynx::pluginAlwaysSeparate (cause.editorPlugin))
  2913. separatePlugin = cause.editorPlugin;
  2914. // LYNX's own drawing crashed in the graphics driver (Direct2D / Direct3D): draw with the CPU from now on
  2915. else if (cause.gpuDriver && lynx::gpuRenderingEnabled())
  2916. {
  2917. lynx::setGpuRenderingEnabled (false);
  2918. message << "\n\n"
  2919. << lynx::tr ("The crash was in the graphics driver ({0}). LYNX SHARE now draws its windows without the GPU; you can turn GPU "
  2920. "rendering back on in Options > General settings (after a driver update, for example).",
  2921. { cause.driverModule });
  2922. }
  2923. // round 165e: the Visualizer's GPU view was drawing when the session ended (a driver crash, a hang, the machine
  2924. // going down): the Visualizer draws with the 2D renderer from now on (its GPU button turns it back on)
  2925. for (int i = uncleanSteps.size(); --i >= 0;)
  2926. {
  2927. if (uncleanSteps[i].contains (lynx::visualgl::stopNote))
  2928. break;
  2929. if (uncleanSteps[i].contains (lynx::visualgl::startNote))
  2930. {
  2931. if (lynx::visualgl::enabled())
  2932. {
  2933. lynx::visualgl::setEnabled (false);
  2934. message << "\n\n"
  2935. << lynx::tr ("The Visualizer was drawing with the GPU (OpenGL) when it happened. It now draws without the GPU; its GPU "
  2936. "button turns it back on.");
  2937. }
  2938. break;
  2939. }
  2940. }
  2941. const auto session = lynx::crashreporter::parseSession (uncleanSessionText);
  2942. auto* devices = engine != nullptr ? &engine->getDeviceManager() : nullptr;
  2943. const auto action = lynx::crashreport::actionFor (lynx::crashreporter::consent());
  2944. lynx::crashreporter::retryPending();
  2945. if (action == lynx::crashreport::Action::askUser)
  2946. {
  2947. if (separatePlugin.isNotEmpty())
  2948. message << "\n\n"
  2949. << lynx::tr ("It happened while the window of {0} was opening{1}.",
  2950. { separatePlugin, cause.gpuDriver ? lynx::tr (" (in the graphics driver, {0})", { cause.driverModule }) : juce::String() });
  2951. lynx::crashreporter::showStartupDialog (session, message, separatePlugin, [separatePlugin] { lynx::setPluginAlwaysSeparate (separatePlugin, true); },
  2952. devices);
  2953. return;
  2954. }
  2955. if (action == lynx::crashreport::Action::sendSilently)
  2956. {
  2957. const auto input = lynx::crashreporter::makeInput (session, session.kind(), devices);
  2958. lynx::crashreporter::send (lynx::crashreporter::buildJson (input, false), juce::String::fromUTF8 (input.id.c_str()));
  2959. message << "\n\n" << lynx::tr ("A crash report is being sent to help fix it (Options > General settings > Crash reports).");
  2960. }
  2961. if (separatePlugin.isNotEmpty())
  2962. {
  2963. juce::AlertWindow::showOkCancelBox (
  2964. juce::MessageBoxIconType::WarningIcon, lynx::tr ("LYNX SHARE closed unexpectedly"),
  2965. message + "\n\n"
  2966. + lynx::tr ("It happened while the window of {0} was opening{1}. Run {0} in a separate process from now on? If it "
  2967. "crashes again, only the plugin stops and LYNX SHARE keeps running (Plugin wrapper menu: \"Always run in a "
  2968. "separate process\").",
  2969. { separatePlugin, cause.gpuDriver ? lynx::tr (" (in the graphics driver, {0})", { cause.driverModule }) : juce::String() }),
  2970. lynx::tr ("Run separately"), lynx::tr ("No"), nullptr,
  2971. juce::ModalCallbackFunction::create ([separatePlugin] (int result) {
  2972. if (result != 0)
  2973. lynx::setPluginAlwaysSeparate (separatePlugin, true);
  2974. }));
  2975. return;
  2976. }
  2977. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, lynx::tr ("LYNX SHARE closed unexpectedly"), message);
  2978. }
  2979. // --opentime: after the start-up file was handed to the window
  2980. void startOpenTimeProbe()
  2981. {
  2982. if (openTimeReport == juce::File())
  2983. return;
  2984. struct Probe final : juce::Timer
  2985. {
  2986. LynxApplication& app;
  2987. juce::File report, project;
  2988. int idleSeconds;
  2989. int phase = 0; // 0 loading, 1 settling, 2 idle measurement
  2990. double revealedS = 0.0, loadedS = -1.0, settledS = -1.0, cpuAtLoaded = 0.0;
  2991. double lastCpu = 0.0, lastT = 0.0, quietSince = -1.0, idleCpu0 = 0.0, idleT0 = 0.0;
  2992. Probe (LynxApplication& a, juce::File r, juce::File p, int idle)
  2993. : app (a), report (std::move (r)), project (std::move (p)), idleSeconds (idle)
  2994. {
  2995. revealedS = startupTrace.seconds();
  2996. startTimer (250);
  2997. }
  2998. bool loaded() const
  2999. {
  3000. if (project == juce::File())
  3001. return true;
  3002. return app.mainWindow != nullptr
  3003. && app.mainWindow->getName().containsIgnoreCase (project.getFileNameWithoutExtension());
  3004. }
  3005. void finish (const juce::String& result)
  3006. {
  3007. stopTimer();
  3008. const auto now = startupTrace.seconds();
  3009. const auto cpu = lynx::processCpuSeconds();
  3010. juce::String text;
  3011. text << "project=" << (project == juce::File() ? juce::String ("-") : project.getFullPathName()) << "\n"
  3012. << "window_s=" << juce::String (revealedS, 3) << "\n"
  3013. << "loaded_s=" << juce::String (loadedS, 3) << "\n"
  3014. << "settled_s=" << juce::String (settledS, 3) << "\n"
  3015. << "cpu_at_loaded_s=" << juce::String (cpuAtLoaded, 3) << "\n"
  3016. << "idle_s=" << juce::String (now - idleT0, 2) << "\n"
  3017. << "idle_cpu_pct=" << juce::String (phase == 2 && now > idleT0 ? 100.0 * (cpu - idleCpu0) / (now - idleT0) : -1.0, 1) << "\n"
  3018. << "working_set_mb=" << juce::String ((double) lynx::toolbar::PerformanceMeter::processMemoryBytes() / 1048576.0, 0) << "\n"
  3019. << "cpu_total_s=" << juce::String (cpu, 3) << "\n"
  3020. << "result=" << result << "\n";
  3021. report.replaceWithText (text);
  3022. app.setApplicationReturnValue (result == "OK" ? 0 : 1);
  3023. app.quit();
  3024. }
  3025. void timerCallback() override
  3026. {
  3027. const auto now = startupTrace.seconds();
  3028. const auto cpu = lynx::processCpuSeconds();
  3029. if (phase == 0)
  3030. {
  3031. if (loaded())
  3032. {
  3033. loadedS = now;
  3034. cpuAtLoaded = cpu;
  3035. phase = 1;
  3036. lastCpu = cpu;
  3037. lastT = now;
  3038. }
  3039. else if (now - revealedS > 240.0)
  3040. finish ("TIMEOUT loading");
  3041. return;
  3042. }
  3043. if (phase == 1)
  3044. {
  3045. // quiet = under 10 % of one core for 1.5 s (the harness's rule), at most 30 s after loading
  3046. const auto use = now > lastT ? 100.0 * (cpu - lastCpu) / (now - lastT) : 0.0;
  3047. lastCpu = cpu;
  3048. lastT = now;
  3049. if (use < 10.0)
  3050. {
  3051. if (quietSince < 0.0)
  3052. quietSince = now - 0.25;
  3053. if (now - quietSince >= 1.5)
  3054. settledS = quietSince;
  3055. }
  3056. else
  3057. quietSince = -1.0;
  3058. if (settledS >= 0.0 || now - loadedS > 30.0)
  3059. {
  3060. phase = 2;
  3061. idleCpu0 = cpu;
  3062. idleT0 = now;
  3063. }
  3064. return;
  3065. }
  3066. if (now - idleT0 >= (double) idleSeconds)
  3067. finish ("OK");
  3068. }
  3069. };
  3070. perf = std::make_unique<Probe> (*this, openTimeReport, fileToOpen, openTimeIdleSeconds);
  3071. }
  3072. // round 166b: the update check of a normal start (never in --opentime and the other command-line modes), a few
  3073. // seconds after the window is up so it never competes with the start-up; and the result of an update just installed
  3074. void startUpdateCheck()
  3075. {
  3076. if (openTimeReport != juce::File())
  3077. return;
  3078. lynx::updater::afterStart();
  3079. juce::Timer::callAfterDelay (3000, [] { lynx::updater::startAutomaticCheck(); });
  3080. }
  3081. void openStartupFile()
  3082. {
  3083. startupFileHandled = true;
  3084. if (fileToOpen != juce::File() && mainWindow != nullptr)
  3085. {
  3086. if (std::exchange (startWithoutPlugins, false)) // --no-plugins (round 190ap)
  3087. mainWindow->getContent().openNextWithoutPlugins (true);
  3088. mainWindow->openFile (fileToOpen);
  3089. mainWindow->getContent().openNextWithoutPlugins (false); // (a file that did not open leaves nothing behind)
  3090. }
  3091. else if (mainWindow != nullptr && openTimeReport == juce::File())
  3092. mainWindow->getContent().openStartupProject(); // issue #123 (FL's Startup project)
  3093. }
  3094. void shutdown() override
  3095. {
  3096. parityShow.reset(); // (LYNX_PARITYSHOT_SHOW's window, before the engine it shows)
  3097. if (relaunched || updateHelper)
  3098. return; // the copy that ran owns the session (its crash notes stay for the next start)
  3099. lynx::crashguard::note ("closing");
  3100. lynx::shutdownPluginSandboxWorker();
  3101. splash = nullptr;
  3102. lynx::shutdownStemExtraction(); // (a separation in flight stops before its window and the engine go)
  3103. lynx::shutdownAudioToMidi(); // (the same for a conversion to MIDI)
  3104. if (mainWindow != nullptr && mainWindow->isVisible())
  3105. mainWindow->saveState();
  3106. lynx::remoteui::shutdown();
  3107. remoteControl = nullptr; // cancels queued control work before its engine and UI go
  3108. mainWindow = nullptr; // the UI goes before the engine
  3109. graphicsDeviceJob = {}; // (round 190hd: the graphics device's holder, after every window)
  3110. lynx::updater::shutdown(); // (a check or download in flight stops)
  3111. crashEngine = nullptr;
  3112. engine = nullptr;
  3113. // separate-process plugins end on threads of their own (issue #159): a moment for them, never the 10 s a dead
  3114. // child's pipe can take
  3115. lynx::finishSandboxTeardowns (2000);
  3116. // CLAP plugins whose instance another thread deleted while this one was busy: deactivated and destroyed now
  3117. lynx::ClapPluginFormat::finishPendingTeardowns();
  3118. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  3119. heartbeat.stopTimer();
  3120. lynx::crashreporter::shutdown(); // (an upload in flight gets a moment, never long)
  3121. lynx::crashguard::stopHangWatch();
  3122. lynx::crashguard::stopMainProfiler();
  3123. lynx::crashguard::endSession(); // a clean exit: no breadcrumb left behind
  3124. // everything is saved and closed: a process that loaded third-party plugins ends here, before the DLLs' own
  3125. // teardown runs (some crash in it at exit, round 111)
  3126. if (sandboxChild || lynx::PluginHost::pluginsWereLoaded())
  3127. lynx::crashguard::exitNow (getApplicationReturnValue());
  3128. }
  3129. void systemRequestedQuit() override
  3130. {
  3131. if (mainWindow != nullptr)
  3132. mainWindow->confirmDiscard ([] { juce::JUCEApplication::quit(); });
  3133. else
  3134. quit();
  3135. }
  3136. private:
  3137. // round 157a: a frozen UI (Windows' "not responding") writes the message thread's stack to autosave\hang <time>.txt
  3138. // and a session step, so a freeze can be told apart from a crash and located. The timer is the heartbeat.
  3139. struct Heartbeat final : juce::Timer
  3140. {
  3141. void timerCallback() override { lynx::crashguard::heartbeat(); }
  3142. } heartbeat;
  3143. void startHangWatch()
  3144. {
  3145. const auto folder = lynx::platform::settingsFile ("autosave");
  3146. folder.createDirectory();
  3147. // keep the newest hang files only
  3148. auto old = folder.findChildFiles (juce::File::findFiles, false, "hang *.txt");
  3149. lynx::filesort::byTime (old, lynx::filesort::By::modificationTime, true);
  3150. for (int i = 20; i < old.size(); ++i)
  3151. old.getReference (i).deleteFile();
  3152. lynx::crashguard::startHangWatch (folder.getFullPathName().replaceCharacter ('\\', '/').toStdString());
  3153. heartbeat.startTimerHz (5);
  3154. }
  3155. bool sandboxChild = false;
  3156. bool relaunched = false; // relaunchFromAsciiPath ran LYNX from its short path: this process only waited
  3157. bool updateHelper = false; // --apply-update (round 166b)
  3158. juce::String uncleanLastStep; // last step of a previous run that ended without closing
  3159. // LYNX_PROFILE_DIR=<folder> LYNX --lv2scantest report.txt (Linux, issue #85): the LV2 scan's promise, with real child
  3160. // processes. A new PluginHost per step, as every start of LYNX has. The LV2 folders of the machine are read too.
  3161. void runLv2ScanTest (const juce::String& reportPath)
  3162. {
  3163. juce::String report;
  3164. auto ok = lynx::platform::profileOverride() != juce::File();
  3165. #if JUCE_LINUX
  3166. const auto folder = lynx::platform::profileOverride().getChildFile ("lv2-test");
  3167. const juce::FileSearchPath paths (folder.getFullPathName());
  3168. const auto check = [&] (const juce::String& name, bool passed) {
  3169. report << name << "=" << (passed ? "ok" : "FAILED") << "\n";
  3170. ok = ok && passed;
  3171. };
  3172. const auto install = [&] (const juce::String& name) {
  3173. const auto bundle = folder.getChildFile (name + ".lv2");
  3174. bundle.createDirectory();
  3175. bundle.getChildFile ("manifest.ttl").replaceWithText ("@prefix lv2: <http://lv2plug.in/ns/lv2core#> .\n@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n"
  3176. "<urn:lynx-test:" + name + "> a lv2:Plugin ; lv2:binary <" + name + ".so> ; rdfs:seeAlso <plugin.ttl> .\n");
  3177. bundle.getChildFile ("plugin.ttl").replaceWithText ("@prefix doap: <http://usefulinc.com/ns/doap#> .\n<urn:lynx-test:" + name + "> doap:name \"" + name + "\" .\n");
  3178. };
  3179. auto date = juce::Time::getCurrentTime();
  3180. const auto touch = [&] { // the next date, whatever the file system's date resolution
  3181. date += juce::RelativeTime::seconds (2.0);
  3182. folder.getChildFile ("a.lv2/plugin.ttl").setLastModificationTime (date);
  3183. };
  3184. const auto listed = [] (lynx::PluginHost& host, const juce::String& name) {
  3185. for (const auto& d : host.getKnownPlugins().getTypes())
  3186. if (d.fileOrIdentifier == "urn:lynx-test:" + name)
  3187. return true;
  3188. return false;
  3189. };
  3190. const auto step = [&] (const juce::String& name, int children, const std::function<void (lynx::PluginHost&)>& prepare = {}) {
  3191. lynx::PluginHost host (true);
  3192. if (prepare)
  3193. prepare (host);
  3194. host.scan (paths, {});
  3195. check (name, host.scanChildrenStarted() == children && listed (host, "a"));
  3196. };
  3197. install ("a");
  3198. step ("first_scan_one_child", 1);
  3199. step ("nothing_changed_no_child", 0);
  3200. touch();
  3201. step ("ttl_updated", 1);
  3202. install ("b");
  3203. step ("bundle_installed", 1);
  3204. step ("forget_file", 1, [] (lynx::PluginHost& host) { host.forgetFile ("urn:lynx-test:a"); });
  3205. step ("forget_all", 1, [] (lynx::PluginHost& host) { host.forgetAll(); });
  3206. lynx::platform::settingsFile ("plugins.xml").deleteFile();
  3207. step ("list_lost", 1);
  3208. step ("nothing_changed_again", 0);
  3209. // cancelled while the child works: stopped at once, and nothing is taken for done
  3210. touch();
  3211. setenv ("LYNX_TEST_CRASH", "lv2-batch-hang", 1);
  3212. {
  3213. lynx::PluginHost host (true);
  3214. const auto started = juce::Time::getMillisecondCounter();
  3215. host.scan (paths, [] (float, const juce::String&) { return false; });
  3216. check ("cancel_stops_the_child", host.scanChildrenStarted() == 1 && juce::Time::getMillisecondCounter() - started < 20000);
  3217. }
  3218. unsetenv ("LYNX_TEST_CRASH");
  3219. step ("described_after_cancel", 1);
  3220. // the child dies: plugin by plugin takes over (stopped after two of them: a machine may have hundreds)
  3221. touch();
  3222. setenv ("LYNX_TEST_CRASH", "lv2-batch", 1);
  3223. {
  3224. lynx::PluginHost host (true);
  3225. host.scan (paths, [&host] (float, const juce::String&) { return host.scanChildrenStarted() < 3; });
  3226. check ("crash_falls_back_plugin_by_plugin", host.scanChildrenStarted() == 3);
  3227. auto blamed = false;
  3228. for (const auto& file : host.getKnownPlugins().getBlacklistedFiles())
  3229. blamed = blamed || file.startsWith ("lv2-folders:");
  3230. check ("crash_blacklists_nothing", ! blamed);
  3231. }
  3232. unsetenv ("LYNX_TEST_CRASH");
  3233. step ("described_after_crash", 1);
  3234. // round 190fw: past the first limit, a child that still works is waited for (FL Studio's own VST plugin boots
  3235. // the FL engine), one that sits still is killed as before, and a busy one only up to the cap. Limits are
  3236. // shortened for the test: 2 s first limit, 2 s without work, 8 s cap (real: 30 s, 30 s, 5 min).
  3237. setenv ("LYNX_TEST_SCAN_MS", "2000,2000,8000", 1);
  3238. const auto timed = [&] (const char* fault, const std::function<bool (lynx::PluginHost&)>& progress) {
  3239. touch();
  3240. setenv ("LYNX_TEST_CRASH", fault, 1);
  3241. lynx::PluginHost host (true);
  3242. const auto started = juce::Time::getMillisecondCounter();
  3243. host.scan (paths, [&] (float, const juce::String&) { return ! progress || progress (host); });
  3244. unsetenv ("LYNX_TEST_CRASH");
  3245. const auto took = (int) (juce::Time::getMillisecondCounter() - started);
  3246. report << " " << fault << ": " << took << " ms, children " << host.scanChildrenStarted() << "\n";
  3247. return std::make_pair (took, host.scanChildrenStarted());
  3248. };
  3249. // (after a failed batch, one plugin-by-plugin child and no more: it describes quickly)
  3250. const auto stopAfterBatch = [] (lynx::PluginHost& host) { return host.scanChildrenStarted() < 2; };
  3251. {
  3252. const auto [took, children] = timed ("lv2-batch-busy:5000", {});
  3253. check ("busy_child_is_waited_for", children == 1 && took >= 4500);
  3254. }
  3255. {
  3256. const auto [took, children] = timed ("lv2-batch-hang", stopAfterBatch);
  3257. check ("idle_child_ends_near_the_first_limit", children == 2 && took >= 1900 && took < 9000);
  3258. }
  3259. {
  3260. const auto [took, children] = timed ("lv2-batch-busy:60000", stopAfterBatch);
  3261. check ("busy_child_ends_at_the_cap", children == 2 && took >= 7500 && took < 20000);
  3262. }
  3263. unsetenv ("LYNX_TEST_SCAN_MS");
  3264. step ("described_after_slow_children", 1);
  3265. #endif
  3266. juce::File (reportPath).replaceWithText (report + "result=" + (ok ? "OK" : "FAILED") + "\n");
  3267. setApplicationReturnValue (ok ? 0 : 1);
  3268. quit();
  3269. }
  3270. // LYNX.exe --selftest report.txt: renders 2 s without a sound card and writes the result.
  3271. // Exit code 0 = audio came out, 1 = silence.
  3272. // --selftest (round 190ci): two more copies of LYNX end by a fault on purpose (--faulttest), one on a normal stack
  3273. // (the top-level filter) and one on a stack Windows cannot walk (the first-chance hook); each must leave
  3274. // "crash <time>.txt" with the access violation in the folder it is given.
  3275. // Round 190dt (Linux / macOS): a plain fault, and LYNX's own fault inside a guarded plugin call (in its code, and in
  3276. // the C library called from its code), must each leave the crash file with the signal: the plugin guard passes
  3277. // LYNX's own faults on to the crash handler instead of swallowing them ("swallowed.txt" = it did).
  3278. // Round 190gj (P9): the inserts' stems from one render are the files each stem's own render writes, byte for byte
  3279. // (a short song with a bus, a send return, delay compensation, a channel on the Master, an automated insert and a
  3280. // side-chained insert), streamed (24-bit WAV with the full mix) and buffered (normalised float).
  3281. static juce::String stemsSinglePassSelfTest()
  3282. {
  3283. auto s = lynx::Song::makeDefault();
  3284. s.mixer = lynx::Song::defaultMixer (7);
  3285. for (std::size_t c = 0; c < s.channels.size(); ++c)
  3286. s.channels[c].mixerTrack = (int) c + 1;
  3287. auto onMaster = s.channels[2];
  3288. onMaster.mixerTrack = 0;
  3289. onMaster.pan = -0.4f;
  3290. s.channels.push_back (onMaster);
  3291. for (int step : { 1, 5, 9, 13 })
  3292. s.patterns[0].toggleStep ((int) s.channels.size() - 1, step);
  3293. for (int step : { 4, 12 })
  3294. s.patterns[0].toggleStep (3, step); // the snare
  3295. for (int k = 0; k < 4; ++k) // the synth under the kick (its compressor listens to it)
  3296. s.patterns[0].notes.push_back ({ (std::int64_t) k * lynx::ppq, lynx::ppq - 60, 4, 57 + 3 * k, 0.9f });
  3297. s.patterns[0].sortNotes();
  3298. s.mixer[0].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::limiter));
  3299. s.mixer[1].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::compressor));
  3300. s.mixer[2].toMaster = false;
  3301. s.mixer[2].sends = { lynx::MixerSend { 6, 1.0f } };
  3302. s.mixer[3].sends = { lynx::MixerSend { 7, 0.5f } };
  3303. s.mixer[3].latencyMs = 3.0f;
  3304. s.mixer[4].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::delay));
  3305. s.mixer[4].latencyMs = 5.0f;
  3306. s.mixer[4].sends = { lynx::MixerSend { 6, 0.7f } };
  3307. s.mixer[4].masterLevel = 0.8f;
  3308. auto keyed = lynx::makeEffectSlot (lynx::EffectKind::compressor);
  3309. keyed.params[0] = 0.5f; // (−30 dB: the kick's hits pull the synth down)
  3310. keyed.sidechain = 1;
  3311. s.mixer[5].effects.push_back (keyed);
  3312. s.mixer[6].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::distortion));
  3313. s.mixer[7].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::reverb));
  3314. lynx::Automation a;
  3315. a.target = { lynx::AutomationTargetKind::mixerPan, 3 };
  3316. a.points = { { 0, 0.2f, 0.0f }, { 8 * lynx::ppq, 0.9f, 0.0f } };
  3317. s.automations.push_back (a);
  3318. s.playlist.clear();
  3319. for (int bar = 0; bar < 2; ++bar)
  3320. s.playlist.push_back ({ 0, 0, bar * 4 * lynx::ppq, 4 * lynx::ppq, 0 });
  3321. lynx::Clip automationClip;
  3322. automationClip.kind = lynx::ClipKind::automation;
  3323. automationClip.automation = 0;
  3324. automationClip.length = 8 * lynx::ppq;
  3325. automationClip.track = 1;
  3326. s.playlist.push_back (automationClip);
  3327. s.mode = lynx::PlayMode::song;
  3328. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-stems190gj-" + juce::String (juce::Time::currentTimeMillis()));
  3329. juce::String problems;
  3330. auto run = [&] (lynx::exportopts::Options o, const juce::String& name) {
  3331. o.stems = lynx::exportopts::Stems::mixerTracks;
  3332. o.maxTailSeconds = 3.0;
  3333. const auto alone = dir.getChildFile ("alone"), shared = dir.getChildFile ("shared");
  3334. alone.createDirectory();
  3335. shared.createDirectory();
  3336. const auto ext = juce::String (lynx::exportopts::extension (o.format));
  3337. const auto planAlone = lynx::planStemExport (s, o, alone.getChildFile (name + ext));
  3338. const auto planShared = lynx::planStemExport (s, o, shared.getChildFile (name + ext));
  3339. auto now = [] (std::function<void()> f) { f(); };
  3340. lynx::StemRunStats stats;
  3341. const auto a = lynx::runStemExport (planAlone, now, {}, {}, {}, {}, true);
  3342. const auto b = lynx::runStemExport (planShared, now, {}, {}, {}, {}, false, true, &stats);
  3343. if (a != (int) planAlone.items.size() || b != a)
  3344. problems << name << ": " << a << " / " << b << " files; ";
  3345. // (every insert from the one render, insert 5 with its side-chain too: it stays ducked as in the mix)
  3346. if (stats.passes != 1 || stats.inPass < 6)
  3347. problems << name << ": renders " << stats.passes << " shared, " << stats.inPass << " in it, " << stats.alone << " alone; ";
  3348. for (std::size_t k = 0; k < planShared.items.size() && k < planAlone.items.size(); ++k)
  3349. {
  3350. juce::MemoryBlock x, y;
  3351. planAlone.items[k].file.loadFileAsData (x);
  3352. planShared.items[k].file.loadFileAsData (y);
  3353. if (x.getSize() == 0 || x != y)
  3354. problems << name << ": " << planShared.items[k].file.getFileName() << " differs; ";
  3355. }
  3356. };
  3357. lynx::exportopts::Options streamed;
  3358. streamed.wavBits = 24;
  3359. streamed.stemsIncludeMaster = true;
  3360. run (streamed, "streamed");
  3361. lynx::exportopts::Options buffered;
  3362. buffered.wavBits = 32;
  3363. buffered.normalize = true;
  3364. run (buffered, "buffered");
  3365. dir.deleteRecursively();
  3366. return problems.isEmpty() ? juce::String ("OK") : "ERROR " + problems;
  3367. }
  3368. static juce::String faultReportSelfTest()
  3369. {
  3370. #if (JUCE_WINDOWS && (defined (_M_X64) || defined (__x86_64__))) \
  3371. || ((JUCE_LINUX || JUCE_MAC) && (defined (__x86_64__) || defined (__aarch64__)))
  3372. const auto exe = juce::File::getSpecialLocation (juce::File::currentExecutableFile);
  3373. const auto root = juce::File::getSpecialLocation (juce::File::tempDirectory)
  3374. .getChildFile ("lynx-faulttest-" + juce::String::toHexString (juce::Random::getSystemRandom().nextInt64()));
  3375. juce::StringArray problems;
  3376. #if JUCE_WINDOWS
  3377. const char* const kinds[] = { "plain", "unwalkable" };
  3378. #else
  3379. const char* const kinds[] = { "plain", "guarded", "guarded-libc", "thread", "thread-libc" };
  3380. #endif
  3381. for (const auto* kind : kinds)
  3382. {
  3383. const auto folder = root.getChildFile (kind);
  3384. folder.createDirectory();
  3385. juce::ChildProcess child;
  3386. const auto started = child.start (juce::StringArray { exe.getFullPathName(), "--faulttest", kind, folder.getFullPathName() }, 0);
  3387. if (! started || ! child.waitForProcessToFinish (60000))
  3388. {
  3389. child.kill();
  3390. problems.add (juce::String (kind) + ": " + (started ? "did not end" : "did not start"));
  3391. continue;
  3392. }
  3393. juce::String text;
  3394. for (const auto& file : folder.findChildFiles (juce::File::findFiles, false, "crash *.txt"))
  3395. text = file.loadFileAsString();
  3396. #if JUCE_WINDOWS
  3397. const auto found = text.contains ("0xc0000005");
  3398. #else
  3399. const auto found = text.contains ("segmentation fault") || text.contains ("bus error");
  3400. #endif
  3401. if (folder.getChildFile ("swallowed.txt").existsAsFile())
  3402. problems.add (juce::String (kind) + ": LYNX's own fault was caught as a plugin's ("
  3403. + folder.getChildFile ("swallowed.txt").loadFileAsString() + ")");
  3404. else if (! found)
  3405. problems.add (juce::String (kind) + ": " + (text.isEmpty() ? "no crash file" : "a crash file without the fault")
  3406. + " (exit code 0x" + juce::String::toHexString ((juce::int64) child.getExitCode()) + ")");
  3407. }
  3408. root.deleteRecursively();
  3409. return problems.isEmpty() ? juce::String ("OK") : "ERROR " + problems.joinIntoString ("; ");
  3410. #else
  3411. return "SKIPPED (Windows x64, Linux / macOS x86-64 / ARM64 only)";
  3412. #endif
  3413. }
  3414. void runSelfTest (const juce::String& reportPath, const juce::String& demoProjectPath)
  3415. {
  3416. lynx::AudioEngine offline (false);
  3417. const auto peak = offline.renderOffline (2.0, 48000.0);
  3418. const auto audioOk = peak > 0.01f && peak < 10.0f;
  3419. // project format round trip, with accents in the name
  3420. auto original = lynx::Song::makeDefault();
  3421. original.channels[0].name = "Bumbo ação";
  3422. original.playlist.push_back ({ 0, 2, 3840, 1920, 960 });
  3423. original.mode = lynx::PlayMode::song;
  3424. original.mixer[3].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::delay));
  3425. original.mixer[3].effects[0].params[1] = 0.25f;
  3426. lynx::Automation automation;
  3427. automation.name = "Pan";
  3428. automation.target = { lynx::AutomationTargetKind::effectParam, 3, 0, 1 };
  3429. automation.points = { { 0, 0.25f, 0.5f }, { 3840, 1.0f, 0.0f } };
  3430. original.automations.push_back (automation);
  3431. lynx::Clip automationClip;
  3432. automationClip.kind = lynx::ClipKind::automation;
  3433. automationClip.automation = 0;
  3434. automationClip.track = 4;
  3435. automationClip.length = 3840;
  3436. original.playlist.push_back (automationClip);
  3437. original.loopStart = 960;
  3438. original.loopEnd = 7680;
  3439. original.playlistTracks.resize (3);
  3440. original.playlistTracks[2].colour = 0xFF2A6FDB; // a track colour (round 90)
  3441. { // the clip grid (round 181a)
  3442. lynx::launcher::setClip (original, 1, 2, { 0, 0, 0, 1920, 0 });
  3443. auto& slot = *lynx::launcher::settingsAt (*original.clipGrid, 1, 2);
  3444. slot.name = "Clip ação";
  3445. slot.mode = lynx::LaunchMode::toggle;
  3446. slot.quant = lynx::LaunchQuant::eighthTriplet;
  3447. slot.legato = true;
  3448. slot.loop = false;
  3449. original.clipGrid->scenes[0].name = "Intro";
  3450. original.clipGrid->globalQuant = lynx::LaunchQuant::bars2;
  3451. }
  3452. std::uint32_t savedGroove = 0;
  3453. { // round 190bv: the groove pool, a groove on the slot's clip, and that clip copied and the copy moved
  3454. lynx::Groove g;
  3455. g.name = "Balanço";
  3456. g.base = lynx::GrooveBase::eighth;
  3457. g.quantize = 0.25f;
  3458. g.timing = 0.8f;
  3459. g.random = 0.1f;
  3460. g.velocity = -0.5f;
  3461. g.length = 1920;
  3462. g.points = { { 0, 1.0f }, { 560, 0.5f } };
  3463. savedGroove = lynx::groove::add (original.grooves, g);
  3464. original.grooves.amount = 1.2f;
  3465. lynx::groove::setClipGroove (original, 1, 2, savedGroove);
  3466. lynx::session::moveClip (original, 1, 2, 0, 1, true);
  3467. lynx::session::moveClip (original, 0, 1, 2, 0, false);
  3468. original.playlist[0].groove = savedGroove; // round 190fm: a Playlist pattern clip's groove
  3469. }
  3470. original.playlistTracks[2].grouped = true; // track groups and rack filter groups (round 104)
  3471. original.playlistTracks[1].collapsed = true;
  3472. original.channelGroups = { "Drums", "Keys" };
  3473. original.channels[1].group = 1;
  3474. original.channels[1].cutOthersOnly = original.channels[1].cutAtNoteEnd = true; // FL Studio Mobile's cut rule (round 190fe)
  3475. juce::String error;
  3476. if (demoProjectPath.isNotEmpty()) // sample project for checking the UI with --snapshot
  3477. lynx::ProjectFile::save (original, juce::File (demoProjectPath), error);
  3478. const auto reloaded = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (original), error);
  3479. // round 190bw: FL's curve modes of automation points come back from a project, tension whole; a bent point
  3480. // without a mode (a project saved before the modes: [tick, value, tension]) keeps LYNX's older law
  3481. const auto curveModesOk = [&original] {
  3482. auto song = original;
  3483. auto& a = song.automations[0];
  3484. a.points = { { 0, 0.25f, 0.5f, (std::uint8_t) lynx::flcurve::stairs },
  3485. { 960, 1.0f, -0.123456f, (std::uint8_t) lynx::flcurve::smooth },
  3486. { 1920, 0.5f, 0.0f, (std::uint8_t) lynx::flcurve::hold },
  3487. { 2400, 0.75f, 0.7f, lynx::AutomationPoint::legacyCurve },
  3488. { 2880, 0.3f, 0.0f, 0 },
  3489. { 3840, 0.6f, 0.0f, 0 } };
  3490. a.lfo.on = true;
  3491. a.lfo.amp = { { 0, 1.0f, -0.25f, (std::uint8_t) lynx::flcurve::pulse }, { 960, 0.5f, 0.0f, 0 } };
  3492. juce::String e;
  3493. const auto text = lynx::ProjectFile::toJson (song);
  3494. const auto back = lynx::ProjectFile::fromJson (text, e);
  3495. return back && back->automations.size() == 1 && back->automations[0].points == a.points && back->automations[0].lfo.amp == a.lfo.amp
  3496. && back->automations[0].valueAt (700.0) == a.valueAt (700.0) && back->automations[0].valueAt (2600.0) == a.valueAt (2600.0);
  3497. }();
  3498. const auto projectOk = curveModesOk && reloaded && reloaded->channels.size() == original.channels.size()
  3499. && reloaded->channels[0].name == original.channels[0].name
  3500. && reloaded->patterns[0].notes.size() == original.patterns[0].notes.size()
  3501. && reloaded->patterns[0].notes[3].start == original.patterns[0].notes[3].start
  3502. && reloaded->mode == lynx::PlayMode::song && reloaded->playlist.size() == 2
  3503. && reloaded->clipGrid.has_value() && reloaded->clipGrid->globalQuant == lynx::LaunchQuant::bars2
  3504. && reloaded->clipGrid->scenes.size() == 3 && reloaded->clipGrid->scenes[0].name == "Intro"
  3505. && lynx::launcher::clipAt (*reloaded->clipGrid, 1, 2) != nullptr
  3506. && [&reloaded] {
  3507. auto grid = *reloaded->clipGrid;
  3508. const auto* slot = lynx::launcher::settingsAt (grid, 1, 2);
  3509. return slot != nullptr && slot->name == "Clip ação" && slot->mode == lynx::LaunchMode::toggle
  3510. && slot->quant == lynx::LaunchQuant::eighthTriplet && slot->legato && ! slot->loop;
  3511. }()
  3512. && [&reloaded, &original, savedGroove] { // round 190bv
  3513. auto grid = *reloaded->clipGrid;
  3514. const auto* kept = lynx::launcher::settingsAt (grid, 1, 2);
  3515. const auto* moved = lynx::launcher::settingsAt (grid, 2, 0);
  3516. const auto* clip = lynx::launcher::clipAt (grid, 2, 0);
  3517. return reloaded->grooves == original.grooves && reloaded->grooves.grooves.size() == 1
  3518. && reloaded->grooves.amount == 1.2f && reloaded->grooves.grooves[0].name == "Balanço"
  3519. && reloaded->grooves.grooves[0].points.size() == 2 && savedGroove != 0
  3520. && kept != nullptr && kept->groove == savedGroove
  3521. && lynx::launcher::clipAt (grid, 0, 1) == nullptr
  3522. && clip != nullptr && clip->pattern == 0 && clip->length == 1920
  3523. && moved != nullptr && moved->groove == savedGroove && moved->name == "Clip ação"
  3524. && moved->mode == lynx::LaunchMode::toggle && moved->legato && ! moved->loop
  3525. && reloaded->playlist[0].groove == savedGroove && reloaded->playlist[1].groove == 0; // (190fm)
  3526. }()
  3527. && reloaded->playlist[1].kind == lynx::ClipKind::automation && reloaded->playlist[1].automation == 0
  3528. && reloaded->automations.size() == 1 && reloaded->automations[0].target == automation.target
  3529. && reloaded->automations[0].points.size() == 2 && reloaded->automations[0].points[0].tension == 0.5f
  3530. && reloaded->automations[0].points[1].tick == 3840
  3531. && reloaded->loopStart == 960 && reloaded->loopEnd == 7680
  3532. && reloaded->playlistTracks.size() == 3 && reloaded->playlistTracks[2].colour == 0xFF2A6FDB
  3533. && reloaded->playlistTracks[1].colour == 0
  3534. && reloaded->playlistTracks[2].grouped && reloaded->playlistTracks[1].collapsed && ! reloaded->playlistTracks[1].grouped
  3535. && reloaded->channelGroups == original.channelGroups && reloaded->channels[1].group == 1 && reloaded->channels[0].group == -1
  3536. && reloaded->channels[1].cutOthersOnly && reloaded->channels[1].cutAtNoteEnd && ! reloaded->channels[0].cutOthersOnly
  3537. && ! reloaded->channels[0].cutAtNoteEnd
  3538. && reloaded->playlist[0].offset == 960 && reloaded->playlist[0].track == 2
  3539. && reloaded->mixer[3].effects.size() == 1
  3540. && reloaded->mixer[3].effects[0].kind == lynx::EffectKind::delay
  3541. && reloaded->mixer[3].effects[0].params[1] == 0.25f;
  3542. // round trip of the newer features: synth/sampler with modulation, EQs, utility, markers
  3543. auto rich = lynx::Song::makeDefault();
  3544. auto& synth = rich.channels[4].synth;
  3545. synth.osc[1] = { lynx::Waveform::square, -1, 7.0f, 0.4f, 5, -0.25f };
  3546. synth.filterType = 2;
  3547. synth.mono = true;
  3548. synth.portaBeats = 0.125f;
  3549. synth.am = true;
  3550. synth.filterEnv = { 3.0f, 0.01f, 0.02f, 0.3f, 0.25f, 0.4f };
  3551. synth.lfo[lynx::lfoPitch] = { 0.5f, 0.25f, true, 1, 0.1f, 0.2f };
  3552. auto& sampler = rich.channels[0].sampler;
  3553. sampler.cutoff = 1200.0f;
  3554. sampler.resonance = 0.3f;
  3555. sampler.filterType = 1;
  3556. sampler.pitchEnv = { -12.0f, 0.0f, 0.0f, 0.05f, 0.0f, 0.1f };
  3557. sampler.lfo[lynx::lfoVolume] = { 0.5f, 0.5f, false, 2, 0.0f, 0.0f };
  3558. rich.mixer[2].eq.gainDb = { 3.0f, -2.5f, 1.0f };
  3559. rich.mixer[2].eq.hz[1] = 2200.0f;
  3560. auto peqSlot = lynx::makeEffectSlot (lynx::EffectKind::parametricEq);
  3561. peqSlot.params[(std::size_t) lynx::peq::param (2, 2)] = lynx::peq::gainValue (6.0);
  3562. peqSlot.params[(std::size_t) (lynx::peq::slopeParam + 0)] = lynx::peq::slopeValue (3);
  3563. rich.mixer[2].effects.push_back (peqSlot);
  3564. auto utilitySlot = lynx::makeEffectSlot (lynx::EffectKind::utility);
  3565. utilitySlot.params[1] = 0.2f;
  3566. rich.mixer[2].effects.push_back (utilitySlot);
  3567. auto vocodexSlot = lynx::makeEffectSlot (lynx::EffectKind::vocodex); // FL's raw state travels as base64
  3568. for (int i = 0; i < 300; ++i)
  3569. vocodexSlot.state.push_back ((std::uint8_t) (i * 37));
  3570. vocodexSlot.sidechain = 1;
  3571. vocodexSlot.sidechain2 = 2;
  3572. rich.mixer[3].effects.push_back (vocodexSlot);
  3573. rich.addMarker ({ 3840, "Refrão", 0, 4 });
  3574. rich.addMarker ({ 7680, {}, 7, 8 });
  3575. const auto richBack = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (rich), error);
  3576. auto paramsClose = [] (const lynx::EffectParams& a, const lynx::EffectParams& b) {
  3577. for (std::size_t i = 0; i < a.size(); ++i)
  3578. if (std::abs (a[i] - b[i]) > 1.0e-3f)
  3579. return false;
  3580. return true;
  3581. };
  3582. // round 190bu: a one-knob effect, the chain's Blend and its preset name travel in the project; a project without
  3583. // them reads as before (no goal, Blend 100 %) and writes none of the new keys
  3584. bool fx190buOk = false;
  3585. {
  3586. auto song = lynx::Song::makeDefault();
  3587. const auto plainJson = lynx::ProjectFile::toJson (song);
  3588. const auto* preset = lynx::chains::find ("Whisper Air");
  3589. if (preset != nullptr && song.mixer.size() > 2)
  3590. {
  3591. lynx::chains::apply (song, 1, *preset);
  3592. song.mixer[2].effects.push_back (lynx::goals::make (lynx::goals::room, 0.62f));
  3593. song.mixer[2].effects.push_back (lynx::goals::make (lynx::goals::bass, 0.3f));
  3594. song.mixer[2].chainBlend = 0.4f;
  3595. const auto json = lynx::ProjectFile::toJson (song);
  3596. const auto back = lynx::ProjectFile::fromJson (json, error);
  3597. const auto plainBack = lynx::ProjectFile::fromJson (plainJson, error);
  3598. auto same = back && back->mixer.size() == song.mixer.size();
  3599. for (std::size_t t = 1; same && t <= 2; ++t)
  3600. {
  3601. const auto& a = song.mixer[t];
  3602. const auto& b = back->mixer[t];
  3603. same = a.effects.size() == b.effects.size() && std::abs (a.chainBlend - b.chainBlend) < 1.0e-6f && a.chainPreset == b.chainPreset;
  3604. for (std::size_t i = 0; same && i < a.effects.size(); ++i)
  3605. same = a.effects[i].kind == b.effects[i].kind && a.effects[i].goal == b.effects[i].goal
  3606. && std::abs (a.effects[i].goalAmount - b.effects[i].goalAmount) < 1.0e-6f && a.effects[i].row == b.effects[i].row
  3607. && lynx::goals::active (b.effects[i]) == lynx::goals::active (a.effects[i]);
  3608. }
  3609. fx190buOk = same && lynx::chains::unchanged (*back, 1) && back->mixer[2].chainPreset.empty()
  3610. && ! plainJson.contains ("\"goal\"") && ! plainJson.contains ("chainBlend") && ! plainJson.contains ("chainPreset")
  3611. && json.contains ("\"goalAmount\"") && plainBack && plainBack->mixer[1].chainBlend == 1.0f
  3612. && lynx::ProjectFile::toJson (*back) == json;
  3613. // a user's chain preset file: the slots, Blend and name come back; the strip's level is not part of it
  3614. song.mixer[2].volume = 0.31f;
  3615. const auto file = lynx::ProjectFile::mixerTrackStateToJson (lynx::chains::stateOf (song.mixer[2], "Mine"));
  3616. const auto state = lynx::ProjectFile::mixerTrackStateFromJson (file, error);
  3617. fx190buOk = fx190buOk && state && state->effects.size() == 2 && state->effects[0].goal == lynx::goals::room
  3618. && lynx::goals::active (state->effects[1]) && std::abs (state->chainBlend - 0.4f) < 1.0e-6f && state->chainPreset == "Mine"
  3619. && state->volume == lynx::MixerTrack().volume;
  3620. }
  3621. }
  3622. const auto richOk = fx190buOk && richBack && richBack->channels[4].synth == synth && richBack->channels[0].sampler == sampler
  3623. && richBack->mixer[2].eq == rich.mixer[2].eq && richBack->mixer[2].effects.size() == 2
  3624. && richBack->mixer[2].effects[0].kind == lynx::EffectKind::parametricEq
  3625. && paramsClose (richBack->mixer[2].effects[0].params, peqSlot.params)
  3626. && richBack->mixer[2].effects[1].kind == lynx::EffectKind::utility
  3627. && paramsClose (richBack->mixer[2].effects[1].params, utilitySlot.params)
  3628. && richBack->mixer[3].effects.size() == 1 && richBack->mixer[3].effects[0].kind == lynx::EffectKind::vocodex
  3629. && richBack->mixer[3].effects[0].state == vocodexSlot.state && richBack->mixer[3].effects[0].sidechain2 == 2
  3630. && richBack->markers() == rich.markers();
  3631. // issue #96's per-plugin option: saved only when on; old projects (no field) read as off
  3632. bool hostKeysOk = false;
  3633. {
  3634. auto song = lynx::Song::makeDefault();
  3635. lynx::ChannelDef plugin;
  3636. plugin.instrument = lynx::InstrumentKind::plugin;
  3637. plugin.plugin.id = "x";
  3638. song.channels.push_back (plugin);
  3639. const auto channel = song.channels.size() - 1;
  3640. const auto off = lynx::ProjectFile::toJson (song);
  3641. song.channels[channel].plugin.allowHostKeys = true;
  3642. song.channels[channel].plugin.hostKeysFirst = true;
  3643. song.channels[channel].plugin.pinned = true; // (round 190ao: Pin on top)
  3644. song.channels[channel].plugin.velocityMode = lynx::prefs::pluginVelocityFixed; // (round 190ao: the plugin's own velocity)
  3645. song.channels[channel].plugin.fixedVelocity = 64;
  3646. const auto on = lynx::ProjectFile::toJson (song);
  3647. const auto offBack = lynx::ProjectFile::fromJson (off, error);
  3648. const auto onBack = lynx::ProjectFile::fromJson (on, error);
  3649. hostKeysOk = ! off.contains ("allowHostKeys") && on.contains ("allowHostKeys") && offBack && onBack
  3650. && ! offBack->channels[channel].plugin.allowHostKeys && onBack->channels[channel].plugin.allowHostKeys
  3651. && ! off.contains ("hostKeysFirst") && ! offBack->channels[channel].plugin.hostKeysFirst && onBack->channels[channel].plugin.hostKeysFirst
  3652. && ! off.contains ("pinnedOnTop") && ! offBack->channels[channel].plugin.pinned && onBack->channels[channel].plugin.pinned
  3653. && ! off.contains ("velocityMode") && ! off.contains ("fixedVelocity") && offBack->channels[channel].plugin.velocityMode == 0
  3654. && offBack->channels[channel].plugin.fixedVelocity == lynx::prefs::defaultFixedVelocity
  3655. && onBack->channels[channel].plugin.velocityMode == lynx::prefs::pluginVelocityFixed && onBack->channels[channel].plugin.fixedVelocity == 64;
  3656. }
  3657. // round 190ad: a new project has FL's plugin levels and keeps them through a save; a project saved before
  3658. // (no "pluginLevels") reads as LYNX's own law, and stays so when it opens
  3659. bool pluginLevelsOk = false;
  3660. {
  3661. const auto fresh = lynx::makeNewProject();
  3662. const auto saved = lynx::ProjectFile::toJson (fresh);
  3663. const auto back = lynx::ProjectFile::fromJson (saved, error);
  3664. auto old = lynx::Song::makeDefault(); // (what every earlier version made)
  3665. const auto oldSaved = lynx::ProjectFile::toJson (old);
  3666. const auto oldBack = lynx::ProjectFile::fromJson (oldSaved, error);
  3667. const auto stripped = lynx::ProjectFile::fromJson (saved.replace ("\"pluginLevels\"", "\"pluginLevelsGone\""), error);
  3668. pluginLevelsOk = fresh.flPluginLevels && saved.contains ("\"pluginLevels\"") && back && back->flPluginLevels
  3669. && ! old.flPluginLevels && ! oldSaved.contains ("pluginLevels") && oldBack && ! oldBack->flPluginLevels
  3670. && stripped && ! stripped->flPluginLevels;
  3671. }
  3672. // hardware output targets (REA round 156): saved only when set; old projects (no field) keep the defaults
  3673. bool hwOutOk = false;
  3674. {
  3675. auto song = lynx::Song::makeDefault();
  3676. const auto plain = lynx::ProjectFile::toJson (song);
  3677. song.mixer[0].outputChannel = lynx::outputNone;
  3678. song.mixer[1].outputChannel = 2;
  3679. song.mixer[1].outputMode = lynx::OutputMode::monoRight;
  3680. song.mixer[2].outputChannel = 6;
  3681. song.mixer[3].outputChannel = 4;
  3682. song.mixer[3].outputMode = lynx::OutputMode::monoSum;
  3683. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  3684. const auto plainBack = lynx::ProjectFile::fromJson (plain, error);
  3685. hwOutOk = back && back->mixer[0].outputChannel == lynx::outputNone && back->mixer[1].outputChannel == 2
  3686. && back->mixer[1].outputMode == lynx::OutputMode::monoRight && back->mixer[2].outputChannel == 6
  3687. && back->mixer[2].outputMode == lynx::OutputMode::stereo && back->mixer[3].outputMode == lynx::OutputMode::monoSum
  3688. && back->mixer[4].outputChannel == lynx::outputDefault && ! plain.contains ("\"output\"") && plainBack
  3689. && plainBack->mixer[0].outputChannel == lynx::outputDefault && plainBack->mixer[1].outputChannel == lynx::outputDefault;
  3690. }
  3691. // round 168j: FL's icons (channel / mixer track / playlist track), PDC Automatic / Compensate automations, Time
  3692. // settings, scale highlighting and data folder — saved only when set, old projects load with FL's defaults
  3693. bool flp168jOk = false;
  3694. {
  3695. auto song = lynx::Song::makeDefault();
  3696. const auto plain = lynx::ProjectFile::toJson (song);
  3697. song.channels[0].icon = 75;
  3698. song.mixer[2].icon = 71;
  3699. song.playlistTracks.resize (3);
  3700. song.playlistTracks[2].icon = 30;
  3701. song.autoPdc = false;
  3702. song.compensateAutomations = false;
  3703. song.timeSignatureMode = true;
  3704. song.scaleHighlight = { 10, 5 };
  3705. song.dataFolder = "D:\\Projects\\data";
  3706. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  3707. const auto plainBack = lynx::ProjectFile::fromJson (plain, error);
  3708. flp168jOk = back && back->channels[0].icon == 75 && back->mixer[2].icon == 71 && back->playlistTracks.size() >= 3
  3709. && back->playlistTracks[2].icon == 30 && ! back->autoPdc && ! back->compensateAutomations && back->timeSignatureMode
  3710. && back->scaleHighlight == song.scaleHighlight && back->dataFolder == song.dataFolder && plainBack && plainBack->autoPdc
  3711. && plainBack->compensateAutomations && ! plainBack->timeSignatureMode && plainBack->scaleHighlight == lynx::Song::ScaleHighlight {}
  3712. && plainBack->dataFolder.empty() && plainBack->channels[0].icon == 0 && ! plain.contains ("\"icon\"")
  3713. && ! plain.contains ("autoPdc") && ! plain.contains ("scaleHighlight");
  3714. }
  3715. // round 180d: clip fades take FL's S curve; a project saved before that keeps its straight fades, also after another
  3716. // save, and a clip made in it takes the S curve. FL's fade tensions and stretch mode and PITCH survive a save.
  3717. // issue #122: playlist tracks linked to inserts (audio) and channels (instrument) survive save, load and save
  3718. // again byte for byte (they were read before the mixer and fell back to Unassigned)
  3719. bool trackModes122Ok = false;
  3720. {
  3721. auto song = lynx::Song::makeDefault();
  3722. song.playlistTracks.resize (6);
  3723. song.playlistTracks[1].mode = lynx::PlaylistTrackMode::audio;
  3724. song.playlistTracks[1].mixerTrack = 3;
  3725. song.playlistTracks[4].mode = lynx::PlaylistTrackMode::audio;
  3726. song.playlistTracks[4].mixerTrack = (int) song.mixer.size() - 1;
  3727. song.playlistTracks[5].mode = lynx::PlaylistTrackMode::instrument;
  3728. song.playlistTracks[5].channel = 1;
  3729. song.playlistTracks[5].mixerTrack = 2;
  3730. const auto json = lynx::ProjectFile::toJson (song, false);
  3731. const auto loaded = lynx::ProjectFile::fromJson (json, error);
  3732. const auto again = loaded ? lynx::ProjectFile::toJson (*loaded, false) : juce::String();
  3733. trackModes122Ok = loaded && json.contains ("playlistTrackModes") && again == json && loaded->playlistTracks.size() >= 6
  3734. && loaded->playlistTracks[1].mode == lynx::PlaylistTrackMode::audio && loaded->playlistTracks[1].mixerTrack == 3
  3735. && loaded->playlistTracks[4].mode == lynx::PlaylistTrackMode::audio
  3736. && loaded->playlistTracks[4].mixerTrack == (int) song.mixer.size() - 1
  3737. && loaded->playlistTracks[5].mode == lynx::PlaylistTrackMode::instrument && loaded->playlistTracks[5].channel == 1;
  3738. }
  3739. bool clipFades180dOk = false;
  3740. {
  3741. auto song = lynx::Song::makeDefault();
  3742. lynx::Clip faded;
  3743. faded.kind = lynx::ClipKind::audio;
  3744. faded.channel = 0;
  3745. faded.length = lynx::ppq * 8;
  3746. faded.fadeIn = lynx::ppq;
  3747. faded.fadeOutTension = -812.933f;
  3748. faded.fadeOut = lynx::ppq * 2;
  3749. lynx::Clip plainClip = faded;
  3750. plainClip.fadeIn = plainClip.fadeOut = 0;
  3751. plainClip.fadeOutTension = 0.0f;
  3752. plainClip.start = lynx::ppq * 16;
  3753. song.playlist = { faded, plainClip };
  3754. song.channels[0].sampler.flStretchMode = 5;
  3755. song.channels[0].sampler.flStretchPitch = 247;
  3756. const auto json = lynx::ProjectFile::toJson (song);
  3757. const auto current = lynx::ProjectFile::fromJson (json, error);
  3758. const auto oldJson = json.replace ("\"clipFadesPerClip\"", "\"clipFadesOther\"");
  3759. auto old = lynx::ProjectFile::fromJson (oldJson, error);
  3760. auto resaved = old;
  3761. if (resaved)
  3762. {
  3763. auto added = faded;
  3764. added.start = lynx::ppq * 32;
  3765. added.linearFades = 0;
  3766. resaved->playlist.push_back (added);
  3767. resaved = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (*resaved), error);
  3768. }
  3769. clipFades180dOk = current && old && resaved && json.contains ("clipFadesPerClip") && ! oldJson.contains ("clipFadesPerClip")
  3770. && current->playlist.size() == 2 && ! current->playlist[0].linearFades
  3771. && current->playlist[0].fadeOutTension == -812.933f && ! current->playlist[1].linearFades
  3772. && current->channels[0].sampler.flStretchMode == 5 && current->channels[0].sampler.flStretchPitch == 247
  3773. && old->playlist.size() == 2 && old->playlist[0].linearFades && ! old->playlist[1].linearFades
  3774. && resaved->playlist.size() == 3 && resaved->playlist[0].linearFades && ! resaved->playlist[1].linearFades
  3775. && ! resaved->playlist[2].linearFades && resaved->playlist[0].fadeOutTension == -812.933f;
  3776. }
  3777. // FL's legacy Pattern Blocks (round 170f): the option and every arrangement's blocks are saved; a project without
  3778. // them has neither in its file and loads with the option off
  3779. bool blocksOk = false;
  3780. {
  3781. auto song = lynx::Song::makeDefault();
  3782. const auto plain = lynx::ProjectFile::toJson (song);
  3783. song.patternBlocksOn = true;
  3784. lynx::patternblocks::place (song, 0, 0);
  3785. lynx::patternblocks::place (song, 0, 4 * 4 * lynx::ppq);
  3786. song.addArrangement ("Second");
  3787. lynx::patternblocks::place (song, 0, 2 * 4 * lynx::ppq);
  3788. song.selectArrangement (0);
  3789. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  3790. const auto plainBack = lynx::ProjectFile::fromJson (plain, error);
  3791. blocksOk = back && back->patternBlocksOn && back->blocks == song.blocks && song.blocks.size() == 2
  3792. && back->arrangements.size() == 2 && back->arrangements[1].blocks == song.arrangements[1].blocks
  3793. && song.arrangements[1].blocks.size() == 1 && back->songLength() == song.songLength() && plainBack
  3794. && ! plainBack->patternBlocksOn && plainBack->blocks.empty() && ! plain.contains ("blocks")
  3795. && ! plain.contains ("patternBlocks");
  3796. }
  3797. // FL's pattern clip takeover (issue #158): saved when on; a project saved before it (no key) loads with it off and
  3798. // keeps playing every overlapping clip of a pattern in full; new projects have it on
  3799. bool takeoverOk = false;
  3800. {
  3801. auto song = lynx::Song::makeDefault();
  3802. const auto plain = lynx::ProjectFile::toJson (song);
  3803. song.patternClipTakeover = true;
  3804. const auto json = lynx::ProjectFile::toJson (song);
  3805. const auto back = lynx::ProjectFile::fromJson (json, error);
  3806. const auto plainBack = lynx::ProjectFile::fromJson (plain, error);
  3807. takeoverOk = back && back->patternClipTakeover && json.contains ("patternClipTakeover") && plainBack
  3808. && ! plainBack->patternClipTakeover && ! plain.contains ("patternClipTakeover")
  3809. && lynx::makeNewProject().patternClipTakeover;
  3810. }
  3811. // comping (round 177c): a comp's equal-power crossfades (Clip::fadeCurve) and the crossfade length are saved; a
  3812. // project without them has neither in its file
  3813. bool compOk = false;
  3814. {
  3815. auto song = lynx::Song::makeDefault();
  3816. const auto plain = lynx::ProjectFile::toJson (song);
  3817. lynx::ChannelDef take;
  3818. take.instrument = lynx::InstrumentKind::audioClip;
  3819. take.samplePath = "take.wav";
  3820. song.channels.push_back (take);
  3821. lynx::Clip a;
  3822. a.kind = lynx::ClipKind::audio;
  3823. a.channel = (int) song.channels.size() - 1;
  3824. a.length = lynx::ppq;
  3825. a.fadeOut = 20;
  3826. a.fadeCurve = 2;
  3827. auto b = a;
  3828. b.start = lynx::ppq - 20;
  3829. b.fadeOut = 0;
  3830. b.fadeIn = 20;
  3831. b.fadeCurve = 1;
  3832. // round 180d's FL fade fields (indices 17..20) and the comp curve (index 21) on one clip, all kept
  3833. auto c = a;
  3834. c.start = 4 * lynx::ppq;
  3835. c.fadeIn = 30;
  3836. c.fadeInTension = -0.75f;
  3837. c.fadeOutTension = 0.5f;
  3838. c.linearFades = 2;
  3839. c.flFadeFlags = 0x1234u;
  3840. c.fadeCurve = 3;
  3841. song.playlist = { a, b, c };
  3842. song.compCrossfadeMs = 12.5f;
  3843. song.playlistTracks.resize (2);
  3844. song.playlistTracks[0].compTrack = true;
  3845. song.playlistTracks[1].grouped = true;
  3846. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  3847. const auto plainBack = lynx::ProjectFile::fromJson (plain, error);
  3848. const auto* both = back && back->playlist.size() == 3 ? &back->playlist[2] : nullptr;
  3849. compOk = back && back->playlist.size() == 3 && back->playlist[0].fadeCurve == 2 && back->playlist[1].fadeCurve == 1
  3850. && both != nullptr && both->fadeCurve == 3 && both->fadeInTension == -0.75f && both->fadeOutTension == 0.5f
  3851. && both->linearFades == 2 && both->flFadeFlags == 0x1234u && both->fadeIn == 30
  3852. && back->playlist[1].fadeIn == 20 && back->compCrossfadeMs == 12.5f && back->playlistTracks[0].compTrack && ! back->playlistTracks[1].compTrack && plainBack
  3853. && plainBack->compCrossfadeMs == lynx::Song::defaultCompCrossfadeMs && ! plain.contains ("compCrossfadeMs") && ! plain.contains ("playlistCompTracks");
  3854. }
  3855. // Misc › Mono / Porta / Slide on every generator (round 168l): kept in the file; a project saved before (an
  3856. // imported engine's flags in its synth settings) gets them back, a Max polyphony of 1 is not Mono
  3857. bool polyOk = false;
  3858. {
  3859. auto song = lynx::Song::makeDefault();
  3860. lynx::ChannelDef osc;
  3861. osc.instrument = lynx::InstrumentKind::threeosc;
  3862. osc.misc.mono = osc.misc.porta = true;
  3863. osc.misc.portaBeats = 0.25f;
  3864. song.channels.push_back (osc);
  3865. auto old = osc;
  3866. old.misc = {};
  3867. old.synth.mono = old.synth.porta = true;
  3868. old.synth.portaBeats = 0.5f;
  3869. song.channels.push_back (old);
  3870. old.maxPolyphony = 1;
  3871. song.channels.push_back (old);
  3872. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  3873. const auto n = song.channels.size();
  3874. polyOk = back && back->channels.size() == n && back->channels[n - 3].misc.mono && back->channels[n - 3].misc.porta
  3875. && std::abs (back->channels[n - 3].misc.portaBeats - 0.25f) < 1e-6f && back->channels[n - 2].misc.mono
  3876. && back->channels[n - 2].misc.porta && std::abs (back->channels[n - 2].misc.portaBeats - 0.5f) < 1e-6f
  3877. && ! back->channels[n - 1].misc.mono && back->channels[n - 1].maxPolyphony == 1
  3878. && ! back->channels[4].misc.mono; // (the LYNX Synth keeps its own flags)
  3879. }
  3880. // FL's track latency (REA round 165f-mixer): manual ms, bypass mode and master compensation saved only when set
  3881. bool latencyOk = false;
  3882. {
  3883. auto song = lynx::Song::makeDefault();
  3884. const auto plain = lynx::ProjectFile::toJson (song);
  3885. song.mixer[1].latencyMs = -20.0f;
  3886. song.mixer[2].latencyMs = 12.5f;
  3887. song.mixer[2].latencyBypass = lynx::LatencyBypass::always;
  3888. song.mixer[3].latencyBypass = lynx::LatencyBypass::whenRecordingOrStopped;
  3889. song.mixer[3].compensateMasterLatency = false;
  3890. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  3891. latencyOk = back && back->mixer[1].latencyMs == -20.0f && back->mixer[2].latencyMs == 12.5f
  3892. && back->mixer[2].latencyBypass == lynx::LatencyBypass::always
  3893. && back->mixer[3].latencyBypass == lynx::LatencyBypass::whenRecordingOrStopped && ! back->mixer[3].compensateMasterLatency
  3894. && back->mixer[4].latencyMs == 0.0f && back->mixer[4].compensateMasterLatency
  3895. && ! plain.contains ("latencyMs") && ! plain.contains ("latencyBypass") && ! plain.contains ("compensateMaster");
  3896. }
  3897. // LYNX's pre-fader sends (round 190aq): saved only when one is used, in a list of its own ("preSends") that a
  3898. // version from before ignores (its sends then play post-fader, as FL's)
  3899. bool preSendOk = false;
  3900. {
  3901. auto song = lynx::Song::makeDefault();
  3902. song.setRoute (1, 3, true, 0.5f);
  3903. song.setRoute (1, 4, true);
  3904. song.setRoute (2, 3, true);
  3905. const auto plain = lynx::ProjectFile::toJson (song);
  3906. song.setSendPre (1, 3, true);
  3907. const auto json = lynx::ProjectFile::toJson (song);
  3908. const auto back = lynx::ProjectFile::fromJson (json, error);
  3909. preSendOk = back && back->sendPre (1, 3) && ! back->sendPre (1, 4) && ! back->sendPre (2, 3)
  3910. && std::abs (back->routeLevel (1, 3) - 0.5f) < 1.0e-4f && back->mixer[1].sends == song.mixer[1].sends
  3911. && ! plain.contains ("preSends") && json.contains ("preSends")
  3912. && json.replace ("\"preSends\"", "\"preSendsOld\"") != json;
  3913. // the same file without the list (what an older version reads): the sends are there, post-fader
  3914. if (const auto old = lynx::ProjectFile::fromJson (json.replace ("\"preSends\"", "\"unknownToOldVersions\""), error))
  3915. preSendOk = preSendOk && old->routes (1, 3) && ! old->sendPre (1, 3) && old->mixer[1].sends.size() == 2;
  3916. else
  3917. preSendOk = false;
  3918. }
  3919. // LYNX's "Low latency while recording" (round 190aq): a latency-adding effect on a monitored insert's path is
  3920. // bypassed in the engine only — PDC drops, the slot is marked, the song and the saved project stay as they are —
  3921. // and it is back when the option goes off
  3922. bool lowLatencyOk = false;
  3923. {
  3924. lynx::AudioEngine live (false);
  3925. live.editSong ([] (lynx::Song& s) {
  3926. s.mixer[1].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::limiter)); // 1.5 ms look-ahead
  3927. s.mixer[1].inputChannel = 0;
  3928. s.mixer[1].monitor = lynx::InputMonitor::on;
  3929. });
  3930. const auto before = live.getLatencySamples();
  3931. const auto saved = lynx::ProjectFile::toJson (live.getSong());
  3932. const auto idle = live.lowLatencyBypassedCount() == 0; // the option is off: nothing is bypassed
  3933. auto o = live.getRecordOptions();
  3934. o.lowLatencyRecording = true;
  3935. live.setRecordOptions (o);
  3936. const auto during = live.getLatencySamples();
  3937. const auto marked = live.isSlotLowLatencyBypassed (1, 0) && live.lowLatencyBypassedLatency (1, 0) > 0 && live.lowLatencyBypassedCount() >= 1;
  3938. const auto untouched = live.getSong().mixer[1].effects[0].enabled && lynx::ProjectFile::toJson (live.getSong()) == saved;
  3939. // monitoring leaves "On" (nothing armed): the effect returns
  3940. live.editSong ([] (lynx::Song& s) { s.mixer[1].monitor = lynx::InputMonitor::whenArmed; });
  3941. const auto released = live.getLatencySamples() == before && ! live.isSlotLowLatencyBypassed (1, 0);
  3942. live.editSong ([] (lynx::Song& s) { s.mixer[1].monitor = lynx::InputMonitor::on; });
  3943. const auto again = live.getLatencySamples() == during && live.isSlotLowLatencyBypassed (1, 0);
  3944. o.lowLatencyRecording = false;
  3945. live.setRecordOptions (o);
  3946. lowLatencyOk = before > 0 && idle && during < before && marked && untouched && released && again
  3947. && live.getLatencySamples() == before && live.lowLatencyBypassedCount() == 0;
  3948. }
  3949. // The Browser's "Preview in time" (round 190aq): a loop whose name gives its tempo is stretched to the project's
  3950. // and starts on the beat; a one-shot plays as it always did; off, nothing changes
  3951. bool previewInTimeOk = false;
  3952. double previewPrepareMs = 0.0;
  3953. {
  3954. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest-preview");
  3955. dir.deleteRecursively();
  3956. dir.createDirectory();
  3957. auto writeWav = [&dir] (const juce::String& name, int frames, bool loop) {
  3958. const auto wav = dir.getChildFile (name);
  3959. juce::WavAudioFormat format;
  3960. juce::AudioBuffer<float> audio (1, frames);
  3961. for (int i = 0; i < frames; ++i) // a click on every beat of 120 BPM over a tone, or a decaying hit
  3962. audio.setSample (0, i, loop ? (i % 24000 < 400 ? 0.8f : 0.0f) + 0.1f * std::sin (0.02f * (float) i)
  3963. : 0.6f * std::exp (-(float) i / 2000.0f) * std::sin (0.05f * (float) i));
  3964. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  3965. if (auto* w = format.createWriterFor (out.get(), 48000.0, 1, 16, {}, 0))
  3966. {
  3967. out.release();
  3968. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  3969. writer->writeFromAudioSampleBuffer (audio, 0, frames);
  3970. }
  3971. return wav;
  3972. };
  3973. const auto loop = writeWav ("selftest loop 120 bpm.wav", 96000, true); // 4 beats at 120 BPM
  3974. const auto hit = writeWav ("selftest hit.wav", 14400, false); // 0.3 s
  3975. lynx::AudioEngine player (false);
  3976. const auto projectBpm = player.getTransport().bpm.load();
  3977. // off (FL's preview): nothing is prepared, the file plays as it is
  3978. player.previewFile (loop);
  3979. const auto offOk = ! player.getPreviewTiming().pending && ! player.getPreviewTiming().inTime;
  3980. player.setPreviewInTime (true);
  3981. player.previewFile (hit); // a one-shot: as it always played, at once
  3982. const auto hitOk = ! player.getPreviewTiming().pending && ! player.getPreviewTiming().inTime;
  3983. player.previewFile (loop);
  3984. const auto queued = player.getPreviewTiming().pending || std::abs (projectBpm - 120.0) < 0.2;
  3985. player.finishPreviewJobs();
  3986. const auto timing = player.getPreviewTiming();
  3987. previewPrepareMs = player.getLastPreviewPrepareMs();
  3988. const auto wanted = lynx::previewtempo::stretchRatio (120.0, projectBpm);
  3989. const auto stretchedOk = timing.inTime && ! timing.pending && timing.source == lynx::previewtempo::Source::name
  3990. && std::abs (timing.fileBpm - 120.0) < 1.0e-9 && std::abs (timing.ratio - wanted) < 1.0e-12
  3991. && std::abs ((double) timing.frames - 96000.0 * wanted) < 96000.0 * 0.01;
  3992. // the second click on the same file has its stretch ready
  3993. player.previewFile (loop);
  3994. const auto cachedOk = ! player.getPreviewTiming().pending && player.getPreviewTiming().inTime && player.getPreviewTiming().frames == timing.frames;
  3995. player.previewFile ({});
  3996. const auto stoppedOk = ! player.getPreviewTiming().inTime && player.getPreviewInTimeProgress() < 0.0;
  3997. // the start: on the next heard beat while the transport plays (sample exact), at once when it is stopped
  3998. auto firstSample = [] (bool playing, double startTick, int latency) {
  3999. lynx::Transport transport;
  4000. transport.sampleRate.store (48000.0);
  4001. transport.bpm.store (120.0); // 0.04 ticks per sample
  4002. transport.playing.store (playing);
  4003. transport.positionTicks.store (startTick);
  4004. lynx::PreviewPlayer p;
  4005. p.prepareToPlay (48000.0, 512);
  4006. p.setTransport (&transport);
  4007. p.setSyncLatency (latency);
  4008. auto dc = std::make_shared<lynx::SampleData>();
  4009. dc->sampleRate = 48000.0;
  4010. dc->left.assign (48000, 0.5f);
  4011. p.playBrowser (dc, 1.0f, true);
  4012. juce::AudioBuffer<float> block (2, 512);
  4013. juce::MidiBuffer midi;
  4014. for (int done = 0; done < 48000; done += 512)
  4015. {
  4016. p.processBlock (block, midi);
  4017. for (int i = 0; i < 512; ++i)
  4018. if (block.getSample (0, i) != 0.0f)
  4019. return done + i;
  4020. if (playing)
  4021. transport.positionTicks.store (transport.positionTicks.load() + 512 * transport.ticksPerSample());
  4022. }
  4023. return -1;
  4024. };
  4025. const auto beatOk = firstSample (true, 480.0, 0) == 12000 // half a beat to go: 480 ticks / 0.04
  4026. && firstSample (true, 480.0, 100) == 12100 // the song is heard 100 samples late (PDC)
  4027. && firstSample (true, 960.0, 0) == 0 // on a beat: now
  4028. && firstSample (false, 480.0, 0) == 0; // stopped: a free start
  4029. previewInTimeOk = loop.existsAsFile() && hit.existsAsFile() && offOk && hitOk && queued && stretchedOk && cachedOk && stoppedOk && beatOk;
  4030. dir.deleteRecursively();
  4031. }
  4032. // LYNX substitutes (round 98): a missing plugin's slot plays a built-in equivalent and the project keeps the
  4033. // original reference byte for byte (.flp record and LYNX plugin state)
  4034. bool substituteOk = false;
  4035. {
  4036. auto song = lynx::Song::makeDefault();
  4037. lynx::ForeignPlugin vv; // an .flp VST3 record (ValhallaVintageVerb's class ID), opaque state
  4038. vv.format = lynx::ForeignPlugin::Format::vst3;
  4039. const std::uint8_t cid[] = { 0x76, 0x54, 0x53, 0x56, 0x65, 0x65, 0x76, 0x33, 0x61, 0x6c, 0x68, 0x61, 0x6c, 0x6c, 0x61, 0x76 };
  4040. std::copy (std::begin (cid), std::end (cid), vv.classId.begin());
  4041. vv.hasClassId = true;
  4042. vv.name = "ValhallaVintageVerb";
  4043. vv.path = "C:\\x\\ValhallaVintageVerb.vst3";
  4044. for (int i = 0; i < 777; ++i)
  4045. vv.state.push_back ((std::uint8_t) (i * 13 + 1));
  4046. lynx::EffectSlot fromFlp;
  4047. fromFlp.kind = lynx::EffectKind::plugin;
  4048. fromFlp.plugin.foreign = vv;
  4049. lynx::EffectSlot fromLynx; // a LYNX reference whose plugin isn't installed here
  4050. fromLynx.kind = lynx::EffectKind::plugin;
  4051. fromLynx.plugin.id = "VST3-FabFilter Pro-Q 3-1a2b3c4d-5e6f7a8b";
  4052. fromLynx.plugin.name = "FabFilter Pro-Q 3";
  4053. fromLynx.plugin.state = "AAECAwQFBgcICQ==";
  4054. const auto flpRef = fromFlp.plugin, lynxRef = fromLynx.plugin;
  4055. song.mixer[1].effects = { fromFlp, fromLynx };
  4056. const auto substitutesOn = lynx::pluginSubstitutesEnabled();
  4057. const auto changed = offline.getPluginHost().applySubstitutes (song);
  4058. auto& fx = song.mixer[1].effects;
  4059. // only the LYNX reference is substituted here (an .flp record is the import's job); do the .flp one directly
  4060. const auto flpSubstituted = lynx::substituteEffectSlot (fx[0], lynx::pluginIdentity (vv));
  4061. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  4062. substituteOk = flpSubstituted && fx[0].kind == lynx::EffectKind::epochVerb
  4063. && (! substitutesOn || (changed == 1 && fx[1].kind == lynx::EffectKind::facetEq && fx[1].substituteFor == lynxRef))
  4064. && back && back->mixer[1].effects.size() == 2 && back->mixer[1].effects[0].kind == lynx::EffectKind::epochVerb
  4065. && back->mixer[1].effects[0].substituteFor == flpRef && back->mixer[1].effects[0].substituteFor.foreign.state == vv.state
  4066. && back->mixer[1].effects[1].kind == fx[1].kind && back->mixer[1].effects[1].substituteFor == fx[1].substituteFor;
  4067. }
  4068. // undo/redo
  4069. offline.editSong ([] (lynx::Song& s) { s.bpm = 99.0; });
  4070. offline.editSong ([] (lynx::Song& s) { s.bpm = 101.0; });
  4071. offline.undo();
  4072. const auto afterUndo = offline.getSong().bpm;
  4073. offline.redo();
  4074. const auto undoOk = afterUndo == 99.0 && offline.getSong().bpm == 101.0 && offline.canUndo() && ! offline.canRedo()
  4075. && offline.isModified();
  4076. // Remote-owned steps still behave as ordinary native history when no RemoteControl instance is enabled.
  4077. // Only API undo/redo refuse device drift; remote reads, staging and publication never hold the audio-device callback lock.
  4078. const auto remoteHistoryResult = []() -> juce::String {
  4079. int checks = 0;
  4080. const auto require = [&] (bool condition, const char* message) {
  4081. ++checks;
  4082. if (! condition) throw std::runtime_error (message);
  4083. };
  4084. try
  4085. {
  4086. for (const auto session : { false, true })
  4087. {
  4088. lynx::AudioEngine history (false);
  4089. lynx::Song initial;
  4090. initial.channels.resize (1);
  4091. initial.channels[0].instrument = lynx::InstrumentKind::synth;
  4092. initial.mixer = lynx::Song::defaultMixer (1);
  4093. initial.bpm = 120.0;
  4094. history.setSong (std::move (initial));
  4095. history.setSessionHistory (session);
  4096. const auto editTempo = [&] (double bpm) {
  4097. require (history.editSongRemoteTransaction ([&] (lynx::Song& s) { s.bpm = bpm; }), "remote tempo edit was not committed");
  4098. };
  4099. const auto refused = [&] (const std::function<void()>& operation) {
  4100. const auto position = history.getHistoryPosition();
  4101. const auto before = lynx::ProjectFile::toJsonExact (history.getSong());
  4102. bool changed = false;
  4103. try { operation(); }
  4104. catch (const lynx::RemoteError& e) { changed = e.code == "changed" && ! e.uncertain; }
  4105. require (changed, "API history did not refuse untracked device changes");
  4106. require (history.getHistoryPosition() == position && lynx::ProjectFile::toJsonExact (history.getSong()) == before,
  4107. "refused API history changed the project or history position");
  4108. };
  4109. const auto withoutDeviceLock = [&] (const std::function<void()>& operation) {
  4110. juce::WaitableEvent locked, release;
  4111. bool timedOut = false;
  4112. std::thread callback ([&] {
  4113. const juce::ScopedLock lock (history.getDeviceManager().getAudioCallbackLock());
  4114. locked.signal();
  4115. timedOut = ! release.wait (3000);
  4116. });
  4117. const auto acquired = locked.wait (3000);
  4118. std::exception_ptr failure;
  4119. try { if (acquired) operation(); }
  4120. catch (...) { failure = std::current_exception(); }
  4121. release.signal();
  4122. callback.join();
  4123. // Check before rethrowing: an expected rejection must not conceal waiting for this lock.
  4124. require (acquired && ! timedOut, "remote read, edit or history publication waited for the audio-device callback lock");
  4125. if (failure) std::rethrow_exception (failure);
  4126. };
  4127. const auto baseline = lynx::ProjectFile::toJsonExact (history.getSong());
  4128. const auto baselineStamp = history.getSongStamp();
  4129. const auto baselinePosition = history.getHistoryPosition();
  4130. const auto unchanged = [&] {
  4131. return history.getSongStamp() == baselineStamp && history.getHistoryPosition() == baselinePosition
  4132. && lynx::ProjectFile::toJsonExact (history.getSong()) == baseline;
  4133. };
  4134. withoutDeviceLock ([&] {
  4135. require (lynx::ProjectFile::toJsonExact (history.snapshotForRemoteControl()) == baseline,
  4136. "remote snapshot changed the project");
  4137. require (history.remoteDeviceStateHash().isNotEmpty(), "remote snapshot did not hash device state");
  4138. });
  4139. require (unchanged(), "remote reads changed the project, revision or history");
  4140. bool staged = false;
  4141. withoutDeviceLock ([&] {
  4142. require (! history.editSongRemoteTransaction ([&] (lynx::Song&) { staged = true; }),
  4143. "remote no-op committed a history step");
  4144. });
  4145. require (staged && unchanged(), "remote no-op did not stage cleanly without changing history");
  4146. bool rejected = false;
  4147. try {
  4148. withoutDeviceLock ([&] {
  4149. history.editSongRemoteTransaction ([] (lynx::Song& next) {
  4150. next.bpm = 999.0;
  4151. throw lynx::RemoteError ("invalid", "selftest stage rejection");
  4152. });
  4153. });
  4154. }
  4155. catch (const lynx::RemoteError& e) { rejected = e.code == "invalid" && ! e.uncertain; }
  4156. require (rejected && unchanged(), "rejected staging changed the project, revision or history");
  4157. for (const auto cancelAfterStage : { false, true })
  4158. {
  4159. int calls = 0;
  4160. staged = false;
  4161. bool cancelledEdit = false;
  4162. try {
  4163. withoutDeviceLock ([&] {
  4164. history.editSongRemoteTransaction ([&] (lynx::Song& next) { staged = true; next.bpm = 999.0; },
  4165. [&] { return ++calls >= (cancelAfterStage ? 2 : 1); });
  4166. });
  4167. }
  4168. catch (const lynx::RemoteError& e) { cancelledEdit = e.code == "failed" && ! e.uncertain; }
  4169. require (cancelledEdit && staged == cancelAfterStage && unchanged(),
  4170. "cancelled edit changed the project, revision or history");
  4171. }
  4172. withoutDeviceLock ([&] { editTempo (130.0); });
  4173. require (history.getSong().bpm == 130.0 && history.getHistoryPosition() == baselinePosition + 1
  4174. && history.getSongStamp() > baselineStamp, "remote commit did not publish one history step");
  4175. history.editSong ([] (lynx::Song& s) { s.channels[0].volume = 0.23f; }, false);
  4176. refused ([&] { history.undoRemoteControl(); });
  4177. withoutDeviceLock ([&] { history.undo(); });
  4178. require (history.getHistoryPosition() == 0 && history.getSong().bpm == 120.0 && history.getRemoteHistoryError().isEmpty(),
  4179. "native undo refused device drift while remote control was disabled");
  4180. history.editSong ([] (lynx::Song& s) { s.channels[0].name = "Untracked change"; }, false);
  4181. refused ([&] { history.redoRemoteControl(); });
  4182. withoutDeviceLock ([&] { history.redo(); });
  4183. require (history.getHistoryPosition() == 1 && history.getSong().bpm == 130.0 && history.getRemoteHistoryError().isEmpty(),
  4184. "native redo refused device drift while remote control was disabled");
  4185. withoutDeviceLock ([&] { editTempo (140.0); });
  4186. history.editSong ([] (lynx::Song& s) { s.channels[0].volume = 0.42f; }, false);
  4187. withoutDeviceLock ([&] { history.jumpToHistory (0); });
  4188. require (history.getHistoryPosition() == 0 && history.getSong().bpm == 120.0, "native history jump stopped at a remote step");
  4189. withoutDeviceLock ([&] { history.jumpToHistory (2); });
  4190. require (history.getHistoryPosition() == 2 && history.getSong().bpm == 140.0, "native redo jump stopped at a remote step");
  4191. withoutDeviceLock ([&] { history.undoRemoteControl(); });
  4192. require (history.getHistoryPosition() == 1 && history.getSong().bpm == 130.0, "API undo failed with an unchanged device fence");
  4193. withoutDeviceLock ([&] { history.redoRemoteControl(); });
  4194. require (history.getHistoryPosition() == 2 && history.getSong().bpm == 140.0, "API redo failed with an unchanged device fence");
  4195. int cancelledChecks = 0;
  4196. bool cancelled = false;
  4197. try { history.undoRemoteControl ([&] { return ++cancelledChecks >= 2; }); }
  4198. catch (const lynx::RemoteError& e) { cancelled = e.code == "failed" && ! e.uncertain; }
  4199. require (cancelled && history.getHistoryPosition() == 2 && history.getSong().bpm == 140.0,
  4200. "cancelled API history moved a step");
  4201. withoutDeviceLock ([&] { history.undo(); });
  4202. require (history.getHistoryPosition() == 1 && history.getSong().bpm == 130.0 && history.getRemoteHistoryError().isEmpty(),
  4203. "API cancellation leaked into native history");
  4204. }
  4205. return "OK (" + juce::String (checks) + " checks)";
  4206. }
  4207. catch (const std::exception& e) { return "ERROR " + juce::String::fromUTF8 (e.what()); }
  4208. }();
  4209. // Hosted state access and processing share a per-instance lock, including fixed blocks and deferred resets.
  4210. const auto hostedStateLockResult = []() -> juce::String {
  4211. struct Probe final : juce::AudioPluginInstance
  4212. {
  4213. struct Parameter final : juce::HostedAudioProcessorParameter
  4214. {
  4215. explicit Parameter (Probe& p) : owner (p) {}
  4216. float getValue() const override { owner.access (owner.parameterReads); return value.load(); }
  4217. void setValue (float v) override { owner.access (owner.parameterWrites); value.store (v); }
  4218. float getDefaultValue() const override { return 0.0f; }
  4219. juce::String getName (int) const override { return "Value"; }
  4220. juce::String getLabel() const override { return {}; }
  4221. juce::String getParameterID() const override { return "value"; }
  4222. float getValueForText (const juce::String& text) const override { return text.getFloatValue(); }
  4223. Probe& owner;
  4224. std::atomic<float> value { 0.0f };
  4225. };
  4226. Probe() : AudioPluginInstance (BusesProperties().withInput ("Input", juce::AudioChannelSet::stereo(), true)
  4227. .withOutput ("Output", juce::AudioChannelSet::stereo(), true))
  4228. {
  4229. addHostedParameter (std::make_unique<Parameter> (*this));
  4230. }
  4231. const juce::String getName() const override { return "State lock probe"; }
  4232. void fillInPluginDescription (juce::PluginDescription& d) const override { d.name = getName(); }
  4233. void prepareToPlay (double, int) override {}
  4234. void releaseResources() override {}
  4235. void processBlock (juce::AudioBuffer<float>& audio, juce::MidiBuffer&) override { access (blocks); audio.clear(); }
  4236. void reset() override { access (resets, std::this_thread::get_id() == ui); } // (on the UI thread: the export reset)
  4237. double getTailLengthSeconds() const override { return 0.0; }
  4238. bool acceptsMidi() const override { return true; }
  4239. bool producesMidi() const override { return false; }
  4240. bool hasEditor() const override { return false; }
  4241. juce::AudioProcessorEditor* createEditor() override { return nullptr; }
  4242. int getNumPrograms() override { return 1; }
  4243. int getCurrentProgram() override { return 0; }
  4244. void setCurrentProgram (int) override {}
  4245. const juce::String getProgramName (int) override { return {}; }
  4246. void changeProgramName (int, const juce::String&) override {}
  4247. void getStateInformation (juce::MemoryBlock& state) override { access (captures); state.replaceAll ("state", 5); }
  4248. void setStateInformation (const void*, int) override { access (restores, true); }
  4249. // Round 190ha: only a restore and the export reset are exclusive with the audio side. A capture and the
  4250. // UI's parameter changes run beside processing, as on JUCE's own hosts (UI-thread calls never overlap
  4251. // each other here: they run in turn).
  4252. void access (std::atomic<int>& calls, bool exclusive = false)
  4253. {
  4254. ++calls;
  4255. if (exclusive)
  4256. {
  4257. ++exclusiveActive;
  4258. if (active.fetch_add (1) != 0) overlap = true;
  4259. }
  4260. else
  4261. {
  4262. ++active;
  4263. if (exclusiveActive.load() != 0) overlap = true;
  4264. }
  4265. juce::Thread::sleep (1); // widen the concurrent vendor-call window without using real plugins
  4266. --active;
  4267. if (exclusive) --exclusiveActive;
  4268. }
  4269. const std::thread::id ui = std::this_thread::get_id();
  4270. std::atomic<int> active { 0 }, exclusiveActive { 0 }, blocks { 0 }, resets { 0 }, captures { 0 }, restores { 0 };
  4271. std::atomic<int> parameterReads { 0 }, parameterWrites { 0 };
  4272. std::atomic<bool> overlap { false };
  4273. };
  4274. int checks = 0;
  4275. const auto require = [&] (bool condition, const char* message) {
  4276. ++checks;
  4277. if (! condition) throw std::runtime_error (message);
  4278. };
  4279. const auto exercise = [&] (auto& adapter, Probe& probe, const auto& render, const auto& reset) {
  4280. const auto saved = adapter.captureState();
  4281. require (saved.has_value(), "mock hosted state could not be captured");
  4282. juce::WaitableEvent start (true);
  4283. std::thread audio ([&] {
  4284. start.wait();
  4285. for (int i = 0; i < 32; ++i)
  4286. {
  4287. adapter.setParameter (0, i % 2 == 0 ? 0.25f : 0.75f);
  4288. (void) adapter.parameterValue (0);
  4289. reset();
  4290. render();
  4291. }
  4292. });
  4293. const juce::ScopeGuard joinAudio { [&] { if (audio.joinable()) audio.join(); } };
  4294. start.signal();
  4295. bool stateOk = true;
  4296. for (int i = 0; i < 32; ++i)
  4297. {
  4298. stateOk = adapter.captureState().has_value() && stateOk;
  4299. stateOk = adapter.restoreState (*saved) && stateOk;
  4300. adapter.setParameterFromUi (0, i % 2 == 0 ? 0.1f : 0.9f);
  4301. if (i % 8 == 0) adapter.resetForExport();
  4302. }
  4303. audio.join();
  4304. // Contended audio callbacks may all have bypassed while state was held.
  4305. // Exercise a successful callback after release before checking coverage.
  4306. adapter.setParameter (0, 0.5f);
  4307. (void) adapter.parameterValue (0);
  4308. reset();
  4309. render();
  4310. require (stateOk && probe.blocks > 0 && probe.resets > 0 && probe.captures > 0 && probe.restores > 0,
  4311. "mock did not exercise processing, resets and hosted state access");
  4312. require (probe.parameterReads > 0 && probe.parameterWrites > 0,
  4313. "mock did not exercise concurrent hosted parameter access");
  4314. require (! probe.overlap, "hosted processing/reset/parameters overlapped a state restore or the export reset");
  4315. require (! adapter.hasCrashed(), "mock hosted adapter crashed");
  4316. };
  4317. try
  4318. {
  4319. for (const auto fixed : { 0, 64 })
  4320. {
  4321. std::array<float, 128> left {}, right {};
  4322. auto instrument = std::make_unique<Probe>();
  4323. auto* instrumentProbe = instrument.get();
  4324. lynx::PluginInstrument voice (std::move (instrument), 128, fixed);
  4325. exercise (voice, *instrumentProbe, [&] { voice.render (left.data(), right.data(), 128, 1.0f, 1.0f); }, [&] { voice.panic(); });
  4326. auto effect = std::make_unique<Probe>();
  4327. auto* effectProbe = effect.get();
  4328. lynx::PluginEffect fx (std::move (effect), 128, fixed);
  4329. exercise (fx, *effectProbe, [&] { fx.process (left.data(), right.data(), 128, {}, 120.0); }, [&] { fx.transportReset(); });
  4330. }
  4331. return "OK (" + juce::String (checks) + " checks)";
  4332. }
  4333. catch (const std::exception& e) { return "ERROR " + juce::String::fromUTF8 (e.what()); }
  4334. }();
  4335. const auto hostedStateContentionResult = lynx::pluginStateContentionSelfTest();
  4336. // recording from the PC keyboard: a one-beat note lands in the pattern, in a single undo step
  4337. // (Blend on: this checks that the take joins the pattern's notes; a new install starts with Blend off)
  4338. const auto notesBefore = offline.getSong().patterns[0].notes.size();
  4339. {
  4340. auto o = offline.getRecordOptions();
  4341. o.mode = lynx::RecordMode::overdub;
  4342. offline.setRecordOptions (o);
  4343. }
  4344. offline.setRecording (true);
  4345. offline.play();
  4346. offline.getTransport().positionTicks.store (960.0);
  4347. offline.sendLiveNote (2, 72, 0.9f, true, true);
  4348. offline.getTransport().positionTicks.store (1920.0);
  4349. offline.sendLiveNote (2, 72, 0.0f, false, true);
  4350. offline.setRecording (false);
  4351. offline.stop();
  4352. const auto& recorded = offline.getSong().patterns[0].notes;
  4353. const auto recordOk = recorded.size() == notesBefore + 1
  4354. && std::any_of (recorded.begin(), recorded.end(), [] (const lynx::Note& n) {
  4355. return n.key == 72 && n.channel == 2 && n.length == 960 && n.start >= 960 && n.start < 3840;
  4356. });
  4357. offline.undo();
  4358. const auto recordUndoOk = offline.getSong().patterns[0].notes.size() == notesBefore;
  4359. // FL's Tools › Cancel recording (round 187a): the pass's notes go, an edit made before it stays, recording turns
  4360. // off and playback goes on; nothing to redo
  4361. bool cancelRecordOk = false;
  4362. {
  4363. offline.editSong ([] (lynx::Song& s) { s.bpm = 123.0; });
  4364. const auto notesThen = offline.getSong().patterns[0].notes.size();
  4365. offline.setRecording (true);
  4366. offline.play();
  4367. offline.getTransport().positionTicks.store (960.0);
  4368. offline.sendLiveNote (2, 74, 0.9f, true, true);
  4369. offline.getTransport().positionTicks.store (1920.0);
  4370. offline.sendLiveNote (2, 74, 0.0f, false, true);
  4371. offline.sendLiveNote (2, 76, 0.9f, true, true); // (still held when the pass is cancelled)
  4372. const auto cancelled = offline.cancelRecording();
  4373. cancelRecordOk = cancelled && ! offline.isRecording() && offline.getTransport().playing.load()
  4374. && offline.getSong().patterns[0].notes.size() == notesThen && offline.getSong().bpm == 123.0 && ! offline.canRedo()
  4375. && ! offline.cancelRecording(); // (not recording: nothing to cancel)
  4376. offline.sendLiveNote (2, 76, 0.0f, false, false);
  4377. offline.stop();
  4378. }
  4379. // MIDI: exporting the pattern and importing it back gives the same notes
  4380. bool midiOk = false;
  4381. {
  4382. auto source = lynx::Song::makeDefault();
  4383. source.patterns[0].notes.push_back ({ 1000, 480, 4, 67, 0.5f });
  4384. source.patterns[0].sortNotes();
  4385. const auto midiFile = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest.mid");
  4386. juce::String midiError;
  4387. const auto saved = lynx::MidiFileIo::savePattern (source, 0, midiFile, midiError);
  4388. const auto song = saved ? lynx::MidiFileIo::loadSong (midiFile, midiError) : std::nullopt;
  4389. midiFile.deleteFile();
  4390. if (song && song->patterns.size() == 1 && song->patterns[0].notes.size() == source.patterns[0].notes.size()
  4391. && std::abs (song->bpm - source.bpm) < 0.01)
  4392. {
  4393. midiOk = true;
  4394. const auto& a = source.patterns[0].notes;
  4395. const auto& b = song->patterns[0].notes;
  4396. for (std::size_t i = 0; i < a.size(); ++i)
  4397. midiOk = midiOk && a[i].start == b[i].start && a[i].key == b[i].key && a[i].length == b[i].length;
  4398. }
  4399. }
  4400. // project package (REA round 118): a project with a sample exported as .zip, extracted and opened again,
  4401. // finds its sample inside the extracted folder
  4402. bool packageOk = false;
  4403. {
  4404. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest-package");
  4405. dir.deleteRecursively();
  4406. dir.getChildFile ("src").createDirectory();
  4407. const auto wav = dir.getChildFile ("src/hit.wav");
  4408. {
  4409. juce::WavAudioFormat format;
  4410. juce::AudioBuffer<float> hit (1, 480);
  4411. for (int i = 0; i < 480; ++i)
  4412. hit.setSample (0, i, 0.5f * std::sin (0.1f * (float) i));
  4413. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  4414. if (auto* w = format.createWriterFor (out.get(), 48000.0, 1, 16, {}, 0))
  4415. {
  4416. out.release();
  4417. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  4418. writer->writeFromAudioSampleBuffer (hit, 0, 480);
  4419. }
  4420. }
  4421. auto source = lynx::Song::makeDefault();
  4422. lynx::ChannelDef c;
  4423. c.name = "Hit";
  4424. c.instrument = lynx::InstrumentKind::sampler;
  4425. c.samplePath = wav.getFullPathName().toStdString();
  4426. source.channels.push_back (c);
  4427. lynx::ProjectPackage::Result packed;
  4428. juce::String packageError;
  4429. const auto zip = dir.getChildFile ("Beat.zip");
  4430. if (wav.existsAsFile() && lynx::ProjectPackage::exportZip (source, "Beat", zip, packed, packageError) && packed.files == 1)
  4431. {
  4432. const auto project = lynx::ProjectPackage::extractZip (zip, dir.getChildFile ("out"), packageError);
  4433. const auto song = project.existsAsFile() ? lynx::ProjectFile::load (project, packageError) : std::nullopt;
  4434. if (song && ! song->channels.empty())
  4435. {
  4436. const juce::File back (juce::String::fromUTF8 (song->channels.back().samplePath.c_str()));
  4437. packageOk = back.existsAsFile() && back.isAChildOf (project.getParentDirectory()) && back.getSize() == wav.getSize();
  4438. }
  4439. }
  4440. dir.deleteRecursively();
  4441. }
  4442. // D#92, round 180a: a non-ASCII folder and a dotted name save and load back; an unwritable place says so, and a
  4443. // relative path resolves as the start-up argument does
  4444. bool projectSaveOk = false;
  4445. {
  4446. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest-save180a");
  4447. dir.deleteRecursively();
  4448. const auto folder = dir.getChildFile (juce::String::fromUTF8 ("M\xc3\xbasica nova"));
  4449. folder.createDirectory();
  4450. const auto named = lynx::ProjectFile::withProjectExtension (folder.getChildFile (juce::String::fromUTF8 ("Can\xc3\xa7\xc3\xa3o.v2")));
  4451. auto song = lynx::Song::makeDefault();
  4452. lynx::Note note;
  4453. note.length = 240;
  4454. note.key = 64;
  4455. song.patterns[0].notes.push_back (note);
  4456. juce::String error, blockedError;
  4457. const auto again = lynx::ProjectFile::save (song, named, error) ? lynx::ProjectFile::load (named, error) : std::nullopt;
  4458. const auto blocker = dir.getChildFile ("a file");
  4459. blocker.replaceWithText ("x");
  4460. const auto cwd = juce::File::getCurrentWorkingDirectory();
  4461. folder.setAsCurrentWorkingDirectory();
  4462. const auto relative = juce::File::getCurrentWorkingDirectory().getChildFile (named.getFileName());
  4463. cwd.setAsCurrentWorkingDirectory();
  4464. projectSaveOk = named.getFileName().endsWith (".v2.lynx") && again && again->patterns[0].notes.size() == song.patterns[0].notes.size()
  4465. && relative == named && ! lynx::ProjectFile::save (song, blocker.getChildFile ("x.lynx"), blockedError)
  4466. && blockedError.isNotEmpty() && lynx::ProjectFile::withProjectExtension (named) == named;
  4467. dir.deleteRecursively();
  4468. }
  4469. // Online Sessions (round 168a): a project sent as a .lynxpack (one sample used twice is stored once, the uids
  4470. // survive), a stand-in rendered through an ExportJob, the guest's part sent back and merged by the host
  4471. juce::String sessionResult = "ERROR";
  4472. {
  4473. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest-session");
  4474. dir.deleteRecursively();
  4475. dir.getChildFile ("src").createDirectory();
  4476. const auto wav = dir.getChildFile ("src/hit.wav");
  4477. {
  4478. juce::WavAudioFormat format;
  4479. juce::AudioBuffer<float> hit (1, 4800);
  4480. for (int i = 0; i < 4800; ++i)
  4481. hit.setSample (0, i, 0.5f * std::sin (0.05f * (float) i) * (1.0f - (float) i / 4800.0f));
  4482. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  4483. if (auto* w = format.createWriterFor (out.get(), 48000.0, 1, 16, {}, 0))
  4484. {
  4485. out.release();
  4486. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  4487. writer->writeFromAudioSampleBuffer (hit, 0, 4800);
  4488. }
  4489. }
  4490. auto host = lynx::Song::makeDefault();
  4491. host.mode = lynx::PlayMode::song;
  4492. const auto copyOfWav = dir.getChildFile ("src/hit copy.wav"); // the same bytes under another name: stored once
  4493. wav.copyFileTo (copyOfWav);
  4494. for (const auto& [name, file] : { std::pair<const char*, juce::File> { "Hit", wav }, { "Hit 2", copyOfWav } })
  4495. {
  4496. lynx::ChannelDef c;
  4497. c.name = name;
  4498. c.instrument = lynx::InstrumentKind::sampler;
  4499. c.samplePath = file.getFullPathName().toStdString();
  4500. host.channels.push_back (c);
  4501. }
  4502. const auto hitChannel = (int) host.channels.size() - 2;
  4503. lynx::Note hitNote;
  4504. hitNote.channel = hitChannel;
  4505. hitNote.length = 480;
  4506. host.patterns[0].notes.push_back (hitNote);
  4507. host.playlist.push_back ({ 0, 0, 0, host.patterns[0].effectiveLength (host.meter()), 0 });
  4508. lynx::uids::normalize (host);
  4509. const auto* guest = lynx::parts::invite (host, "Host", "Ana", 0xFF3D9BE9, false);
  4510. juce::String e;
  4511. std::vector<lynx::sessionpack::Rendered> rendered;
  4512. // (a sampler stands in for a plugin channel here: render() renders whatever it is given)
  4513. const std::vector<lynx::sessionpack::RenderItem> items { { false, hitChannel, false, "Hit", "Test" } };
  4514. const auto renderedOk = guest != nullptr && lynx::sessionpack::render (host, items, 44100.0, dir.getChildFile ("stems"), "Host", rendered, {}, e)
  4515. && rendered.size() == 1 && rendered[0].standIns.size() == 2
  4516. && juce::File (juce::String::fromUTF8 (rendered[0].standIns[0].path.c_str())).getSize() > 1000;
  4517. if (renderedOk)
  4518. lynx::sessionpack::apply (host, rendered);
  4519. lynx::sessionpack::Manifest m;
  4520. m.projectName = "Selftest";
  4521. m.from = *host.session.find (lynx::session::hostTag);
  4522. m.to = *host.session.find (2);
  4523. lynx::sessionpack::WriteResult written;
  4524. const auto pack = dir.getChildFile (juce::String ("Selftest") + lynx::sessionpack::extension);
  4525. const auto packOk = renderedOk && lynx::sessionpack::write (lynx::parts::guestCopy (host, 2), m, offline.getPluginHost(), pack, written, e)
  4526. && written.media == 3 && written.duplicates == 1; // the sample once (used twice), the stand-in pair
  4527. auto opened = packOk ? lynx::sessionpack::open (pack, dir.getChildFile ("received"), e) : std::nullopt;
  4528. bool openOk = false, mergeOk = false;
  4529. if (opened && opened->corrupt.isEmpty())
  4530. {
  4531. const auto& g = opened->song;
  4532. const juce::File sample (juce::String::fromUTF8 (g.channels[(std::size_t) hitChannel].samplePath.c_str()));
  4533. openOk = g.session.me == 2 && g.projectId == host.projectId && g.channels[(std::size_t) hitChannel].uid == host.channels[(std::size_t) hitChannel].uid
  4534. && sample.existsAsFile() && sample.isAChildOf (opened->folder) && g.channels[(std::size_t) hitChannel].standIns.size() == 2
  4535. && juce::File (juce::String::fromUTF8 (g.channels[(std::size_t) hitChannel].standIns[1].path.c_str())).existsAsFile();
  4536. // the guest adds a channel and a pattern of his own, sends his part back
  4537. auto copy = g;
  4538. lynx::ChannelDef mine;
  4539. mine.name = "Ana's hit";
  4540. mine.instrument = lynx::InstrumentKind::sampler;
  4541. mine.samplePath = sample.getFullPathName().toStdString();
  4542. copy.channels.push_back (mine);
  4543. lynx::Pattern p;
  4544. p.name = "Ana";
  4545. lynx::Note note;
  4546. note.channel = (int) copy.channels.size() - 1;
  4547. note.length = 240;
  4548. note.key = 64;
  4549. p.notes.push_back (note);
  4550. copy.patterns.push_back (p);
  4551. lynx::uids::normalize (copy);
  4552. // its uids survive a save and a load
  4553. const auto saved = dir.getChildFile ("guest.lynx");
  4554. auto reloaded = lynx::ProjectFile::save (copy, saved, e) ? lynx::ProjectFile::load (saved, e) : std::nullopt;
  4555. lynx::sessionpack::Manifest back;
  4556. back.part = true;
  4557. back.from = *copy.session.self();
  4558. const auto partFile = dir.getChildFile (juce::String ("Ana part") + lynx::sessionpack::extension);
  4559. lynx::sessionpack::WriteResult partWritten;
  4560. auto part = reloaded && reloaded->channels.back().uid == copy.channels.back().uid && lynx::uids::tagOf (reloaded->channels.back().uid) == 2
  4561. ? lynx::sessionpack::write (lynx::parts::extract (*reloaded, 2), back, offline.getPluginHost(), partFile, partWritten, e)
  4562. : false;
  4563. auto partOpened = part ? lynx::sessionpack::open (partFile, dir.getChildFile ("parts"), e) : std::nullopt;
  4564. if (partOpened && partOpened->manifest.part && lynx::sessionpack::adoptMedia (partOpened->song, dir.getChildFile ("Session media/Ana"), e))
  4565. {
  4566. const auto report = lynx::parts::merge (host, partOpened->song, 2);
  4567. const auto& added = host.channels.back();
  4568. mergeOk = report.ok && report.channels >= 1 && added.name == "Ana's hit" && lynx::uids::tagOf (added.uid) == 2
  4569. && juce::File (juce::String::fromUTF8 (added.samplePath.c_str())).isAChildOf (dir.getChildFile ("Session media/Ana"))
  4570. && host.channels[(std::size_t) hitChannel].name == "Hit";
  4571. }
  4572. }
  4573. // a crafted package whose project points at a file elsewhere on this computer: opening it must not
  4574. // reach that file, or merging would copy it into the project and the next package would send it on
  4575. if (mergeOk)
  4576. {
  4577. const auto secret = dir.getChildFile ("secret.wav");
  4578. wav.copyFileTo (secret);
  4579. auto evil = lynx::Song::makeDefault();
  4580. lynx::ChannelDef c;
  4581. c.instrument = lynx::InstrumentKind::sampler;
  4582. c.samplePath = secret.getFullPathName().toStdString();
  4583. evil.channels.push_back (c);
  4584. lynx::ChannelDef keys; // (FL Keys' zones are read by the engine but are not in the media list)
  4585. keys.instrument = lynx::InstrumentKind::flkeys;
  4586. keys.zones.push_back ({});
  4587. keys.zones.back().path = c.samplePath;
  4588. evil.channels.push_back (keys);
  4589. lynx::ChannelDef patch; // (a Patcher's nodes are not in the media list either)
  4590. patch.instrument = lynx::InstrumentKind::patcher;
  4591. patch.patcher.nodes.resize (2);
  4592. patch.patcher.nodes[0].generator = true;
  4593. patch.patcher.nodes[0].channel = c;
  4594. patch.patcher.nodes[1].effect.samplePath = c.samplePath;
  4595. evil.channels.push_back (patch);
  4596. evil.mixer[1].recordTo = dir.getChildFile ("overwritten.wav").getFullPathName().toStdString();
  4597. const auto evilProject = dir.getChildFile ("evil.lynx");
  4598. lynx::sessionpack::Manifest em;
  4599. em.part = true;
  4600. juce::ZipFile::Builder b;
  4601. const auto json = lynx::sessionpack::manifestToJson (em);
  4602. b.addEntry (new juce::MemoryInputStream (json.toRawUTF8(), json.getNumBytesAsUTF8(), true), 0, "manifest.json", {});
  4603. const auto evilPack = dir.getChildFile (juce::String ("Evil") + lynx::sessionpack::extension);
  4604. bool zipped = false;
  4605. if (lynx::ProjectFile::save (evil, evilProject, e))
  4606. {
  4607. b.addFile (evilProject, 0, "project.lynx");
  4608. juce::FileOutputStream out (evilPack);
  4609. zipped = out.openedOk() && b.writeToStream (out, nullptr);
  4610. }
  4611. auto evilOpened = zipped ? lynx::sessionpack::open (evilPack, dir.getChildFile ("evil"), e) : std::nullopt;
  4612. const auto media = dir.getChildFile ("Session media/Evil");
  4613. mergeOk = evilOpened && lynx::sessionpack::adoptMedia (evilOpened->song, media, e)
  4614. && std::none_of (evilOpened->song.channels.begin(), evilOpened->song.channels.end(), [&] (const lynx::ChannelDef& ch) {
  4615. return juce::File (juce::String::fromUTF8 (ch.samplePath.c_str())) == secret
  4616. || std::any_of (ch.zones.begin(), ch.zones.end(), [&] (const lynx::SampleZone& z) { return juce::File (juce::String::fromUTF8 (z.path.c_str())) == secret; });
  4617. })
  4618. && evilOpened->song.channels.back().patcher.nodes.size() == 2
  4619. && juce::File (juce::String::fromUTF8 (evilOpened->song.channels.back().patcher.nodes[0].channel.samplePath.c_str())) != secret
  4620. && juce::File (juce::String::fromUTF8 (evilOpened->song.channels.back().patcher.nodes[1].effect.samplePath.c_str())) != secret
  4621. && evilOpened->song.mixer[1].recordTo.empty()
  4622. && media.findChildFiles (juce::File::findFiles, true).isEmpty();
  4623. if (! mergeOk && e.isEmpty())
  4624. e = "a received package reached a file outside it";
  4625. }
  4626. // ... nor through its own folder: "..", Windows' dotted names (". ." climbs like ".." there), and a manifest
  4627. // media entry outside the package (it must not even be read: "/dev/zero" would never end)
  4628. if (mergeOk)
  4629. {
  4630. const auto secret = dir.getChildFile ("secret.wav");
  4631. const auto folder = dir.getChildFile ("evil2").getChildFile ("Evil2"); // (where open() will unpack it)
  4632. const auto climb = folder.getFullPathName() + "/media/../../../secret.wav";
  4633. const auto dotted = folder.getFullPathName() + "/. ./.. ./secret.wav";
  4634. auto evil = lynx::Song::makeDefault();
  4635. for (const auto& path : { climb, dotted })
  4636. {
  4637. lynx::ChannelDef c;
  4638. c.instrument = lynx::InstrumentKind::sampler;
  4639. c.samplePath = path.toStdString();
  4640. evil.channels.push_back (c);
  4641. }
  4642. juce::MemoryBlock secretBytes;
  4643. secret.loadFileAsData (secretBytes);
  4644. lynx::sessionpack::Manifest em;
  4645. em.part = true;
  4646. em.media.push_back ({ "sha256-" + juce::String (lynx::sha256Hex ((const std::uint8_t*) secretBytes.getData(), secretBytes.getSize())),
  4647. "secret.wav", (juce::int64) secretBytes.getSize(), "../../secret.wav" });
  4648. const auto evilProject = dir.getChildFile ("evil2.lynx");
  4649. juce::ZipFile::Builder b;
  4650. const auto json = lynx::sessionpack::manifestToJson (em);
  4651. b.addEntry (new juce::MemoryInputStream (json.toRawUTF8(), json.getNumBytesAsUTF8(), true), 0, "manifest.json", {});
  4652. const auto evilPack = dir.getChildFile (juce::String ("Evil2") + lynx::sessionpack::extension);
  4653. bool zipped = false;
  4654. if (lynx::ProjectFile::save (evil, evilProject, e))
  4655. {
  4656. b.addFile (evilProject, 0, "project.lynx");
  4657. juce::FileOutputStream out (evilPack);
  4658. zipped = out.openedOk() && b.writeToStream (out, nullptr);
  4659. }
  4660. auto evilOpened = zipped ? lynx::sessionpack::open (evilPack, dir.getChildFile ("evil2"), e) : std::nullopt;
  4661. const auto media = dir.getChildFile ("Session media/Evil2");
  4662. mergeOk = evilOpened && evilOpened->folder == folder && evilOpened->corrupt.contains ("secret.wav")
  4663. && lynx::sessionpack::adoptMedia (evilOpened->song, media, e) && evilOpened->song.channels.size() >= 2
  4664. && std::none_of (evilOpened->song.channels.begin(), evilOpened->song.channels.end(), [&] (const lynx::ChannelDef& ch) {
  4665. const auto p = juce::String::fromUTF8 (ch.samplePath.c_str());
  4666. return p == climb || p == dotted || (juce::File::isAbsolutePath (p) && juce::File (p) == secret);
  4667. })
  4668. && media.findChildFiles (juce::File::findFiles, true).isEmpty();
  4669. if (! mergeOk && e.isEmpty())
  4670. e = "a received package climbed out of its folder";
  4671. }
  4672. if (! packOk && e.isEmpty())
  4673. e = "media " + juce::String (written.media) + ", duplicates " + juce::String (written.duplicates) + ", missing "
  4674. + written.missing.joinIntoString (";");
  4675. sessionResult = mergeOk ? juce::String ("OK")
  4676. : "ERROR (" + juce::String (renderedOk ? packOk ? openOk ? "merge" : "open" : "pack" : "render") + (e.isEmpty() ? "" : ": " + e) + ")";
  4677. dir.deleteRecursively();
  4678. }
  4679. // WavPack: a .wv from the FL packs (if installed) opens through the sample loader
  4680. juce::String wavpack = "NO_FL";
  4681. {
  4682. const auto roots = lynx::findFlStudioRoots();
  4683. const auto packs = juce::File (juce::String::fromUTF8 (roots.data.c_str())).getChildFile ("Patches/Packs");
  4684. const auto found = packs.isDirectory() ? packs.findChildFiles (juce::File::findFiles, true, "*.wv") : juce::Array<juce::File> {};
  4685. if (! found.isEmpty())
  4686. {
  4687. lynx::SampleLibrary library;
  4688. const auto sample = library.load (found.getFirst().getFullPathName());
  4689. float peakWv = 0.0f;
  4690. if (sample != nullptr)
  4691. for (std::size_t i = 0; i < sample->frames(); ++i)
  4692. peakWv = std::max (peakWv, std::abs (sample->leftData()[i]));
  4693. wavpack = sample != nullptr && sample->frames() > 0 && peakWv > 1e-4f ? "OK" : "ERROR";
  4694. }
  4695. }
  4696. // every built-in effect's editor and engine with extreme settings (round 111): a crash or NaN output fails here
  4697. const auto effectsOk = runEffectFuzz (4, {}); // (no mouse drags: nothing may open on screen)
  4698. // FL's Patcher (round 141): a mixer slot and a generator channel with their graphs survive save / load, and the
  4699. // generator one plays through the rack
  4700. bool patcherOk = false;
  4701. {
  4702. auto song = lynx::Song::makeDefault();
  4703. song.mixer.resize (4);
  4704. auto slot = lynx::makeEffectSlot (lynx::EffectKind::patcher);
  4705. lynx::PatchNode reverb, gain;
  4706. reverb.effect = lynx::makeEffectSlot (lynx::EffectKind::utility); // (exact defaults: params are saved to 4 decimals)
  4707. reverb.label = "Room";
  4708. reverb.x = 120.5f;
  4709. reverb.y = 40.0f;
  4710. gain.effect = lynx::makeEffectSlot (lynx::EffectKind::utility);
  4711. gain.effect.enabled = false;
  4712. slot.patcher.nodes = { reverb, gain };
  4713. lynx::PatchWire a, b, c, control;
  4714. a.to = 0;
  4715. b.from = 0, b.to = 1, b.gain = 0.5f;
  4716. c.from = 1;
  4717. control.kind = lynx::PatchWire::Kind::control, control.from = 0, control.to = 1, control.toPort = 0, control.curve = { 0.0f, 0.25f, 1.0f };
  4718. slot.patcher.wires = { a, b, c, control };
  4719. slot.patcher.outputTracks = { 3 };
  4720. song.mixer[1].effects = { slot };
  4721. lynx::ChannelDef ch;
  4722. ch.name = "Patched";
  4723. ch.instrument = lynx::InstrumentKind::patcher;
  4724. lynx::PatchNode synth;
  4725. synth.generator = true;
  4726. synth.channel.instrument = lynx::InstrumentKind::synth;
  4727. synth.channel.name = "Synth";
  4728. ch.patcher.nodes = { synth };
  4729. lynx::PatchWire notes, out;
  4730. notes.kind = lynx::PatchWire::Kind::midi, notes.to = 0;
  4731. out.from = 0;
  4732. ch.patcher.wires = { notes, out };
  4733. // round 162: the I/O nodes' MIDI pins and a MIDI Out node between them
  4734. lynx::PatchNode midiOutNode;
  4735. midiOutNode.generator = true;
  4736. midiOutNode.channel.instrument = lynx::InstrumentKind::midiOut;
  4737. lynx::midictl::writeMidiOut (midiOutNode.channel.pluginState, { 4, 0, 0, -1, -1 });
  4738. ch.patcher.nodes.push_back (midiOutNode);
  4739. lynx::PatchWire portIn, portOut;
  4740. portIn.kind = portOut.kind = lynx::PatchWire::Kind::midi;
  4741. portIn.fromPort = lynx::patchMidiPortPin (7), portIn.to = 1;
  4742. portOut.from = 1, portOut.to = lynx::patchToHost, portOut.toPort = 9;
  4743. ch.patcher.wires.push_back (portIn);
  4744. ch.patcher.wires.push_back (portOut);
  4745. ch.patcher.fromMidiPorts = { 2, 7 };
  4746. ch.patcher.toMidiPorts = { 9, 11 };
  4747. ch.patcher.fromNotesHidden = true;
  4748. song.channels.push_back (ch);
  4749. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  4750. patcherOk = back && back->mixer.size() >= 2 && back->mixer[1].effects.size() == 1
  4751. && back->mixer[1].effects[0].kind == lynx::EffectKind::patcher && back->mixer[1].effects[0].patcher == slot.patcher
  4752. && back->channels.back().instrument == lynx::InstrumentKind::patcher && back->channels.back().patcher.nodes.size() == 2
  4753. && back->channels.back().patcher.fromMidiPorts == ch.patcher.fromMidiPorts
  4754. && back->channels.back().patcher.toMidiPorts == ch.patcher.toMidiPorts && back->channels.back().patcher.fromNotesHidden
  4755. && back->channels.back().patcher.nodes[1].channel.pluginState == midiOutNode.channel.pluginState
  4756. && back->channels.back().patcher.nodes[0].generator
  4757. && back->channels.back().patcher.nodes[0].channel.instrument == lynx::InstrumentKind::synth
  4758. && back->channels.back().patcher.wires == ch.patcher.wires;
  4759. }
  4760. // Round 183c, Racks: (1) a plain Patcher's stored JSON loads and saves back byte for byte and never holds a
  4761. // "rack" key (FL's Patcher is untouched); (2) an Audio Effect Rack slot and an Instrument Rack channel survive save /
  4762. // load with their chains, zones, macros, mappings, variations and compiled cables
  4763. juce::String rackResult = "OK";
  4764. {
  4765. lynx::MixerTrack plain;
  4766. plain.name = "Plain Patcher";
  4767. auto fx = lynx::makeEffectSlot (lynx::EffectKind::patcher);
  4768. lynx::PatchNode a, b;
  4769. a.effect = lynx::makeEffectSlot (lynx::EffectKind::utility);
  4770. a.label = "A";
  4771. a.x = 120.5f;
  4772. b.effect = lynx::makeEffectSlot (lynx::EffectKind::utility);
  4773. b.effect.enabled = false;
  4774. fx.patcher.nodes = { a, b };
  4775. lynx::PatchWire w1, w2, w3, wc;
  4776. w1.to = 0;
  4777. w2.from = 0, w2.to = 1, w2.gain = 0.5f;
  4778. w3.from = 1;
  4779. wc.kind = lynx::PatchWire::Kind::control, wc.from = 0, wc.to = 1, wc.toPort = 0, wc.curve = { 0.0f, 0.25f, 1.0f };
  4780. fx.patcher.wires = { w1, w2, w3, wc };
  4781. lynx::SurfaceControl knob;
  4782. knob.name = "Drive";
  4783. knob.value = 0.25f;
  4784. fx.patcher.surface = { knob };
  4785. lynx::PatchParam pp;
  4786. pp.node = 0, pp.param = 1, pp.name = "Balance";
  4787. fx.patcher.published = { pp };
  4788. plain.effects = { fx };
  4789. const auto first = juce::JSON::toString (lynx::ProjectFile::mixerTrackToVar (plain), true);
  4790. const auto again = juce::JSON::toString (lynx::ProjectFile::mixerTrackToVar (lynx::ProjectFile::mixerTrackFromVar (juce::JSON::parse (first))), true);
  4791. if (first != again || first.contains ("\"rack\"") || first.contains ("rackMixer"))
  4792. rackResult = "ERROR plain Patcher changed";
  4793. auto song = lynx::Song::makeDefault();
  4794. song.mixer.resize (3);
  4795. auto rackSlot = lynx::rack::makeRackSlot (lynx::RackDoc::Kind::audioEffect);
  4796. auto& doc = rackSlot.patcher;
  4797. lynx::PatchNode u;
  4798. u.effect = lynx::makeEffectSlot (lynx::EffectKind::utility);
  4799. const auto n0 = lynx::rack::addDevice (doc, 0, u);
  4800. lynx::rack::addChain (doc, "Wet");
  4801. lynx::rack::addDevice (doc, 1, u);
  4802. doc.rack[0].chains[1].select = { 10, 90, 30, 70 };
  4803. lynx::rack::setChainPan (doc, 1, -0.5f);
  4804. lynx::RackMapping m;
  4805. m.node = n0, m.param = 0, m.min = 0.2f, m.max = 0.9f;
  4806. lynx::rack::map (doc, 0, m);
  4807. lynx::RackMapping v;
  4808. v.target = lynx::RackMapping::Target::chainVolume, v.chain = 1, v.min = 0.0f, v.max = lynx::rack::unityVolume;
  4809. lynx::rack::map (doc, 1, v);
  4810. lynx::rack::setMacro (doc, 0, 64.0f);
  4811. lynx::rack::storeVariation (doc);
  4812. lynx::rack::setMacro (doc, 0, 100.0f);
  4813. lynx::rack::storeVariation (doc);
  4814. doc.rack[0].morphOn = true, doc.rack[0].morphA = 0, doc.rack[0].morphB = 1;
  4815. lynx::rack::setMorph (doc, 0.5f);
  4816. lynx::rack::compile (doc);
  4817. song.mixer[1].effects = { rackSlot };
  4818. lynx::ChannelDef inst;
  4819. inst.name = "Instrument Rack";
  4820. inst.instrument = lynx::InstrumentKind::patcher;
  4821. inst.patcher = lynx::rack::makeRack (lynx::RackDoc::Kind::instrument);
  4822. lynx::PatchNode synth;
  4823. synth.generator = true;
  4824. synth.channel.instrument = lynx::InstrumentKind::synth;
  4825. synth.channel.name = "Synth";
  4826. lynx::rack::addDevice (inst.patcher, 0, synth);
  4827. inst.patcher.rack[0].chains[0].velocity = { 1, 127, 64, 127 };
  4828. lynx::rack::compile (inst.patcher);
  4829. song.channels.push_back (inst);
  4830. const auto json = lynx::ProjectFile::toJson (song);
  4831. const auto back = lynx::ProjectFile::fromJson (json, error);
  4832. // (the devices' parameters are stored to 4 decimals: the documents are compared as stored, the rack exactly)
  4833. const auto loaded = back && back->mixer.size() >= 2 && back->mixer[1].effects.size() == 1;
  4834. const auto& got = loaded ? back->mixer[1].effects[0].patcher : doc;
  4835. if (! loaded)
  4836. rackResult = "ERROR rack slot not loaded";
  4837. else if (got.rack != doc.rack)
  4838. rackResult = "ERROR rack model";
  4839. else if (got.wires != doc.wires)
  4840. rackResult = "ERROR rack cables";
  4841. else if (got.nodes.size() != doc.nodes.size())
  4842. rackResult = "ERROR rack devices";
  4843. else if (back->channels.back().patcher.rack != inst.patcher.rack || back->channels.back().patcher.wires != inst.patcher.wires
  4844. || back->channels.back().patcher.zones != inst.patcher.zones || back->channels.back().patcher.nodes.size() != inst.patcher.nodes.size())
  4845. rackResult = "ERROR instrument rack";
  4846. // the slot's insert as stored, once more: the same text (the stored form is stable)
  4847. else if (const auto once = juce::JSON::toString (lynx::ProjectFile::mixerTrackToVar (back->mixer[1]), true);
  4848. once != juce::JSON::toString (lynx::ProjectFile::mixerTrackToVar (lynx::ProjectFile::mixerTrackFromVar (juce::JSON::parse (once))), true))
  4849. rackResult = "ERROR rack stored form not stable";
  4850. }
  4851. // Round 190ec, Drum Rack: pads (Receive / Play / Choke / Audio To / sends), return chains and the views survive save /
  4852. // load with their compiled zones and cables
  4853. if (rackResult == "OK")
  4854. {
  4855. lynx::Song song;
  4856. song.mixer.resize (2);
  4857. lynx::ChannelDef ch;
  4858. ch.name = "Drums";
  4859. ch.instrument = lynx::InstrumentKind::patcher;
  4860. ch.patcher = lynx::rack::makeDrumRack();
  4861. lynx::PatchNode synth;
  4862. synth.generator = true;
  4863. synth.channel.instrument = lynx::InstrumentKind::synth;
  4864. const auto kick = lynx::rack::addPad (ch.patcher, 36, "Kick", synth);
  4865. const auto hat = lynx::rack::addPad (ch.patcher, 42, "Hat", synth);
  4866. lynx::rack::addPad (ch.patcher, -1, "Every note");
  4867. lynx::rack::addReturn (ch.patcher, "A Verb");
  4868. lynx::rack::setPlay (ch.patcher, kick, 64);
  4869. lynx::rack::setChoke (ch.patcher, hat, 2);
  4870. lynx::rack::setSend (ch.patcher, hat, 0, 0.25f, false);
  4871. lynx::rack::setAudioTo (ch.patcher, kick, 0);
  4872. lynx::rack::rackOf (ch.patcher)->showIO = true;
  4873. lynx::rack::rackOf (ch.patcher)->padScroll = 17;
  4874. song.channels.push_back (ch);
  4875. juce::String error;
  4876. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  4877. const auto& got = back && ! back->channels.empty() ? back->channels.back().patcher : lynx::PatcherDoc {};
  4878. if (! back || ! lynx::rack::isDrumRack (got))
  4879. rackResult = "ERROR drum rack not loaded";
  4880. else if (got.rack != ch.patcher.rack)
  4881. rackResult = "ERROR drum rack model";
  4882. else if (got.zones != ch.patcher.zones || got.wires != ch.patcher.wires)
  4883. rackResult = "ERROR drum rack cables";
  4884. }
  4885. // FL engines in a native project (round 142, issue #5): every engine this PC can make survives save / load and
  4886. // the instruments play through the rack
  4887. juce::String nativesResult = "OK";
  4888. int nativesMade = 0, nativesSilent = 0;
  4889. {
  4890. auto song = lynx::Song::makeDefault();
  4891. song.channels.clear();
  4892. song.patterns[0].notes.clear();
  4893. song.mixer.resize (3);
  4894. const auto& fl = lynx::flStudioAccess();
  4895. for (const auto& e : lynx::natives::instrumentEngines())
  4896. if (lynx::natives::available (e, fl))
  4897. if (auto c = lynx::natives::makeChannel (e.kind, fl))
  4898. {
  4899. c->mixerTrack = 1;
  4900. song.channels.push_back (*c);
  4901. }
  4902. for (const auto& e : lynx::natives::effectEngines())
  4903. if (auto fx = lynx::natives::makeSlot (e.kind, fl))
  4904. song.mixer[2].effects.push_back (*fx);
  4905. nativesMade = (int) (song.channels.size() + song.mixer[2].effects.size());
  4906. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  4907. auto same = back && back->channels.size() == song.channels.size() && back->mixer.size() >= 3
  4908. && back->mixer[2].effects.size() == song.mixer[2].effects.size();
  4909. for (std::size_t i = 0; same && i < song.channels.size(); ++i)
  4910. {
  4911. const auto& a = song.channels[i];
  4912. const auto& b = back->channels[i];
  4913. same = a.instrument == b.instrument && a.pluginState == b.pluginState && a.samplePath == b.samplePath && a.zones.size() == b.zones.size()
  4914. && a.modelParams.size() == b.modelParams.size();
  4915. if (! same)
  4916. nativesResult = "ERROR channel " + juce::String::fromUTF8 (a.name.c_str());
  4917. }
  4918. for (std::size_t i = 0; same && i < song.mixer[2].effects.size(); ++i)
  4919. {
  4920. const auto& a = song.mixer[2].effects[i];
  4921. const auto& b = back->mixer[2].effects[i];
  4922. same = a.kind == b.kind && a.state == b.state;
  4923. for (std::size_t p = 0; same && p < a.params.size(); ++p)
  4924. same = std::abs (a.params[p] - b.params[p]) < 1.0e-3f;
  4925. if (! same)
  4926. nativesResult = juce::String ("ERROR effect ") + lynx::effectInfo (a.kind).name;
  4927. }
  4928. if (! back)
  4929. nativesResult = "ERROR " + error;
  4930. // each instrument plays a note alone. The Granulizer and Wave Traveller play the channel's sample, and a new
  4931. // one has none (a PC without FL Studio, macOS / Linux: FL's presets are not there either), so they get a
  4932. // generated one: a second of a 220 Hz tone (round 167m, PR #19: Wave Traveller was "SILENT 1" on macOS)
  4933. const auto toneWav = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest-natives.wav");
  4934. {
  4935. juce::WavAudioFormat format;
  4936. juce::AudioBuffer<float> tone (1, 48000);
  4937. for (int i = 0; i < 48000; ++i)
  4938. tone.setSample (0, i, 0.5f * std::sin (juce::MathConstants<float>::twoPi * 220.0f * (float) i / 48000.0f));
  4939. toneWav.deleteFile();
  4940. std::unique_ptr<juce::OutputStream> out (toneWav.createOutputStream().release());
  4941. if (auto* w = format.createWriterFor (out.get(), 48000.0, 1, 16, {}, 0))
  4942. {
  4943. out.release();
  4944. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  4945. writer->writeFromAudioSampleBuffer (tone, 0, 48000);
  4946. }
  4947. }
  4948. juce::StringArray silentNames;
  4949. for (std::size_t i = 0; same && i < song.channels.size(); ++i)
  4950. {
  4951. auto one = song;
  4952. one.channels = { song.channels[i] };
  4953. one.channels[0].mixerTrack = 1;
  4954. const auto kind = song.channels[i].instrument;
  4955. // A new Fruity Slicer has no sample and no slices, and FL's is silent then too (round 180c), so it is
  4956. // not one of the engines that must sound here (Linux / macOS CI: "SILENT 1 [Fruity Slicer]", 0.1.25)
  4957. if (kind == lynx::InstrumentKind::fruityslicer && one.channels[0].samplePath.empty())
  4958. continue;
  4959. if (kind == lynx::InstrumentKind::slicex && one.channels[0].samplePath.empty()) // (the same: no sample on its decks yet)
  4960. continue;
  4961. if ((kind == lynx::InstrumentKind::granulizer || kind == lynx::InstrumentKind::wavetraveller) && one.channels[0].samplePath.empty())
  4962. one.channels[0].samplePath = toneWav.getFullPathName().toStdString();
  4963. one.mixer[2].effects.clear();
  4964. // Drumaxx plays pad 1's key: FL's default kit has a pad at 48, LYNX's own bank kits (a PC without FL,
  4965. // macOS / Linux; round 168p) start at 36 (round 169d: "SILENT 1 [Drumaxx]" on the Linux / macOS CI)
  4966. auto key = 60;
  4967. if (kind == lynx::InstrumentKind::drumaxx)
  4968. {
  4969. const auto padKey = lynx::drumaxxParam (one.channels[0].pluginState, 4);
  4970. key = std::isfinite (padKey) && padKey >= 0.0f && padKey <= 127.0f ? (int) padKey : 48;
  4971. }
  4972. // FPC plays its pads' keys; a kit without a sample (FL's "Empty" kit: no FL Studio on this PC) is silent
  4973. // in FL too (round 190q)
  4974. if (kind == lynx::InstrumentKind::fpc)
  4975. {
  4976. const auto pads = lynx::fpcChannelPads (one.channels[0]);
  4977. if (pads.empty())
  4978. continue;
  4979. key = pads.front().key;
  4980. }
  4981. one.patterns[0].notes = { { 0, 1920, 0, key, 0.8f } };
  4982. lynx::AudioEngine player (false);
  4983. player.setSong (std::move (one));
  4984. player.dispatchPendingMessages();
  4985. if (! (player.renderOffline (1.0, 48000.0) > 1.0e-4f))
  4986. {
  4987. ++nativesSilent;
  4988. silentNames.add (juce::String::fromUTF8 (song.channels[i].name.c_str()));
  4989. }
  4990. }
  4991. toneWav.deleteFile();
  4992. if (nativesSilent > 0 && nativesResult == "OK")
  4993. nativesResult = "SILENT " + juce::String (nativesSilent) + " [" + silentNames.joinIntoString (", ") + "]";
  4994. }
  4995. const auto nativesOk = nativesResult == "OK";
  4996. // The metronome as FL 2026 plays it (round 165z-a2): FL's five sounds from its install, the downbeat at
  4997. // 0.9404 × the Tick two semitones up, into the Master ("---") by default; insert 2 as its track plays it through
  4998. // insert 2 (muted: silent); never in an export
  4999. juce::String metronomeResult = "OK";
  5000. int metronomeFlSounds = 0;
  5001. float metronomeMaster = 0.0f;
  5002. {
  5003. const auto& flData = lynx::flStudioAccess().roots.data;
  5004. const auto sounds = lynx::Metronome::loadSounds (flData.empty() ? juce::File() : lynx::platform::localFile (flData));
  5005. for (const auto& s : sounds)
  5006. metronomeFlSounds += s.fromFl ? 1 : 0;
  5007. auto renderClick = [] (int track, bool muteInsert, bool include) {
  5008. auto song = lynx::Song::makeDefault();
  5009. song.channels.clear();
  5010. song.playlist.clear();
  5011. for (auto& p : song.patterns)
  5012. p.notes.clear();
  5013. song.mixer[0].effects.clear(); // (the default Master limiter)
  5014. song.mixer[2].muted = muteInsert;
  5015. lynx::AudioEngine player (false);
  5016. player.setSong (std::move (song));
  5017. player.dispatchPendingMessages();
  5018. auto& t = player.getTransport();
  5019. t.metronome = true;
  5020. t.metronomeSound = 1; // Tick
  5021. t.metronomeTrack = track;
  5022. lynx::AudioEngine::RenderOptions o;
  5023. o.seconds = 0.25;
  5024. o.sampleRate = 44100.0;
  5025. o.pluginWarmUp = false;
  5026. o.includeMetronome = include;
  5027. return player.renderOffline (o);
  5028. };
  5029. metronomeMaster = renderClick (0, false, true);
  5030. const auto insert = renderClick (2, false, true);
  5031. const auto muted = renderClick (2, true, true);
  5032. const auto exported = renderClick (0, false, false);
  5033. // FL's Tick peaks at 1.0: its downbeat at most 0.9404 (the interpolation may land between peaks)
  5034. const auto expectHigh = metronomeFlSounds == lynx::metronome::soundCount ? lynx::metronome::downbeatGain + 1.0e-3f : 1.0f;
  5035. if (! (metronomeMaster > 0.5f && metronomeMaster < expectHigh))
  5036. metronomeResult = "ERROR master " + juce::String (metronomeMaster, 4);
  5037. else if (std::abs (insert - metronomeMaster) > 2.0e-3f)
  5038. metronomeResult = "ERROR insert " + juce::String (insert, 4);
  5039. else if (muted > 1.0e-4f)
  5040. metronomeResult = "ERROR muted insert " + juce::String (muted, 4);
  5041. else if (exported > 1.0e-4f)
  5042. metronomeResult = "ERROR in export " + juce::String (exported, 4);
  5043. }
  5044. const auto metronomeOk = metronomeResult == "OK";
  5045. // Settings › Audio "Driver settings…" with a fake driver panel (issue #13's crash, the panel's buffer kept)
  5046. const auto driverPanel = lynx::AudioEngine::driverPanelSelfTest();
  5047. // issue #134 (round 190c): the output device, its rate and its buffer changed under a playing project, on
  5048. // stand-in devices (a short run; --devicechangetest plays every instrument and effect)
  5049. const auto deviceChange = lynx::AudioEngine::deviceChangeSelfTest (10, false);
  5050. // round 190gh: export parity (B7) and MIDI device hot-plug (B8)
  5051. const auto exportParity = lynx::AudioEngine::exportParitySelfTest();
  5052. const auto midiHotplug = lynx::AudioEngine::midiHotplugSelfTest();
  5053. // Online Sessions P2 (round 169b): live sessions without a network (the JSON round trip of every entity, replicas
  5054. // through it, the invite code's keys)
  5055. const auto liveResult = lynx::livetest::selfTest (&rich);
  5056. // issue #67: every built-in effect's parameters, named and hidden (the Parametric EQ's FL law, processing, band
  5057. // mask...), at odd values, through a project save and reload: the same floats back
  5058. juce::String effectParamsResult = "OK";
  5059. {
  5060. auto song = lynx::Song::makeDefault();
  5061. song.mixer.resize (1);
  5062. for (int k = 0; k <= (int) lynx::lastEffectKind; ++k)
  5063. {
  5064. const auto kind = (lynx::EffectKind) k;
  5065. if (kind == lynx::EffectKind::plugin || kind == lynx::EffectKind::parallel)
  5066. continue;
  5067. auto fx = lynx::makeEffectSlot (kind);
  5068. for (std::size_t i = 0; i < fx.params.size(); ++i)
  5069. {
  5070. auto v = (float) ((double) ((i * 7919 + (std::size_t) k * 104729) % 65521) / 65521.0);
  5071. fx.params[i] = v == fx.params[i] ? 1.0f - v : v;
  5072. }
  5073. if (kind == lynx::EffectKind::fruitySend) // ("Send to" is written over the insert span)
  5074. fx.params[3] = 0.0f;
  5075. song.mixer.emplace_back();
  5076. song.mixer.back().name = "Insert " + std::to_string (song.mixer.size() - 1);
  5077. song.mixer.back().effects.push_back (fx);
  5078. }
  5079. // round 171b's Patcher round trip (coordinator): the Frequency Splitter, Fruity Delay 3 and Peak Controller
  5080. // nodes came back different (their FL defaults, e.g. the LFO speed 32750 / 65336, lost to 4 decimals)
  5081. {
  5082. auto patch = lynx::makeEffectSlot (lynx::EffectKind::patcher);
  5083. for (const auto kind : { lynx::EffectKind::frequencySplitter, lynx::EffectKind::fruityDelay3, lynx::EffectKind::peakController,
  5084. lynx::EffectKind::reverb, lynx::EffectKind::hardwareInsert })
  5085. {
  5086. lynx::PatchNode node;
  5087. node.effect = lynx::natives::newEffect (kind, lynx::flStudioAccess()).value_or (lynx::makeEffectSlot (kind));
  5088. if (kind == lynx::EffectKind::peakController)
  5089. node.effect.params[7] = 32750.0f / 65336.0f;
  5090. node.x = 200.0f, node.y = 60.0f * (float) patch.patcher.nodes.size();
  5091. patch.patcher.nodes.push_back (node);
  5092. }
  5093. song.mixer.emplace_back();
  5094. song.mixer.back().name = "Patcher";
  5095. song.mixer.back().effects.push_back (patch);
  5096. }
  5097. juce::String why;
  5098. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
  5099. if (back && back->mixer.size() == song.mixer.size())
  5100. {
  5101. const auto& a = song.mixer.back().effects[0].patcher.nodes;
  5102. const auto& b = back->mixer.back().effects[0].patcher.nodes;
  5103. for (std::size_t n = 0; n < a.size(); ++n)
  5104. if (n >= b.size() || ! (a[n].effect == b[n].effect))
  5105. effectParamsResult = juce::String ("ERROR Patcher node ") + lynx::effectInfo (a[n].effect.kind).name;
  5106. }
  5107. if (! back || back->mixer.size() != song.mixer.size())
  5108. effectParamsResult = "ERROR load " + why;
  5109. else
  5110. for (std::size_t t = 1; t + 1 < song.mixer.size() && effectParamsResult == "OK"; ++t)
  5111. if (back->mixer[t].effects.size() != 1 || back->mixer[t].effects[0].params != song.mixer[t].effects[0].params)
  5112. {
  5113. effectParamsResult = juce::String ("ERROR ") + lynx::effectInfo (song.mixer[t].effects[0].kind).name;
  5114. break;
  5115. }
  5116. }
  5117. // round 170j: the Themed plugin style (its resolution with and without art; every art draws)
  5118. const auto artResult = lynx::skin::artSelfTest();
  5119. // round 177b: a plugin's sidechain bus gets the slot's sidechain (one-click sidechain)
  5120. const auto sidechainResult = lynx::pluginSidechainSelfTest();
  5121. // round 190ap: the Versions panel's list of files, and its labels on disk beside them
  5122. const auto versionsResult = lynx::versionsSelfTest();
  5123. // round 190ap: a project opened with its plugins off creates none of them and saves their settings unchanged
  5124. const auto pluginsOffResult = lynx::pluginsOffSelfTest();
  5125. const auto missingFilesResult = lynx::missingFilesSelfTest(); // issue #165
  5126. // round 190cj: a dancer's own native window stays where the stage put it (it drifted off the screen: JUCE
  5127. // moved a transparent child window by the main window's client offset on every repaint)
  5128. juce::String danceWindowDetail;
  5129. const auto danceWindowResult = lynx::danceWindowSelfTest (&danceWindowDetail);
  5130. // issue #161: a click in a panel (a native child window that takes no focus on a click) of an inactive main
  5131. // window activates it (back from another app, Space played nothing until the Browser was clicked)
  5132. const auto clickActivationResult = lynx::nativechild::clickActivationSelfTest();
  5133. // round 177b: automation lanes come back from a project (track, automation, height, folded)
  5134. juce::String lanesResult = "OK";
  5135. {
  5136. auto song = lynx::Song::makeDefault();
  5137. const auto lane = lynx::autolanes::addLane (song, 3, { lynx::AutomationTargetKind::mixerVolume, 1, 0, 0 }, "Vol", 0.4f);
  5138. song.playlistTracks[3].lanes[0].height = 72;
  5139. song.playlistTracks[3].lanesFolded = true;
  5140. // (the same round's clip LFO and modulators ride along)
  5141. auto& lfo = song.automations[(std::size_t) lane].lfo;
  5142. lfo.on = true;
  5143. lfo.level = -40;
  5144. lfo.speed = 30000;
  5145. lfo.flags = 1 | 4;
  5146. lfo.phase = 123456789u;
  5147. lfo.amp = { { 0, 0.5f, 0.0f }, { 960, 1.0f, 0.0f } };
  5148. lynx::Modulator mod;
  5149. mod.name = "LFO 1";
  5150. mod.shape = lynx::ModShape::square;
  5151. mod.sync = false;
  5152. mod.hz = 2.5;
  5153. mod.routes = { { { lynx::AutomationTargetKind::mixerPan, 1, 0, 0 }, -0.5f } };
  5154. song.modulators.push_back (mod);
  5155. juce::String why;
  5156. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
  5157. if (! back || back->playlistTracks.size() < 4 || ! (back->playlistTracks[3].lanes == song.playlistTracks[3].lanes)
  5158. || ! back->playlistTracks[3].lanesFolded || back->automations.size() != song.automations.size()
  5159. || ! (back->automations[(std::size_t) lane].points == song.automations[(std::size_t) lane].points)
  5160. || ! (back->automations[(std::size_t) lane].lfo == lfo) || ! (back->modulators == song.modulators))
  5161. lanesResult = "ERROR " + why;
  5162. }
  5163. // round 190cg: the loop switch, folded tracks and the tempo lane's range come back from a project; a project
  5164. // without them loads as before (loop on, nothing folded, the whole range)
  5165. juce::String arrange190cgResult = "OK";
  5166. {
  5167. auto song = lynx::Song::makeDefault();
  5168. juce::String why;
  5169. const auto plain = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
  5170. song.loopStart = 960;
  5171. song.loopEnd = 4800;
  5172. song.loopOff = true;
  5173. song.tempoViewLow = 80.0;
  5174. song.tempoViewHigh = 160.0;
  5175. song.playlistTracks.resize (std::max<std::size_t> (song.playlistTracks.size(), 6));
  5176. song.playlistTracks[2].folded = song.playlistTracks[5].folded = true;
  5177. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
  5178. if (! plain || plain->loopOff || plain->tempoViewLow != 0.0 || plain->tempoViewHigh != 0.0
  5179. || std::any_of (plain->playlistTracks.begin(), plain->playlistTracks.end(), [] (const lynx::PlaylistTrack& t) { return t.folded; }))
  5180. arrange190cgResult = "ERROR defaults " + why;
  5181. else if (! back || ! back->loopOff || back->loopStart != 960 || back->loopEnd != 4800 || back->loopPlays() || back->tempoViewLow != 80.0
  5182. || back->tempoViewHigh != 160.0 || back->playlistTracks.size() < 6 || ! back->playlistTracks[2].folded
  5183. || ! back->playlistTracks[5].folded || back->playlistTracks[3].folded)
  5184. arrange190cgResult = "ERROR round trip " + why;
  5185. }
  5186. // round 190gz (issue #170): "Link Playlist tracks to mixer tracks" comes back from a project with its links; a
  5187. // project without it loads with it off (FL's tracks)
  5188. juce::String trackauto190gzResult = "OK";
  5189. {
  5190. auto song = lynx::Song::makeDefault();
  5191. juce::String why;
  5192. const auto plain = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
  5193. lynx::Clip clip;
  5194. clip.kind = lynx::ClipKind::pattern;
  5195. clip.pattern = 0; // (the default pattern: Kick, Clap and Hat; a second one plays Kick alone)
  5196. song.playlist.push_back (clip);
  5197. auto& kick = song.patterns.emplace_back();
  5198. kick.name = "Kick";
  5199. kick.toggleStep (0, 0);
  5200. clip.pattern = (int) song.patterns.size() - 1;
  5201. clip.track = 1;
  5202. song.playlist.push_back (clip);
  5203. lynx::autolink::setOn (song, true);
  5204. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
  5205. if (! plain || plain->linkTracksToMixer)
  5206. trackauto190gzResult = "ERROR defaults " + why;
  5207. // (round 190ib: Track 1 holds Kick, Clap and Hat, so they all go through insert 1 and Track 1 is its audio
  5208. // track; Track 2 only repeats Kick and stays unassigned)
  5209. // (a .lynx keeps the tracks up to the last one that differs from a plain track: Track 2 may not be written)
  5210. else if (! back || ! back->linkTracksToMixer || back->playlistTracks.empty() || back->playlistTracks[0].mode != lynx::PlaylistTrackMode::audio
  5211. || back->playlistTracks[0].mixerTrack != 1
  5212. || (back->playlistTracks.size() > 1 && back->playlistTracks[1].mode != lynx::PlaylistTrackMode::unassigned)
  5213. || back->channels[1].mixerTrack != 1 || back->channels[2].mixerTrack != 1)
  5214. {
  5215. trackauto190gzResult = "ERROR round trip " + why;
  5216. if (back && ! back->playlistTracks.empty() && back->channels.size() >= 3)
  5217. trackauto190gzResult << " tracks " << (int) back->playlistTracks.size() << " mode " << (int) back->playlistTracks[0].mode << " insert "
  5218. << back->playlistTracks[0].mixerTrack << " routes " << back->channels[0].mixerTrack << " "
  5219. << back->channels[1].mixerTrack << " " << back->channels[2].mixerTrack;
  5220. }
  5221. }
  5222. // round 190fm: the MIDI Tools generators' settings come back from a project; a project without them loads with
  5223. // Live's defaults (and saves none)
  5224. juce::String midigen190fmResult = "OK";
  5225. {
  5226. auto song = lynx::Song::makeDefault();
  5227. juce::String why;
  5228. const auto plainJson = lynx::ProjectFile::toJson (song);
  5229. const auto plain = lynx::ProjectFile::fromJson (plainJson, why);
  5230. song.midiGenerate.tool = lynx::midigen::Settings::stacks;
  5231. song.midiGenerate.rhythmOptions.pattern = 3;
  5232. song.midiGenerate.seedOptions.voices = 2;
  5233. song.midiGenerate.shapeOptions.levels[4] = 0.25f;
  5234. song.midiGenerate.shapeOptions.preset = lynx::midigen::ShapeOptions::custom;
  5235. song.midiGenerate.stacksOptions.sequence.push_back ({ 4, 3, 67, 1, 1, 0.5f, 2.0f });
  5236. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
  5237. if (! plain || ! plain->midiGenerate.isDefault() || plainJson.contains ("midiGenerate"))
  5238. midigen190fmResult = "ERROR defaults " + why;
  5239. else if (! back || ! (back->midiGenerate == song.midiGenerate))
  5240. midigen190fmResult = "ERROR round trip " + why;
  5241. }
  5242. // round 190gi: audio clip envelopes come back from a project (an entry two clips share stays shared, an unused one
  5243. // is not written, the lane shown, FL's curve modes); a project without them writes neither "clipEnvelopes" nor a
  5244. // clip field 25 (older projects save byte-identical)
  5245. juce::String clipenv190giResult = "OK";
  5246. {
  5247. auto song = lynx::Song::makeDefault();
  5248. lynx::ChannelDef channel;
  5249. channel.instrument = lynx::InstrumentKind::audioClip;
  5250. channel.samplePath = "clipenv190gi.wav";
  5251. song.channels.push_back (channel);
  5252. lynx::Clip clip;
  5253. clip.kind = lynx::ClipKind::audio;
  5254. clip.channel = (int) song.channels.size() - 1;
  5255. clip.length = lynx::ppq * 4;
  5256. song.playlist.push_back (clip);
  5257. juce::String why;
  5258. const auto plainJson = lynx::ProjectFile::toJson (song);
  5259. lynx::ClipEnvelope e;
  5260. e.volume = { { 0, 1.0f, 0.0f, 0 }, { lynx::ppq * 4, 0.25f, 0.3f, 1 } };
  5261. e.pan = { { 0, 0.5f, 0.0f, 0 }, { lynx::ppq * 2, 0.0f, 0.0f, 0 } };
  5262. e.shown = lynx::clipenv::panLane;
  5263. song.clipEnvelopes.emplace_back(); // (no clip uses it: not written)
  5264. song.clipEnvelopes.push_back (e);
  5265. song.playlist.back().envelope = 1;
  5266. auto twin = song.playlist.back();
  5267. twin.start = lynx::ppq * 8;
  5268. song.playlist.push_back (twin);
  5269. const auto json = lynx::ProjectFile::toJson (song);
  5270. const auto back = lynx::ProjectFile::fromJson (json, why);
  5271. if (plainJson.contains ("clipEnvelopes") || ! json.contains ("clipEnvelopes"))
  5272. clipenv190giResult = "ERROR written " + why;
  5273. else if (! back || back->clipEnvelopes.size() != 1 || ! (back->clipEnvelopes[0] == e))
  5274. clipenv190giResult = "ERROR table " + why;
  5275. else
  5276. {
  5277. int withEnvelope = 0;
  5278. for (const auto& c : back->playlist)
  5279. withEnvelope += c.kind == lynx::ClipKind::audio && c.envelope == 0 ? 1 : 0;
  5280. if (withEnvelope != 2)
  5281. clipenv190giResult = "ERROR clips " + why;
  5282. }
  5283. }
  5284. // round 190gx: Beats' law in the .lynx — a new project's channels are Measured; a project saved before the law
  5285. // (no "beatsLaw190gx" mark, or a nine-number warpModes list) loads Classic; a Classic channel stays Classic
  5286. juce::String beatslaw190gxResult = "OK";
  5287. {
  5288. auto song = lynx::Song::makeDefault();
  5289. lynx::ChannelDef channel;
  5290. channel.instrument = lynx::InstrumentKind::audioClip;
  5291. channel.samplePath = "beatslaw190gx.wav";
  5292. channel.sampler.keepPitch = true;
  5293. channel.sampler.stretchMethod = lynx::StretchMethod::beats;
  5294. song.channels.push_back (channel);
  5295. const auto index = song.channels.size() - 1;
  5296. juce::String why;
  5297. const auto json = lynx::ProjectFile::toJson (song);
  5298. const auto lawOf = [&] (const juce::String& text) {
  5299. const auto back = lynx::ProjectFile::fromJson (text, why);
  5300. return back && back->channels.size() > index ? (int) back->channels[index].sampler.warpModes.beatsLaw : -1;
  5301. };
  5302. auto oldVar = juce::JSON::parse (json); // (the mark removed: a project saved before 190gx)
  5303. if (auto* o = oldVar.getDynamicObject())
  5304. o->removeProperty ("beatsLaw190gx");
  5305. const auto old = juce::JSON::toString (oldVar);
  5306. auto classic = song;
  5307. classic.channels[index].sampler.warpModes.beatsLaw = lynx::WarpModeSettings::beatsLawClassic;
  5308. auto nine = song;
  5309. nine.channels[index].sampler.warpModes.beatsLoop = 0; // (a 190fm project with a changed setting: nine numbers)
  5310. // (the list with its tenth number, the law, removed: what a 190fm build wrote)
  5311. auto nineVar = juce::JSON::parse (lynx::ProjectFile::toJson (nine));
  5312. bool trimmed = false;
  5313. if (auto* channels = nineVar.getProperty ("channels", {}).getArray(); channels != nullptr && (int) index < channels->size())
  5314. if (auto* modes = (*channels)[(int) index].getProperty ("samplerSettings", {}).getProperty ("warpModes", {}).getArray(); modes != nullptr && modes->size() == 10)
  5315. {
  5316. modes->removeLast();
  5317. trimmed = true;
  5318. }
  5319. const auto nineJson = juce::JSON::toString (nineVar);
  5320. if (! json.contains ("beatsLaw190gx") || old.contains ("beatsLaw190gx"))
  5321. beatslaw190gxResult = "ERROR mark";
  5322. else if (lawOf (json) != lynx::WarpModeSettings::beatsLawMeasured)
  5323. beatslaw190gxResult = "ERROR new " + why;
  5324. else if (lawOf (old) != lynx::WarpModeSettings::beatsLawClassic)
  5325. beatslaw190gxResult = "ERROR old " + why;
  5326. else if (lawOf (lynx::ProjectFile::toJson (classic)) != lynx::WarpModeSettings::beatsLawClassic)
  5327. beatslaw190gxResult = "ERROR classic kept " + why;
  5328. else if (! trimmed || lawOf (nineJson) != lynx::WarpModeSettings::beatsLawClassic)
  5329. beatslaw190gxResult = "ERROR nine-number list";
  5330. }
  5331. // round 190he (issue #152): a channel window's Scaling is saved with the channel; the default (125 %) writes
  5332. // nothing, so older projects and untouched channels read as before
  5333. juce::String editorScale190heResult = "OK";
  5334. {
  5335. auto song = lynx::Song::makeDefault();
  5336. song.channels[0].editorScale = 100;
  5337. song.channels[1].editorScale = 0;
  5338. juce::String why;
  5339. const auto json = lynx::ProjectFile::toJson (song);
  5340. const auto back = lynx::ProjectFile::fromJson (json, why);
  5341. auto outOfRange = juce::JSON::parse (json);
  5342. if (auto* chans = outOfRange.getProperty ("channels", {}).getArray(); chans != nullptr && ! chans->isEmpty())
  5343. if (auto* o = (*chans)[0].getDynamicObject())
  5344. o->setProperty ("editorScale", 9000);
  5345. const auto clamped = lynx::ProjectFile::fromJson (juce::JSON::toString (outOfRange), why);
  5346. if (! back || back->channels[0].editorScale != 100 || back->channels[1].editorScale != 0)
  5347. editorScale190heResult = "ERROR round trip " + why;
  5348. else if (json.indexOf ("editorScale") != json.lastIndexOf ("editorScale"))
  5349. editorScale190heResult = "ERROR written for a default channel";
  5350. else if (! clamped || clamped->channels[0].editorScale != lynx::editorscale::maxPercent)
  5351. editorScale190heResult = "ERROR not clamped";
  5352. }
  5353. // round 190he (coordinator's gate): a project saved before 190he (no "sfModBase190he") keeps the old 0.5 centre of
  5354. // a Modulation route on a Soundfont knob; a new song, saved and opened again, centres on the knob
  5355. juce::String sfModBase190heResult = "OK";
  5356. {
  5357. auto song = lynx::Song::makeDefault();
  5358. juce::String why;
  5359. const auto json = lynx::ProjectFile::toJson (song);
  5360. auto oldVar = juce::JSON::parse (json);
  5361. if (auto* o = oldVar.getDynamicObject())
  5362. o->removeProperty ("sfModBase190he");
  5363. const auto back = lynx::ProjectFile::fromJson (json, why);
  5364. const auto old = lynx::ProjectFile::fromJson (juce::JSON::toString (oldVar), why);
  5365. auto resaved = old ? lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (*old), why) : std::optional<lynx::Song> {};
  5366. if (! json.contains ("sfModBase190he") || ! back || ! back->soundfontModBaseReal)
  5367. sfModBase190heResult = "ERROR new song " + why;
  5368. else if (! old || old->soundfontModBaseReal)
  5369. sfModBase190heResult = "ERROR old project " + why;
  5370. else if (! resaved || resaved->soundfontModBaseReal)
  5371. sfModBase190heResult = "ERROR old project saved again";
  5372. }
  5373. // round 190dr: the Session mixer's sections come back from a project (a project without them: Live's defaults);
  5374. // a device dragged to another track and a Warp switch are one undo step each in a real engine
  5375. juce::String livescr190drResult = "OK";
  5376. {
  5377. auto song = lynx::Song::makeDefault();
  5378. lynx::launcher::ensureGrid (song);
  5379. juce::String why;
  5380. const auto plain = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
  5381. song.clipGrid->mixerView.io = false;
  5382. song.clipGrid->mixerView.trackOptions = true;
  5383. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
  5384. if (! plain || ! plain->clipGrid || ! (plain->clipGrid->mixerView == lynx::SessionMixerView {}))
  5385. livescr190drResult = "ERROR view defaults " + why;
  5386. else if (! back || ! back->clipGrid || back->clipGrid->mixerView.io || ! back->clipGrid->mixerView.trackOptions || ! back->clipGrid->mixerView.shown)
  5387. livescr190drResult = "ERROR view round trip " + why;
  5388. lynx::AudioEngine e (false);
  5389. e.editSong ([] (lynx::Song& s) {
  5390. if (s.mixer.size() < 4)
  5391. s.mixer.resize (4);
  5392. s.mixer[2].effects.clear();
  5393. s.mixer[3].effects.clear();
  5394. for (auto kind : { lynx::EffectKind::eq, lynx::EffectKind::compressor })
  5395. {
  5396. lynx::EffectSlot fx;
  5397. fx.kind = kind;
  5398. s.mixer[2].effects.push_back (fx);
  5399. }
  5400. lynx::Automation a;
  5401. a.target = { lynx::AutomationTargetKind::effectMix, 2, 1, 0 };
  5402. s.automations.push_back (a);
  5403. }, false);
  5404. const auto id = e.getSong().mixer[2].effects[1].instance.id;
  5405. const auto automations = e.getSong().automations.size();
  5406. e.editSongStructural ([] (lynx::Song& s) { lynx::detailchain::moveEffectToInsert (s, 2, 1, 3, false); });
  5407. const auto& moved = e.getSong();
  5408. if (livescr190drResult == "OK"
  5409. && (moved.mixer[2].effects.size() != 1 || moved.mixer[3].effects.size() != 1 || moved.mixer[3].effects[0].instance.id != id
  5410. || moved.automations.size() != automations || moved.automations.back().target.index != 3 || moved.automations.back().target.slot != 0))
  5411. livescr190drResult = "ERROR device move";
  5412. e.undo();
  5413. const auto& undone = e.getSong();
  5414. if (livescr190drResult == "OK"
  5415. && (undone.mixer[2].effects.size() != 2 || undone.mixer[3].effects.size() != 0 || undone.mixer[2].effects[1].instance.id != id
  5416. || undone.automations.back().target.index != 2 || undone.automations.back().target.slot != 1))
  5417. livescr190drResult = "ERROR device move undo";
  5418. e.editSong ([] (lynx::Song& s) {
  5419. s.channels.resize (std::max<std::size_t> (s.channels.size(), 1));
  5420. s.channels[0].sampler.stretchBeats = 16.0f;
  5421. lynx::Clip c;
  5422. c.kind = lynx::ClipKind::audio;
  5423. c.channel = 0;
  5424. c.offset = 4 * lynx::ppq;
  5425. c.length = 8 * lynx::ppq;
  5426. lynx::launcher::setClip (s, 0, 0, c);
  5427. }, false);
  5428. e.editSong ([] (lynx::Song& s) { lynx::clipsample::setWarp (s, 0, false, 4.0); });
  5429. const auto* off = e.getSong().clipGrid ? lynx::launcher::clipAt (*e.getSong().clipGrid, 0, 0) : nullptr;
  5430. 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)))
  5431. livescr190drResult = "ERROR warp off";
  5432. e.undo();
  5433. const auto* on = e.getSong().clipGrid ? lynx::launcher::clipAt (*e.getSong().clipGrid, 0, 0) : nullptr;
  5434. if (livescr190drResult == "OK" && (e.getSong().channels[0].sampler.stretchBeats != 16.0f || on == nullptr || on->length != 8 * lynx::ppq))
  5435. livescr190drResult = "ERROR warp undo";
  5436. }
  5437. // round 190ef: the map modes' storage (.lynx round trip of key / MIDI mappings and a link's Min / Max; an older
  5438. // reader keeps the plain link), and in a real engine: a link's range, MIDI Map Mode catching the control instead
  5439. // of moving anything, a slot's MIDI mapping firing on its press and release
  5440. juce::String livewf190efResult = "OK";
  5441. {
  5442. using namespace lynx::remotemap;
  5443. auto song = lynx::Song::makeDefault();
  5444. lynx::launcher::ensureGrid (song);
  5445. const lynx::AutomationTarget vol { lynx::AutomationTargetKind::mixerVolume, 1, 0, 0 };
  5446. assignMidi (song, Target::parameter (vol), { 0, 20, -1 });
  5447. assignMidi (song, Target::slot (0, 0), { 0, lynx::linkNoteBase + 36, 2 });
  5448. assignKey (song, Target::sceneLaunch (0), 'S');
  5449. assignKey (song, Target::parameter ({ lynx::AutomationTargetKind::tempo, 0, 0, 0 }), 'T');
  5450. setRange (song, rows (song, Mode::midi)[0], 0.25f, 0.75f);
  5451. setRange (song, rows (song, Mode::key)[1], 0.9f, 0.1f);
  5452. juce::String why;
  5453. const auto json = lynx::ProjectFile::toJson (song);
  5454. const auto back = lynx::ProjectFile::fromJson (json, why);
  5455. if (! back || back->remoteMappings != song.remoteMappings || back->midiLinks != song.midiLinks)
  5456. livewf190efResult = "ERROR round trip " + why;
  5457. auto parsed = juce::JSON::parse (json);
  5458. if (auto* o = parsed.getDynamicObject())
  5459. {
  5460. o->removeProperty ("remoteMappings");
  5461. o->removeProperty ("midiLinkSettings");
  5462. }
  5463. const auto older = lynx::ProjectFile::fromJson (juce::JSON::toString (parsed), why);
  5464. if (livewf190efResult == "OK" && (! older || ! older->remoteMappings.empty() || older->midiLinks.size() != 1 || older->midiLinks[0].max != 1.0f))
  5465. livewf190efResult = "ERROR older reader";
  5466. const auto plain = lynx::ProjectFile::toJson (lynx::Song::makeDefault());
  5467. if (livewf190efResult == "OK" && plain.contains ("remoteMappings"))
  5468. livewf190efResult = "ERROR written without mappings";
  5469. lynx::AudioEngine e (false);
  5470. e.editSong ([vol] (lynx::Song& s) {
  5471. if (s.mixer.size() < 3)
  5472. s.mixer.resize (3);
  5473. lynx::MidiLink l { 20, 0, vol };
  5474. l.min = 0.25f;
  5475. l.max = 0.75f;
  5476. s.midiLinks = { l };
  5477. lynx::launcher::ensureGrid (s);
  5478. assignMidi (s, Target::slot (0, 0), { 0, 21, -1 });
  5479. });
  5480. e.injectControllerForTest (20, 0, 127);
  5481. const auto top = e.currentTargetValue (vol);
  5482. e.injectControllerForTest (20, 0, 0);
  5483. const auto bottom = e.currentTargetValue (vol);
  5484. if (livewf190efResult == "OK" && (std::abs (top - 0.75f) > 0.01f || std::abs (bottom - 0.25f) > 0.01f))
  5485. livewf190efResult = "ERROR range " + juce::String (bottom) + " " + juce::String (top);
  5486. std::vector<Fire> fired;
  5487. e.onRemoteFire = [&fired] (const Fire& f) { fired.push_back (f); };
  5488. e.injectControllerForTest (21, 0, 127);
  5489. e.injectControllerForTest (21, 0, 127); // (still down: no new press)
  5490. e.injectControllerForTest (21, 0, 0);
  5491. if (livewf190efResult == "OK"
  5492. && (fired.size() != 2 || fired[0].edge != Edge::press || fired[1].edge != Edge::release || ! (fired[0].target == Target::slot (0, 0))))
  5493. livewf190efResult = "ERROR slot fire " + juce::String ((int) fired.size());
  5494. e.setMapMode (Mode::midi);
  5495. fired.clear();
  5496. e.injectControllerForTest (20, 0, 127);
  5497. e.injectControllerForTest (21, 0, 127);
  5498. const auto caught = e.takeMapCapture();
  5499. if (livewf190efResult == "OK" && (std::abs (e.currentTargetValue (vol) - 0.25f) > 0.01f || ! fired.empty()))
  5500. livewf190efResult = "ERROR mappings acted in MIDI Map Mode";
  5501. else if (livewf190efResult == "OK" && (! caught || caught->number != 21 || caught->channel != 0 || e.takeMapCapture().has_value()))
  5502. livewf190efResult = "ERROR map capture";
  5503. e.setMapMode (Mode::off);
  5504. e.onRemoteFire = nullptr;
  5505. }
  5506. // round 190em: a scene's time signature denominator (.lynx round trip; an older file without it reads n/4; a
  5507. // 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
  5508. // armed track, the selected scene's slot, the tempo from a phrase played while stopped (8 notes at 148 BPM), the
  5509. // new clip launched and the transport started
  5510. juce::String livewf190emResult = "OK";
  5511. {
  5512. auto song = lynx::Song::makeDefault();
  5513. auto& grid = lynx::launcher::ensureGrid (song);
  5514. grid.scenes.resize (3);
  5515. lynx::session::setSceneSignature (song, 1, 6, 8);
  5516. lynx::session::setSceneTempo (song, 1, 100.0);
  5517. juce::String why;
  5518. const auto json = lynx::ProjectFile::toJson (song);
  5519. const auto back = lynx::ProjectFile::fromJson (json, why);
  5520. if (! back || ! back->clipGrid || back->clipGrid->scenes != song.clipGrid->scenes || back->clipGrid->scenes[1].beatUnit != 8)
  5521. livewf190emResult = "ERROR round trip " + why;
  5522. {
  5523. // a captured clip's blank label (ClipGridSlot::blankName) survives the round trip
  5524. auto withClip = song;
  5525. lynx::Clip c;
  5526. c.pattern = 0;
  5527. c.length = 4 * lynx::ppq;
  5528. if (withClip.patterns.empty())
  5529. withClip.patterns.emplace_back();
  5530. const auto slot = lynx::launcher::setClip (withClip, 0, 0, c);
  5531. if (slot >= 0)
  5532. withClip.clipGrid->slots[(std::size_t) slot].blankName = true;
  5533. const auto again = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (withClip), why);
  5534. const auto* keptClip = again && again->clipGrid ? lynx::launcher::clipAt (*again->clipGrid, 0, 0) : nullptr;
  5535. const auto* kept = keptClip != nullptr ? &again->clipGrid->slots[(std::size_t) keptClip->gridSlot] : nullptr;
  5536. if (livewf190emResult == "OK" && (slot < 0 || kept == nullptr || ! kept->blankName))
  5537. livewf190emResult = "ERROR blank clip name round trip";
  5538. }
  5539. auto parsed = juce::JSON::parse (json);
  5540. if (auto* scenes = parsed.getProperty ("clipGrid", {}).getProperty ("scenes", {}).getArray(); scenes != nullptr && scenes->size() > 1)
  5541. if (auto* o = (*scenes)[1].getDynamicObject())
  5542. o->removeProperty ("beatUnit");
  5543. const auto older = lynx::ProjectFile::fromJson (juce::JSON::toString (parsed), why);
  5544. if (livewf190emResult == "OK" && (! older || ! older->clipGrid || older->clipGrid->scenes.size() < 2 || older->clipGrid->scenes[1].beatUnit != 4
  5545. || older->clipGrid->scenes[1].beatsPerBar != 6))
  5546. livewf190emResult = "ERROR older reader";
  5547. if (livewf190emResult == "OK" && lynx::ProjectFile::toJson (lynx::Song::makeDefault()).contains ("beatUnit"))
  5548. livewf190emResult = "ERROR beatUnit written by default";
  5549. // round 190fg: the song meter's denominator round-trips through .lynx; a file without it reads n/4
  5550. {
  5551. auto six = lynx::Song::makeDefault();
  5552. six.beatsPerBar = 6;
  5553. six.beatUnit = 8;
  5554. const auto text = lynx::ProjectFile::toJson (six);
  5555. juce::String why2;
  5556. const auto back = lynx::ProjectFile::fromJson (text, why2);
  5557. auto json = juce::JSON::parse (text);
  5558. if (auto* o = json.getDynamicObject())
  5559. o->removeProperty ("beatUnit");
  5560. const auto old = lynx::ProjectFile::fromJson (juce::JSON::toString (json), why2);
  5561. if (livewf190emResult == "OK" && (! back || back->beatsPerBar != 6 || back->beatUnit != 8 || ! old || old->beatsPerBar != 6 || old->beatUnit != 4))
  5562. livewf190emResult = "ERROR song meter round trip";
  5563. }
  5564. lynx::AudioEngine e (false);
  5565. e.editSong ([] (lynx::Song& s) {
  5566. s.bpm = 120.0;
  5567. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 4));
  5568. auto& g = lynx::launcher::ensureGrid (s);
  5569. g.scenes.resize (3);
  5570. lynx::session::setSceneSignature (s, 2, 6, 8);
  5571. lynx::session::setSceneTempo (s, 2, 90.0);
  5572. }, false);
  5573. e.launcherCommand ({ lynx::launcher::Command::Type::launchScene, 0, 2 });
  5574. // (round 190fg: the song takes the scene's 6 / 8 as it is: six eighths a bar, 3 quarters long)
  5575. if (livewf190emResult == "OK" && (e.getSong().beatsPerBar != 6 || e.getSong().beatUnit != 8 || e.getSong().barTicks() != 3 * lynx::ppq
  5576. || e.getSong().bpm != 90.0))
  5577. livewf190emResult = "ERROR scene launch " + juce::String (e.getSong().beatsPerBar) + "/" + juce::String (e.getSong().beatUnit) + " "
  5578. + juce::String (e.getSong().bpm);
  5579. e.stop();
  5580. e.editSong ([] (lynx::Song& s) {
  5581. s.bpm = 120.0;
  5582. s.beatsPerBar = 4;
  5583. s.beatUnit = 4;
  5584. }, false);
  5585. e.setGridTrackArmed (2, true, true);
  5586. const auto now = juce::Time::getMillisecondCounterHiRes();
  5587. const auto beat = 60000.0 / 148.0;
  5588. for (int i = 0; i < 8; ++i)
  5589. {
  5590. const auto at = now - 9.0 * beat + i * beat;
  5591. e.logPlayedNoteForTest (at, 0, 60 + (i % 4) * 2, 0.8f, true);
  5592. e.logPlayedNoteForTest (at + beat * 0.5, 0, 60 + (i % 4) * 2, 0.8f, false);
  5593. }
  5594. int placed = -1;
  5595. bool into = true;
  5596. const auto r = e.captureMidiToSlot (2, 1, placed, into);
  5597. const auto& g = *e.getSong().clipGrid;
  5598. const auto* clip = lynx::launcher::clipAt (g, 2, 1);
  5599. if (livewf190emResult == "OK" && (r.notes != 8 || placed != 1 || into || clip == nullptr || clip->length != 8 * lynx::ppq))
  5600. livewf190emResult = "ERROR capture " + juce::String (r.notes) + " " + juce::String (placed) + (clip == nullptr ? " no clip" : " " + juce::String ((int) clip->length));
  5601. else if (livewf190emResult == "OK" && std::abs (e.getSong().bpm - 148.0) > 0.5)
  5602. livewf190emResult = "ERROR tempo " + juce::String (e.getSong().bpm, 2);
  5603. else if (livewf190emResult == "OK" && ! e.getTransport().playing.load())
  5604. livewf190emResult = "ERROR the capture did not start the transport";
  5605. e.stop();
  5606. }
  5607. const auto mixerBasics = lynx::mixerbasics::run();
  5608. // issue #142: every font has a typeface, and one without does not crash (fonts get theirs through the
  5609. // look and feel, as in the app)
  5610. auto& lookBefore = juce::LookAndFeel::getDefaultLookAndFeel();
  5611. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  5612. const auto fontsResult = lynx::theme::fontSelfTest();
  5613. const auto paintCachesResult = lynx::theme::paintCacheSelfTest(); // (round 190gr)
  5614. // round 190bm (0.1.25 showed the Mixer and the Playlist black): their cached pictures shown on native and
  5615. // software targets against straight paints (ui/PictureCheck.h; --picturetest runs more sizes and scales)
  5616. juce::String picturesResult = "OK";
  5617. {
  5618. lynx::AudioEngine pictureEngine (false);
  5619. auto pictureFailures = 0;
  5620. juce::String lines;
  5621. {
  5622. lynx::PlaylistComponent playlist (pictureEngine);
  5623. playlist.setBounds (0, 0, 1200, 700);
  5624. playlist.setVisible (true);
  5625. lines << lynx::ui::picturecheck::run (playlist, "Playlist 1200 x 700", { 1.0f, 1.5f }, pictureFailures, {});
  5626. }
  5627. {
  5628. lynx::MixerComponent mixer (pictureEngine);
  5629. mixer.setBounds (0, 0, 1200, 500);
  5630. mixer.setVisible (true);
  5631. lines << lynx::ui::picturecheck::run (mixer, "Mixer 1200 x 500", { 1.0f, 1.5f }, pictureFailures, {});
  5632. }
  5633. if (pictureFailures > 0 || ! lines.contains (": ok"))
  5634. picturesResult = "ERROR " + lines.trim().replace ("\n", "; ");
  5635. }
  5636. // round 190ci (the 0.1.26 release candidate ended when an FPC channel was added): every built-in generator and
  5637. // effect, its editor built as the Channel Rack / mixer opens it and painted once. The report file names the
  5638. // plugin being opened, so a run that dies there says which one.
  5639. const auto editorsResult = lynx::pluginthumbs::checkEditors ([&reportPath] (const juce::String& key) {
  5640. if (reportPath.isNotEmpty())
  5641. juce::File (reportPath).replaceWithText ("(opening the editor of " + key + ")\n");
  5642. });
  5643. // round 190ci: a fault leaves a crash file, also on a stack Windows cannot walk (that FPC fault left none)
  5644. const auto faultResult = faultReportSelfTest();
  5645. const auto stemsResult = stemsSinglePassSelfTest(); // round 190gj
  5646. juce::LookAndFeel::setDefaultLookAndFeel (&lookBefore);
  5647. const auto ok = editorsResult.startsWith ("OK") && ! faultResult.startsWith ("ERROR") && stemsResult == "OK"
  5648. && mixerBasics == "OK" && fontsResult == "OK" && paintCachesResult.startsWith ("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
  5649. && sessionResult == "OK" && liveResult.startsWith ("OK")
  5650. && wavpack != "ERROR" && effectsOk && driverPanel == "OK" && deviceChange.startsWith ("OK") && exportParity.startsWith ("OK") && midiHotplug.startsWith ("OK") && metronomeOk && artResult == "OK" && effectParamsResult == "OK"
  5651. && sidechainResult == "OK" && lanesResult == "OK" && arrange190cgResult == "OK" && livescr190drResult == "OK" && livewf190efResult == "OK" && livewf190emResult == "OK" && versionsResult == "OK" && pluginsOffResult == "OK" && missingFilesResult == "OK"
  5652. && midigen190fmResult == "OK" && clipenv190giResult == "OK" && beatslaw190gxResult == "OK" && editorScale190heResult == "OK" && sfModBase190heResult == "OK" && trackauto190gzResult == "OK"
  5653. && remoteHistoryResult.startsWith ("OK") && hostedStateLockResult.startsWith ("OK")
  5654. && hostedStateContentionResult.startsWith ("OK")
  5655. && danceWindowResult == "OK" && clickActivationResult == "OK";
  5656. juce::String report;
  5657. report << "connections=" << offline.getNumGraphConnections() << "\n"
  5658. << "peak=" << peak << "\n"
  5659. << "stems_single_pass=" << stemsResult << "\n"
  5660. << "project=" << (projectOk ? "OK" : "ERROR " + error) << "\n"
  5661. << "playlist_track_modes_roundtrip=" << (trackModes122Ok ? "OK" : "ERROR") << "\n"
  5662. << "project_features=" << (richOk ? "OK" : "ERROR") << "\n"
  5663. << "hardware_outputs=" << (hwOutOk ? "OK" : "ERROR") << "\n"
  5664. << "plugin_host_keys_option=" << (hostKeysOk ? "OK" : "ERROR") << "\n"
  5665. << "plugin_levels_new_project=" << (pluginLevelsOk ? "OK" : "ERROR") << "\n"
  5666. << "flp168j_fields=" << (flp168jOk ? "OK" : "ERROR") << "\n"
  5667. << "clip_fades_180d=" << (clipFades180dOk ? "OK" : "ERROR") << "\n"
  5668. << "pattern_blocks=" << (blocksOk ? "OK" : "ERROR") << "\n"
  5669. << "pattern_clip_takeover=" << (takeoverOk ? "OK" : "ERROR") << "\n"
  5670. << "comp_crossfades=" << (compOk ? "OK" : "ERROR") << "\n"
  5671. << "channel_polyphony=" << (polyOk ? "OK" : "ERROR") << "\n"
  5672. << "track_latency=" << (latencyOk ? "OK" : "ERROR") << "\n"
  5673. << "pre_fader_sends=" << (preSendOk ? "OK" : "ERROR") << "\n"
  5674. << "low_latency_recording=" << (lowLatencyOk ? "OK" : "ERROR") << "\n"
  5675. << "preview_in_time=" << (previewInTimeOk ? "OK" : "ERROR") << " (2 s loop prepared in " << juce::String (previewPrepareMs, 1) << " ms)\n"
  5676. << "plugin_substitutes=" << (substituteOk ? "OK" : "ERROR") << "\n"
  5677. << "patcher=" << (patcherOk ? "OK" : "ERROR") << "\n"
  5678. << "racks=" << rackResult << "\n"
  5679. << "native_engines=" << nativesResult << " (" << nativesMade << " made)\n"
  5680. << "undo=" << (undoOk ? "OK" : "ERROR") << "\n"
  5681. << "mixer_basics=" << mixerBasics << "\n"
  5682. << "remote_history=" << remoteHistoryResult << "\n"
  5683. << "hosted_state_lock=" << hostedStateLockResult << "\n"
  5684. << "hosted_state_contention=" << hostedStateContentionResult << "\n"
  5685. << "fonts=" << fontsResult << "\n"
  5686. << "paint_caches=" << paintCachesResult << "\n"
  5687. << "cached_pictures=" << picturesResult << "\n"
  5688. << "plugin_editors=" << editorsResult << "\n"
  5689. << "fault_report=" << faultResult << "\n"
  5690. << "recording=" << (recordOk && recordUndoOk ? "OK" : "ERROR") << "\n"
  5691. << "cancel_recording=" << (cancelRecordOk ? "OK" : "ERROR") << "\n"
  5692. << "midi=" << (midiOk ? "OK" : "ERROR") << "\n"
  5693. << "package=" << (packageOk ? "OK" : "ERROR") << "\n"
  5694. << "projectSave=" << (projectSaveOk ? "OK" : "ERROR") << "\n"
  5695. << "online_session=" << sessionResult << "\n"
  5696. << "live_session=" << liveResult << "\n"
  5697. << "wavpack=" << wavpack << "\n"
  5698. << "effects=" << (effectsOk ? "OK" : "NONFINITE") << "\n"
  5699. << "effect_params_saved=" << effectParamsResult << "\n"
  5700. << "driver_panel=" << driverPanel << "\n"
  5701. << "device_change=" << deviceChange << "\n"
  5702. << "export_parity=" << exportParity << "\n"
  5703. << "midi_hotplug=" << midiHotplug << "\n"
  5704. << "plugin_art=" << artResult << "\n"
  5705. << "plugin_sidechain=" << sidechainResult << "\n"
  5706. << "versions_panel=" << versionsResult << "\n"
  5707. << "plugins_off=" << pluginsOffResult << "\n"
  5708. << "missing_files_rows=" << missingFilesResult << "\n"
  5709. << "dance_window=" << danceWindowResult << "\n"
  5710. << "dance_window_detail=" << danceWindowDetail << "\n"
  5711. << "click_activation=" << clickActivationResult << "\n"
  5712. << "lanes_saved=" << lanesResult << "\n"
  5713. << "arrange190cg_saved=" << arrange190cgResult << "\n"
  5714. << "livescr190dr=" << livescr190drResult << "\n"
  5715. << "livewf190ef=" << livewf190efResult << "\n"
  5716. << "livewf190em=" << livewf190emResult << "\n"
  5717. << "midigen190fm_saved=" << midigen190fmResult << "\n"
  5718. << "trackauto190gz_saved=" << trackauto190gzResult << "\n"
  5719. << "clipenv190gi_saved=" << clipenv190giResult << "\n"
  5720. << "beatslaw190gx_saved=" << beatslaw190gxResult << "\n"
  5721. << "editor_scale190he_saved=" << editorScale190heResult << "\n"
  5722. << "sf_mod_base190he=" << sfModBase190heResult << "\n"
  5723. << "metronome=" << metronomeResult << " (FL sounds " << metronomeFlSounds << "/" << lynx::metronome::soundCount
  5724. << ", downbeat peak " << juce::String (metronomeMaster, 4) << ")\n";
  5725. // issue #138 (round 190c): a short note at the very start of the Playlist against the same note at bar 2, through
  5726. // the Export window's path (its own thread while the message loop runs: the report is finished from there)
  5727. if (reportPath.isNotEmpty())
  5728. juce::File (reportPath).replaceWithText (report + "(short_export running)\n");
  5729. lynx::shortexport::run (false, 1, {}, {}, [this, report, ok, reportPath] (juce::String shortExport) {
  5730. const auto all = ok && shortExport.startsWith ("OK");
  5731. const auto text = report + "short_export=" + shortExport + "\nresult=" + (all ? "OK" : "FAILED") + "\n";
  5732. if (reportPath.isNotEmpty())
  5733. juce::File (reportPath).replaceWithText (text);
  5734. setApplicationReturnValue (all ? 0 : 1);
  5735. quit();
  5736. });
  5737. }
  5738. // Every built-in effect in its native editor: random / extreme parameters, mouse drags over the editor, the editor
  5739. // painted, audio rendered at 44.1 / 48 / 96 kHz. Returns false when an effect output NaN / inf (muted by the
  5740. // renderer's guard). The report lists each effect. Used by --fxfuzz and (a short run) by --selftest.
  5741. bool runEffectFuzz (int rounds, const juce::String& reportPath, bool drags = false)
  5742. {
  5743. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  5744. lynx::setNativeEditorDemo (true);
  5745. juce::String report;
  5746. auto allFinite = true;
  5747. {
  5748. lynx::AudioEngine offline (false);
  5749. juce::Random random (111);
  5750. const auto value = [&] { const auto r = random.nextInt (6); return r == 0 ? 0.0f : r == 1 ? 1.0f : random.nextFloat(); };
  5751. for (int k = 0; k <= (int) lynx::lastEffectKind; ++k)
  5752. {
  5753. const auto kind = (lynx::EffectKind) k;
  5754. if (! lynx::NativeEffectWindows::canOpen (kind) || kind == lynx::EffectKind::patcher) // (the Patcher's editor is a graph window)
  5755. continue;
  5756. const auto before = lynx::RackRenderer::nonFiniteEffectBlocks();
  5757. const auto& info = lynx::effectInfo (kind);
  5758. // (FL engines: a fresh instance as the menus make it, from the user's FL installation; round 142)
  5759. auto fx = lynx::natives::newEffect (kind, lynx::flStudioAccess()).value_or (lynx::makeEffectSlot (kind));
  5760. int dragged = 0; // parameter changes made by the mouse drags
  5761. for (int round = 0; round < rounds; ++round)
  5762. {
  5763. if (round > 0)
  5764. for (std::size_t p = 0; p < info.params.size(); ++p)
  5765. fx.params[p] = round == 1 ? 0.0f : round == 2 ? 1.0f : value();
  5766. auto song = lynx::Song::makeDefault(); // its demo beat feeds the effect
  5767. song.mixer.resize (2);
  5768. song.mixer[0].name = "Master";
  5769. song.mixer[1].name = "Insert 1";
  5770. song.mixer[1].effects.assign (1, fx);
  5771. for (auto& channel : song.channels)
  5772. channel.mixerTrack = 1;
  5773. offline.setSong (std::move (song));
  5774. offline.dispatchPendingMessages();
  5775. const auto pages = juce::jmax (1, (int) lynx::plugui::layoutFor (kind).pages.size());
  5776. for (int page = 0; page < pages; ++page)
  5777. {
  5778. auto editor = kind == lynx::EffectKind::facetEq ? lynx::makeFacetEqEditor (offline, 1, 0, false)
  5779. : lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, page);
  5780. if (editor == nullptr || editor->getWidth() <= 0 || editor->getHeight() <= 0)
  5781. continue;
  5782. juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
  5783. const auto paint = [&] {
  5784. juce::Graphics g (image);
  5785. editor->paintEntireComponent (g, false);
  5786. };
  5787. paint();
  5788. // drags from a grid of points, as a user moving every control (plain left button)
  5789. if (round >= 3 && drags)
  5790. {
  5791. const auto source = juce::Desktop::getInstance().getMainMouseSource();
  5792. const auto step = juce::jmax (12, juce::jmin (editor->getWidth(), editor->getHeight()) / 8);
  5793. for (int y = step / 2; y < editor->getHeight(); y += step)
  5794. for (int x = step / 2; x < editor->getWidth(); x += step)
  5795. {
  5796. auto* target = editor->getComponentAt (x, y);
  5797. if (target == nullptr)
  5798. continue;
  5799. const auto at = target->getLocalPoint (editor.get(), juce::Point<float> ((float) x, (float) y));
  5800. const auto now = juce::Time::getCurrentTime();
  5801. const auto event = [&] (juce::Point<float> p, juce::ModifierKeys mods) {
  5802. return juce::MouseEvent (source, p, mods, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, target, target, now, at, now, 1, false);
  5803. };
  5804. const auto down = juce::ModifierKeys (juce::ModifierKeys::leftButtonModifier);
  5805. const juce::Component::SafePointer<juce::Component> alive (target);
  5806. target->mouseDown (event (at, down));
  5807. const auto dy = (float) (random.nextBool() ? 400 : -400), dx = (float) (random.nextInt (401) - 200);
  5808. if (alive != nullptr)
  5809. target->mouseDrag (event (at + juce::Point<float> (dx * 0.5f, dy * 0.5f), down));
  5810. if (alive != nullptr)
  5811. target->mouseDrag (event (at + juce::Point<float> (dx, dy), down));
  5812. if (alive != nullptr)
  5813. target->mouseUp (event (at + juce::Point<float> (dx, dy), juce::ModifierKeys()));
  5814. juce::PopupMenu::dismissAllActiveMenus();
  5815. offline.dispatchPendingMessages();
  5816. }
  5817. paint();
  5818. }
  5819. }
  5820. for (const auto rate : { 44100.0, 48000.0, 96000.0 })
  5821. offline.renderOffline (0.05, rate);
  5822. if (round == 0 || round >= 3) // keep what the drags set for the next round
  5823. if (offline.getSong().mixer.size() > 1 && ! offline.getSong().mixer[1].effects.empty())
  5824. {
  5825. const auto& now = offline.getSong().mixer[1].effects[0];
  5826. for (std::size_t p = 0; p < fx.params.size(); ++p)
  5827. dragged += now.params[p] != fx.params[p] ? 1 : 0;
  5828. dragged += now.state != fx.state ? 1 : 0;
  5829. fx = now;
  5830. }
  5831. }
  5832. const auto broken = lynx::RackRenderer::nonFiniteEffectBlocks() - before;
  5833. allFinite = allFinite && broken == 0;
  5834. report << info.name << ": " << (broken == 0 ? juce::String ("OK") : "non-finite output in " + juce::String ((juce::int64) broken) + " blocks")
  5835. << " (" << dragged << " changes by mouse)\n";
  5836. if (reportPath.isNotEmpty())
  5837. juce::File (reportPath).replaceWithText (report + "(running)\n"); // what was reached, if it crashes
  5838. }
  5839. }
  5840. lynx::setNativeEditorDemo (false);
  5841. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  5842. report << "result=" << (allFinite ? "OK" : "NONFINITE") << "\n";
  5843. if (reportPath.isNotEmpty())
  5844. juce::File (reportPath).replaceWithText (report);
  5845. return allFinite;
  5846. }
  5847. // --opentest (round 157a): see the command line. Runs on the message loop (the editors' timers, animations and
  5848. // native windows are real); one step per timer tick.
  5849. void runOpenTest (const juce::String& reportPath, bool visible, std::function<void (bool)> done)
  5850. {
  5851. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  5852. struct OpenTest final : juce::Timer
  5853. {
  5854. juce::String reportPath, report;
  5855. bool visible = false, ok = true;
  5856. std::function<void (bool)> done;
  5857. std::unique_ptr<lynx::AudioEngine> engine;
  5858. std::vector<std::pair<juce::String, std::function<void()>>> steps;
  5859. std::size_t next = 0;
  5860. std::atomic<std::int64_t> lastStep { 0 };
  5861. std::atomic<bool> finished { false };
  5862. std::thread watchdog;
  5863. juce::String current;
  5864. std::mutex currentLock;
  5865. int opened = 0, painted = 0;
  5866. // LYNX_OPENTEST_TIMEOUT (seconds): longer for sanitizer builds
  5867. const std::int64_t timeoutMs = 1000 * juce::jmax (5, juce::SystemStats::getEnvironmentVariable ("LYNX_OPENTEST_TIMEOUT", "20").getIntValue());
  5868. static std::int64_t now() { return (std::int64_t) juce::Time::getMillisecondCounter(); }
  5869. void write (const juce::String& tail = {}) { juce::File (reportPath).replaceWithText (report + tail); }
  5870. ~OpenTest() override
  5871. {
  5872. finished = true;
  5873. if (watchdog.joinable())
  5874. watchdog.join();
  5875. }
  5876. void start()
  5877. {
  5878. lastStep = now();
  5879. // the UI hang watch runs during the whole test (5 s): a slow step leaves its stack next to the report
  5880. const auto folder = juce::File (reportPath).getParentDirectory().getChildFile ("opentest-hang");
  5881. folder.deleteRecursively();
  5882. folder.createDirectory();
  5883. lynx::crashguard::startHangWatch (folder.getFullPathName().replaceCharacter ('\\', '/').toStdString(), 5000);
  5884. watchdog = std::thread ([this] {
  5885. while (! finished)
  5886. {
  5887. std::this_thread::sleep_for (std::chrono::milliseconds (200));
  5888. if (now() - lastStep.load() > timeoutMs)
  5889. {
  5890. juce::String at;
  5891. {
  5892. const std::lock_guard<std::mutex> l (currentLock);
  5893. at = current;
  5894. }
  5895. juce::File (reportPath).replaceWithText (report + "HANG at " + at + " (no progress for " + juce::String (timeoutMs / 1000) + " s; stack in opentest-hang)\nresult=HANG\n");
  5896. lynx::crashguard::exitNow (3);
  5897. }
  5898. }
  5899. });
  5900. startTimer (30);
  5901. }
  5902. // every LYNX window but none of the main one (there is none here): moved off-screen, painted once into an image
  5903. void touchWindows (bool resize, bool large)
  5904. {
  5905. auto& desktop = juce::Desktop::getInstance();
  5906. for (int i = desktop.getNumComponents(); --i >= 0;)
  5907. if (auto* c = desktop.getComponent (i); c != nullptr && c->isVisible())
  5908. {
  5909. if (! visible && c->getScreenX() > -3000)
  5910. c->setTopLeftPosition (-6000, -6000);
  5911. if (resize)
  5912. if (auto* w = dynamic_cast<juce::ResizableWindow*> (c))
  5913. {
  5914. const auto b = w->getBounds();
  5915. w->setSize (large ? b.getWidth() * 2 : juce::jmax (40, b.getWidth() / 3), large ? b.getHeight() * 2 : juce::jmax (40, b.getHeight() / 3));
  5916. }
  5917. if (c->getWidth() > 0 && c->getHeight() > 0 && c->getWidth() < 8000 && c->getHeight() < 8000)
  5918. {
  5919. juce::Image image (juce::Image::ARGB, c->getWidth(), c->getHeight(), true);
  5920. juce::Graphics g (image);
  5921. c->paintEntireComponent (g, false);
  5922. ++painted;
  5923. // LYNX_OPENTEST_SHOTS=folder: each window as first painted (before the resizes), for a look
  5924. if (const auto shots = juce::SystemStats::getEnvironmentVariable ("LYNX_OPENTEST_SHOTS", {}); shots.isNotEmpty() && ! resize)
  5925. {
  5926. juce::FileOutputStream out (juce::File (shots).getChildFile (juce::String (painted).paddedLeft ('0', 4) + ".png"));
  5927. if (out.openedOk())
  5928. {
  5929. out.setPosition (0), out.truncate();
  5930. juce::PNGImageFormat().writeImageToStream (c->createComponentSnapshot (c->getLocalBounds()), out);
  5931. }
  5932. }
  5933. }
  5934. }
  5935. }
  5936. void timerCallback() override
  5937. {
  5938. if (next >= steps.size())
  5939. {
  5940. stopTimer();
  5941. lynx::NativeEffectWindows::closeAll();
  5942. lynx::closeChannelSettings();
  5943. // the UI hang watch itself: the message thread spins past the stall time; the watcher must write the stack
  5944. {
  5945. const auto before = lynx::crashguard::lastHangFile();
  5946. for (const auto until = now() + 7000; now() < until;)
  5947. lastStep = now(); // (busy: no heartbeat; the test's own watchdog stays quiet)
  5948. for (const auto until = now() + 1500; now() < until && lynx::crashguard::lastHangFile() == before;)
  5949. std::this_thread::sleep_for (std::chrono::milliseconds (20));
  5950. lynx::crashguard::stopHangWatch();
  5951. const juce::File hang (juce::String::fromUTF8 (lynx::crashguard::lastHangFile().c_str()));
  5952. const auto text = hang.loadFileAsString();
  5953. const auto frames = juce::StringArray::fromLines (text).size() - 2;
  5954. #if JUCE_WINDOWS
  5955. const auto hangOk = lynx::crashguard::lastHangFile() != before && hang.existsAsFile() && text.contains ("LYNX.exe+0x") && frames >= 3;
  5956. #else
  5957. const auto hangOk = lynx::crashguard::lastHangFile() != before && hang.existsAsFile() && frames >= 3;
  5958. #endif
  5959. report << "hang watch: " << (hangOk ? "OK" : "FAIL") << " (" << hang.getFileName() << ", " << frames << " lines"
  5960. << (before.empty() ? juce::String() : "; a step stalled > 5 s earlier: " + juce::String::fromUTF8 (before.c_str())) << ")\n";
  5961. ok = ok && hangOk;
  5962. }
  5963. report << "windows opened: " << opened << ", paints: " << painted << "\nresult=" << (ok ? "OK" : "FAIL") << "\n";
  5964. write();
  5965. finished = true;
  5966. if (done)
  5967. done (ok);
  5968. return;
  5969. }
  5970. auto& [label, fn] = steps[next++];
  5971. {
  5972. const std::lock_guard<std::mutex> l (currentLock);
  5973. current = label;
  5974. }
  5975. fn();
  5976. lastStep = now();
  5977. lynx::crashguard::heartbeat();
  5978. }
  5979. };
  5980. auto* test = new OpenTest();
  5981. test->reportPath = reportPath;
  5982. test->visible = visible;
  5983. test->engine = std::make_unique<lynx::AudioEngine> (false);
  5984. test->done = [test, done] (bool ok) {
  5985. juce::MessageManager::callAsync ([test, done, ok] {
  5986. delete test;
  5987. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  5988. done (ok);
  5989. });
  5990. };
  5991. auto& engine = *test->engine;
  5992. lynx::setNativeEditorDemo (true); // live displays animate without an audio device
  5993. const auto songWith = [] (const lynx::EffectSlot& fx) {
  5994. auto song = lynx::Song::makeDefault();
  5995. song.mixer.resize (2);
  5996. song.mixer[0].name = "Master";
  5997. song.mixer[1].name = "Insert 1";
  5998. song.mixer[1].effects.assign (1, fx);
  5999. for (auto& channel : song.channels)
  6000. channel.mixerTrack = 1;
  6001. return song;
  6002. };
  6003. // an older project's slot: its parameter list cut to `count` and read back by the project reader (the
  6004. // parameters a newer LYNX added after them take their defaults)
  6005. const auto oldState = [songWith] (const lynx::EffectSlot& fx, std::size_t count) -> std::optional<lynx::Song> {
  6006. auto json = juce::JSON::parse (lynx::ProjectFile::toJson (songWith (fx)));
  6007. if (auto* mixer = json["mixer"].getArray(); mixer != nullptr && mixer->size() > 1)
  6008. if (auto* effects = (*mixer)[1]["effects"].getArray(); effects != nullptr && ! effects->isEmpty())
  6009. if (auto* params = (*effects)[0]["params"].getArray())
  6010. params->removeRange ((int) count, params->size());
  6011. juce::String error;
  6012. return lynx::ProjectFile::fromJson (juce::JSON::toString (json), error);
  6013. };
  6014. auto& steps = test->steps;
  6015. juce::Random random (157);
  6016. for (int k = 0; k <= (int) lynx::lastEffectKind; ++k)
  6017. {
  6018. const auto kind = (lynx::EffectKind) k;
  6019. if (! lynx::NativeEffectWindows::canOpen (kind) || kind == lynx::EffectKind::patcher)
  6020. continue;
  6021. const auto& info = lynx::effectInfo (kind);
  6022. const auto base = lynx::natives::newEffect (kind, lynx::flStudioAccess()).value_or (lynx::makeEffectSlot (kind));
  6023. const auto n = info.params.size();
  6024. std::vector<std::pair<juce::String, std::function<std::optional<lynx::Song>()>>> variants;
  6025. variants.push_back ({ "default", [=] { return std::optional<lynx::Song> (songWith (base)); } });
  6026. for (const auto value : { 0.0f, 1.0f })
  6027. variants.push_back ({ value == 0.0f ? "all 0" : "all 1", [=] {
  6028. auto fx = base;
  6029. for (std::size_t p = 0; p < n; ++p) fx.params[p] = value;
  6030. return std::optional<lynx::Song> (songWith (fx));
  6031. } });
  6032. const auto seed = random.nextInt64();
  6033. variants.push_back ({ "random", [=] {
  6034. juce::Random r (seed);
  6035. auto fx = base;
  6036. for (std::size_t p = 0; p < n; ++p) fx.params[p] = r.nextFloat();
  6037. return std::optional<lynx::Song> (songWith (fx));
  6038. } });
  6039. std::vector<std::size_t> cuts { n / 2 };
  6040. 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)
  6041. if (c < n) cuts.push_back (c);
  6042. for (const auto c : cuts)
  6043. variants.push_back ({ "old project (" + juce::String ((int) c) + " of " + juce::String ((int) n) + " params)", [=] { return oldState (base, c); } });
  6044. for (const auto& [variant, makeSong] : variants)
  6045. {
  6046. const auto label = juce::String::fromUTF8 (info.name) + " / " + variant;
  6047. steps.push_back ({ label + ": open", [test, &engine, label, makeSong = makeSong] {
  6048. auto song = makeSong();
  6049. if (! song)
  6050. {
  6051. test->report << "FAIL " << label << ": project reader refused the state\n";
  6052. test->ok = false;
  6053. return;
  6054. }
  6055. engine.setSong (std::move (*song));
  6056. engine.dispatchPendingMessages();
  6057. lynx::NativeEffectWindows::open (engine, 1, 0);
  6058. ++test->opened;
  6059. test->touchWindows (false, false);
  6060. } });
  6061. steps.push_back ({ label + ": run", [test, &engine] {
  6062. for (const auto rate : { 44100.0, 48000.0, 96000.0 })
  6063. engine.renderOffline (0.03, rate);
  6064. test->touchWindows (false, false);
  6065. } });
  6066. steps.push_back ({ label + ": small", [test] { test->touchWindows (true, false); } });
  6067. steps.push_back ({ label + ": large", [test] { test->touchWindows (true, true); } });
  6068. steps.push_back ({ label + ": close", [test, label] {
  6069. lynx::NativeEffectWindows::closeAll();
  6070. test->report << label << ": OK\n";
  6071. test->write ("(running)\n");
  6072. } });
  6073. }
  6074. }
  6075. // instruments: the channel window the Channel rack opens (Patcher: its graph window, not here)
  6076. for (int k = 0; k <= (int) lynx::InstrumentKind::soundfont; ++k)
  6077. {
  6078. const auto kind = (lynx::InstrumentKind) k;
  6079. if (kind == lynx::InstrumentKind::plugin || kind == lynx::InstrumentKind::patcher)
  6080. continue;
  6081. for (const auto* variant : { "default", "old project (saved and read back)", "odd settings" })
  6082. {
  6083. if (juce::String (variant) == "odd settings" && kind != lynx::InstrumentKind::soundfont)
  6084. continue;
  6085. const auto label = "instrument " + juce::String (k) + " / " + variant;
  6086. steps.push_back ({ label + ": open", [test, &engine, kind, label, variant = juce::String (variant), old = juce::String (variant) != "default"] {
  6087. auto song = lynx::Song::makeDefault();
  6088. auto channel = lynx::natives::makeChannel (kind, lynx::flStudioAccess());
  6089. lynx::ChannelDef def;
  6090. def.instrument = kind;
  6091. def.name = "Test";
  6092. song.channels.push_back (channel ? *channel : def);
  6093. if (kind == lynx::InstrumentKind::soundfont && variant != "default")
  6094. {
  6095. // a real font when FL's is there; NaN / huge / truncated settings
  6096. const auto& roots = lynx::flStudioAccess().roots;
  6097. if (! roots.data.empty())
  6098. song.channels.back().samplePath = (juce::File (juce::String::fromUTF8 (roots.data.c_str()))
  6099. .getChildFile ("Patches/Soundfonts/STR_Ensemble.sf2"))
  6100. .getFullPathName().toStdString();
  6101. if (variant == "odd settings")
  6102. song.channels.back().modelParams = { NAN, 1.0e9f, -1.0e9f, 0.5f, 7.0f };
  6103. }
  6104. if (old)
  6105. {
  6106. juce::String error;
  6107. if (auto again = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error))
  6108. song = std::move (*again);
  6109. }
  6110. const auto index = (int) song.channels.size() - 1;
  6111. engine.setSong (std::move (song));
  6112. engine.dispatchPendingMessages();
  6113. lynx::openChannelSettings (engine, index);
  6114. ++test->opened;
  6115. test->touchWindows (false, false);
  6116. } });
  6117. steps.push_back ({ label + ": run", [test, &engine] {
  6118. engine.renderOffline (0.03, 48000.0);
  6119. test->touchWindows (false, false);
  6120. } });
  6121. steps.push_back ({ label + ": small", [test] { test->touchWindows (true, false); } });
  6122. steps.push_back ({ label + ": large", [test] { test->touchWindows (true, true); } });
  6123. steps.push_back ({ label + ": close", [test, label] {
  6124. lynx::closeChannelSettings();
  6125. test->report << label << ": OK\n";
  6126. test->write ("(running)\n");
  6127. } });
  6128. }
  6129. }
  6130. test->start();
  6131. }
  6132. void runPluginOptionsTest (const juce::String& pluginPath, const juce::String& reportPath, const juce::String& shotsPath)
  6133. {
  6134. struct Test final : juce::Timer
  6135. {
  6136. juce::String reportPath, report;
  6137. juce::File shots;
  6138. std::unique_ptr<lynx::AudioEngine> engine;
  6139. std::unique_ptr<juce::DocumentWindow> mainWindow, other; // LYNX's main window stand-in; another secondary window
  6140. bool instrument = false, ok = true;
  6141. int channelIndex = -1, phase = 0;
  6142. juce::uint32 phaseStart = 0;
  6143. juce::AudioPluginInstance* instance = nullptr;
  6144. std::function<void (bool)> done;
  6145. void step (const juce::String& line)
  6146. {
  6147. report << line << "\n";
  6148. juce::File (reportPath).replaceWithText (report);
  6149. }
  6150. void expect (const juce::String& name, bool value)
  6151. {
  6152. step (name + "=" + juce::String ((int) value));
  6153. ok = ok && value;
  6154. }
  6155. void next (int to)
  6156. {
  6157. phase = to;
  6158. phaseStart = juce::Time::getMillisecondCounter();
  6159. }
  6160. int elapsed() const { return (int) (juce::Time::getMillisecondCounter() - phaseStart); }
  6161. lynx::PluginRef* ref (lynx::Song& song) const
  6162. {
  6163. if (instrument)
  6164. return channelIndex < 0 || channelIndex >= (int) song.channels.size() ? nullptr : &song.channels[(size_t) channelIndex].plugin;
  6165. return song.mixer.size() < 2 || song.mixer[1].effects.empty() ? nullptr : &song.mixer[1].effects[0].plugin;
  6166. }
  6167. const lynx::PluginRef& refNow() const { return *ref (const_cast<lynx::Song&> (engine->getSong())); }
  6168. juce::AudioPluginInstance* find()
  6169. {
  6170. if (instrument)
  6171. {
  6172. if (auto* p = dynamic_cast<lynx::PluginInstrument*> (engine->getChannelInstrument (channelIndex).get()))
  6173. return &p->getInstance();
  6174. }
  6175. else if (auto* p = dynamic_cast<lynx::PluginEffect*> (engine->getEffect (1, 0).get()))
  6176. return &p->getInstance();
  6177. return nullptr;
  6178. }
  6179. void openWindow()
  6180. {
  6181. std::shared_ptr<void> owner = instrument ? std::shared_ptr<void> (engine->getChannelInstrument (channelIndex))
  6182. : std::shared_ptr<void> (engine->getEffect (1, 0));
  6183. lynx::PluginWindows::open (owner, *instance, instance->getName(),
  6184. { engine.get(), [this] (lynx::Song& song) { return ref (song); }, instrument, instrument ? -1 : 1,
  6185. instrument ? -1 : 0, {}, {} });
  6186. }
  6187. void shot (const char* name, bool settingsPage = false)
  6188. {
  6189. if (shots != juce::File() && instance != nullptr)
  6190. step (juce::String ("shot_") + name + "=" + juce::String ((int) lynx::PluginWindows::saveWindowShot (*instance, shots.getChildFile (juce::String (name) + ".png"), settingsPage)));
  6191. }
  6192. // the plugin window is in front of the other secondary window
  6193. bool pluginInFront()
  6194. {
  6195. auto* plug = lynx::PluginWindows::hostWindowHandle (*instance);
  6196. #if JUCE_WINDOWS
  6197. return plug != nullptr && lynx::nativechild::isAbove (plug, other->getWindowHandle());
  6198. #else
  6199. auto& desktop = juce::Desktop::getInstance();
  6200. for (int i = 0; i < desktop.getNumComponents(); ++i)
  6201. if (auto* c = desktop.getComponent (i); c->getWindowHandle() == plug)
  6202. return c->isAlwaysOnTop() || desktop.getComponent (desktop.getNumComponents() - 1) == c;
  6203. return false;
  6204. #endif
  6205. }
  6206. void timerCallback() override
  6207. {
  6208. if (phase == 0) // waiting for the engine to host the plugin
  6209. {
  6210. instance = find();
  6211. if (instance == nullptr)
  6212. {
  6213. if (elapsed() > 20000)
  6214. finish ("not hosted");
  6215. return;
  6216. }
  6217. step ("hosted=" + instance->getName() + " format=" + instance->getPluginDescription().pluginFormatName);
  6218. openWindow();
  6219. next (1);
  6220. return;
  6221. }
  6222. if (phase == 1 && elapsed() >= 800) // Pin on top: off for a new plugin
  6223. {
  6224. expect ("pin_off_by_default", ! lynx::PluginWindows::isPinnedOnTop (*instance) && ! refNow().pinned);
  6225. shot ("pin-off");
  6226. const auto history = engine->getHistoryPosition();
  6227. lynx::PluginWindows::setPinnedOnTop (*instance, true);
  6228. expect ("pin_set", lynx::PluginWindows::isPinnedOnTop (*instance) && refNow().pinned);
  6229. expect ("pin_no_undo_step_project_modified", engine->getHistoryPosition() == history && engine->isModified());
  6230. // another secondary window brought in front of it
  6231. other = std::make_unique<juce::DocumentWindow> ("Another LYNX window", juce::Colours::darkslategrey, juce::DocumentWindow::closeButton);
  6232. other->setUsingNativeTitleBar (true);
  6233. other->setBounds (mainWindow->getX() + 60, mainWindow->getY() + 60, 420, 300);
  6234. other->setVisible (true);
  6235. lynx::keepAboveMainWindow (*other);
  6236. lynx::forceForegroundForTest (*other);
  6237. other->toFront (true);
  6238. next (2);
  6239. return;
  6240. }
  6241. if (phase == 2 && elapsed() >= 1200)
  6242. {
  6243. expect ("pinned_stays_in_front_of_a_clicked_window", pluginInFront());
  6244. shot ("pin-on");
  6245. // closed and opened again: the pin comes back from the project
  6246. lynx::PluginWindows::close (*instance);
  6247. openWindow();
  6248. next (3);
  6249. return;
  6250. }
  6251. if (phase == 3 && elapsed() >= 600)
  6252. {
  6253. expect ("pin_remembered_when_reopened", lynx::PluginWindows::isPinnedOnTop (*instance));
  6254. lynx::PluginWindows::setPinnedOnTop (*instance, false);
  6255. expect ("pin_cleared", ! lynx::PluginWindows::isPinnedOnTop (*instance) && ! refNow().pinned);
  6256. other->toFront (true);
  6257. next (4);
  6258. return;
  6259. }
  6260. if (phase == 4 && elapsed() >= 1000)
  6261. {
  6262. #if JUCE_WINDOWS
  6263. expect ("unpinned_goes_behind_a_clicked_window", ! pluginInFront());
  6264. #endif
  6265. other = nullptr;
  6266. // the wrapper settings page: LYNX's Velocity row in the MIDI group (instruments), default = follow
  6267. expect ("velocity_follows_midi_settings_by_default", refNow().velocityMode == lynx::prefs::pluginVelocityFollow
  6268. && refNow().fixedVelocity == lynx::prefs::defaultFixedVelocity);
  6269. shot ("wrapper-velocity-default", true);
  6270. engine->editSong ([this] (lynx::Song& song) {
  6271. if (auto* r = ref (song))
  6272. {
  6273. r->velocityMode = lynx::prefs::pluginVelocityFixed;
  6274. r->fixedVelocity = 96;
  6275. }
  6276. });
  6277. next (5);
  6278. return;
  6279. }
  6280. if (phase == 5 && elapsed() >= 400)
  6281. {
  6282. expect ("velocity_change_keeps_the_running_plugin", find() == instance);
  6283. shot ("wrapper-velocity-fixed", true);
  6284. engine->undo();
  6285. expect ("velocity_undo", refNow().velocityMode == lynx::prefs::pluginVelocityFollow && find() == instance);
  6286. // the preset menu's "Play a note when a preset loads": off by default, a user setting
  6287. expect ("audition_off_by_default", ! lynx::pluginpresetui::auditionOnLoad());
  6288. lynx::pluginpresetui::setAuditionOnLoad (true);
  6289. expect ("audition_menu_opened", lynx::PluginWindows::showPresetMenu (*instance));
  6290. next (6);
  6291. return;
  6292. }
  6293. if (phase == 6 && elapsed() >= 500) // the menu, as drawn
  6294. {
  6295. auto found = false;
  6296. auto& desktop = juce::Desktop::getInstance();
  6297. for (int c = desktop.getNumComponents(); --c >= 0 && ! found;)
  6298. if (auto* menu = desktop.getComponent (c); dynamic_cast<juce::TopLevelWindow*> (menu) == nullptr && menu->isVisible()
  6299. && menu->getHeight() > 60 && shots != juce::File())
  6300. {
  6301. const auto image = menu->createComponentSnapshot (menu->getLocalBounds(), true, 1.0f);
  6302. juce::FileOutputStream out (shots.getChildFile ("preset-menu-audition.png"));
  6303. found = out.openedOk() && juce::PNGImageFormat().writeImageToStream (image, out);
  6304. }
  6305. step ("shot_preset-menu-audition=" + juce::String ((int) found));
  6306. juce::PopupMenu::dismissAllActiveMenus();
  6307. // a preset loaded while the song is stopped: the note waits a moment, sounds, ends
  6308. const auto asked = engine->auditionPreset (*instance);
  6309. expect ("audition_only_for_channel_instruments", asked == instrument);
  6310. expect ("audition_waits_first", ! instrument || engine->auditionState() == 1);
  6311. next (7);
  6312. return;
  6313. }
  6314. if (phase == 7 && elapsed() >= 300)
  6315. {
  6316. expect ("audition_sounds", ! instrument || engine->auditionState() == 2);
  6317. next (8);
  6318. return;
  6319. }
  6320. if (phase == 8 && elapsed() >= 700)
  6321. {
  6322. expect ("audition_ends", engine->auditionState() == 0);
  6323. engine->getTransport().playing.store (true); // the song plays: no audition
  6324. expect ("no_audition_while_playing", ! engine->auditionPreset (*instance) && engine->auditionState() == 0);
  6325. engine->getTransport().playing.store (false);
  6326. lynx::pluginpresetui::setAuditionOnLoad (false);
  6327. expect ("audition_setting_off_again", ! lynx::pluginpresetui::auditionOnLoad());
  6328. finish ({});
  6329. }
  6330. }
  6331. void finish (const juce::String& failure)
  6332. {
  6333. stopTimer();
  6334. if (failure.isNotEmpty())
  6335. step ("failed=" + failure);
  6336. ok = ok && failure.isEmpty();
  6337. step (ok ? "result=OK" : "result=FAILED");
  6338. lynx::PluginWindows::closeAll();
  6339. done (ok);
  6340. }
  6341. };
  6342. auto* test = new Test();
  6343. test->reportPath = reportPath;
  6344. if (shotsPath.isNotEmpty())
  6345. {
  6346. test->shots = juce::File (shotsPath);
  6347. test->shots.createDirectory();
  6348. }
  6349. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  6350. test->done = [this, test] (bool ok) {
  6351. setApplicationReturnValue (ok ? 0 : 1);
  6352. juce::MessageManager::callAsync ([this, test] {
  6353. lynx::setMainWindowForOwnership (nullptr);
  6354. test->other = nullptr;
  6355. test->mainWindow = nullptr;
  6356. test->engine = nullptr;
  6357. delete test;
  6358. quit();
  6359. });
  6360. };
  6361. test->engine = std::make_unique<lynx::AudioEngine> (false);
  6362. test->mainWindow = std::make_unique<juce::DocumentWindow> ("LYNX test main window", juce::Colours::darkgrey, 0);
  6363. test->mainWindow->setBounds (20, 20, 300, 200);
  6364. test->mainWindow->setVisible (true);
  6365. lynx::setMainWindowForOwnership (test->mainWindow.get());
  6366. auto& host = test->engine->getPluginHost();
  6367. test->step ("plugins_in_file=" + juce::String (host.addPluginFile (juce::File (pluginPath))));
  6368. std::optional<juce::PluginDescription> chosen;
  6369. for (const auto& type : host.getKnownPlugins().getTypes())
  6370. if (juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginPath).getFileName() || type.fileOrIdentifier == pluginPath)
  6371. {
  6372. chosen = type;
  6373. break;
  6374. }
  6375. if (! chosen)
  6376. {
  6377. test->step ("result=FAILED (no plugin)");
  6378. test->done (false);
  6379. return;
  6380. }
  6381. test->instrument = chosen->isInstrument;
  6382. lynx::PluginRef ref;
  6383. ref.id = chosen->createIdentifierString().toStdString();
  6384. ref.name = chosen->name.toStdString();
  6385. test->engine->editSong ([&] (lynx::Song& song) {
  6386. if (test->instrument)
  6387. {
  6388. lynx::ChannelDef c;
  6389. c.name = ref.name;
  6390. c.instrument = lynx::InstrumentKind::plugin;
  6391. c.plugin = ref;
  6392. test->channelIndex = (int) song.channels.size();
  6393. song.channels.push_back (c);
  6394. }
  6395. else
  6396. {
  6397. while (song.mixer.size() < 2)
  6398. song.mixer.emplace_back();
  6399. lynx::EffectSlot slot;
  6400. slot.kind = lynx::EffectKind::plugin;
  6401. slot.plugin = ref;
  6402. song.mixer[1].effects.push_back (slot);
  6403. }
  6404. });
  6405. test->engine->markSaved();
  6406. test->step ("plugin=" + chosen->name + " instrument=" + juce::String ((int) test->instrument));
  6407. test->next (0);
  6408. test->startTimerHz (20);
  6409. }
  6410. void runReloadTest (const juce::String& pluginPath, const juce::String& reportPath, const juce::String& shotsPath, bool waitKill)
  6411. {
  6412. struct Test final : juce::Timer
  6413. {
  6414. juce::String reportPath, report;
  6415. juce::File shots;
  6416. std::unique_ptr<lynx::AudioEngine> engine;
  6417. std::unique_ptr<juce::DocumentWindow> mainWindow; // stands for LYNX's main window (window ownership)
  6418. bool instrument = false, waitKill = false, ok = true;
  6419. int channelIndex = -1, phase = 0, round = 0;
  6420. juce::uint32 phaseStart = 0;
  6421. int firstPid = 0, pid = 0, historyBefore = 0;
  6422. bool modifiedBefore = false;
  6423. float captured = -1.0f;
  6424. juce::AudioPluginInstance* instance = nullptr;
  6425. std::vector<lynx::ChannelDef> channelsBefore;
  6426. std::function<void (bool)> done;
  6427. lynx::AudioEngine::HostedSlot where() const { return instrument ? lynx::AudioEngine::HostedSlot { channelIndex, -1, -1 } : lynx::AudioEngine::HostedSlot { -1, 1, 0 }; }
  6428. void step (const juce::String& line)
  6429. {
  6430. report << line << "\n";
  6431. juce::File (reportPath).replaceWithText (report);
  6432. }
  6433. void expect (const juce::String& name, bool value)
  6434. {
  6435. step (name + "=" + juce::String ((int) value));
  6436. ok = ok && value;
  6437. }
  6438. void next (int to)
  6439. {
  6440. phase = to;
  6441. phaseStart = juce::Time::getMillisecondCounter();
  6442. }
  6443. int elapsed() const { return (int) (juce::Time::getMillisecondCounter() - phaseStart); }
  6444. juce::AudioPluginInstance* find()
  6445. {
  6446. if (instrument)
  6447. {
  6448. if (auto* p = dynamic_cast<lynx::PluginInstrument*> (engine->getChannelInstrument (channelIndex).get()))
  6449. return &p->getInstance();
  6450. }
  6451. else if (auto* p = dynamic_cast<lynx::PluginEffect*> (engine->getEffect (1, 0).get()))
  6452. return &p->getInstance();
  6453. return nullptr;
  6454. }
  6455. // a few blocks through the plugin (the offline engine has no audio thread): they carry parameter changes to
  6456. // the plugin's process and its values back
  6457. void pump (int blocks)
  6458. {
  6459. std::vector<float> l (512), r (512);
  6460. lynx::EffectParams none {};
  6461. for (int b = 0; b < blocks; ++b)
  6462. {
  6463. std::fill (l.begin(), l.end(), 0.0f);
  6464. std::fill (r.begin(), r.end(), 0.0f);
  6465. if (instrument)
  6466. {
  6467. if (auto in = engine->getChannelInstrument (channelIndex))
  6468. in->render (l.data(), r.data(), 512, 1.0f, 1.0f);
  6469. }
  6470. else if (auto fx = engine->getEffect (1, 0))
  6471. fx->process (l.data(), r.data(), 512, none, 120.0);
  6472. }
  6473. }
  6474. juce::AudioProcessorParameter* firstParam()
  6475. {
  6476. if (instance != nullptr)
  6477. for (auto* candidate : instance->getParameters())
  6478. if (candidate->isAutomatable() && ! candidate->isMetaParameter() && candidate != instance->getBypassParameter())
  6479. return candidate;
  6480. return nullptr;
  6481. }
  6482. void openWindow()
  6483. {
  6484. std::shared_ptr<void> owner = instrument ? std::shared_ptr<void> (engine->getChannelInstrument (channelIndex))
  6485. : std::shared_ptr<void> (engine->getEffect (1, 0));
  6486. lynx::PluginWindows::WrapperContext context { engine.get(), [this] (lynx::Song& song) -> lynx::PluginRef* {
  6487. if (instrument)
  6488. return channelIndex < 0 || channelIndex >= (int) song.channels.size()
  6489. ? nullptr : &song.channels[(size_t) channelIndex].plugin;
  6490. return song.mixer.size() < 2 || song.mixer[1].effects.empty() ? nullptr : &song.mixer[1].effects[0].plugin;
  6491. }, instrument, instrument ? -1 : 1, instrument ? -1 : 0, {}, {} };
  6492. context.reload = [] {}; // (the test reloads by itself; with it the window shows the notice)
  6493. lynx::PluginWindows::open (owner, *instance, instance->getName(), std::move (context));
  6494. }
  6495. void shot (const char* name, bool settingsPage = false)
  6496. {
  6497. if (shots != juce::File() && instance != nullptr)
  6498. step (juce::String ("shot_") + name + "=" + juce::String ((int) lynx::PluginWindows::saveWindowShot (*instance, shots.getChildFile (juce::String (name) + ".png"), settingsPage)));
  6499. }
  6500. void timerCallback() override
  6501. {
  6502. if (phase == 0) // waiting for the engine to host the plugin
  6503. {
  6504. instance = find();
  6505. if (instance == nullptr)
  6506. {
  6507. if (elapsed() > 20000)
  6508. finish ("not hosted");
  6509. return;
  6510. }
  6511. pid = firstPid = lynx::sandboxedPluginProcessId (*instance);
  6512. step ("hosted=" + instance->getName() + " format=" + instance->getPluginDescription().pluginFormatName + " pid=" + juce::String (pid));
  6513. expect ("separate_process", lynx::isSandboxedPlugin (*instance) && pid != 0);
  6514. expect ("running", ! engine->hostedPluginDown (where()) && engine->downHostedPlugins().empty());
  6515. // a setting that is captured (what a save or a backup does), then one that is not
  6516. if (auto* param = firstParam())
  6517. {
  6518. param->setValue (param->getValue() > 0.5f ? 0.13f : 0.87f);
  6519. pump (4);
  6520. engine->capturePluginStates();
  6521. captured = param->getValue();
  6522. param->setValue (captured > 0.5f ? 0.31f : 0.69f);
  6523. pump (4);
  6524. step ("param=" + param->getName (64) + " captured=" + juce::String (captured, 4) + " then=" + juce::String (param->getValue(), 4));
  6525. }
  6526. else
  6527. {
  6528. engine->capturePluginStates();
  6529. step ("param=none");
  6530. }
  6531. channelsBefore = engine->getSong().channels;
  6532. historyBefore = engine->getHistoryPosition();
  6533. modifiedBefore = engine->isModified();
  6534. if (shots != juce::File())
  6535. openWindow();
  6536. next (1);
  6537. return;
  6538. }
  6539. if (phase == 1 && elapsed() >= 600) // the plugin's process goes
  6540. {
  6541. shot (round == 0 ? "window-running" : "window-reloaded");
  6542. if (waitKill && round == 0)
  6543. {
  6544. juce::File (reportPath + ".pid").replaceWithText (juce::String (pid));
  6545. step ("waiting_for_kill pid=" + juce::String (pid));
  6546. }
  6547. else
  6548. lynx::crashSandboxedPluginForTest (*instance);
  6549. next (2);
  6550. return;
  6551. }
  6552. if (phase == 2) // LYNX notices
  6553. {
  6554. if (! engine->hostedPluginDown (where()))
  6555. {
  6556. pump (1); // (as the audio thread would: a block that gets no answer marks it too)
  6557. if (elapsed() > (waitKill && round == 0 ? 120000 : 10000))
  6558. finish ("the plugin never went down");
  6559. return;
  6560. }
  6561. step ("down_after_ms=" + juce::String (elapsed()));
  6562. const auto down = engine->downHostedPlugins();
  6563. expect ("listed_down", down.size() == 1 && down.front() == where());
  6564. expect ("listed_by_name", engine->downHostedPlugins (nameInSong()).size() == 1 && engine->downHostedPlugins ("no such plugin").empty());
  6565. next (3);
  6566. return;
  6567. }
  6568. if (phase == 3 && elapsed() >= 1500) // nothing reloads by itself
  6569. {
  6570. expect ("still_down_without_asking", engine->hostedPluginDown (where()) && find() == instance
  6571. && lynx::sandboxedPluginProcessId (*instance) == pid);
  6572. shot (round == 0 ? "reload-notice" : "reload-notice-again");
  6573. if (shots != juce::File() && round == 0)
  6574. {
  6575. lynx::PluginWindows::close (*instance);
  6576. lynx::PluginWindows::promptReload (*engine, where(), {});
  6577. next (4);
  6578. return;
  6579. }
  6580. next (5);
  6581. return;
  6582. }
  6583. if (phase == 4 && elapsed() >= 500) // the prompt a click on the channel / slot shows
  6584. {
  6585. auto found = false;
  6586. for (int c = juce::Desktop::getInstance().getNumComponents(); --c >= 0;)
  6587. if (auto* alert = dynamic_cast<juce::AlertWindow*> (juce::Desktop::getInstance().getComponent (c)))
  6588. {
  6589. const auto image = alert->createComponentSnapshot (alert->getLocalBounds(), true, 1.0f);
  6590. juce::FileOutputStream out (shots.getChildFile ("reload-prompt.png"));
  6591. found = out.openedOk() && juce::PNGImageFormat().writeImageToStream (image, out);
  6592. alert->exitModalState (0); // Close: nothing reloads
  6593. break;
  6594. }
  6595. step ("shot_reload-prompt=" + juce::String ((int) found));
  6596. next (45);
  6597. return;
  6598. }
  6599. if (phase == 45 && elapsed() >= 300)
  6600. {
  6601. expect ("still_down_after_close", engine->hostedPluginDown (where()));
  6602. next (5);
  6603. return;
  6604. }
  6605. if (phase == 5) // Reload, as the notice's button / the prompt / the menu item do
  6606. {
  6607. auto* old = instance;
  6608. const auto running = lynx::PluginWindows::reload (*engine, { where() });
  6609. instance = find();
  6610. const auto newPid = instance != nullptr ? lynx::sandboxedPluginProcessId (*instance) : 0;
  6611. expect ("reloaded", running == 1 && instance != nullptr && ! engine->hostedPluginDown (where()) && engine->downHostedPlugins().empty());
  6612. expect ("new_process", newPid != 0 && newPid != pid);
  6613. step ("pid=" + juce::String (newPid) + " same_object=" + juce::String ((int) (instance == old)));
  6614. expect ("old_window_closed", ! lynx::PluginWindows::isOpen (*old) || instance == old);
  6615. pid = newPid;
  6616. if (instance != nullptr)
  6617. {
  6618. pump (4);
  6619. if (auto* param = firstParam(); param != nullptr && captured >= 0.0f)
  6620. {
  6621. step ("param_after_reload=" + juce::String (param->getValue(), 4));
  6622. expect ("state_captured_last", std::abs (param->getValue() - captured) < 0.02f);
  6623. }
  6624. }
  6625. expect ("song_untouched", engine->getSong().channels == channelsBefore);
  6626. expect ("no_undo_step", engine->getHistoryPosition() == historyBefore && engine->isModified() == modifiedBefore);
  6627. if (instance == nullptr)
  6628. {
  6629. finish ("no instance after the reload");
  6630. return;
  6631. }
  6632. if (shots != juce::File())
  6633. openWindow();
  6634. if (round == 0) // once more: a plugin that crashes again waits for the user again
  6635. {
  6636. round = 1;
  6637. next (1);
  6638. return;
  6639. }
  6640. next (6);
  6641. return;
  6642. }
  6643. if (phase == 6 && elapsed() >= 400) // an edit and its undo keep the reloaded plugin
  6644. {
  6645. shot ("window-reloaded-twice");
  6646. auto* before = find();
  6647. engine->editSong ([] (lynx::Song& song) { song.bpm += 1.0f; });
  6648. engine->undo();
  6649. expect ("undo_keeps_the_reloaded_plugin", find() == before && ! engine->hostedPluginDown (where()));
  6650. lynx::PluginWindows::closeAll();
  6651. finish ({});
  6652. }
  6653. }
  6654. std::string nameInSong() const
  6655. {
  6656. const auto& song = engine->getSong();
  6657. return instrument ? song.channels[(size_t) channelIndex].plugin.name : song.mixer[1].effects[0].plugin.name;
  6658. }
  6659. void finish (const juce::String& failure)
  6660. {
  6661. stopTimer();
  6662. if (failure.isNotEmpty())
  6663. step ("failed=" + failure);
  6664. ok = ok && failure.isEmpty();
  6665. step (ok ? "result=OK" : "result=FAILED");
  6666. lynx::PluginWindows::closeAll();
  6667. done (ok);
  6668. }
  6669. };
  6670. lynx::setPluginSandboxAlerts (true); // (the deaths are recorded as in the app; no box: there is no main component)
  6671. auto* test = new Test();
  6672. test->reportPath = reportPath;
  6673. test->waitKill = waitKill;
  6674. if (shotsPath.isNotEmpty())
  6675. {
  6676. test->shots = juce::File (shotsPath);
  6677. test->shots.createDirectory();
  6678. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  6679. }
  6680. juce::File (reportPath + ".pid").deleteFile();
  6681. test->done = [this, test] (bool ok) {
  6682. setApplicationReturnValue (ok ? 0 : 1);
  6683. juce::MessageManager::callAsync ([this, test] {
  6684. lynx::setMainWindowForOwnership (nullptr);
  6685. test->mainWindow = nullptr;
  6686. test->engine = nullptr;
  6687. delete test;
  6688. quit();
  6689. });
  6690. };
  6691. test->engine = std::make_unique<lynx::AudioEngine> (false);
  6692. if (shotsPath.isNotEmpty())
  6693. {
  6694. test->mainWindow = std::make_unique<juce::DocumentWindow> ("LYNX test main window", juce::Colours::darkgrey, 0);
  6695. test->mainWindow->setBounds (20, 20, 300, 200);
  6696. test->mainWindow->setVisible (true);
  6697. lynx::setMainWindowForOwnership (test->mainWindow.get());
  6698. }
  6699. auto& host = test->engine->getPluginHost();
  6700. test->step ("plugins_in_file=" + juce::String (host.addPluginFile (juce::File (pluginPath))));
  6701. std::optional<juce::PluginDescription> chosen;
  6702. for (const auto& type : host.getKnownPlugins().getTypes())
  6703. if (juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginPath).getFileName() || type.fileOrIdentifier == pluginPath)
  6704. {
  6705. chosen = type;
  6706. break;
  6707. }
  6708. if (! chosen)
  6709. {
  6710. test->step ("result=FAILED (no plugin)");
  6711. test->done (false);
  6712. return;
  6713. }
  6714. test->instrument = chosen->isInstrument;
  6715. lynx::PluginRef ref;
  6716. ref.separateProcess = true;
  6717. ref.id = chosen->createIdentifierString().toStdString();
  6718. ref.name = chosen->name.toStdString();
  6719. test->engine->editSong ([&] (lynx::Song& song) {
  6720. if (test->instrument)
  6721. {
  6722. lynx::ChannelDef c;
  6723. c.name = ref.name;
  6724. c.instrument = lynx::InstrumentKind::plugin;
  6725. c.plugin = ref;
  6726. test->channelIndex = (int) song.channels.size();
  6727. song.channels.push_back (c);
  6728. }
  6729. else
  6730. {
  6731. while (song.mixer.size() < 2)
  6732. song.mixer.emplace_back();
  6733. lynx::EffectSlot slot;
  6734. slot.kind = lynx::EffectKind::plugin;
  6735. slot.plugin = ref;
  6736. song.mixer[1].effects.push_back (slot);
  6737. }
  6738. });
  6739. test->step ("plugin=" + chosen->name + " instrument=" + juce::String ((int) test->instrument));
  6740. test->next (0);
  6741. test->startTimerHz (20);
  6742. }
  6743. void runPlugWinTest (const juce::String& pluginPath, const juce::String& reportPath, const juce::String& only, int seconds)
  6744. {
  6745. struct Test final : juce::Timer
  6746. {
  6747. juce::String reportPath, report;
  6748. std::unique_ptr<lynx::AudioEngine> engine;
  6749. bool instrument = false;
  6750. int phase = 0, ticks = 0, seconds = 15, dockStep = 0;
  6751. juce::uint32 phaseStartMs = 0; // (phase 1 counts real time: the timer's ticks ran faster than 20 Hz here)
  6752. juce::AudioPluginInstance* instance = nullptr;
  6753. juce::AudioProcessorParameter* checked = nullptr;
  6754. std::unique_ptr<juce::DocumentWindow> mainWindow; // stands for LYNX's main window (window ownership)
  6755. lynx::Workspace* workspace = nullptr; // LYNX_PLUGWIN_DOCK=1: the real main window's desktop (issue #116)
  6756. int channelIndex = -1; // an instrument: its channel (added after the song's own channels)
  6757. int stepMs = 3000; // dock mode: each state held that long (screenshots)
  6758. bool keysDone = false;
  6759. bool dockOk = true;
  6760. std::function<void (bool)> done;
  6761. // LYNX_PLUGWIN_DROP=<sample> (issue #174): a Sample browser window beside the plugin window with that file
  6762. // selected. The report gives the row's and the editor's places on screen with what LYNX sees there (for a
  6763. // real drag by xdotool / SendInput in that time), and, before the plugin is removed, whether the plugin took
  6764. // the file (its saved state names it).
  6765. juce::File dropFile;
  6766. std::unique_ptr<juce::DocumentWindow> dropWindow;
  6767. lynx::BrowserComponent* dropBrowser = nullptr;
  6768. int dropStage = 0;
  6769. juce::uint32 dropReadyMs = 0; // (the Browser may take long to list a big library: the time counts from here)
  6770. void dropTick (int elapsedMs)
  6771. {
  6772. if (dropStage == 0 && elapsedMs >= 1000)
  6773. {
  6774. lynx::externaldrag::install();
  6775. auto content = lynx::BrowserComponent::makeSampleBrowserContent (*engine, [this] (lynx::BrowserComponent& b) { dropBrowser = &b; });
  6776. dropWindow = std::make_unique<juce::DocumentWindow> ("LYNX test sample browser", juce::Colours::darkgrey, 0);
  6777. dropWindow->setContentOwned (content.release(), false);
  6778. dropWindow->setBounds (20, 240, 340, 520);
  6779. dropWindow->setVisible (true);
  6780. if (dropBrowser != nullptr)
  6781. {
  6782. dropBrowser->showFilterForSnapshot (dropFile.getParentDirectory(), lynx::browserview::ContentFilter::all);
  6783. step ("drop_locate=" + juce::String ((int) dropBrowser->locateFile (dropFile)));
  6784. }
  6785. dropStage = 1;
  6786. }
  6787. else if (dropStage == 1 && elapsedMs >= 2500)
  6788. {
  6789. using namespace lynx::externaldrag;
  6790. const auto row = dropBrowser != nullptr ? dropBrowser->selectedRowScreenBounds() : juce::Rectangle<int>();
  6791. const auto from = row.getCentre();
  6792. // (physical pixels too: SendInput / xdotool work in those)
  6793. auto physical = [] (juce::Point<int> p) {
  6794. const auto q = juce::Desktop::getInstance().getDisplays().logicalToPhysical (p);
  6795. return " phys=" + juce::String (q.x) + "," + juce::String (q.y);
  6796. };
  6797. step ("drop_source=" + juce::String (from.x) + "," + juce::String (from.y) + " place=" + placeName (placeAt (from)) + physical (from));
  6798. if (const auto pid = lynx::sandboxedPluginProcessId (*instance); pid != 0)
  6799. step ("drop_target_pid=" + juce::String (pid)); // (its window is the other process's)
  6800. else if (auto* editor = instance->getActiveEditor())
  6801. {
  6802. const auto to = editor->getScreenBounds().getCentre();
  6803. step ("drop_target=" + juce::String (to.x) + "," + juce::String (to.y) + " place=" + placeName (placeAt (to)) + physical (to));
  6804. }
  6805. const auto files = filesOf (juce::String (lynx::BrowserComponent::dragDescription) + "|" + dropFile.getFullPathName(), nullptr);
  6806. step ("drop_files=" + files.joinIntoString (";"));
  6807. dropStage = 2;
  6808. dropReadyMs = juce::Time::getMillisecondCounter();
  6809. }
  6810. }
  6811. void dropResult()
  6812. {
  6813. juce::MemoryBlock state;
  6814. instance->getStateInformation (state);
  6815. const auto name = dropFile.getFileNameWithoutExtension().toStdString();
  6816. auto holds = [&name] (const juce::MemoryBlock& block) {
  6817. const auto* bytes = static_cast<const char*> (block.getData());
  6818. return ! name.empty() && std::search (bytes, bytes + block.getSize(), name.begin(), name.end()) != bytes + block.getSize();
  6819. };
  6820. auto received = holds (state);
  6821. // (JUCE's VST3 host keeps the plugin's own state base64-encoded inside an XML of its own)
  6822. auto xml = juce::AudioProcessor::getXmlFromBinary (state.getData(), (int) state.getSize());
  6823. if (xml == nullptr)
  6824. xml = juce::parseXML (state.toString());
  6825. if (! received && xml != nullptr)
  6826. for (auto* e : xml->getChildIterator())
  6827. {
  6828. juce::MemoryBlock inner;
  6829. if (inner.fromBase64Encoding (e->getAllSubText().trim()) && holds (inner))
  6830. received = true;
  6831. }
  6832. step ("drop_received=" + juce::String ((int) received));
  6833. }
  6834. // issue #116 (with LYNX_DOCKED_PLUGINS=1 and LYNX_PLUGWIN_DOCK=1), FL's f116 sequence for every floating
  6835. // panel: the docked plugin window goes behind a clicked panel and comes back in front when clicked; a
  6836. // panel called by its key comes in front too; Detached reopens it as a window of its own, which stays above
  6837. // every panel clicked (it is owned by the main window).
  6838. const std::array<lynx::workspace::Panel, 4> dockPanels { lynx::workspace::Panel::channelRack, lynx::workspace::Panel::playlist,
  6839. lynx::workspace::Panel::pianoRoll, lynx::workspace::Panel::mixer };
  6840. const int dockSteps = 2 * 4 + 18; // (the last one reports dock_result)
  6841. int danceChannel = -1; // issue #116 slice 4: a dance channel's dancer over the docked plugin
  6842. lynx::MainComponent* ui = nullptr; // dock mode: the real main window's contents
  6843. struct ScaleSpy final : juce::ComponentPeer::ScaleFactorListener
  6844. {
  6845. int calls = 0;
  6846. double last = 0.0;
  6847. void nativeScaleFactorChanged (double s) override { ++calls; last = s; }
  6848. } scaleSpy;
  6849. juce::ComponentPeer* spiedPeer = nullptr;
  6850. void* panelHandle (lynx::workspace::Panel p) const { return workspace->getFrame (p).getWindowHandle(); }
  6851. void dockCheck (int at)
  6852. {
  6853. using lynx::workspace::Panel;
  6854. auto* main = mainWindow->getWindowHandle();
  6855. auto* plug = lynx::PluginWindows::hostWindowHandle (*instance);
  6856. auto expect = [this] (const juce::String& name, bool value) {
  6857. step (name + "=" + juce::String ((int) value));
  6858. dockOk = dockOk && value;
  6859. };
  6860. auto id = [] (Panel p) { return juce::String (lynx::workspace::panelId (p)); };
  6861. if (at == 0)
  6862. {
  6863. expect ("docked", lynx::PluginWindows::isDocked (*instance));
  6864. expect ("plugin_native_child", plug != nullptr && lynx::nativechild::parentOf (plug) == main);
  6865. for (auto p : dockPanels)
  6866. {
  6867. auto* h = panelHandle (p);
  6868. expect (id (p) + "_visible", workspace->isPanelVisible (p));
  6869. expect (id (p) + "_native_child", h != nullptr && h != main && lynx::nativechild::parentOf (h) == main);
  6870. expect ("plugin_above_" + id (p) + "_when_opened", lynx::nativechild::isAbove (plug, h));
  6871. }
  6872. expect ("browser_plain", ! workspace->isNativePanel (Panel::browser));
  6873. }
  6874. if (at < 2 * 4)
  6875. {
  6876. const auto p = dockPanels[at / 2];
  6877. if (at % 2 == 0)
  6878. {
  6879. workspace->activate (p); // a click on the panel
  6880. expect (id (p) + "_above_plugin_after_its_click", lynx::nativechild::isAbove (panelHandle (p), plug));
  6881. // the plugin stays above the panels nobody clicked
  6882. for (auto other : dockPanels)
  6883. if (other != p)
  6884. expect ("plugin_above_" + id (other) + "_after_" + id (p) + "_click", lynx::nativechild::isAbove (plug, panelHandle (other)));
  6885. }
  6886. else
  6887. {
  6888. lynx::PluginWindows::open ({}, *instance, {}); // (open again = a click on the plugin)
  6889. expect ("plugin_above_" + id (p) + "_after_plugin_click", lynx::nativechild::isAbove (plug, panelHandle (p)));
  6890. }
  6891. return;
  6892. }
  6893. if (at == 8)
  6894. {
  6895. // a layout change elsewhere (a panel resized, the Browser shown) keeps the plugin in front; a panel
  6896. // called by its key comes in front of it
  6897. workspace->hide (Panel::browser);
  6898. workspace->show (Panel::browser);
  6899. for (auto p : dockPanels)
  6900. expect ("plugin_above_" + id (p) + "_after_layout_change", lynx::nativechild::isAbove (plug, panelHandle (p)));
  6901. workspace->show (Panel::mixer);
  6902. expect ("mixer_above_plugin_after_show", lynx::nativechild::isAbove (panelHandle (Panel::mixer), plug));
  6903. }
  6904. else if (at == 9)
  6905. {
  6906. // the setup wizard (Options › Setup wizard; first start) in front of the native panels and the plugin
  6907. ui->showSetupWizard();
  6908. }
  6909. else if (at == 10)
  6910. {
  6911. auto* overlay = ui->setupOverlayForTest();
  6912. auto* h = overlay != nullptr ? overlay->getWindowHandle() : nullptr;
  6913. expect ("setup_overlay_native_child", h != nullptr && h != main && lynx::nativechild::parentOf (h) == main);
  6914. expect ("setup_overlay_above_plugin", lynx::nativechild::isAbove (h, plug));
  6915. for (auto p : dockPanels)
  6916. expect ("setup_overlay_above_" + id (p), lynx::nativechild::isAbove (h, panelHandle (p)));
  6917. workspace->activate (Panel::playlist); // (a panel brought in front by code: the overlay stays in front)
  6918. lynx::PluginWindows::open ({}, *instance, {});
  6919. expect ("setup_overlay_stays_in_front", lynx::nativechild::isAbove (h, plug) && lynx::nativechild::isAbove (h, panelHandle (Panel::playlist)));
  6920. }
  6921. else if (at == 11)
  6922. {
  6923. ui->closeSetupWizardForSnapshot();
  6924. expect ("setup_overlay_closed", ui->setupOverlayForTest() == nullptr);
  6925. // drops: JUCE's list of windows in the native stacking order once a drag starts
  6926. workspace->activate (Panel::mixer);
  6927. workspace->hide (Panel::browser);
  6928. workspace->show (Panel::browser);
  6929. lynx::matchWindowOrderToScreen();
  6930. auto children = lynx::nativechild::attachedChildren (main);
  6931. auto& desktop = juce::Desktop::getInstance();
  6932. int last = -1;
  6933. bool ordered = children.size() >= 5;
  6934. for (auto* c : children)
  6935. if (c->isVisible())
  6936. {
  6937. int at2 = -1;
  6938. for (int k = 0; k < desktop.getNumComponents(); ++k)
  6939. if (desktop.getComponent (k) == c)
  6940. at2 = k;
  6941. ordered = ordered && at2 > last;
  6942. last = at2;
  6943. }
  6944. expect ("drop_order_matches_screen", ordered);
  6945. }
  6946. else if (at == 12)
  6947. {
  6948. // the main window's scale changes (a display with another scale): every native child placed again in
  6949. // physical pixels, the docked editor's window told (JUCE tells child windows nothing by itself)
  6950. for (int i = 0; i < juce::ComponentPeer::getNumPeers(); ++i)
  6951. if (auto* peer = juce::ComponentPeer::getPeer (i); peer != nullptr && peer->getNativeHandle() == plug)
  6952. spiedPeer = peer;
  6953. if (spiedPeer != nullptr)
  6954. spiedPeer->addScaleFactorListener (&scaleSpy);
  6955. lynx::nativechild::notifyScaleListenersForTest (*mainWindow);
  6956. juce::Desktop::getInstance().setGlobalScaleFactor (1.25f); // and LYNX's own UI zoom
  6957. }
  6958. else if (at == 13)
  6959. {
  6960. bool placed = true;
  6961. for (auto* c : lynx::nativechild::attachedChildren (main))
  6962. placed = placed && (! c->isVisible() || lynx::nativechild::placedPhysically (*c));
  6963. expect ("native_children_placed_at_125", placed);
  6964. expect ("docked_editor_told_the_scale", scaleSpy.calls > 0 && spiedPeer != nullptr
  6965. && std::abs (scaleSpy.last - spiedPeer->getPlatformScaleFactor()) < 0.001);
  6966. if (spiedPeer != nullptr && juce::ComponentPeer::isValidPeer (spiedPeer))
  6967. spiedPeer->removeScaleFactorListener (&scaleSpy);
  6968. juce::Desktop::getInstance().setGlobalScaleFactor (1.0f);
  6969. lynx::PluginWindows::setDetached (*instance, true);
  6970. }
  6971. else if (at == 14)
  6972. {
  6973. expect ("detached_reopened", lynx::PluginWindows::isOpen (*instance) && ! lynx::PluginWindows::isDocked (*instance));
  6974. expect ("detached_owned_by_main", plug != nullptr && lynx::nativechild::ownerOf (plug) == main);
  6975. expect ("detached_saved", find() == instance && engineRef() != nullptr && engineRef()->detached);
  6976. for (auto p : dockPanels)
  6977. workspace->activate (p);
  6978. }
  6979. else if (at == 15)
  6980. {
  6981. // (an owned top-level window: above the main window and so above all its child windows)
  6982. expect ("detached_stays_above_clicked_panels", plug != nullptr && lynx::nativechild::ownerOf (plug) == main
  6983. && lynx::nativechild::parentOf (plug) != main && lynx::PluginWindows::isOpen (*instance));
  6984. lynx::PluginWindows::setDetached (*instance, false);
  6985. }
  6986. else if (at == 16)
  6987. {
  6988. // issue #116 slice 4: a Fruity Dance dancer standing on the docked plugin window, in front of it
  6989. auto* stage = dynamic_cast<lynx::DanceStage*> (ui->danceStageForTest());
  6990. juce::Rectangle<int> over;
  6991. for (auto* c : lynx::nativechild::attachedChildren (main))
  6992. if (c->getWindowHandle() == plug)
  6993. over = ui->getLocalArea (nullptr, c->getScreenBounds());
  6994. expect ("dance_stage", stage != nullptr && ! over.isEmpty());
  6995. lynx::dance::Settings s;
  6996. s.move = lynx::dance::held; // (a still pose: the pixels tested below stay where they are)
  6997. s.x = over.getCentreX();
  6998. s.y = over.getCentreY() + 70;
  6999. const auto state = lynx::dance::toState (s);
  7000. engine->editSongStructural ([this, state] (lynx::Song& song) {
  7001. lynx::ChannelDef c;
  7002. c.name = "Fruity Dance";
  7003. c.instrument = lynx::InstrumentKind::fruitydance;
  7004. c.pluginState = state;
  7005. danceChannel = (int) song.channels.size();
  7006. song.channels.push_back (c);
  7007. });
  7008. engine->dispatchPendingMessages();
  7009. if (stage != nullptr)
  7010. stage->update();
  7011. }
  7012. else if (at == 17)
  7013. {
  7014. auto* stage = dynamic_cast<lynx::DanceStage*> (ui->danceStageForTest());
  7015. auto* w = stage != nullptr ? stage->windowOf (danceChannel) : nullptr;
  7016. auto* h = w != nullptr ? w->getWindowHandle() : nullptr;
  7017. expect ("dancer_window_native_child", h != nullptr && h != main && lynx::nativechild::parentOf (h) == main);
  7018. expect ("dancer_window_layered", lynx::nativechild::isLayered (h));
  7019. expect ("dancer_above_plugin", lynx::nativechild::isAbove (h, plug));
  7020. for (auto p : dockPanels)
  7021. expect ("dancer_above_" + id (p), lynx::nativechild::isAbove (h, panelHandle (p)));
  7022. // panels and the plugin brought in front (clicks, keys): the dancer stays in front of them
  7023. workspace->activate (Panel::mixer);
  7024. workspace->show (Panel::pianoRoll);
  7025. lynx::PluginWindows::open ({}, *instance, {});
  7026. expect ("dancer_stays_in_front", lynx::nativechild::isAbove (h, plug) && lynx::nativechild::isAbove (h, panelHandle (Panel::mixer))
  7027. && lynx::nativechild::isAbove (h, panelHandle (Panel::pianoRoll)));
  7028. // the mouse: the dancer's body takes it, its window's transparent pixels let it through
  7029. if (w != nullptr)
  7030. {
  7031. const auto picture = w->createComponentSnapshot (w->getLocalBounds(), true, 1.0f);
  7032. const auto body = stage->bodyOf (danceChannel) - (w->getScreenPosition() - stage->getScreenPosition());
  7033. juce::Point<int> solid { -1, -1 }, clear { -1, -1 };
  7034. for (int y = body.getCentreY() - 10; y < body.getBottom() && solid.x < 0; ++y)
  7035. for (int x = body.getX(); x < body.getRight() && solid.x < 0; ++x)
  7036. if (picture.getBounds().contains (x, y) && picture.getPixelAt (x, y).getAlpha() == 255)
  7037. solid = { x, y };
  7038. for (int y = 0; y < picture.getHeight() && clear.x < 0; y += 2)
  7039. for (int x = 0; x < picture.getWidth() && clear.x < 0; x += 2)
  7040. if (picture.getPixelAt (x, y).getAlpha() == 0 && ! body.expanded (8).contains (x, y))
  7041. clear = { x, y };
  7042. step ("dancer_window=" + w->getBounds().toString() + " solid=" + solid.toString() + " clear=" + clear.toString());
  7043. auto* atSolid = lynx::nativechild::windowAt (*w, solid);
  7044. auto* atClear = lynx::nativechild::windowAt (*w, clear);
  7045. expect ("dancer_takes_its_body_clicks", solid.x >= 0 && atSolid == h);
  7046. expect ("dancer_lets_clicks_through", clear.x >= 0 && atClear != nullptr && atClear != h);
  7047. expect ("stage_leaves_the_mouse", ! stage->hitTest (stage->bodyOf (danceChannel).getCentreX(), stage->bodyOf (danceChannel).getCentreY()));
  7048. }
  7049. }
  7050. else if (at == 18)
  7051. {
  7052. // no dance channel: no dancer window (nothing drawn, no cost)
  7053. auto* stage = dynamic_cast<lynx::DanceStage*> (ui->danceStageForTest());
  7054. engine->editSongStructural ([this] (lynx::Song& song) {
  7055. if (danceChannel >= 0 && danceChannel < (int) song.channels.size())
  7056. song.channels.erase (song.channels.begin() + danceChannel);
  7057. });
  7058. engine->dispatchPendingMessages();
  7059. if (stage != nullptr)
  7060. stage->update();
  7061. expect ("dancer_window_gone", stage != nullptr && stage->windowCount() == 0);
  7062. }
  7063. else if (at == 19 || at == 20)
  7064. {
  7065. // round 190ev (issue #152, "flickering windows"): on Windows a docked panel no longer fades by its
  7066. // window's alpha (each fade switched its drawing surface twice and the panel flashed); it shows and
  7067. // hides at once, as FL's docked windows. Elsewhere round 190i's fade stays.
  7068. auto& frame = workspace->getFrame (Panel::mixer);
  7069. if (at == 19)
  7070. {
  7071. workspace->show (Panel::mixer);
  7072. expect ("mixer_above_plugin_when_shown", lynx::nativechild::isAbove (panelHandle (Panel::mixer), plug));
  7073. workspace->hide (Panel::mixer);
  7074. expect ("mixer_hides_at_once", ! frame.isVisible() && workspace->nativeFadeDirection (Panel::mixer) == 0
  7075. && frame.getAlpha() == 1.0f && ! lynx::nativechild::isLayered (frame.getWindowHandle()));
  7076. }
  7077. else
  7078. {
  7079. workspace->show (Panel::mixer);
  7080. expect ("mixer_shows_at_once", frame.isVisible() && frame.getAlpha() == 1.0f && workspace->nativeFadeDirection (Panel::mixer) == 0
  7081. && ! lynx::nativechild::isLayered (frame.getWindowHandle())
  7082. && lynx::nativechild::isAbove (panelHandle (Panel::mixer), plug));
  7083. }
  7084. }
  7085. else if (at >= 21 && at <= 23)
  7086. {
  7087. // round 190ev (issue #152, "the Channel rack almost never comes to the front"): LYNX's own editor
  7088. // windows (here a channel's settings) are docked like FL's plugin windows, so a click on the rack
  7089. // brings the rack in front of them and a click on one brings it back; a click inside a docked
  7090. // plugin's own view (a native window JUCE never hears of) brings that plugin window in front.
  7091. auto docked = [] {
  7092. auto& desktop = juce::Desktop::getInstance();
  7093. for (int i = 0; i < desktop.getNumComponents(); ++i)
  7094. if (auto* c = desktop.getComponent (i); c != nullptr && c->isVisible() && (bool) c->getProperties()["lynxDockedWindow"])
  7095. return c;
  7096. return (juce::Component*) nullptr;
  7097. };
  7098. auto* rack = panelHandle (Panel::channelRack);
  7099. if (at == 21)
  7100. {
  7101. lynx::openChannelSettings (*engine, 0);
  7102. auto* ed = docked();
  7103. auto* h = ed != nullptr ? ed->getWindowHandle() : nullptr;
  7104. expect ("editor_docked", h != nullptr && lynx::nativechild::parentOf (h) == main && lynx::nativechild::ownerOf (h) == nullptr);
  7105. expect ("editor_above_rack_when_opened", h != nullptr && lynx::nativechild::isAbove (h, rack));
  7106. workspace->activate (Panel::channelRack); // a click on the rack
  7107. expect ("rack_above_editor_after_its_click", h != nullptr && lynx::nativechild::isAbove (rack, h));
  7108. // a real click (a message to the editor's own window) on its title bar, at a point where the editor
  7109. // can be seen. Round 190fc (0.1.27 RC M1): JUCE takes a button-down only where the system says its
  7110. // window is the one under the point (HWNDComponentPeer::contains asks WindowFromPoint), so the old
  7111. // fixed point (60, 8) was dropped whenever the rack, raised just above, covered it there: the
  7112. // check read 0 while real clicks (on what can be seen) raise the editor.
  7113. if (h != nullptr && ed != nullptr)
  7114. {
  7115. juce::Point<int> at (-1, -1);
  7116. for (int x = 30; x < ed->getWidth() - 40 && at.x < 0; x += 12)
  7117. if (lynx::nativechild::windowAt (*ed, { x, 8 }) == h)
  7118. at = { x, 8 };
  7119. step (juce::String ("editor_title_visible_at=") + juce::String (at.x));
  7120. if (at.x >= 0)
  7121. {
  7122. const auto scale = ed->getPeer() != nullptr ? ed->getPeer()->getPlatformScaleFactor() * (double) ed->getDesktopScaleFactor() : 1.0;
  7123. lynx::nativechild::postClickForTest (h, (at.toDouble() * scale).roundToInt());
  7124. }
  7125. }
  7126. }
  7127. else if (at == 22)
  7128. {
  7129. auto* ed = docked();
  7130. auto* h = ed != nullptr ? ed->getWindowHandle() : nullptr;
  7131. expect ("editor_above_rack_after_its_click", h != nullptr && lynx::nativechild::isAbove (h, rack));
  7132. workspace->activate (Panel::channelRack);
  7133. expect ("rack_above_plugin_after_its_click", lynx::nativechild::isAbove (rack, plug));
  7134. auto* view = lynx::nativechild::innermostChild (plug);
  7135. step (juce::String ("plugin_view_window=") + (view != nullptr ? "1" : "0"));
  7136. if (view != nullptr) // a click in the plugin's own view, near its top-left corner
  7137. lynx::nativechild::postClickForTest (view, { 2, 2 });
  7138. }
  7139. else
  7140. {
  7141. if (lynx::nativechild::innermostChild (plug) != nullptr)
  7142. expect ("plugin_above_rack_after_click_in_its_view", lynx::nativechild::isAbove (plug, rack));
  7143. lynx::closeChannelSettings();
  7144. // FL's Tools > Macros > Switch all plugin editors to > Detached (round 190i)
  7145. lynx::PluginWindows::setAllDetached (*engine, true);
  7146. }
  7147. }
  7148. else if (at == 24)
  7149. {
  7150. expect ("macro_detached_the_open_editor", lynx::PluginWindows::isOpen (*instance) && ! lynx::PluginWindows::isDocked (*instance)
  7151. && plug != nullptr && lynx::nativechild::ownerOf (plug) == main);
  7152. expect ("macro_detached_saved", find() == instance && engineRef() != nullptr && engineRef()->detached);
  7153. lynx::PluginWindows::setAllDetached (*engine, false); // ... > Attached
  7154. }
  7155. else
  7156. {
  7157. expect ("docked_again", lynx::PluginWindows::isDocked (*instance) && engineRef() != nullptr && ! engineRef()->detached);
  7158. step (juce::String ("dock_result=") + (dockOk ? "OK" : "FAILED"));
  7159. }
  7160. }
  7161. const lynx::PluginRef* engineRef() const
  7162. {
  7163. const auto& song = engine->getSong();
  7164. if (instrument)
  7165. return channelIndex < 0 || channelIndex >= (int) song.channels.size() ? nullptr : &song.channels[(size_t) channelIndex].plugin;
  7166. return song.mixer.size() < 2 || song.mixer[1].effects.empty() ? nullptr : &song.mixer[1].effects[0].plugin;
  7167. }
  7168. void step (const juce::String& line)
  7169. {
  7170. report << line << "\n";
  7171. juce::File (reportPath).replaceWithText (report);
  7172. }
  7173. juce::AudioPluginInstance* find()
  7174. {
  7175. if (instrument)
  7176. {
  7177. if (auto* p = dynamic_cast<lynx::PluginInstrument*> (engine->getChannelInstrument (channelIndex).get()))
  7178. return &p->getInstance();
  7179. }
  7180. else if (auto* p = dynamic_cast<lynx::PluginEffect*> (engine->getEffect (1, 0).get()))
  7181. return &p->getInstance();
  7182. return nullptr;
  7183. }
  7184. void timerCallback() override
  7185. {
  7186. ++ticks;
  7187. if (phase == 0) // waiting for the engine to host the plugin
  7188. {
  7189. instance = find();
  7190. if (instance == nullptr)
  7191. {
  7192. if (ticks > 200)
  7193. {
  7194. step ("result=FAILED (not hosted)");
  7195. stopTimer();
  7196. done (false);
  7197. }
  7198. return;
  7199. }
  7200. step ("hosted=" + instance->getName() + " format=" + instance->getPluginDescription().pluginFormatName);
  7201. step ("programs=" + juce::String (instance->getNumPrograms()));
  7202. for (int p = 0; p < juce::jmin (5, instance->getNumPrograms()); ++p)
  7203. step ("program" + juce::String (p) + "=" + instance->getProgramName (p));
  7204. step ("save_formats=" + lynx::pluginpresetui::saveWildcard (*instance));
  7205. // preset round trip: save, change the first parameter, load, compare
  7206. juce::AudioProcessorParameter* param = nullptr;
  7207. for (auto* candidate : instance->getParameters())
  7208. if (candidate->isAutomatable() && ! candidate->isMetaParameter() && candidate != instance->getBypassParameter())
  7209. {
  7210. param = candidate;
  7211. break;
  7212. }
  7213. if (param != nullptr)
  7214. {
  7215. step ("param=" + param->getName (64));
  7216. checked = param;
  7217. const auto file = lynx::pluginpresetui::folderFor (instance->getName()).getChildFile ("plugwintest.lynxpreset");
  7218. juce::String error;
  7219. const auto before = param->getValue();
  7220. const auto saved = lynx::pluginpresetui::save (*instance, file, "plugwintest", error);
  7221. param->setValueNotifyingHost (before > 0.5f ? 0.1f : 0.9f);
  7222. const auto changed = param->getValue();
  7223. const auto loaded = saved && lynx::pluginpresetui::load (*instance, file, error);
  7224. step ("preset_roundtrip saved=" + juce::String ((int) saved) + " loaded=" + juce::String ((int) loaded) + " param0 before="
  7225. + juce::String (before, 4) + " changed=" + juce::String (changed, 4) + " after=" + juce::String (param->getValue(), 4)
  7226. + (error.isNotEmpty() ? " error=" + error : juce::String()));
  7227. for (const auto* ext : { "fxp", "fxb", "vstpreset" })
  7228. {
  7229. juce::String e2;
  7230. const auto f2 = file.withFileExtension (ext);
  7231. const auto ok2 = lynx::pluginpresetui::save (*instance, f2, "plugwintest", e2) && lynx::pluginpresetui::load (*instance, f2, e2);
  7232. step (juce::String ("preset_") + ext + "=" + juce::String ((int) ok2) + (e2.isNotEmpty() ? " (" + e2 + ")" : juce::String()));
  7233. f2.deleteFile();
  7234. }
  7235. step ("browser_lists=" + juce::String (lynx::pluginpresetui::userPresets (instance->getName()).size()));
  7236. }
  7237. std::shared_ptr<void> owner = instrument ? std::shared_ptr<void> (engine->getChannelInstrument (channelIndex))
  7238. : std::shared_ptr<void> (engine->getEffect (1, 0));
  7239. lynx::PluginWindows::open (owner, *instance, instance->getName(),
  7240. { engine.get(), [this] (lynx::Song& song) -> lynx::PluginRef* {
  7241. if (instrument)
  7242. return channelIndex < 0 || channelIndex >= (int) song.channels.size()
  7243. ? nullptr : &song.channels[(size_t) channelIndex].plugin;
  7244. return song.mixer.size() < 2 || song.mixer[1].effects.empty() ? nullptr : &song.mixer[1].effects[0].plugin;
  7245. }, instrument });
  7246. owner.reset();
  7247. step ("window_open=" + juce::String ((int) lynx::PluginWindows::isOpen (*instance)));
  7248. phase = 1;
  7249. ticks = 0;
  7250. phaseStartMs = juce::Time::getMillisecondCounter();
  7251. return;
  7252. }
  7253. if (phase == 1 && ticks >= 30 && ! keysDone && juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGWIN_KEYS", {}).isNotEmpty() && instance->getActiveEditor() != nullptr)
  7254. keysDone = ! lynx::pluginKeysTestTick (*instance->getActiveEditor(),
  7255. [this] (bool on) {
  7256. engine->editSong ([this, on] (lynx::Song& song) {
  7257. (instrument ? song.channels[(size_t) channelIndex].plugin : song.mixer[1].effects[0].plugin).hostKeysFirst = on;
  7258. });
  7259. },
  7260. [this] (const juce::String& line) { step (line); });
  7261. const auto elapsedMs = (int) (juce::Time::getMillisecondCounter() - phaseStartMs);
  7262. if (phase == 1 && ticks == 20 && checked != nullptr)
  7263. step ("param_after_1s=" + juce::String (checked->getValue(), 4));
  7264. // (3 s apart: time for screenshots of each state)
  7265. if (phase == 1 && workspace != nullptr && dockStep < dockSteps && elapsedMs >= (dockStep + 1) * stepMs)
  7266. dockCheck (dockStep++);
  7267. if (phase == 1 && dropFile.existsAsFile())
  7268. dropTick (elapsedMs);
  7269. // (with LYNX_PLUGWIN_DROP: `seconds` after the drop places were reported, time for the drag)
  7270. const auto dropDone = ! dropFile.existsAsFile()
  7271. || (dropStage == 2 && (int) (juce::Time::getMillisecondCounter() - dropReadyMs) >= seconds * 1000);
  7272. if (phase == 1 && elapsedMs >= seconds * 1000 && dropDone && (workspace == nullptr || dockStep >= dockSteps)) // remove the plugin from the song
  7273. {
  7274. if (dropFile.existsAsFile())
  7275. dropResult();
  7276. engine->editSong ([this] (lynx::Song& song) {
  7277. if (instrument)
  7278. {
  7279. if (channelIndex >= 0 && channelIndex < (int) song.channels.size())
  7280. song.channels.erase (song.channels.begin() + channelIndex);
  7281. }
  7282. else
  7283. song.mixer[1].effects.clear();
  7284. });
  7285. step ("removed");
  7286. phase = 2;
  7287. ticks = 0;
  7288. return;
  7289. }
  7290. if (phase == 2 && ticks >= 40)
  7291. {
  7292. const auto open = lynx::PluginWindows::isOpen (*instance);
  7293. step ("window_open_after_remove=" + juce::String ((int) open));
  7294. step (open || ! dockOk ? "result=FAILED" : "result=OK");
  7295. stopTimer();
  7296. lynx::PluginWindows::closeAll();
  7297. done (! open && dockOk);
  7298. }
  7299. }
  7300. };
  7301. auto* test = new Test();
  7302. test->reportPath = reportPath;
  7303. test->seconds = seconds;
  7304. if (const auto drop = juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGWIN_DROP", {}); drop.isNotEmpty())
  7305. test->dropFile = juce::File (drop);
  7306. test->done = [this, test] (bool ok) {
  7307. setApplicationReturnValue (ok ? 0 : 1);
  7308. juce::MessageManager::callAsync ([this, test] {
  7309. lynx::setMainWindowForOwnership (nullptr);
  7310. lynx::PluginWindows::setDockWorkspace (nullptr);
  7311. test->dropWindow = nullptr; // (its Browser before the engine)
  7312. test->workspace = nullptr;
  7313. test->mainWindow = nullptr; // (dock mode: the main component with it, before the engine)
  7314. test->engine = nullptr;
  7315. delete test;
  7316. quit();
  7317. });
  7318. };
  7319. test->engine = std::make_unique<lynx::AudioEngine> (false);
  7320. test->mainWindow = std::make_unique<juce::DocumentWindow> ("LYNX test main window", juce::Colours::darkgrey, 0);
  7321. test->mainWindow->setBounds (20, 20, 300, 200);
  7322. if (juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGWIN_DOCK", {}) == "1" && lynx::nativechild::dockingEnabled())
  7323. {
  7324. // the real main window's contents (it docks plugin windows in its own desktop), so the panels are real
  7325. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  7326. auto* ui = new lynx::MainComponent (*test->engine, false);
  7327. test->mainWindow->setUsingNativeTitleBar (true);
  7328. test->mainWindow->setContentOwned (ui, false);
  7329. test->mainWindow->setBounds (20, 20, 1500, 900);
  7330. test->workspace = &ui->workspaceForTest();
  7331. test->ui = ui;
  7332. if (const auto ms = juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGWIN_STEP_MS", {}).getIntValue(); ms > 0)
  7333. test->stepMs = ms;
  7334. }
  7335. test->mainWindow->setVisible (true);
  7336. lynx::setMainWindowForOwnership (test->mainWindow.get());
  7337. if (test->workspace != nullptr)
  7338. {
  7339. using lynx::workspace::Panel;
  7340. for (auto p : { Panel::playlist, Panel::mixer, Panel::pianoRoll, Panel::channelRack })
  7341. test->workspace->show (p);
  7342. test->step ("dock_test=2 rack_visible=" + juce::String ((int) test->workspace->isPanelVisible (Panel::channelRack)));
  7343. }
  7344. auto& host = test->engine->getPluginHost();
  7345. test->step ("plugins_in_file=" + juce::String (host.addPluginFile (juce::File (pluginPath))));
  7346. std::optional<juce::PluginDescription> chosen;
  7347. for (const auto& type : host.getKnownPlugins().getTypes())
  7348. if ((juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginPath).getFileName() || type.fileOrIdentifier == pluginPath)
  7349. && (only.isEmpty() || type.name == only))
  7350. {
  7351. chosen = type;
  7352. break;
  7353. }
  7354. if (! chosen)
  7355. {
  7356. test->step ("result=FAILED (no plugin)");
  7357. test->done (false);
  7358. return;
  7359. }
  7360. test->instrument = chosen->isInstrument;
  7361. lynx::PluginRef ref;
  7362. ref.separateProcess = juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGWIN_SEPARATE", {}) == "1"; // (issue #96's other-process check)
  7363. ref.id = chosen->createIdentifierString().toStdString();
  7364. ref.name = chosen->name.toStdString();
  7365. test->engine->editSong ([&] (lynx::Song& song) {
  7366. if (test->instrument)
  7367. {
  7368. lynx::ChannelDef c;
  7369. c.name = ref.name;
  7370. c.instrument = lynx::InstrumentKind::plugin;
  7371. c.plugin = ref;
  7372. test->channelIndex = (int) song.channels.size();
  7373. song.channels.push_back (c);
  7374. }
  7375. else
  7376. {
  7377. while (song.mixer.size() < 2)
  7378. song.mixer.emplace_back();
  7379. lynx::EffectSlot slot;
  7380. slot.kind = lynx::EffectKind::plugin;
  7381. slot.plugin = ref;
  7382. song.mixer[1].effects.push_back (slot);
  7383. }
  7384. });
  7385. test->step ("plugin=" + chosen->name + " instrument=" + juce::String ((int) test->instrument));
  7386. test->startTimerHz (20);
  7387. }
  7388. void runEditorCrashTest (const juce::String& pluginPath, const juce::String& reportPath)
  7389. {
  7390. struct CrashTest final : juce::Timer
  7391. {
  7392. juce::String reportPath, report;
  7393. std::unique_ptr<lynx::PluginHost> host;
  7394. juce::AudioPluginInstance* plugin = nullptr;
  7395. std::shared_ptr<juce::AudioPluginInstance> keep; // a window whose plugin nobody else holds is closed as orphaned
  7396. std::function<void (bool)> done;
  7397. int ticks = 0, crashesBefore = 0;
  7398. void step (const juce::String& line)
  7399. {
  7400. report << line << "\n";
  7401. juce::File (reportPath).replaceWithText (report); // at each step: a crash leaves the last one
  7402. }
  7403. void timerCallback() override
  7404. {
  7405. ++ticks;
  7406. const auto crashes = lynx::PluginWindows::editorCrashCount() - crashesBefore;
  7407. const auto open = lynx::PluginWindows::isOpen (*plugin);
  7408. if ((crashes > 0 && ! open) || ticks >= 50) // 100 ms ticks: up to 5 s
  7409. {
  7410. stopTimer();
  7411. step ("editor_crashes=" + juce::String (crashes) + " window_open=" + juce::String ((int) open) + " ticks=" + juce::String (ticks));
  7412. bool traced = false;
  7413. if (crashes > 0)
  7414. {
  7415. const auto last = lynx::PluginWindows::editorCrashes().back();
  7416. traced = last.traceFile.existsAsFile() && last.traceFile.loadFileAsString().contains ("LYNX Test Crash");
  7417. step ("plugin=" + last.plugin + " detail=" + last.detail + " trace=" + last.traceFile.getFileName() + " traced="
  7418. + juce::String ((int) traced));
  7419. last.traceFile.deleteFile();
  7420. }
  7421. // still alive: one more message through the loop after the fault
  7422. juce::MessageManager::callAsync ([this, ok = crashes == 1 && ! open && traced] {
  7423. step ("message_loop_after_fault=1");
  7424. step (juce::String ("result=") + (ok ? "OK" : "FAILED"));
  7425. done (ok);
  7426. });
  7427. }
  7428. }
  7429. };
  7430. auto* test = new CrashTest();
  7431. test->reportPath = reportPath;
  7432. test->done = [this, test] (bool ok)
  7433. {
  7434. setApplicationReturnValue (ok ? 0 : 1);
  7435. juce::MessageManager::callAsync ([this, test] { lynx::PluginWindows::closeAll(); delete test; quit(); });
  7436. };
  7437. #if ! JUCE_WINDOWS
  7438. test->step ("result=SKIPPED (Windows only: on macOS / Linux a plugin fault is a signal, see docs/analise/REA_rodada174a.md)");
  7439. test->done (true);
  7440. return;
  7441. #else
  7442. _putenv_s ("LYNX_TEST_CRASH", "editor");
  7443. test->host = std::make_unique<lynx::PluginHost> (false);
  7444. test->step ("plugins_in_file=" + juce::String (test->host->addPluginFile (juce::File (pluginPath))));
  7445. std::shared_ptr<juce::AudioPluginInstance> instance;
  7446. for (const auto& type : test->host->getKnownPlugins().getTypes())
  7447. {
  7448. if (juce::File (type.fileOrIdentifier).getFileName() != juce::File (pluginPath).getFileName())
  7449. continue;
  7450. juce::String error;
  7451. instance = std::shared_ptr<juce::AudioPluginInstance> (lynx::createRightInstance (test->host->getFormats(), type, 48000.0, 512, error).release());
  7452. test->step ("plugin=" + type.name + (instance == nullptr ? " error=" + error : juce::String()));
  7453. break;
  7454. }
  7455. if (instance == nullptr || ! instance->hasEditor())
  7456. {
  7457. test->step ("result=FAILED (no plugin with an editor)");
  7458. test->done (false);
  7459. return;
  7460. }
  7461. lynx::preparePlugin (*instance, 48000.0, 512);
  7462. test->plugin = instance.get();
  7463. test->keep = instance;
  7464. test->crashesBefore = lynx::PluginWindows::editorCrashCount();
  7465. lynx::PluginWindows::open (instance, *instance, instance->getName()); // (the window keeps the plugin alive)
  7466. test->step ("window_open=" + juce::String ((int) lynx::PluginWindows::isOpen (*instance)));
  7467. test->startTimer (100);
  7468. #endif
  7469. }
  7470. void runEditorTest (const juce::String& pluginPath, const juce::String& reportPath, const juce::String& only)
  7471. {
  7472. struct EditorTest final : juce::Timer
  7473. {
  7474. juce::String reportPath, report;
  7475. std::unique_ptr<lynx::PluginHost> host;
  7476. std::unique_ptr<juce::AudioPluginInstance> plugin;
  7477. std::unique_ptr<juce::DocumentWindow> window;
  7478. std::function<void (bool)> done;
  7479. void step (const juce::String& line)
  7480. {
  7481. report << line << "\n";
  7482. juce::File (reportPath).replaceWithText (report); // written at each step: a crash leaves the last one
  7483. }
  7484. void timerCallback() override
  7485. {
  7486. stopTimer();
  7487. window = nullptr;
  7488. step ("step=closed");
  7489. plugin = nullptr;
  7490. step ("result=OK");
  7491. done (true);
  7492. }
  7493. };
  7494. auto* test = new EditorTest();
  7495. test->reportPath = reportPath;
  7496. test->done = [this, test] (bool ok)
  7497. {
  7498. setApplicationReturnValue (ok ? 0 : 1);
  7499. juce::MessageManager::callAsync ([this, test] { delete test; quit(); });
  7500. };
  7501. test->host = std::make_unique<lynx::PluginHost> (false);
  7502. test->step ("plugins_in_file=" + juce::String (test->host->addPluginFile (juce::File (pluginPath))));
  7503. test->step ("exe=" + juce::File::getSpecialLocation (juce::File::currentExecutableFile).getFullPathName());
  7504. for (const auto& type : test->host->getKnownPlugins().getTypes())
  7505. {
  7506. if (juce::File (type.fileOrIdentifier).getFileName() != juce::File (pluginPath).getFileName()
  7507. || (only.isNotEmpty() && type.name != only))
  7508. continue;
  7509. juce::String error;
  7510. test->plugin = lynx::createRightInstance (test->host->getFormats(), type, 48000.0, 512, error);
  7511. test->step ("plugin=" + type.name + (test->plugin == nullptr ? " error=" + error : juce::String()));
  7512. break;
  7513. }
  7514. if (test->plugin == nullptr)
  7515. {
  7516. test->step ("result=FAILED");
  7517. test->done (false);
  7518. return;
  7519. }
  7520. lynx::preparePlugin (*test->plugin, 48000.0, 512);
  7521. test->step ("step=create_editor");
  7522. test->window = std::make_unique<juce::DocumentWindow> (test->plugin->getName(), juce::Colours::black, juce::DocumentWindow::closeButton);
  7523. test->window->setUsingNativeTitleBar (true);
  7524. if (auto* editor = test->plugin->createEditorIfNeeded())
  7525. test->window->setContentOwned (editor, true);
  7526. else
  7527. test->step ("no_editor");
  7528. test->step ("step=show");
  7529. test->window->centreWithSize (test->window->getWidth(), test->window->getHeight());
  7530. test->window->setVisible (true);
  7531. test->step ("step=shown");
  7532. test->startTimer (4000);
  7533. }
  7534. void runFitTest (const juce::String& reportPath, int percent)
  7535. {
  7536. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  7537. struct FitTest final : juce::Timer
  7538. {
  7539. juce::String path, report;
  7540. bool ok = true;
  7541. int step = 0, percent = 150;
  7542. std::unique_ptr<juce::DocumentWindow> tall, big;
  7543. std::function<void()> done;
  7544. // `whole`: the window must fit entirely (a resizable one); else its title bar and close button must be on the screen
  7545. void check (const juce::String& what, juce::Component& w, bool whole)
  7546. {
  7547. juce::BorderSize<int> frame;
  7548. if (auto* peer = w.getPeer())
  7549. if (const auto f = peer->getFrameSizeIfPresent())
  7550. frame = *f;
  7551. auto outer = frame.addedTo (w.getBounds());
  7552. const auto* display = juce::Desktop::getInstance().getDisplays().getDisplayForRect (outer);
  7553. const auto area = display != nullptr ? display->userArea : outer;
  7554. #if JUCE_LINUX
  7555. // round 164: a compositor that draws the frame itself (WSLg's Weston) reports its invisible shadow in
  7556. // the frame (59 px on top, 38 around at 100%): only what is visible is checked, give or take 4 px
  7557. const auto shadow = frame.getLeft() >= 16 ? frame.getLeft() : 0;
  7558. outer = outer.reduced (shadow);
  7559. const auto slack = shadow > 0 ? 4 : 0;
  7560. #else
  7561. const auto slack = 0;
  7562. #endif
  7563. const auto passed = outer.getY() >= area.getY() - slack && outer.getRight() <= area.getRight() + slack && outer.getX() >= area.getX() - slack
  7564. && (! whole || outer.getBottom() <= area.getBottom() + 1 + slack);
  7565. report << (passed ? "ok " : "FAIL ") << what << " window=" << outer.toString() << " (frame " << frame.getTop() << ","
  7566. << frame.getLeft() << ") screen=" << area.toString() << "\n";
  7567. ok = ok && passed;
  7568. }
  7569. void start()
  7570. {
  7571. report << "scale=" << percent << "%\n";
  7572. juce::Desktop::getInstance().setGlobalScaleFactor ((float) percent / 100.0f);
  7573. // a tool window taller than the screen, centred (its title bar would be above the screen)
  7574. tall = std::make_unique<juce::DocumentWindow> ("LYNX fit test - tall", lynx::theme::colour::bg2, juce::DocumentWindow::closeButton);
  7575. tall->setUsingNativeTitleBar (true);
  7576. auto* content = new juce::Component();
  7577. const auto area = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea;
  7578. content->setSize (500, area.getHeight() + 200);
  7579. tall->setContentOwned (content, true);
  7580. tall->setCentrePosition (area.getCentre());
  7581. tall->setVisible (true);
  7582. lynx::keepAboveMainWindow (*tall);
  7583. // LYNX_FITTEST_MS: how long each window stays (default 700 ms; longer to take screenshots of them)
  7584. startTimer (juce::jlimit (300, 60000, juce::SystemStats::getEnvironmentVariable ("LYNX_FITTEST_MS", "700").getIntValue()));
  7585. }
  7586. void timerCallback() override
  7587. {
  7588. ++step;
  7589. if (step == 1)
  7590. {
  7591. check ("tall tool window: title bar and close button on the screen", *tall, false);
  7592. tall.reset();
  7593. // round 164: a fixed-size LYNX tool window whose content is taller than the screen: it scrolls
  7594. auto content = std::make_unique<juce::Component>();
  7595. const auto screen = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea;
  7596. content->setSize (520, screen.getHeight() + 300);
  7597. lynx::openToolWindow (std::move (content), "LYNX fit test - fixed size", "fittest-fixed");
  7598. return;
  7599. }
  7600. if (step == 2)
  7601. {
  7602. if (auto* w = lynx::findToolWindow ("fittest-fixed"))
  7603. {
  7604. check ("fixed-size tool window taller than the screen: fits (its content scrolls)", *w, true);
  7605. const auto scrolls = w->getContentComponent() != nullptr && w->getContentComponent()->getNumChildComponents() > 0
  7606. && dynamic_cast<juce::Viewport*> (w->getContentComponent()->getChildComponent (0)) != nullptr;
  7607. report << (scrolls ? "ok " : "FAIL ") << "its content is in a scrolling viewport\n";
  7608. ok = ok && scrolls;
  7609. }
  7610. else
  7611. {
  7612. report << "FAIL fixed-size tool window not found\n";
  7613. ok = false;
  7614. }
  7615. lynx::closeAllToolWindows();
  7616. // a resizable window that fits at 100%, then the zoom goes up (the main window's case)
  7617. juce::Desktop::getInstance().setGlobalScaleFactor (1.0f);
  7618. big = std::make_unique<juce::DocumentWindow> ("LYNX fit test - zoom", lynx::theme::colour::bg2, juce::DocumentWindow::allButtons);
  7619. big->setUsingNativeTitleBar (true);
  7620. big->setResizable (true, false);
  7621. big->setResizeLimits (400, 300, 10000, 10000);
  7622. const auto area = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea;
  7623. big->setBounds (area.getX() + 40, area.getY() + 60, area.getWidth() * 9 / 10 - 40, area.getHeight() * 9 / 10 - 60);
  7624. big->setVisible (true);
  7625. return;
  7626. }
  7627. if (step == 3)
  7628. {
  7629. juce::Desktop::getInstance().setGlobalScaleFactor ((float) percent / 100.0f);
  7630. juce::Timer::callAfterDelay (200, [] { lynx::fitAllWindowsOnScreen(); });
  7631. return;
  7632. }
  7633. if (step == 4)
  7634. {
  7635. check ("resizable window after the zoom change: fits the screen", *big, true);
  7636. big.reset();
  7637. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  7638. juce::File (path).replaceWithText (report);
  7639. stopTimer();
  7640. if (done)
  7641. done();
  7642. }
  7643. }
  7644. };
  7645. static std::unique_ptr<FitTest> test;
  7646. test = std::make_unique<FitTest>();
  7647. test->path = reportPath;
  7648. test->percent = juce::jlimit (50, 300, percent);
  7649. test->done = [this] { juce::MessageManager::callAsync ([this] { test.reset(); quit(); }); };
  7650. test->start();
  7651. }
  7652. void runFocusTest (const juce::String& reportPath)
  7653. {
  7654. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  7655. struct FocusTest final : juce::Timer
  7656. {
  7657. juce::String reportPath, report;
  7658. bool ok = true;
  7659. int stepIndex = 0;
  7660. std::unique_ptr<lynx::AudioEngine> engine;
  7661. lynx::MainComponent* ui = nullptr;
  7662. std::unique_ptr<juce::DocumentWindow> main;
  7663. std::function<void()> done;
  7664. void line (const juce::String& text)
  7665. {
  7666. report << text << "\n";
  7667. juce::File (reportPath).replaceWithText (report);
  7668. }
  7669. void check (const juce::String& what, bool passed)
  7670. {
  7671. line ((passed ? "ok " : "FAIL ") + what);
  7672. ok = ok && passed;
  7673. }
  7674. juce::ComponentPeer* mainPeer() const { return main != nullptr ? main->getPeer() : nullptr; }
  7675. bool focusInMain() const
  7676. {
  7677. auto* f = juce::Component::getCurrentlyFocusedComponent();
  7678. return f != nullptr && main->isParentOf (f);
  7679. }
  7680. // a click (press and release) at the middle of the panel's content, through the native window it is in
  7681. static void click (juce::Component& frame, bool right)
  7682. {
  7683. auto* peer = frame.getPeer();
  7684. if (peer == nullptr)
  7685. return;
  7686. const auto at = peer->getComponent().getLocalPoint (&frame, frame.getLocalBounds().getCentre().toFloat());
  7687. const auto button = right ? juce::ModifierKeys::rightButtonModifier : juce::ModifierKeys::leftButtonModifier;
  7688. const auto now = juce::Time::currentTimeMillis();
  7689. peer->handleMouseEvent (juce::MouseInputSource::InputSourceType::mouse, at, juce::ModifierKeys (button), 1.0f, 0.0f, now);
  7690. peer->handleMouseEvent (juce::MouseInputSource::InputSourceType::mouse, at, juce::ModifierKeys(), 1.0f, 0.0f, now + 40);
  7691. }
  7692. bool space()
  7693. {
  7694. auto* peer = mainPeer(); // (the system sends the key to the window with the focus: the main one)
  7695. return peer != nullptr && peer->handleKeyPress (juce::KeyPress (juce::KeyPress::spaceKey, juce::ModifierKeys(), ' '));
  7696. }
  7697. juce::TextEditor* firstField (juce::Component& c)
  7698. {
  7699. if (auto* t = dynamic_cast<juce::TextEditor*> (&c); t != nullptr && t->isShowing() && t->getWantsKeyboardFocus())
  7700. return t;
  7701. for (auto* child : c.getChildren())
  7702. if (auto* t = firstField (*child))
  7703. return t;
  7704. return nullptr;
  7705. }
  7706. // the user tabs away and comes back with a click in `panel`
  7707. void backWithClickIn (lynx::workspace::Panel panel, bool right)
  7708. {
  7709. auto& frame = ui->workspaceForTest().getFrame (panel);
  7710. const auto name = juce::String (lynx::workspace::panelId (panel)) + (right ? " (right click)" : "");
  7711. auto* peer = mainPeer();
  7712. line (name + ": native child window=" + juce::String ((int) lynx::nativechild::isAttached (frame)));
  7713. check (name + ": the main window has the keys before", ui->hasKeyboardFocus (true));
  7714. peer->handleFocusLoss(); // (another app is in front: the main window lost the system focus)
  7715. check (name + ": nothing in LYNX has the keys while it is in the background", ! focusInMain());
  7716. // the cause: JUCE answers the system's "activate?" from the panel's own component, which takes no focus on a click
  7717. line (name + ": JUCE's answer alone would activate the window=" + juce::String ((int) frame.getMouseClickGrabsKeyboardFocus()));
  7718. const auto activates = lynx::nativechild::clickActivatesWindow (frame, false);
  7719. check (name + ": a click in it activates the inactive main window", activates);
  7720. #if JUCE_WINDOWS
  7721. if (lynx::nativechild::isAttached (frame))
  7722. check (name + ": its native window answers WM_MOUSEACTIVATE with MA_ACTIVATE",
  7723. lynx::nativechild::mouseActivateAnswerForTest (frame, true) == 1 /* MA_ACTIVATE */);
  7724. #endif
  7725. if (activates)
  7726. peer->handleFocusGain(); // (the system activates the main window and gives it the focus)
  7727. click (frame, right);
  7728. }
  7729. void spacePlays (lynx::workspace::Panel panel, bool right)
  7730. {
  7731. const auto name = juce::String (lynx::workspace::panelId (panel)) + (right ? " (right click)" : "");
  7732. check (name + ": the main window has the keys after the click", ui->hasKeyboardFocus (true));
  7733. auto& transport = engine->getTransport();
  7734. if (transport.playing.load())
  7735. engine->stop();
  7736. const auto used = space();
  7737. check (name + ": Space starts playback", used && transport.playing.load());
  7738. engine->stop();
  7739. }
  7740. void timerCallback() override
  7741. {
  7742. using lynx::workspace::Panel;
  7743. auto& ws = ui->workspaceForTest();
  7744. switch (stepIndex++)
  7745. {
  7746. case 0:
  7747. line ("docking=" + juce::String ((int) lynx::nativechild::dockingEnabled()));
  7748. ws.show (Panel::playlist);
  7749. ws.show (Panel::pianoRoll);
  7750. ui->grabKeyboardFocus();
  7751. break;
  7752. case 1: backWithClickIn (Panel::playlist, false); break;
  7753. case 2: spacePlays (Panel::playlist, false); ui->grabKeyboardFocus(); break;
  7754. case 3: backWithClickIn (Panel::pianoRoll, false); break;
  7755. case 4: spacePlays (Panel::pianoRoll, false); ui->grabKeyboardFocus(); break;
  7756. case 5: backWithClickIn (Panel::playlist, true); break;
  7757. case 6:
  7758. juce::PopupMenu::dismissAllActiveMenus(); // (the right click's menu)
  7759. spacePlays (Panel::playlist, true);
  7760. break;
  7761. case 7:
  7762. {
  7763. // a text field (the Browser's search box) keeps the keys through a switch to another app and back:
  7764. // nothing in LYNX takes them from it (no periodic grab); inside the active window the click's
  7765. // activation answer is unchanged, and a click in the Playlist ends the typing as before (issue #9,
  7766. // as FL ends typing in its search field)
  7767. auto* field = firstField (*ui);
  7768. line ("text field found=" + juce::String ((int) (field != nullptr)));
  7769. if (field != nullptr)
  7770. {
  7771. auto& frame = ws.getFrame (Panel::playlist);
  7772. field->grabKeyboardFocus();
  7773. check ("the text field has the keys", field->hasKeyboardFocus (false));
  7774. mainPeer()->handleFocusLoss();
  7775. mainPeer()->handleFocusGain(); // (back with Alt+Tab, or a click that activates the window)
  7776. check ("the text field gets the keys back with the window", field->hasKeyboardFocus (false));
  7777. check ("active window: a click in a panel does not activate it again", ! lynx::nativechild::clickActivatesWindow (frame, true));
  7778. click (frame, false);
  7779. check ("a click in the Playlist ends the typing: the main window has the keys", ui->hasKeyboardFocus (true) && ! field->hasKeyboardFocus (false));
  7780. }
  7781. line (ok ? "result=OK" : "result=FAILED");
  7782. stopTimer();
  7783. done();
  7784. break;
  7785. }
  7786. default:
  7787. break;
  7788. }
  7789. }
  7790. };
  7791. auto* test = new FocusTest();
  7792. test->reportPath = reportPath;
  7793. startFocusTestWindow (*test);
  7794. test->startTimer (600);
  7795. }
  7796. // --simplekeytest (round 190fc, 0.1.27 RC H2): in the Simple layout Space often did nothing after a click in the
  7797. // window (the dock, a track header, the grid, the Lyrics button) or after a demo opened from Welcome › Start from. The
  7798. // main window in the Simple layout; each step clicks as the system would (through the native window under the point)
  7799. // and presses Space where the system sends it (the native window of the component with the focus): playback must
  7800. // start, except while a text field the user clicked into has the keys (it types). Shows a window (Windows: GUI lock).
  7801. void runSimpleKeyTest (const juce::String& reportPath)
  7802. {
  7803. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  7804. struct KeyTest final : juce::Timer
  7805. {
  7806. juce::String reportPath, report;
  7807. bool ok = true;
  7808. int stepIndex = 0, instrumentTrack = 0;
  7809. std::unique_ptr<lynx::AudioEngine> engine;
  7810. lynx::MainComponent* ui = nullptr;
  7811. std::unique_ptr<juce::DocumentWindow> main;
  7812. std::function<void()> done;
  7813. void line (const juce::String& text)
  7814. {
  7815. report << text << "\n";
  7816. juce::File (reportPath).replaceWithText (report);
  7817. }
  7818. void check (const juce::String& what, bool passed)
  7819. {
  7820. line ((passed ? "ok " : "FAIL ") + what);
  7821. ok = ok && passed;
  7822. }
  7823. static juce::String describe (juce::Component* c)
  7824. {
  7825. if (c == nullptr)
  7826. return "nothing";
  7827. juce::String path;
  7828. for (auto* p = c; p != nullptr && path.length() < 160; p = p->getParentComponent())
  7829. {
  7830. auto name = p->getComponentID().isNotEmpty() ? p->getComponentID() : p->getName();
  7831. if (name.isEmpty())
  7832. name = juce::String (typeid (*p).name()).fromLastOccurrenceOf ("::", false, false).substring (0, 28);
  7833. path << (path.isEmpty() ? "" : " < ") << name;
  7834. }
  7835. return path;
  7836. }
  7837. // the first showing component with this ID in the main window or a native child window of it
  7838. juce::Component* find (const juce::String& id)
  7839. {
  7840. std::function<juce::Component* (juce::Component&)> in = [&] (juce::Component& root) -> juce::Component* {
  7841. if (root.getComponentID() == id && root.isShowing())
  7842. return &root;
  7843. for (auto* c : root.getChildren())
  7844. if (auto* f = in (*c))
  7845. return f;
  7846. return nullptr;
  7847. };
  7848. if (auto* f = in (*main))
  7849. return f;
  7850. if (auto* peer = main->getPeer())
  7851. for (auto* attached : lynx::nativechild::attachedChildren (peer->getNativeHandle()))
  7852. if (auto* f = in (*attached))
  7853. return f;
  7854. return nullptr;
  7855. }
  7856. // a click (press and release) at `local` in `c`, through the native window it is in
  7857. juce::String lastHit;
  7858. void click (juce::Component& c, juce::Point<int> local)
  7859. {
  7860. auto* peer = c.getPeer();
  7861. if (peer == nullptr)
  7862. return;
  7863. const auto at = peer->getComponent().getLocalPoint (&c, local.toFloat());
  7864. lastHit = describe (peer->getComponent().getComponentAt (at.roundToInt()));
  7865. line (" click at " + local.toString() + " in " + describe (&c).upToFirstOccurrenceOf (" < ", false, false) + " -> " + lastHit);
  7866. const auto now = juce::Time::currentTimeMillis();
  7867. peer->handleMouseEvent (juce::MouseInputSource::InputSourceType::mouse, at, juce::ModifierKeys (juce::ModifierKeys::leftButtonModifier), 1.0f, 0.0f, now);
  7868. peer->handleMouseEvent (juce::MouseInputSource::InputSourceType::mouse, at, juce::ModifierKeys(), 1.0f, 0.0f, now + 40);
  7869. }
  7870. void click (juce::Component& c) { click (c, c.getLocalBounds().getCentre()); }
  7871. // Space where the system sends it: the native window of the focused component (else the main one)
  7872. bool space()
  7873. {
  7874. // Windows: posted to the window with the system's focus, as a real key goes (the system's own routing)
  7875. if (lynx::nativechild::pressSpaceForTest (main->getWindowHandle()))
  7876. return true;
  7877. auto* focused = juce::Component::getCurrentlyFocusedComponent();
  7878. auto* peer = focused != nullptr && focused->getPeer() != nullptr ? focused->getPeer() : main->getPeer();
  7879. return peer != nullptr && peer->handleKeyPress (juce::KeyPress (juce::KeyPress::spaceKey, juce::ModifierKeys(), ' '));
  7880. }
  7881. void spacePlays (const juce::String& after)
  7882. {
  7883. line (" keys at: " + describe (juce::Component::getCurrentlyFocusedComponent()));
  7884. auto& transport = engine->getTransport();
  7885. if (transport.playing.load())
  7886. engine->stop();
  7887. space();
  7888. check ("Space plays after " + after, transport.playing.load());
  7889. engine->stop();
  7890. }
  7891. void timerCallback() override
  7892. {
  7893. auto* simple = ui->getSimpleWorkflowForSnapshot();
  7894. auto& playlist = ui->getPlaylistForSnapshot();
  7895. switch (stepIndex++)
  7896. {
  7897. case 0:
  7898. ui->setLayoutStyle (lynx::layoutstyle::Style::simple);
  7899. ui->grabKeyboardFocus();
  7900. break;
  7901. case 1:
  7902. check ("the Simple workflow is up", simple != nullptr);
  7903. if (simple == nullptr)
  7904. return finish();
  7905. spacePlays ("the layout came up");
  7906. simple->showWelcome();
  7907. break;
  7908. case 2:
  7909. if (auto* demo = find ("tour.welcome.demo"))
  7910. click (*demo); // Welcome › Open a demo song: the Start from list
  7911. else
  7912. check ("Welcome > Open a demo song found", false);
  7913. break;
  7914. case 3:
  7915. {
  7916. if (! simple->isStartFromShowing()) // (X11: a child window just mapped may miss the first click)
  7917. if (auto* demo = find ("tour.welcome.demo"))
  7918. {
  7919. line (" the first click was not taken: once more");
  7920. click (*demo);
  7921. }
  7922. check ("Start from is up", simple->isStartFromShowing());
  7923. if (auto* start = dynamic_cast<lynx::StartFromPanel*> (simple->startFromForSnapshot()))
  7924. check ("a demo song opens from it", start->openForSnapshot (1));
  7925. break;
  7926. }
  7927. case 4:
  7928. check ("Start from closed with the demo open", ! simple->isStartFromShowing() && ! engine->getSong().playlist.empty());
  7929. spacePlays ("a demo opened from Welcome > Start from");
  7930. instrumentTrack = [] (const lynx::Song& song) { // the first Instrument track (the dock's Keyboard and Editor tabs are for it)
  7931. for (int t = 0; t < (int) song.playlistTracks.size(); ++t)
  7932. if (lynx::simpletracks::kindOf (song, t) == lynx::simpletracks::Kind::instrument)
  7933. return t;
  7934. return 0;
  7935. } (engine->getSong());
  7936. line ("instrument track: " + juce::String (instrumentTrack));
  7937. playlist.selectTrack (instrumentTrack);
  7938. simple->trackSelected (instrumentTrack);
  7939. break;
  7940. case 5:
  7941. if (auto* dock = simple->dockForSnapshot(); dock != nullptr && dock->isShowing())
  7942. {
  7943. click (*dock, { dock->getWidth() - 6, dock->getHeight() - 6 }); // (its empty corner)
  7944. spacePlays ("a click in the dock");
  7945. }
  7946. else
  7947. check ("the dock shows", false);
  7948. break;
  7949. case 6:
  7950. if (auto* tab = find ("simple.dock.keyboard"))
  7951. {
  7952. click (*tab);
  7953. spacePlays ("a click on a dock tab (Keyboard)");
  7954. }
  7955. if (auto* tab = find ("simple.dock.editor"))
  7956. {
  7957. click (*tab);
  7958. spacePlays ("a click on a dock tab (Editor)");
  7959. }
  7960. break;
  7961. case 7:
  7962. if (auto* lyrics = find ("simple.lyrics"))
  7963. {
  7964. click (*lyrics);
  7965. spacePlays ("a click on the Lyrics button");
  7966. }
  7967. else
  7968. check ("the Lyrics button found", false);
  7969. break;
  7970. case 8:
  7971. {
  7972. const auto lane = playlist.trackRowForSnapshot (instrumentTrack).withTrimmedLeft (playlist.headerWidth);
  7973. click (playlist, { juce::jmax (4, playlist.headerWidth / 2), lane.getCentreY() });
  7974. spacePlays ("a click on a track header");
  7975. click (playlist, lane.getCentre() + juce::Point<int> (40, 0));
  7976. spacePlays ("a click in the Playlist grid");
  7977. break;
  7978. }
  7979. case 9:
  7980. {
  7981. // a text field the user clicks into keeps its typing keys; a click outside gives Space back
  7982. // a dock knob clicked keeps the arrow keys, and Space still plays from it
  7983. for (auto tab : { lynx::SimpleDock::Tab::effects, lynx::SimpleDock::Tab::instrument })
  7984. {
  7985. juce::Component* knob = nullptr;
  7986. std::function<void (juce::Component&)> seek = [&] (juce::Component& c) {
  7987. if (knob == nullptr && c.isShowing() && (bool) c.getProperties().getWithDefault ("lynxClickKeepsKeys", false))
  7988. knob = &c;
  7989. for (auto* child : c.getChildren())
  7990. seek (*child);
  7991. };
  7992. if (auto* dock = simple->dockForSnapshot())
  7993. {
  7994. dock->setTab (tab);
  7995. seek (*dock);
  7996. }
  7997. if (knob != nullptr)
  7998. {
  7999. click (*knob);
  8000. spacePlays ("a click on a dock knob");
  8001. break;
  8002. }
  8003. }
  8004. if (auto* dock = simple->dockForSnapshot())
  8005. dock->setTab (lynx::SimpleDock::Tab::instrument);
  8006. juce::TextEditor* field = nullptr;
  8007. std::function<void (juce::Component&)> look = [&] (juce::Component& c) {
  8008. if (auto* t = dynamic_cast<juce::TextEditor*> (&c); t != nullptr && t->isShowing() && field == nullptr)
  8009. field = t;
  8010. for (auto* child : c.getChildren())
  8011. look (*child);
  8012. };
  8013. if (auto* dock = simple->dockForSnapshot())
  8014. look (*dock);
  8015. line ("text field in the dock found=" + juce::String ((int) (field != nullptr)));
  8016. if (field != nullptr)
  8017. {
  8018. click (*field);
  8019. const auto before = field->getText();
  8020. space();
  8021. check ("Space types into the text field the user clicked", field->getText() != before && ! engine->getTransport().playing.load());
  8022. engine->stop();
  8023. field->clear();
  8024. const auto lane = playlist.trackRowForSnapshot (instrumentTrack).withTrimmedLeft (playlist.headerWidth);
  8025. click (playlist, lane.getCentre() + juce::Point<int> (60, 0));
  8026. spacePlays ("a click in the grid after typing");
  8027. }
  8028. // H1: the first-song tour's card in front of the native panels, taking no keys (started on the demo
  8029. // as it is: Help's question about a new project is a dialog)
  8030. if (auto* tour = simple->tourForSnapshot())
  8031. tour->start();
  8032. break;
  8033. }
  8034. case 10:
  8035. {
  8036. auto* tour = simple->tourForSnapshot();
  8037. auto* card = tour != nullptr ? tour->cardForSnapshot() : nullptr;
  8038. check ("the tour runs", tour != nullptr && tour->isRunning() && card != nullptr && card->isVisible());
  8039. if (card == nullptr)
  8040. return finish();
  8041. auto& frame = ui->workspaceForTest().getFrame (lynx::workspace::Panel::playlist);
  8042. const auto native = lynx::nativechild::dockingEnabled() && lynx::nativechild::isAttached (frame);
  8043. line ("playlist native child window=" + juce::String ((int) native) + ", tour card native child window="
  8044. + juce::String ((int) lynx::nativechild::isAttached (*card)));
  8045. if (native)
  8046. {
  8047. check ("the tour card is a native child window of the main window (not under the panels)", lynx::nativechild::isAttached (*card));
  8048. #if JUCE_WINDOWS
  8049. check ("the tour card is above the Playlist's native window", lynx::nativechild::isAbove (card->getWindowHandle(), frame.getWindowHandle()));
  8050. juce::Component* layer = nullptr;
  8051. for (auto* c : lynx::nativechild::attachedChildren (main->getPeer()->getNativeHandle()))
  8052. if (c != nullptr && c->getComponentID() == "tour.layer")
  8053. layer = c;
  8054. check ("the ring's layer is above the Playlist too", layer != nullptr && lynx::nativechild::isAbove (layer->getWindowHandle(), frame.getWindowHandle()));
  8055. check ("the ring's layer lets clicks through to the Playlist",
  8056. layer != nullptr && lynx::nativechild::windowAt (*layer, layer->getLocalBounds().getCentre()) != layer->getWindowHandle());
  8057. #endif
  8058. }
  8059. check ("the tour card took no keys", ! card->hasKeyboardFocus (true));
  8060. spacePlays ("the tour came up");
  8061. if (auto* next = card->findChildWithID ("tour.next"); next != nullptr && next->isShowing())
  8062. {
  8063. click (*next);
  8064. check ("a click on the card took no keys", ! card->hasKeyboardFocus (true));
  8065. spacePlays ("a click on the tour card");
  8066. }
  8067. finish();
  8068. break;
  8069. }
  8070. default:
  8071. break;
  8072. }
  8073. }
  8074. void finish()
  8075. {
  8076. line (ok ? "result=OK" : "result=FAILED");
  8077. stopTimer();
  8078. done();
  8079. }
  8080. };
  8081. auto* test = new KeyTest();
  8082. test->reportPath = reportPath;
  8083. startFocusTestWindow (*test);
  8084. // Windows: kept above other apps' windows for its few seconds (JUCE takes a button-down only where the system finds
  8085. // its window under the point, and the test clicks through LYNX's own peers, not the system's input)
  8086. #if JUCE_WINDOWS
  8087. test->main->setAlwaysOnTop (true); // (Linux: JUCE makes the X11 window again for it; the private X server has no other windows)
  8088. #endif
  8089. test->startTimer (700);
  8090. }
  8091. template <typename Test>
  8092. void startFocusTestWindow (Test& t)
  8093. {
  8094. auto* test = &t;
  8095. test->engine = std::make_unique<lynx::AudioEngine> (false);
  8096. test->main = std::make_unique<juce::DocumentWindow> ("LYNX focus test", lynx::theme::window, juce::DocumentWindow::allButtons);
  8097. test->main->setUsingNativeTitleBar (true);
  8098. test->ui = new lynx::MainComponent (*test->engine, false);
  8099. test->main->setContentOwned (test->ui, true);
  8100. test->main->setResizable (true, true);
  8101. test->main->centreWithSize (1280, 760);
  8102. test->main->setVisible (true);
  8103. lynx::setMainWindowForOwnership (test->main.get());
  8104. test->done = [this, test] {
  8105. setApplicationReturnValue (test->ok ? 0 : 1);
  8106. juce::MessageManager::callAsync ([this, test] {
  8107. lynx::setMainWindowForOwnership (nullptr);
  8108. test->main = nullptr;
  8109. delete test;
  8110. quit();
  8111. });
  8112. };
  8113. }
  8114. void runWindowTest (const juce::String& reportPath)
  8115. {
  8116. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  8117. struct WindowTest final : juce::Timer
  8118. {
  8119. juce::String reportPath, report;
  8120. bool ok = true;
  8121. int stepIndex = 0;
  8122. std::unique_ptr<lynx::AudioEngine> engine;
  8123. lynx::MainComponent* ui = nullptr;
  8124. std::unique_ptr<juce::DocumentWindow> main, pluginLike;
  8125. juce::TextEditor* pluginField = nullptr;
  8126. std::unique_ptr<juce::AlertWindow> nameDialog;
  8127. std::function<void()> done;
  8128. void line (const juce::String& text)
  8129. {
  8130. report << text << "\n";
  8131. juce::File (reportPath).replaceWithText (report);
  8132. }
  8133. void check (const juce::String& what, bool passed)
  8134. {
  8135. line ((passed ? "ok " : "FAIL ") + what);
  8136. ok = ok && passed;
  8137. }
  8138. bool isAbove (juce::Component* w) { return w != nullptr && lynx::isAboveMainWindow (*w); }
  8139. bool focusIn (juce::Component* w)
  8140. {
  8141. auto* f = juce::Component::getCurrentlyFocusedComponent();
  8142. return w != nullptr && f != nullptr && (f == w || w->isParentOf (f));
  8143. }
  8144. void timerCallback() override
  8145. {
  8146. switch (stepIndex++)
  8147. {
  8148. case 0:
  8149. line ("foreground=" + juce::String (juce::Process::isForegroundProcess() ? 1 : 0));
  8150. ui->openQuickAddForTest();
  8151. break;
  8152. case 1:
  8153. {
  8154. auto* w = lynx::findToolWindow ("quickadd");
  8155. check ("quick-add palette open", w != nullptr);
  8156. check ("quick-add palette active", w != nullptr && w->isActiveWindow());
  8157. check ("quick-add palette owned by the main window", w != nullptr && lynx::isOwnedByMainWindow (*w));
  8158. check ("quick-add palette above the main window", isAbove (w));
  8159. auto* f = juce::Component::getCurrentlyFocusedComponent();
  8160. check ("quick-add search box has the keyboard focus", focusIn (w) && dynamic_cast<juce::TextEditor*> (f) != nullptr && f->hasKeyboardFocus (false) && w->isActiveWindow());
  8161. lynx::closeAllToolWindows();
  8162. lynx::openAudioEditor (*engine);
  8163. break;
  8164. }
  8165. case 2:
  8166. {
  8167. auto* w = lynx::findToolWindow ("audioeditor");
  8168. check ("audio editor open", w != nullptr);
  8169. check ("audio editor active", w != nullptr && w->isActiveWindow());
  8170. check ("audio editor owned by the main window", w != nullptr && lynx::isOwnedByMainWindow (*w));
  8171. check ("audio editor above the main window", isAbove (w));
  8172. lynx::forceForegroundForTest (*main); // the user clicks the main window
  8173. break;
  8174. }
  8175. case 3:
  8176. {
  8177. auto* w = lynx::findToolWindow ("audioeditor");
  8178. check ("audio editor stays above the main window after clicking it", isAbove (w));
  8179. lynx::closeAllToolWindows();
  8180. // a plugin editor's window: its own controls keep the keyboard focus
  8181. pluginLike = std::make_unique<juce::DocumentWindow> ("Plugin", juce::Colours::black, juce::DocumentWindow::closeButton);
  8182. pluginLike->setUsingNativeTitleBar (true);
  8183. auto* field = new juce::TextEditor();
  8184. field->setSize (300, 120);
  8185. pluginLike->setContentOwned (field, true);
  8186. pluginLike->centreWithSize (300, 120);
  8187. pluginLike->setVisible (true);
  8188. lynx::keepAboveMainWindow (*pluginLike);
  8189. pluginLike->toFront (true);
  8190. field->grabKeyboardFocus();
  8191. pluginField = field;
  8192. break;
  8193. }
  8194. case 4:
  8195. check ("plugin window active", pluginLike->isActiveWindow());
  8196. check ("plugin window keeps the keyboard focus", pluginField->hasKeyboardFocus (false) && pluginLike->isActiveWindow());
  8197. check ("plugin window above the main window", isAbove (pluginLike.get()));
  8198. pluginLike = nullptr;
  8199. lynx::forceForegroundForTest (*main);
  8200. juce::Component::unfocusAllComponents();
  8201. break;
  8202. case 5:
  8203. check ("main window takes the keyboard focus back when it is active", ui->hasKeyboardFocus (true));
  8204. // round 165q: a name dialog (F4's next empty pattern, Rename and color...) opens ready to type
  8205. nameDialog = lynx::makeNameAndColourDialog ("Rename pattern", "Pattern 2", 0xff808080u);
  8206. nameDialog->enterModalState (true, nullptr, false);
  8207. lynx::keepAboveMainWindow (*nameDialog);
  8208. break;
  8209. case 6:
  8210. {
  8211. auto* f = juce::Component::getCurrentlyFocusedComponent();
  8212. auto* field = dynamic_cast<juce::TextEditor*> (f);
  8213. check ("name dialog: its text field has the keyboard focus", field != nullptr && focusIn (nameDialog.get()));
  8214. if (field != nullptr)
  8215. field->keyPressed (juce::KeyPress ('x', {}, 'x'));
  8216. check ("name dialog: typing replaces the name", nameDialog->getTextEditorContents ("name") == "x");
  8217. nameDialog->exitModalState (0);
  8218. nameDialog = nullptr;
  8219. line (ok ? "result=OK" : "result=FAILED");
  8220. stopTimer();
  8221. done();
  8222. break;
  8223. }
  8224. default:
  8225. break;
  8226. }
  8227. }
  8228. };
  8229. auto* test = new WindowTest();
  8230. test->reportPath = reportPath;
  8231. test->engine = std::make_unique<lynx::AudioEngine> (false);
  8232. test->main = std::make_unique<juce::DocumentWindow> ("LYNX window test", lynx::theme::window, juce::DocumentWindow::allButtons);
  8233. test->main->setUsingNativeTitleBar (true);
  8234. test->ui = new lynx::MainComponent (*test->engine, false);
  8235. test->main->setContentOwned (test->ui, true);
  8236. test->main->setResizable (true, true);
  8237. test->main->centreWithSize (1280, 760);
  8238. test->main->setVisible (true);
  8239. lynx::setMainWindowForOwnership (test->main.get());
  8240. lynx::forceForegroundForTest (*test->main);
  8241. test->main->toFront (true);
  8242. test->done = [this, test] {
  8243. setApplicationReturnValue (test->ok ? 0 : 1);
  8244. juce::MessageManager::callAsync ([this, test] {
  8245. lynx::closeAllToolWindows();
  8246. lynx::setMainWindowForOwnership (nullptr);
  8247. test->main = nullptr;
  8248. delete test;
  8249. quit();
  8250. });
  8251. };
  8252. test->startTimer (1500);
  8253. }
  8254. // LYNX.exe --plugintest plugin.vst3 report.txt ["name"]: loads the plugin (or the one named in a shell), plays notes if it is an
  8255. // instrument (and runs audio through it if it is an effect) and measures the audio.
  8256. // Round 190fw: an instrument plugin file on channel 5 of an offline engine (Image-Line's "FL Studio VSTi", which
  8257. // runs FL Studio inside it). Without a project: four chords at 137 BPM, rendered (notes.wav), the plugin's state
  8258. // saved in <folder>/vstitest.lynx. With a project (one saved by LYNX with the plugin on a channel, e.g. after its
  8259. // window was used): that project. Then: the project loaded back from the file renders the same (reload.wav) and
  8260. // gives the same state back; the project's own notes removed, rendered at 100 and 150 BPM (tempo-100/150.wav), the
  8261. // onsets of what the plugin plays by itself must follow the host tempo; and the outputs the plugin offers.
  8262. void runVstiTest (const juce::String& pluginPath, const juce::String& folderPath, const juce::String& projectPath)
  8263. {
  8264. juce::String report;
  8265. auto ok = true;
  8266. const juce::File folder (folderPath);
  8267. folder.createDirectory();
  8268. const auto check = [&] (const juce::String& name, bool passed) {
  8269. report << name << "=" << (passed ? "OK" : "FAILED") << "\n";
  8270. ok = ok && passed;
  8271. };
  8272. struct Take
  8273. {
  8274. float peak = 0.0f;
  8275. std::vector<float> left;
  8276. };
  8277. // renders `song` with the plugin file known to the engine's host; `wav` (in the folder) gets the audio
  8278. const auto render = [&] (const lynx::Song& song, double seconds, const juce::String& wav, std::function<void (lynx::AudioEngine&)> after = {}) {
  8279. Take take;
  8280. lynx::AudioEngine engine (false);
  8281. engine.getPluginHost().addPluginFile (juce::File (pluginPath));
  8282. engine.setSong (song);
  8283. const auto file = folder.getChildFile (wav);
  8284. file.deleteFile();
  8285. std::unique_ptr<juce::AudioFormatWriter> writer;
  8286. if (auto stream = file.createOutputStream())
  8287. {
  8288. juce::WavAudioFormat format;
  8289. writer.reset (format.createWriterFor (stream.get(), 48000.0, 2, 24, {}, 0));
  8290. if (writer != nullptr)
  8291. stream.release();
  8292. }
  8293. lynx::AudioEngine::RenderOptions o;
  8294. o.seconds = seconds;
  8295. o.sampleRate = 48000.0;
  8296. o.output = writer.get();
  8297. o.capture = [&take] (const float* l, const float*, int n) { take.left.insert (take.left.end(), l, l + n); };
  8298. take.peak = engine.renderOffline (o);
  8299. writer.reset();
  8300. if (after)
  8301. after (engine);
  8302. return take;
  8303. };
  8304. // the channel that holds the plugin
  8305. const auto pluginChannel = [&] (const lynx::Song& song) {
  8306. for (std::size_t c = 0; c < song.channels.size(); ++c)
  8307. if (song.channels[c].instrument == lynx::InstrumentKind::plugin
  8308. && juce::String (song.channels[c].plugin.name).containsIgnoreCase (juce::File (pluginPath).getFileNameWithoutExtension().upToFirstOccurrenceOf (" (", false, false)))
  8309. return (int) c;
  8310. return -1;
  8311. };
  8312. lynx::Song song;
  8313. const auto saved = folder.getChildFile ("vstitest.lynx");
  8314. if (projectPath.isEmpty())
  8315. {
  8316. lynx::AudioEngine scanner (false);
  8317. report << "plugins_in_file=" << scanner.getPluginHost().addPluginFile (juce::File (pluginPath)) << "\n";
  8318. std::optional<juce::PluginDescription> type;
  8319. for (const auto& t : scanner.getPluginHost().getKnownPlugins().getTypes())
  8320. if (t.isInstrument && juce::File (t.fileOrIdentifier) == juce::File (pluginPath))
  8321. type = t;
  8322. check ("instrument_found", type.has_value());
  8323. if (! type)
  8324. {
  8325. juce::File (folder.getChildFile ("report.txt")).replaceWithText (report + "result=FAILED\n");
  8326. setApplicationReturnValue (1);
  8327. quit();
  8328. return;
  8329. }
  8330. report << "plugin=" << type->name << " (" << type->manufacturerName << ") outputs=" << type->numOutputChannels << "\n";
  8331. song = lynx::Song::makeDefault();
  8332. song.bpm = 137.0;
  8333. auto& c = song.channels[4];
  8334. c.instrument = lynx::InstrumentKind::plugin;
  8335. c.plugin = {};
  8336. c.plugin.id = type->createIdentifierString().toStdString();
  8337. c.plugin.name = type->name.toStdString();
  8338. c.name = type->name.toStdString();
  8339. c.volume = 1.0f;
  8340. for (std::size_t k = 0; k < song.channels.size(); ++k)
  8341. song.channels[k].muted = k != 4;
  8342. song.patterns[0].notes.clear();
  8343. for (int beat = 0; beat < 8; ++beat) // a chord per beat, two bars
  8344. for (int key : { 60, 64, 67 })
  8345. song.patterns[0].notes.push_back ({ (std::int64_t) beat * lynx::ppq, lynx::ppq / 2, 4, key + (beat / 4) * 5, 0.9f });
  8346. song.patterns[0].sortNotes();
  8347. const auto notes = render (song, 4.0, "notes.wav", [&song] (lynx::AudioEngine& engine) {
  8348. engine.capturePluginStates();
  8349. song = engine.getSong();
  8350. });
  8351. report << "notes_peak=" << notes.peak << "\n";
  8352. check ("notes_play", notes.peak > 0.001f && notes.peak < 10.0f);
  8353. juce::String error;
  8354. check ("project_saved", lynx::ProjectFile::save (song, saved, error));
  8355. }
  8356. else
  8357. {
  8358. juce::String error;
  8359. const auto loaded = lynx::ProjectFile::load (juce::File (projectPath), error);
  8360. check ("project_loaded", loaded.has_value());
  8361. if (loaded)
  8362. song = *loaded;
  8363. juce::File (projectPath).copyFileTo (saved);
  8364. }
  8365. const auto channel = pluginChannel (song);
  8366. check ("plugin_channel", channel >= 0);
  8367. if (channel >= 0)
  8368. {
  8369. const auto& plugin = song.channels[(std::size_t) channel].plugin;
  8370. juce::MemoryBlock state;
  8371. state.fromBase64Encoding (juce::String (plugin.state));
  8372. report << "channel=" << channel + 1 << " state_bytes=" << (int) state.getSize() << "\n";
  8373. check ("state_saved", state.getSize() > 0);
  8374. // the project read back from the file: the same sound, and the same state handed back
  8375. juce::String error;
  8376. const auto again = lynx::ProjectFile::load (saved, error);
  8377. check ("project_reloaded", again.has_value());
  8378. if (again)
  8379. {
  8380. std::string stateBack;
  8381. const auto first = render (*again, 4.0, "reload-a.wav");
  8382. const auto second = render (*again, 4.0, "reload-b.wav", [&] (lynx::AudioEngine& engine) {
  8383. engine.capturePluginStates();
  8384. stateBack = engine.getSong().channels[(std::size_t) channel].plugin.state;
  8385. });
  8386. // two loads of the same project: the same audio (sample for sample, or within -60 dB for a plugin
  8387. // with free-running modulation)
  8388. double energy = 0.0, difference = 0.0;
  8389. const auto n = std::min (first.left.size(), second.left.size());
  8390. for (std::size_t k = 0; k < n; ++k)
  8391. {
  8392. energy += (double) first.left[k] * first.left[k];
  8393. difference += ((double) first.left[k] - second.left[k]) * ((double) first.left[k] - second.left[k]);
  8394. }
  8395. const auto ratioDb = energy > 0.0 ? 10.0 * std::log10 (std::max (difference, 1e-30) / energy) : 0.0;
  8396. report << "reload_peak=" << first.peak << " reload_difference_db=" << juce::String (ratioDb, 1) << "\n";
  8397. check ("reload_plays", first.peak > 0.001f);
  8398. check ("reload_same_sound", energy > 0.0 && ratioDb < -60.0);
  8399. juce::MemoryBlock back;
  8400. back.fromBase64Encoding (juce::String (stateBack));
  8401. report << "state_back_bytes=" << (int) back.getSize() << " identical=" << (int) (back == state) << "\n";
  8402. check ("state_handed_back", back.getSize() > 0);
  8403. }
  8404. // the host tempo: what the plugin plays by itself (FL Studio's own patterns inside FL Studio VSTi) at two
  8405. // tempos, without the project's notes
  8406. auto self = song;
  8407. for (std::size_t k = 0; k < self.channels.size(); ++k)
  8408. self.channels[k].muted = (int) k != channel;
  8409. for (auto& pattern : self.patterns)
  8410. pattern.notes.erase (std::remove_if (pattern.notes.begin(), pattern.notes.end(), [channel] (const lynx::Note& n) { return n.channel == channel; }),
  8411. pattern.notes.end());
  8412. const auto onsets = [] (const std::vector<float>& x) {
  8413. // envelope rises over a threshold (10 ms hold-off of 60 ms): the times in seconds
  8414. std::vector<double> at;
  8415. float peak = 0.0f;
  8416. for (const auto v : x)
  8417. peak = std::max (peak, std::abs (v));
  8418. const auto threshold = peak * 0.3f;
  8419. auto quietFor = 1 << 30;
  8420. for (std::size_t k = 0; k < x.size(); ++k)
  8421. {
  8422. const auto loud = std::abs (x[k]) >= threshold;
  8423. if (loud && quietFor >= 48000 * 60 / 1000)
  8424. at.push_back ((double) k / 48000.0);
  8425. quietFor = loud ? 0 : quietFor + 1;
  8426. }
  8427. return at;
  8428. };
  8429. const auto medianGap = [] (const std::vector<double>& at) {
  8430. std::vector<double> gaps;
  8431. for (std::size_t k = 1; k < at.size(); ++k)
  8432. gaps.push_back (at[k] - at[k - 1]);
  8433. if (gaps.empty())
  8434. return 0.0;
  8435. std::sort (gaps.begin(), gaps.end());
  8436. return gaps[gaps.size() / 2];
  8437. };
  8438. self.bpm = 100.0;
  8439. const auto slow = render (self, 6.0, "tempo-100.wav");
  8440. self.bpm = 150.0;
  8441. const auto fast = render (self, 6.0, "tempo-150.wav");
  8442. const auto gapSlow = medianGap (onsets (slow.left)), gapFast = medianGap (onsets (fast.left));
  8443. report << "self_peak_100=" << slow.peak << " self_peak_150=" << fast.peak << " onsets_100=" << (int) onsets (slow.left).size()
  8444. << " onsets_150=" << (int) onsets (fast.left).size() << " gap_100=" << juce::String (gapSlow, 4) << " gap_150="
  8445. << juce::String (gapFast, 4) << "\n";
  8446. if (slow.peak > 0.001f && gapFast > 0.0)
  8447. {
  8448. report << "tempo_ratio=" << juce::String (gapSlow / gapFast, 3) << " (expected 1.5)\n";
  8449. check ("follows_host_tempo", std::abs (gapSlow / gapFast - 1.5) < 0.05);
  8450. }
  8451. else
  8452. report << "tempo: the plugin plays nothing by itself in this project\n";
  8453. // the outputs it offers (FL Studio VSTi (Multi): FL's mixer tracks as separate outputs)
  8454. lynx::AudioEngine engine (false);
  8455. engine.getPluginHost().addPluginFile (juce::File (pluginPath));
  8456. engine.setSong (song);
  8457. engine.renderOffline (0.2, 48000.0);
  8458. if (auto instrument = std::dynamic_pointer_cast<lynx::PluginInstrument> (engine.getChannelInstrument (channel)))
  8459. {
  8460. report << "outputs=" << (int) instrument->outputs().size() << ":";
  8461. for (const auto& o : instrument->outputs())
  8462. report << " [" << o.name << "]";
  8463. report << "\n";
  8464. check ("outputs_listed", ! instrument->outputs().empty());
  8465. }
  8466. else
  8467. check ("instrument_loaded", false);
  8468. }
  8469. report << "plugin_crashes=" << lynx::pluginCrashCount() << "\n";
  8470. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  8471. folder.getChildFile ("report.txt").replaceWithText (report);
  8472. setApplicationReturnValue (ok ? 0 : 1);
  8473. quit();
  8474. }
  8475. void runPluginTest (const juce::String& pluginPath, const juce::String& reportPath, const juce::String& only = {})
  8476. {
  8477. juce::String report;
  8478. bool ok = false;
  8479. {
  8480. lynx::AudioEngine offline (false);
  8481. auto& host = offline.getPluginHost();
  8482. const auto added = host.addPluginFile (juce::File (pluginPath));
  8483. report << "plugins_in_file=" << added << "\n";
  8484. juce::PluginDescription instrument, effect;
  8485. bool hasInstrument = false, hasEffect = false;
  8486. for (const auto& type : host.getKnownPlugins().getTypes())
  8487. {
  8488. if (juce::File (type.fileOrIdentifier).getFileName() != juce::File (pluginPath).getFileName()
  8489. || (only.isNotEmpty() && type.name != only))
  8490. continue;
  8491. report << " " << (type.isInstrument ? "instrument: " : "effect: ") << type.name << " (" << type.manufacturerName
  8492. << ") in " << type.fileOrIdentifier << "\n";
  8493. if (type.isInstrument && ! hasInstrument) { instrument = type; hasInstrument = true; }
  8494. if (! type.isInstrument && ! hasEffect) { effect = type; hasEffect = true; }
  8495. }
  8496. auto song = lynx::Song::makeDefault();
  8497. if (hasInstrument)
  8498. {
  8499. auto& c = song.channels[4]; // the "Synth" channel becomes the plugin
  8500. c.instrument = lynx::InstrumentKind::plugin;
  8501. c.plugin.id = instrument.createIdentifierString().toStdString();
  8502. c.plugin.name = instrument.name.toStdString();
  8503. c.volume = 1.0f;
  8504. for (int i = 0; i < 4; ++i) // one chord per beat
  8505. for (int key : { 60, 64, 67 })
  8506. song.patterns[0].notes.push_back ({ (std::int64_t) i * lynx::ppq, lynx::ppq / 2, 4, key, 0.9f });
  8507. song.patterns[0].sortNotes();
  8508. }
  8509. if (hasEffect)
  8510. {
  8511. lynx::EffectSlot slot;
  8512. slot.kind = lynx::EffectKind::plugin;
  8513. slot.plugin.id = effect.createIdentifierString().toStdString();
  8514. slot.plugin.name = effect.name.toStdString();
  8515. song.mixer[0].effects.push_back (slot);
  8516. }
  8517. const auto effectSlot = (int) song.mixer[0].effects.size() - 1; // (the default master may hold effects already)
  8518. offline.setSong (song);
  8519. // after a render: the rack (and its plugins) is built when the engine is prepared
  8520. const auto peak = offline.renderOffline (3.0, 48000.0);
  8521. const auto* loadedInstrument = dynamic_cast<lynx::PluginInstrument*> (offline.getChannelInstrument (4).get());
  8522. const auto* loadedEffect = dynamic_cast<lynx::PluginEffect*> (offline.getEffect (0, effectSlot).get());
  8523. report << "instrument_loaded=" << (loadedInstrument != nullptr ? "yes" : "no") << "\n"
  8524. << "effect_loaded=" << (loadedEffect != nullptr ? "yes" : "no") << "\n";
  8525. if (host.getLoadFailures().size() > 0) // why: the host's own message (license, missing file, load failure)
  8526. report << "load_failures=" << host.getLoadFailures().joinIntoString (" | ") << "\n";
  8527. report << "peak=" << peak << "\n";
  8528. // plugins that crashed inside a call, were caught and switched off (round 111)
  8529. report << "plugin_crashes=" << lynx::pluginCrashCount() << "\n";
  8530. for (const auto& c : lynx::pluginCrashes())
  8531. report << " crashed: " << c.plugin << " (" << lynx::crashguard::describe (c.code) << ")\n";
  8532. offline.capturePluginStates();
  8533. const auto stateSize = hasInstrument ? offline.getSong().channels[4].plugin.state.size() : (size_t) 0;
  8534. report << "state_bytes_base64=" << (int) stateSize << "\n";
  8535. ok = (hasInstrument || hasEffect) && (! hasInstrument || loadedInstrument != nullptr)
  8536. && (! hasEffect || loadedEffect != nullptr) && peak > 0.001f && peak < 10.0f;
  8537. }
  8538. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  8539. juce::File (reportPath).replaceWithText (report);
  8540. setApplicationReturnValue (ok ? 0 : 1);
  8541. quit();
  8542. }
  8543. // Round 190gg (B4): --crashguardtest plugin report.txt thread | ui. "thread": the plugin's own thread faults in its 40th
  8544. // block (Linux / macOS): that thread is parked, LYNX switches the plugin off (as the main window's timer does) and goes
  8545. // on; the other inserts play; Reload brings it back. "ui": the calls the UI makes into a plugin, under the guard: a
  8546. // preset load that crashes (the Plugin window's preset menu path) and making the editor (PluginWindows::open, the CLAP
  8547. // test plugin's "editor-create": a display is needed, e.g. Xvfb); each switches the plugin off, LYNX goes on.
  8548. void runCrashGuardThreadOrUiTest (const juce::String& pluginPath, const juce::String& reportPath, const juce::String& mode)
  8549. {
  8550. juce::String report;
  8551. bool ok = true;
  8552. const auto expect = [&] (const char* name, bool value) {
  8553. report << name << "=" << (value ? 1 : 0) << "\n";
  8554. ok = ok && value;
  8555. };
  8556. const auto setEnv = [] (const char* name, const char* value) {
  8557. #if JUCE_WINDOWS
  8558. _putenv_s (name, value);
  8559. #else
  8560. setenv (name, value, 1);
  8561. #endif
  8562. };
  8563. const auto render = [] (lynx::AudioEngine& engine, double seconds, float* peak) {
  8564. lynx::AudioEngine::RenderOptions o;
  8565. o.seconds = seconds;
  8566. o.sampleRate = 48000.0;
  8567. o.pluginWarmUp = false;
  8568. if (peak != nullptr)
  8569. o.capture = [peak] (const float* l, const float* r, int n) {
  8570. for (int k = 0; k < n; ++k)
  8571. *peak = std::max (*peak, std::max (std::abs (l[k]), std::abs (r[k])));
  8572. };
  8573. return engine.renderOffline (o);
  8574. };
  8575. report << "mode=" << mode << "\nthread_guard=" << (lynx::crashguard::pluginThreadFaultsCaught() ? "on" : "off") << "\n";
  8576. setEnv ("LYNX_TEST_CRASH", mode == "thread" ? "thread" : "");
  8577. setEnv ("LYNX_TEST_CRASH_AFTER", "40");
  8578. const auto tmp = juce::File::getSpecialLocation (juce::File::tempDirectory)
  8579. .getChildFile ("lynx-crashguardtest-" + juce::String::toHexString (juce::Random::getSystemRandom().nextInt64()));
  8580. tmp.createDirectory();
  8581. {
  8582. lynx::AudioEngine offline (false);
  8583. auto& host = offline.getPluginHost();
  8584. host.addPluginFile (juce::File (pluginPath));
  8585. juce::PluginDescription effect;
  8586. bool found = false;
  8587. for (const auto& type : host.getKnownPlugins().getTypes())
  8588. if (! found && ! type.isInstrument && juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginPath).getFileName())
  8589. {
  8590. effect = type;
  8591. found = true;
  8592. }
  8593. expect ("plugin_found", found);
  8594. auto song = lynx::Song::makeDefault();
  8595. lynx::EffectSlot slot;
  8596. slot.kind = lynx::EffectKind::plugin;
  8597. slot.plugin.id = effect.createIdentifierString().toStdString();
  8598. slot.plugin.name = effect.name.toStdString();
  8599. song.mixer[1].effects.push_back (slot);
  8600. offline.setSong (song);
  8601. const lynx::AudioEngine::HostedSlot where { -1, 1, 0 };
  8602. render (offline, 0.05, nullptr);
  8603. offline.editSong ([] (lynx::Song& s) { s.channels[0].volume = 0.85f; }, false);
  8604. render (offline, 0.05, nullptr);
  8605. auto* first = dynamic_cast<lynx::PluginEffect*> (offline.getEffect (1, 0).get());
  8606. expect ("plugin_loaded", first != nullptr);
  8607. const auto crashesBefore = lynx::pluginCrashCount();
  8608. if (mode == "thread")
  8609. {
  8610. const auto faultsBefore = lynx::crashguard::pluginThreadFaultCount();
  8611. float peak = 0.0f;
  8612. render (offline, 3.0, &peak); // (the plugin starts its faulting thread in its 40th block)
  8613. for (int i = 0; i < 200 && lynx::crashguard::pluginThreadFaultCount() == faultsBefore; ++i)
  8614. juce::Thread::sleep (10);
  8615. const auto faults = lynx::crashguard::pluginThreadFaults();
  8616. expect ("thread_fault_parked", lynx::crashguard::pluginThreadFaultCount() == faultsBefore + 1 && ! faults.empty());
  8617. if (! faults.empty())
  8618. report << "thread_fault=" << faults.back().where << " (" << lynx::crashguard::describe (faults.back().code) << ")\n";
  8619. expect ("not_yet_counted_as_a_call_crash", lynx::pluginCrashCount() == crashesBefore);
  8620. // what the main window's timer does
  8621. // (every instance of that module: the engine may hold more than the slot's, e.g. the offline render's)
  8622. if (first != nullptr)
  8623. report << "slot_file=" << first->getInstance().getPluginDescription().fileOrIdentifier << "\n";
  8624. const auto switched = lynx::switchOffPluginsOfThreadFaults();
  8625. report << "switched_off=" << switched << "\n";
  8626. expect ("plugin_switched_off", switched >= 1 && first != nullptr && first->hasCrashed() && lynx::pluginCrashCount() == crashesBefore + switched);
  8627. expect ("only_once", lynx::switchOffPluginsOfThreadFaults() == 0);
  8628. const auto down = offline.downHostedPlugins();
  8629. expect ("slot_down", down.size() == 1 && down[0] == where);
  8630. float after = 0.0f;
  8631. render (offline, 1.0, &after);
  8632. report << "peak_after=" << after << "\n";
  8633. expect ("audio_after_fault", after > 0.01f);
  8634. offline.editSong ([] (lynx::Song& s) { s.channels[0].volume = 0.0f; }, false);
  8635. float others = 0.0f;
  8636. render (offline, 1.0, &others);
  8637. expect ("other_inserts_play", others > 0.01f);
  8638. offline.editSong ([] (lynx::Song& s) { s.channels[0].volume = 0.85f; }, false);
  8639. const auto running = offline.reloadHostedPlugins (down);
  8640. auto* again = dynamic_cast<lynx::PluginEffect*> (offline.getEffect (1, 0).get());
  8641. float reloaded = 0.0f;
  8642. render (offline, 1.0, &reloaded);
  8643. expect ("reloaded_plays", running == 1 && again != nullptr && again != first && ! again->hasCrashed() && reloaded > 0.01f);
  8644. }
  8645. else
  8646. {
  8647. // a preset that crashes the plugin (the preset menu's load), saved first from the running plugin
  8648. auto& instance = first->getInstance();
  8649. const auto preset = tmp.getChildFile ("crash.lynxpreset");
  8650. juce::String error;
  8651. expect ("preset_saved", lynx::pluginpresetui::save (instance, preset, "crash", error) && preset.existsAsFile());
  8652. setEnv ("LYNX_TEST_CRASH", "state");
  8653. const auto loaded = lynx::pluginpresetui::load (instance, preset, error);
  8654. setEnv ("LYNX_TEST_CRASH", "");
  8655. report << "preset_error=" << error << "\n";
  8656. expect ("preset_crash_caught", ! loaded && lynx::pluginCrashCount() == crashesBefore + 1 && first->hasCrashed());
  8657. expect ("preset_plugin_down", offline.hostedPluginDown (where) && lynx::pluginInstanceDown (instance));
  8658. expect ("not_called_again", ! lynx::callPluginFromUi (instance, "test", [] {}) && lynx::pluginCrashCount() == crashesBefore + 1);
  8659. float after = 0.0f;
  8660. render (offline, 1.0, &after);
  8661. expect ("audio_after_preset_crash", after > 0.01f);
  8662. // Reload; then its editor crashes as it is made (PluginWindows::open): no window, the plugin is down
  8663. setEnv ("LYNX_TEST_CRASH", "editor-create");
  8664. const auto running = offline.reloadHostedPlugins (offline.downHostedPlugins());
  8665. auto held = offline.getEffect (1, 0);
  8666. auto* again = dynamic_cast<lynx::PluginEffect*> (held.get());
  8667. expect ("reloaded", running == 1 && again != nullptr && again != first && ! again->hasCrashed());
  8668. if (again != nullptr)
  8669. {
  8670. lynx::PluginWindows::open (held, again->getInstance(), "crash test", {});
  8671. expect ("editor_crash_caught", lynx::pluginCrashCount() == crashesBefore + 2 && again->hasCrashed());
  8672. expect ("no_window", ! lynx::PluginWindows::isOpen (again->getInstance()));
  8673. float editorAfter = 0.0f;
  8674. render (offline, 1.0, &editorAfter);
  8675. expect ("audio_after_editor_crash", editorAfter > 0.01f);
  8676. }
  8677. setEnv ("LYNX_TEST_CRASH", "");
  8678. }
  8679. }
  8680. setEnv ("LYNX_TEST_CRASH", "");
  8681. // LYNX's own faults (also on its own threads) stay crashes (child processes; the selftest runs the same)
  8682. const auto own = faultReportSelfTest();
  8683. report << "own_faults=" << own << "\n";
  8684. ok = ok && ! own.startsWith ("ERROR");
  8685. for (const auto& c : lynx::pluginCrashes())
  8686. report << " crashed: " << c.plugin << " (" << lynx::crashguard::describe (c.code) << ")\n";
  8687. tmp.deleteRecursively();
  8688. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  8689. juce::File (reportPath).replaceWithText (report);
  8690. setApplicationReturnValue (ok ? 0 : 1);
  8691. quit();
  8692. }
  8693. // LYNX --crashguardtest plugin report.txt [process|memcpy] (round 190dt): see the dispatch in initialise().
  8694. void runCrashGuardTest (const juce::String& pluginPath, const juce::String& reportPath, const juce::String& mode)
  8695. {
  8696. if (mode == "thread" || mode == "ui")
  8697. {
  8698. runCrashGuardThreadOrUiTest (pluginPath, reportPath, mode);
  8699. return;
  8700. }
  8701. juce::String report;
  8702. bool ok = true;
  8703. const auto expect = [&] (const char* name, bool value) {
  8704. report << name << "=" << (value ? 1 : 0) << "\n";
  8705. ok = ok && value;
  8706. };
  8707. const auto setEnv = [] (const char* name, const char* value) {
  8708. #if JUCE_WINDOWS
  8709. _putenv_s (name, value);
  8710. #else
  8711. setenv (name, value, 1);
  8712. #endif
  8713. };
  8714. // renders without the plugin warm-up (its silent blocks would count towards the crash)
  8715. const auto render = [] (lynx::AudioEngine& engine, double seconds, const std::function<void (const float*, const float*, int)>& capture) {
  8716. lynx::AudioEngine::RenderOptions o;
  8717. o.seconds = seconds;
  8718. o.sampleRate = 48000.0;
  8719. o.pluginWarmUp = false;
  8720. o.capture = capture;
  8721. return engine.renderOffline (o);
  8722. };
  8723. const auto peakOf = [] (float& peak) {
  8724. return [&peak] (const float* l, const float* r, int n) {
  8725. for (int k = 0; k < n; ++k)
  8726. peak = std::max (peak, std::max (std::abs (l[k]), std::abs (r[k])));
  8727. };
  8728. };
  8729. report << "guard=" << (lynx::crashguard::pluginFaultsCaught() ? "on" : "off") << "\nmode=" << mode << "\n";
  8730. setEnv ("LYNX_TEST_CRASH", mode == "memcpy" ? "memcpy" : "process");
  8731. setEnv ("LYNX_TEST_CRASH_AFTER", "40");
  8732. const auto tmp = juce::File::getSpecialLocation (juce::File::tempDirectory)
  8733. .getChildFile ("lynx-crashguardtest-" + juce::String::toHexString (juce::Random::getSystemRandom().nextInt64()));
  8734. tmp.createDirectory();
  8735. std::optional<lynx::Song> saved;
  8736. std::string savedState;
  8737. {
  8738. lynx::AudioEngine offline (false);
  8739. auto& host = offline.getPluginHost();
  8740. host.addPluginFile (juce::File (pluginPath));
  8741. juce::PluginDescription effect;
  8742. bool found = false;
  8743. for (const auto& type : host.getKnownPlugins().getTypes())
  8744. if (! found && ! type.isInstrument && juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginPath).getFileName())
  8745. {
  8746. effect = type;
  8747. found = true;
  8748. }
  8749. expect ("plugin_found", found);
  8750. // the plugin on insert 1 (the kick's); the clap and the hat play on inserts 2 and 3
  8751. auto song = lynx::Song::makeDefault();
  8752. lynx::EffectSlot slot;
  8753. slot.kind = lynx::EffectKind::plugin;
  8754. slot.plugin.id = effect.createIdentifierString().toStdString();
  8755. slot.plugin.name = effect.name.toStdString();
  8756. song.mixer[1].effects.push_back (slot);
  8757. offline.setSong (song);
  8758. const lynx::AudioEngine::HostedSlot where { -1, 1, 0 };
  8759. // the rack is published at the engine's rate and an offline render runs at its own (48 kHz) without publishing:
  8760. // one edit after a first render puts the rack (and the plugin) at the render's rate, so later edits keep it
  8761. render (offline, 0.05, {}); // (a few blocks, far from the 40th)
  8762. offline.editSong ([] (lynx::Song& s) { s.channels[0].volume = 0.85f; }, false);
  8763. render (offline, 0.05, {});
  8764. auto* first = dynamic_cast<lynx::PluginEffect*> (offline.getEffect (1, 0).get());
  8765. expect ("plugin_loaded", first != nullptr);
  8766. offline.capturePluginStates();
  8767. savedState = offline.getSong().mixer[1].effects[0].plugin.state;
  8768. expect ("state_captured", ! savedState.empty());
  8769. // the crash: 3 s, the plugin faults in its 40th block
  8770. const auto crashesBefore = lynx::pluginCrashCount();
  8771. juce::int64 position = 0, crashAt = -1;
  8772. float peakAfter = 0.0f;
  8773. const auto afterPeak = peakOf (peakAfter);
  8774. const auto peak = render (offline, 3.0, [&] (const float* l, const float* r, int n) {
  8775. if (crashAt < 0 && lynx::pluginCrashCount() != crashesBefore)
  8776. crashAt = position;
  8777. else if (crashAt >= 0)
  8778. afterPeak (l, r, n);
  8779. position += n;
  8780. });
  8781. report << "peak=" << peak << "\ncrash_at_sample=" << crashAt << "\npeak_after_crash=" << peakAfter << "\n";
  8782. const auto crashes = lynx::pluginCrashes();
  8783. expect ("crash_caught", lynx::pluginCrashCount() == crashesBefore + 1 && ! crashes.empty() && ! crashes.back().onLoad);
  8784. if (! crashes.empty())
  8785. report << "crash=" << crashes.back().plugin << " (" << lynx::crashguard::describe (crashes.back().code) << ")\n";
  8786. expect ("slot_marked_crashed", first != nullptr && offline.getEffect (1, 0).get() == first && first->hasCrashed());
  8787. const auto down = offline.downHostedPlugins();
  8788. expect ("slot_down", down.size() == 1 && down[0] == where);
  8789. expect ("audio_after_crash", crashAt >= 0 && peakAfter > 0.01f);
  8790. // the other inserts: with the kick (through the crashed slot) silent, the clap and the hat still play
  8791. offline.editSong ([] (lynx::Song& s) { s.channels[0].volume = 0.0f; }, false);
  8792. float othersPeak = 0.0f;
  8793. render (offline, 1.0, peakOf (othersPeak));
  8794. report << "other_inserts_peak=" << othersPeak << "\n";
  8795. expect ("other_inserts_play", othersPeak > 0.01f);
  8796. expect ("nothing_reloads_by_itself", offline.hostedPluginDown (where) && offline.getEffect (1, 0).get() == first);
  8797. offline.editSong ([] (lynx::Song& s) { s.channels[0].volume = 0.85f; }, false);
  8798. // the project saves with the settings the plugin had before it crashed, and opens again
  8799. offline.capturePluginStates();
  8800. expect ("state_kept", offline.getSong().mixer[1].effects[0].plugin.state == savedState);
  8801. const auto file = tmp.getChildFile ("crashed.lynx");
  8802. juce::String error;
  8803. expect ("project_saved", lynx::ProjectFile::save (offline.getSong(), file, error) && file.existsAsFile());
  8804. saved = lynx::ProjectFile::load (file, error);
  8805. expect ("project_reopens", saved.has_value() && saved->mixer.size() > 1 && saved->mixer[1].effects.size() == 1
  8806. && saved->mixer[1].effects[0].plugin.state == savedState);
  8807. // Reload (the prompt's button, round 190ao): a new instance; the module's block count is past 40 now
  8808. const auto running = offline.reloadHostedPlugins (down);
  8809. auto* again = dynamic_cast<lynx::PluginEffect*> (offline.getEffect (1, 0).get());
  8810. expect ("reloaded", running == 1 && again != nullptr && again != first && ! again->hasCrashed());
  8811. float reloadedPeak = 0.0f;
  8812. render (offline, 1.0, peakOf (reloadedPeak));
  8813. report << "reloaded_peak=" << reloadedPeak << "\n";
  8814. expect ("reloaded_plays", reloadedPeak > 0.01f && lynx::pluginCrashCount() == crashesBefore + 1 && again != nullptr && ! again->hasCrashed());
  8815. }
  8816. // the saved project opens again with the plugin crashing on its saved settings: left out, the rest plays, the
  8817. // settings stay in the project
  8818. setEnv ("LYNX_TEST_CRASH", "state");
  8819. if (saved.has_value())
  8820. {
  8821. lynx::AudioEngine reopened (false);
  8822. reopened.getPluginHost().addPluginFile (juce::File (pluginPath));
  8823. const auto before = lynx::pluginCrashCount();
  8824. reopened.setSong (*saved);
  8825. float reopenedPeak = 0.0f;
  8826. render (reopened, 1.0, peakOf (reopenedPeak));
  8827. const auto crashes = lynx::pluginCrashes();
  8828. report << "reopened_peak=" << reopenedPeak << "\n";
  8829. if (reopened.getPluginHost().getLoadFailures().size() > 0)
  8830. report << "load_failures=" << reopened.getPluginHost().getLoadFailures().joinIntoString (" | ") << "\n";
  8831. expect ("state_crash_caught", lynx::pluginCrashCount() == before + 1 && ! crashes.empty() && crashes.back().onLoad);
  8832. expect ("state_crash_left_out", dynamic_cast<lynx::PluginEffect*> (reopened.getEffect (1, 0).get()) == nullptr);
  8833. expect ("state_crash_project_plays", reopenedPeak > 0.01f);
  8834. reopened.capturePluginStates();
  8835. expect ("state_crash_settings_kept", reopened.getSong().mixer[1].effects.size() == 1
  8836. && reopened.getSong().mixer[1].effects[0].plugin.state == savedState);
  8837. }
  8838. setEnv ("LYNX_TEST_CRASH", "");
  8839. // LYNX's own faults inside a guarded call stay crashes (child processes; the selftest runs the same)
  8840. const auto own = faultReportSelfTest();
  8841. report << "own_faults=" << own << "\n";
  8842. ok = ok && ! own.startsWith ("ERROR");
  8843. report << "plugin_crashes=" << lynx::pluginCrashCount() << "\n";
  8844. for (const auto& c : lynx::pluginCrashes())
  8845. report << " crashed: " << c.plugin << " (" << lynx::crashguard::describe (c.code) << (c.onLoad ? ", loading its state" : "") << ")\n";
  8846. tmp.deleteRecursively();
  8847. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  8848. juce::File (reportPath).replaceWithText (report);
  8849. setApplicationReturnValue (ok ? 0 : 1);
  8850. quit();
  8851. }
  8852. // LYNX.exe --mpetest "LYNX Test MPE.clap" report.txt (tools/testplugin/lynx_test_mpe.c, issue #108): a hosted CLAP
  8853. // instrument with the wrapper's MPE switch on gets each note on its own member channel, its fine pitch / Mod X /
  8854. // Mod Y as tuning / brightness / pressure note expressions before the note on, and a sounding note's expression
  8855. // on that note's channel alone. The plugin writes down what it received; no window, no audio device.
  8856. void runMpeTest (const juce::String& pluginPath, const juce::String& reportPath)
  8857. {
  8858. const auto log = juce::File (reportPath).getSiblingFile (juce::File (reportPath).getFileNameWithoutExtension() + "-plugin.txt");
  8859. log.deleteFile();
  8860. #if JUCE_WINDOWS
  8861. _putenv_s ("LYNX_TEST_MPE_REPORT", log.getFullPathName().toRawUTF8());
  8862. #else
  8863. setenv ("LYNX_TEST_MPE_REPORT", log.getFullPathName().toRawUTF8(), 1);
  8864. #endif
  8865. juce::String report;
  8866. auto failures = 0;
  8867. {
  8868. lynx::AudioEngine engine (false);
  8869. auto& host = engine.getPluginHost();
  8870. report << "plugins_in_file=" << host.addPluginFile (juce::File (pluginPath)) << "\n";
  8871. std::optional<juce::PluginDescription> clap;
  8872. for (const auto& type : host.getKnownPlugins().getTypes())
  8873. if (type.pluginFormatName == "CLAP" && juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginPath).getFileName())
  8874. clap = type;
  8875. lynx::PluginRef ref;
  8876. if (clap)
  8877. {
  8878. ref.id = clap->createIdentifierString().toStdString();
  8879. ref.name = clap->name.toStdString();
  8880. }
  8881. ref.mpe = true;
  8882. juce::String error;
  8883. auto instrument = clap ? host.makeInstrument (ref, 48000.0, &error) : nullptr;
  8884. report << "instrument_loaded=" << (instrument != nullptr ? "yes" : "no") << (error.isNotEmpty() ? " (" + error + ")" : juce::String()) << "\n";
  8885. if (instrument != nullptr)
  8886. {
  8887. std::vector<float> l (256), r (256);
  8888. auto block = [&] { instrument->render (l.data(), r.data(), 256, 1.0f, 1.0f); };
  8889. block(); // (the zone's setup)
  8890. instrument->setNextNoteFinePitch (30.0f); // +30 cents
  8891. instrument->setNextNoteModulation (0.75f, 1.0f); // timbre 0.75, full pressure
  8892. instrument->noteOn (60, 0.8f);
  8893. instrument->noteOn (64, 0.5f); // a second note: its own channel, centre values
  8894. block();
  8895. instrument->noteExpression (60, (int) lynx::vfx::Prop::pitch, 200.0f, 0.0f);
  8896. instrument->noteExpression (64, (int) lynx::vfx::Prop::modX, 0.25f, 0.0f);
  8897. instrument->noteExpression (60, (int) lynx::vfx::Prop::modY, 0.75f, 0.0f);
  8898. block();
  8899. instrument->noteOff (60);
  8900. instrument->noteOff (64);
  8901. block();
  8902. }
  8903. else
  8904. ++failures;
  8905. } // (the plugin writes its log as it is destroyed)
  8906. struct Line
  8907. {
  8908. juce::String kind;
  8909. int a = 0, b = 0, c = 0, d = 0;
  8910. };
  8911. std::vector<Line> lines;
  8912. for (const auto& text : juce::StringArray::fromLines (log.loadFileAsString()))
  8913. {
  8914. const auto t = juce::StringArray::fromTokens (text, " ", "");
  8915. if (t.size() >= 3)
  8916. 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 });
  8917. }
  8918. report << "plugin_events=" << (int) lines.size() << "\n";
  8919. // the first line at or after `from` that matches (−1 = none); `value` within `tolerance` (thousandths)
  8920. auto find = [&lines] (const juce::String& kind, int a, int b, int value, int tolerance, int from = 0) {
  8921. for (auto i = (std::size_t) from; i < lines.size(); ++i)
  8922. {
  8923. const auto& x = lines[i];
  8924. const auto v = kind == "expr" ? x.d : x.c;
  8925. if (x.kind == kind && x.a == a && x.b == b && std::abs (v - value) <= tolerance)
  8926. return (int) i;
  8927. }
  8928. return -1;
  8929. };
  8930. auto check = [&] (const char* what, bool ok) {
  8931. report << what << "=" << (ok ? "ok" : "FAILED") << "\n";
  8932. failures += ok ? 0 : 1;
  8933. };
  8934. // (CLAP expression ids: 2 tuning in semitones, 5 brightness, 6 pressure; channels 0-based: the first member = 1)
  8935. const auto on60 = find ("on", 1, 60, 800, 5), on64 = find ("on", 2, 64, 500, 5);
  8936. check ("zone_setup_sent", find ("midi", 176, 6, 15, 0) >= 0 && find ("midi", 177, 6, 48, 0) >= 0);
  8937. check ("notes_on_their_own_channels", on60 >= 0 && on64 > on60);
  8938. const auto tune = find ("expr", 2, 1, 300, 3), bright = find ("expr", 5, 1, 756, 4), press = find ("expr", 6, 1, 1000, 1);
  8939. check ("expression_before_the_note_on", tune >= 0 && bright >= 0 && press >= 0 && tune < on60 && bright < on60 && press < on60);
  8940. 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);
  8941. const auto later = std::max (on60, on64) + 1;
  8942. check ("sounding_note_expression", later > 0 && find ("expr", 2, 1, 2000, 3, later) >= 0 && find ("expr", 5, 2, 252, 4, later) >= 0
  8943. && find ("expr", 6, 1, 504, 4, later) >= 0);
  8944. check ("other_note_untouched", later > 0 && find ("expr", 2, 2, 2000, 3, later) < 0 && find ("expr", 6, 2, 504, 4, later) < 0);
  8945. check ("notes_off_on_their_channels", find ("off", 1, 60, 0, 100000) >= 0 && find ("off", 2, 64, 0, 100000) >= 0);
  8946. auto expressionAsMidi = false; // (a CLAP-dialect plugin gets no raw bend / pressure / CC 74 on a member channel)
  8947. for (const auto& x : lines)
  8948. if (x.kind == "midi" && (x.a & 0x0f) != 0 && ((x.a & 0xf0) == 0xe0 || (x.a & 0xf0) == 0xd0 || ((x.a & 0xf0) == 0xb0 && x.b == 74)))
  8949. expressionAsMidi = true;
  8950. check ("no_duplicate_midi_expression", ! expressionAsMidi);
  8951. report << "--- plugin log ---\n" << log.loadFileAsString() << "result=" << (failures == 0 ? "OK" : "FAILED") << "\n";
  8952. juce::File (reportPath).replaceWithText (report);
  8953. setApplicationReturnValue (failures == 0 ? 0 : 1);
  8954. quit();
  8955. }
  8956. // LYNX.exe --claprestarttest "LYNX Test Restart.clap" report.txt (tools/testplugin/lynx_test_restart.c, PR #29): a
  8957. // CLAP effect on the Master that asks for a restart every 8 blocks while an export renders on a thread of its own
  8958. // (the message thread is free to run the restarts, as with the Export window). The plugin aborts the process when
  8959. // start / stop_processing run off the audio thread or activate / deactivate off the main thread (issue #46, as u-he
  8960. // Presswerk does; an export at 44.1 kHz and prepare calls from the export's thread check the latter) and counts deactivations that
  8961. // landed inside its process() call (must be none), the restarts must happen, and the delay compensation must end on
  8962. // the latency the plugin reports after its last restart.
  8963. void runClapRestartTest (const juce::String& pluginPath, const juce::String& reportPath)
  8964. {
  8965. struct Run
  8966. {
  8967. std::unique_ptr<lynx::AudioEngine> engine;
  8968. juce::String report;
  8969. int slot = -1;
  8970. std::thread render;
  8971. std::atomic<bool> done { false };
  8972. double renderSeconds = 0.0;
  8973. };
  8974. auto run = std::make_shared<Run>();
  8975. const auto counters = juce::File (reportPath).getSiblingFile (juce::File (reportPath).getFileNameWithoutExtension() + "-plugin.txt");
  8976. counters.deleteFile();
  8977. #if JUCE_WINDOWS
  8978. _putenv_s ("LYNX_TEST_RESTART_REPORT", counters.getFullPathName().toRawUTF8());
  8979. #else
  8980. setenv ("LYNX_TEST_RESTART_REPORT", counters.getFullPathName().toRawUTF8(), 1);
  8981. #endif
  8982. const auto fail = [this, reportPath] (juce::String report) {
  8983. report << "result=FAILED\n";
  8984. juce::File (reportPath).replaceWithText (report);
  8985. setApplicationReturnValue (1);
  8986. quit();
  8987. };
  8988. run->engine = std::make_unique<lynx::AudioEngine> (false);
  8989. auto& host = run->engine->getPluginHost();
  8990. run->report << "plugins_in_file=" << host.addPluginFile (juce::File (pluginPath)) << "\n";
  8991. std::optional<juce::PluginDescription> clap;
  8992. for (const auto& type : host.getKnownPlugins().getTypes())
  8993. if (type.pluginFormatName == "CLAP" && juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginPath).getFileName())
  8994. clap = type;
  8995. if (! clap)
  8996. {
  8997. fail (run->report + "no CLAP plugin in the file\n");
  8998. return;
  8999. }
  9000. auto song = lynx::Song::makeDefault();
  9001. lynx::EffectSlot slot;
  9002. slot.kind = lynx::EffectKind::plugin;
  9003. slot.plugin.id = clap->createIdentifierString().toStdString();
  9004. slot.plugin.name = clap->name.toStdString();
  9005. slot.smartDisable = false; // (processed every block, as with music playing: the export itself is silent)
  9006. song.mixer[0].effects = { slot }; // alone on the Master: the delay compensation is the plugin's latency
  9007. run->slot = (int) song.mixer[0].effects.size() - 1;
  9008. run->engine->setSong (song);
  9009. run->engine->renderOffline (0.1, 48000.0); // builds the rack (and the plugin) on the message thread
  9010. if (dynamic_cast<lynx::PluginEffect*> (run->engine->getEffect (0, run->slot).get()) == nullptr)
  9011. {
  9012. fail (run->report + "effect_loaded=no\n");
  9013. return;
  9014. }
  9015. auto effect = std::dynamic_pointer_cast<lynx::PluginEffect> (run->engine->getEffect (0, run->slot));
  9016. run->render = std::thread ([run, effect] () mutable {
  9017. const auto start = juce::Time::getMillisecondCounterHiRes();
  9018. run->engine->renderOffline (30.0, 48000.0);
  9019. run->renderSeconds = (juce::Time::getMillisecondCounterHiRes() - start) * 0.001;
  9020. // issue #46: an export at another rate / block size prepares the plugin from the export's thread; the
  9021. // plugin aborts unless activate / deactivate reach the main thread
  9022. auto& instance = effect->getInstance();
  9023. instance.prepareToPlay (44100.0, 1024);
  9024. instance.releaseResources();
  9025. instance.prepareToPlay (48000.0, 512);
  9026. run->engine->renderOffline (3.0, 44100.0); // (the engine rebuilds its rack at that rate)
  9027. // The engine has replaced this instance (made for 48 kHz) by then, so this is its last reference: it is
  9028. // deleted here, on the export's thread, and its deactivate / destroy go to the message thread, which this
  9029. // waits for. That has to happen before `done`: once the message thread sees it, it blocks in join() until
  9030. // this thread ends, and an instance deleted after that waited 10 s for it and then deactivated the plugin
  9031. // right here, off the main thread (the plugin aborts: about 1 run in 40 under load, round 190au).
  9032. effect.reset();
  9033. run->done = true;
  9034. });
  9035. // after the render: a second for the restarts still queued and the engine's timer (the new PDC plan)
  9036. auto finish = std::make_shared<std::function<void()>>();
  9037. *finish = [this, run, counters, reportPath, fail, finish] {
  9038. if (! run->done)
  9039. {
  9040. juce::Timer::callAfterDelay (50, *finish);
  9041. return;
  9042. }
  9043. run->render.join();
  9044. juce::Timer::callAfterDelay (1000, [this, run, counters, reportPath, fail] {
  9045. auto report = run->report;
  9046. int pluginLatency = -1;
  9047. if (const auto effect = run->engine->getEffect (0, run->slot)) // (not held past the engine's reset)
  9048. pluginLatency = effect->latencySamples();
  9049. const auto pdc = run->engine->getLatencySamples();
  9050. report << "render_seconds=" << juce::String (run->renderSeconds, 2) << "\n"
  9051. << "plugin_latency=" << pluginLatency << "\npdc_total=" << pdc << "\n"
  9052. << "plugin_crashes=" << lynx::pluginCrashCount() << "\n";
  9053. run->engine.reset(); // destroys the plugin: it writes its counters
  9054. // one line per plugin instance (the engine may have made more than one): none may have been
  9055. // deactivated inside process(), and the one that rendered must have restarted
  9056. int overlapped = 0, inactive = 0, requests = 0, activations = 0, lines = 0, wrongThread = 0, misordered = 0, unstopped = 0;
  9057. bool otherRate = false;
  9058. for (const auto& line : juce::StringArray::fromLines (counters.loadFileAsString()))
  9059. {
  9060. juce::StringPairArray values;
  9061. for (const auto& token : juce::StringArray::fromTokens (line, " ", ""))
  9062. if (token.contains ("="))
  9063. values.set (token.upToFirstOccurrenceOf ("=", false, false), token.fromFirstOccurrenceOf ("=", false, false));
  9064. if (values.size() == 0)
  9065. continue;
  9066. ++lines;
  9067. report << "instance: " << line << "\n";
  9068. overlapped += values["overlapped"].getIntValue();
  9069. inactive += values["inactive_blocks"].getIntValue();
  9070. // issue #46: activate / deactivate on the main thread, start / stop_processing on the audio thread
  9071. // (the plugin aborts the process otherwise, as u-he's do), in order, every start stopped
  9072. wrongThread += values["wrong_thread"].getIntValue();
  9073. misordered += values["misordered"].getIntValue();
  9074. unstopped += values["starts"].getIntValue() - values["stops"].getIntValue();
  9075. otherRate = otherRate || values["last_rate"].getIntValue() == 44100;
  9076. if (values["requests"].getIntValue() > requests)
  9077. {
  9078. requests = values["requests"].getIntValue();
  9079. activations = values["activations"].getIntValue();
  9080. }
  9081. }
  9082. report << "wrong_thread=" << wrongThread << "\nmisordered=" << misordered << "\nunstopped=" << unstopped
  9083. << "\nactivated_at_44100=" << (otherRate ? "yes" : "no") << "\n";
  9084. const auto ok = lines > 0 && requests > 0 && activations > requests / 2 && overlapped == 0 && inactive == 0
  9085. && wrongThread == 0 && misordered == 0 && unstopped == 0 && otherRate
  9086. && pluginLatency > 0 && pdc == pluginLatency && lynx::pluginCrashCount() == 0;
  9087. if (! ok)
  9088. {
  9089. fail (report);
  9090. return;
  9091. }
  9092. report << "result=OK\n";
  9093. juce::File (reportPath).replaceWithText (report);
  9094. setApplicationReturnValue (0);
  9095. quit();
  9096. });
  9097. };
  9098. juce::Timer::callAfterDelay (50, *finish);
  9099. }
  9100. // LYNX.exe --vst2test "LYNX Test Synth.dll" report.txt (tools/testplugin/lynx_test_vst2.c): LYNX's own VST2 host.
  9101. // Scans the DLL, imports it the way an .flp holds it (Fruity Wrapper VST2 state with a chunk, REA_rodada89 §2),
  9102. // renders with two saved gains (the level must follow the restored state) and checks the plugin saw the song tempo.
  9103. void runVst2Test (const juce::String& pluginPath, const juce::String& reportPath)
  9104. {
  9105. juce::String report;
  9106. bool ok = false;
  9107. {
  9108. lynx::AudioEngine offline (false);
  9109. auto& host = offline.getPluginHost();
  9110. report << "plugins_in_file=" << host.addPluginFile (juce::File (pluginPath)) << "\n";
  9111. std::optional<juce::PluginDescription> vst2;
  9112. for (const auto& type : host.getKnownPlugins().getTypes())
  9113. if (type.pluginFormatName == "VST")
  9114. vst2 = type;
  9115. auto render = [&] (float gain, float& tempoSeen, int& adopted) {
  9116. lynx::FlVst2State state;
  9117. state.flags = 8;
  9118. state.chunk = { 'L', 'X', 'V', '2', 0, 0, 0, 0 };
  9119. std::memcpy (state.chunk.data() + 4, &gain, 4);
  9120. auto song = lynx::Song::makeDefault();
  9121. song.bpm = 137.0;
  9122. auto& f = song.channels[4].plugin.foreign;
  9123. f.format = lynx::ForeignPlugin::Format::vst2;
  9124. f.vst2Id = (std::uint32_t) vst2->uniqueId;
  9125. f.name = "Some other name"; // found by the VST2 ID
  9126. f.state = lynx::writeFlVst2State (state);
  9127. song.channels[4].volume = 1.0f;
  9128. song.patterns[0].notes.clear();
  9129. song.patterns[0].notes.push_back ({ 0, 4 * lynx::ppq, 4, 69, 1.0f });
  9130. for (std::size_t c = 0; c < song.channels.size(); ++c)
  9131. if (c != 4)
  9132. song.channels[c].muted = true;
  9133. adopted = host.adoptFlPlugins (song);
  9134. offline.setSong (song);
  9135. const auto peak = offline.renderOffline (1.0, 48000.0);
  9136. offline.capturePluginStates();
  9137. juce::MemoryBlock saved;
  9138. saved.fromBase64Encoding (juce::String (offline.getSong().channels[4].plugin.state));
  9139. lynx::FlVst2State back;
  9140. tempoSeen = 0.0f;
  9141. if (lynx::parseFlVst2State (std::vector<std::uint8_t> ((const std::uint8_t*) saved.getData(), (const std::uint8_t*) saved.getData() + saved.getSize()), back)
  9142. && back.chunk.size() >= 12)
  9143. std::memcpy (&tempoSeen, back.chunk.data() + 8, 4);
  9144. return peak;
  9145. };
  9146. if (vst2)
  9147. {
  9148. report << "plugin=" << vst2->name << " id=" << vst2->uniqueId << " instrument=" << (int) vst2->isInstrument << "\n";
  9149. float tempoA = 0, tempoB = 0;
  9150. int adoptedA = 0, adoptedB = 0;
  9151. const auto quiet = render (0.1f, tempoA, adoptedA);
  9152. const auto loud = render (0.4f, tempoB, adoptedB);
  9153. report << "adopted=" << adoptedA << "," << adoptedB << " peak_gain_0.1=" << quiet << " peak_gain_0.4=" << loud
  9154. << " tempo_seen=" << tempoB * 1000.0f << "\n";
  9155. ok = adoptedA == 1 && adoptedB == 1 && quiet > 0.01f && std::abs (loud / quiet - 4.0f) < 0.2f
  9156. && std::abs (tempoB * 1000.0f - 137.0f) < 0.01f;
  9157. }
  9158. }
  9159. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  9160. juce::File (reportPath).replaceWithText (report);
  9161. setApplicationReturnValue (ok ? 0 : 1);
  9162. quit();
  9163. }
  9164. // LYNX --vst3noteidtest "LYNX Test Synth.vst3" report.txt (round 190fg, cmake/LynxPatchJuce.cmake fix 26): the VST3
  9165. // test synth (tools/testplugin/lynx_test_synth_vst3.cpp: voices kept by noteId, its log the ids it got) plays two
  9166. // 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).
  9167. // 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
  9168. // 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).
  9169. void runVst3NoteIdTest (const juce::String& pluginPath, const juce::String& reportPath)
  9170. {
  9171. juce::String report;
  9172. bool ok = false;
  9173. const auto logBase = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-noteid-" + juce::String (juce::Time::currentTimeMillis()));
  9174. // (read by each new instance)
  9175. #if JUCE_WINDOWS
  9176. _putenv_s ("LYNX_TEST_SYNTH_LOG", logBase.getFullPathName().toRawUTF8());
  9177. #else
  9178. setenv ("LYNX_TEST_SYNTH_LOG", logBase.getFullPathName().toRawUTF8(), 1);
  9179. #endif
  9180. struct E
  9181. {
  9182. bool on = false;
  9183. int key = 0, id = -1;
  9184. };
  9185. // (the lines each render added: a running instance keeps its log file open, so the files stay until the end)
  9186. std::map<juce::String, int> linesRead;
  9187. const auto readLog = [&logBase, &linesRead] {
  9188. std::vector<E> events;
  9189. for (const auto& f : logBase.getParentDirectory().findChildFiles (juce::File::findFiles, false, logBase.getFileName() + ".*"))
  9190. {
  9191. juce::StringArray lines;
  9192. f.readLines (lines);
  9193. auto& done = linesRead[f.getFullPathName()];
  9194. for (int i = done; i < lines.size(); ++i)
  9195. {
  9196. const auto p = juce::StringArray::fromTokens (lines[i], " ", {});
  9197. if (p.size() >= 5 && p[0].startsWith ("E"))
  9198. events.push_back ({ p[1] == "on", p[2].getIntValue(), p[4].getIntValue() });
  9199. }
  9200. done = lines.size() - (lines.isEmpty() || lines[lines.size() - 1].isNotEmpty() ? 0 : 1);
  9201. }
  9202. return events;
  9203. };
  9204. {
  9205. lynx::AudioEngine offline (false);
  9206. auto& host = offline.getPluginHost();
  9207. report << "plugins_in_file=" << host.addPluginFile (juce::File (pluginPath)) << "\n";
  9208. std::optional<juce::PluginDescription> vst3;
  9209. for (const auto& type : host.getKnownPlugins().getTypes())
  9210. if (type.pluginFormatName == "VST3" && type.isInstrument)
  9211. vst3 = type;
  9212. const auto render = [&] (bool tags) {
  9213. auto song = lynx::Song::makeDefault();
  9214. song.bpm = 120.0;
  9215. auto& c = song.channels[0];
  9216. c.instrument = lynx::InstrumentKind::plugin;
  9217. c.plugin.id = vst3->createIdentifierString().toStdString();
  9218. c.plugin.name = vst3->name.toStdString();
  9219. for (std::size_t k = 1; k < song.channels.size(); ++k)
  9220. song.channels[k].muted = true;
  9221. auto& notes = song.patterns[0].notes;
  9222. notes.clear();
  9223. const auto beat = (std::int64_t) lynx::ppq;
  9224. notes.push_back ({ 0, 4 * beat, 0, 60, 0.8f }); // A
  9225. notes.push_back ({ 2 * beat, 4 * beat, 0, 60, 0.8f }); // B
  9226. notes.push_back ({ 8 * beat, 6 * beat, 0, 64, 0.8f }); // C
  9227. notes.push_back ({ 10 * beat, 2 * beat, 0, 64, 0.8f }); // D (inside C)
  9228. song.patterns[0].sortNotes();
  9229. song.patterns[0].lengthTicks = 16 * beat;
  9230. offline.setSong (song);
  9231. offline.dispatchPendingMessages();
  9232. if (! tags)
  9233. juce::lynxNoteTagHook = nullptr; // (fix 14 alone: the oldest sounding id; the next instance sets it again)
  9234. offline.renderOffline (7.9, 48000.0); // (C ends at 7 s; the 8 s pattern does not loop yet)
  9235. return readLog();
  9236. };
  9237. const auto check = [&report] (const char* name, const std::vector<E>& events, bool expectOwn) {
  9238. // ons and offs of each key in the order the plugin got them
  9239. std::map<int, std::vector<int>> ons, offs;
  9240. for (const auto& e : events)
  9241. (e.on ? ons : offs)[e.key].push_back (e.id);
  9242. const auto& a = ons[60]; const auto& o60 = offs[60];
  9243. const auto& c = ons[64]; const auto& o64 = offs[64];
  9244. report << name << ": key 60 ons";
  9245. for (auto id : a) report << " " << id;
  9246. report << " offs";
  9247. for (auto id : o60) report << " " << id;
  9248. report << "; key 64 ons";
  9249. for (auto id : c) report << " " << id;
  9250. report << " offs";
  9251. for (auto id : o64) report << " " << id;
  9252. report << "\n";
  9253. if (a.size() != 2 || o60.size() != 2 || c.size() != 2 || o64.size() != 2 || a[0] < 0 || c[0] < 0)
  9254. return false;
  9255. const auto fifo = o60[0] == a[0] && o60[1] == a[1]; // A ends first: A's id either way
  9256. // LIFO: D (c[1]) ends first; its own id with the tags, C's (the oldest) without
  9257. const auto lifo = expectOwn ? (o64[0] == c[1] && o64[1] == c[0]) : (o64[0] == c[0] && o64[1] == c[1]);
  9258. return fifo && lifo;
  9259. };
  9260. if (vst3)
  9261. {
  9262. report << "plugin=" << vst3->name << "\n";
  9263. const auto withTags = render (true);
  9264. const auto okTags = check ("with_tags", withTags, true);
  9265. const auto withoutTags = render (false);
  9266. const auto okBefore = check ("fix14_only", withoutTags, false);
  9267. report << "own_ids=" << (okTags ? "yes" : "NO") << " fix14_only_oldest=" << (okBefore ? "yes" : "NO") << "\n";
  9268. ok = okTags && okBefore;
  9269. }
  9270. }
  9271. if (ok) // (a failure leaves the logs for a look: their path is in the report)
  9272. for (const auto& f : logBase.getParentDirectory().findChildFiles (juce::File::findFiles, false, logBase.getFileName() + ".*"))
  9273. f.deleteFile();
  9274. else
  9275. report << "synth_logs=" << logBase.getFullPathName() << ".*\n";
  9276. #if JUCE_WINDOWS
  9277. _putenv_s ("LYNX_TEST_SYNTH_LOG", "");
  9278. #else
  9279. unsetenv ("LYNX_TEST_SYNTH_LOG");
  9280. #endif
  9281. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  9282. juce::File (reportPath).replaceWithText (report);
  9283. setApplicationReturnValue (ok ? 0 : 1);
  9284. quit();
  9285. }
  9286. // Round 181c: a wrapper MIDI option changed on a running plugin must act like the same option on a new one. For each
  9287. // option: a control engine whose plugin is created with the option set (proves the test can see it), then an engine
  9288. // whose plugin is already running when the option changes through editSong, as the wrapper page does it. What the
  9289. // plugin received comes from the test plugin's own log. The running instance must also stay the same one.
  9290. void runWrapperMidiTest (const juce::String& pluginPath, const juce::String& reportPath)
  9291. {
  9292. juce::String report;
  9293. auto ok = true;
  9294. const juce::File logFile (juce::SystemStats::getEnvironmentVariable ("LYNX_TEST_VST2_MIDILOG", {}));
  9295. struct Event { juce::String instance; int status, data1, data2; };
  9296. auto take = [&] {
  9297. std::vector<Event> out;
  9298. juce::StringArray lines;
  9299. logFile.readLines (lines);
  9300. for (const auto& line : lines)
  9301. {
  9302. const auto p = juce::StringArray::fromTokens (line, " ", {});
  9303. if (p.size() == 4)
  9304. out.push_back ({ p[0], p[1].getIntValue(), p[2].getIntValue(), p[3].getIntValue() });
  9305. }
  9306. logFile.deleteFile();
  9307. return out;
  9308. };
  9309. auto count = [] (const std::vector<Event>& events, int status, int data1, int data2) {
  9310. int n = 0;
  9311. for (const auto& e : events)
  9312. n += (e.status & 0xF0) == status && (data1 < 0 || e.data1 == data1) && (data2 < 0 || e.data2 == data2) ? 1 : 0;
  9313. return n;
  9314. };
  9315. struct Option
  9316. {
  9317. const char* name;
  9318. std::function<void (lynx::PluginRef&)> before, change;
  9319. std::function<juce::String (const std::vector<Event>&)> seen;
  9320. };
  9321. const Option options[] = {
  9322. { "Send note release velocity off", {}, [] (lynx::PluginRef& r) { r.releaseVelocity = false; },
  9323. [&] (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)); } },
  9324. { "Send pitch bend range on", {}, [] (lynx::PluginRef& r) { r.sendBendRange = true; },
  9325. [&] (const std::vector<Event>& e) { return "rpn_range_12=" + juce::String (count (e, 0xB0, 6, 12)); } },
  9326. { "Pitch bend range 24", [] (lynx::PluginRef& r) { r.sendBendRange = true; }, [] (lynx::PluginRef& r) { r.bendRange = 24; },
  9327. [&] (const std::vector<Event>& e) { return "rpn_range_24=" + juce::String (count (e, 0xB0, 6, 24)); } },
  9328. { "Send MOD X as polyphonic aftertouch on", {}, [] (lynx::PluginRef& r) { r.modXAftertouch = true; },
  9329. [&] (const std::vector<Event>& e) { return "aftertouch=" + juce::String (count (e, 0xA0, 69, -1)); } },
  9330. { "Send All Notes Off when playback stops off", {}, [] (lynx::PluginRef& r) { r.allNotesOffOnStop = false; },
  9331. [&] (const std::vector<Event>& e) { return "cc123=" + juce::String (count (e, 0xB0, 123, -1)); } },
  9332. };
  9333. // each phase has its own engine: an engine keeps the running instance across setSong, so one engine would
  9334. // carry the control's plugin into the "before" phase
  9335. lynx::AudioEngine scanner (false);
  9336. auto& host = scanner.getPluginHost();
  9337. report << "plugins_in_file=" << host.addPluginFile (juce::File (pluginPath)) << "\n";
  9338. std::optional<juce::PluginDescription> vst2;
  9339. for (const auto& type : host.getKnownPlugins().getTypes())
  9340. if (type.pluginFormatName == "VST")
  9341. vst2 = type;
  9342. if (! vst2 || logFile.getFullPathName().isEmpty())
  9343. ok = false;
  9344. else
  9345. for (const auto& option : options)
  9346. {
  9347. auto makeSong = [&] (bool changed) {
  9348. auto song = lynx::Song::makeDefault();
  9349. auto& channel = song.channels[0];
  9350. channel.instrument = lynx::InstrumentKind::plugin;
  9351. channel.plugin = {};
  9352. channel.plugin.id = vst2->createIdentifierString().toStdString();
  9353. channel.plugin.name = vst2->name.toStdString();
  9354. if (option.before)
  9355. option.before (channel.plugin);
  9356. if (changed)
  9357. option.change (channel.plugin);
  9358. song.patterns[0].notes.clear();
  9359. lynx::Note note;
  9360. note.start = 0;
  9361. note.length = lynx::ppq;
  9362. note.channel = 0;
  9363. note.key = 69;
  9364. note.velocity = 1.0f;
  9365. note.release = 0.25f; // 32 of 127
  9366. note.modX = 0.75f;
  9367. song.patterns[0].notes.push_back (note);
  9368. for (std::size_t c = 1; c < song.channels.size(); ++c)
  9369. song.channels[c].muted = true;
  9370. return song;
  9371. };
  9372. // a block of the song, then a note held across "playback stopped", as the options act on either
  9373. auto play = [&] (lynx::AudioEngine& engine) {
  9374. logFile.deleteFile();
  9375. engine.renderOffline (1.0, 48000.0);
  9376. if (auto instrument = engine.getChannelInstrument (0))
  9377. {
  9378. instrument->noteOn (60, 1.0f);
  9379. instrument->transportStopped();
  9380. }
  9381. engine.renderOffline (0.1, 48000.0);
  9382. return take();
  9383. };
  9384. auto newEngine = [&] {
  9385. auto engine = std::make_unique<lynx::AudioEngine> (false);
  9386. engine->getPluginHost().addPluginFile (juce::File (pluginPath));
  9387. return engine;
  9388. };
  9389. std::vector<Event> control;
  9390. {
  9391. auto engine = newEngine();
  9392. engine->setSong (makeSong (true));
  9393. control = play (*engine);
  9394. }
  9395. auto engine = newEngine();
  9396. engine->setSong (makeSong (false));
  9397. const auto before = play (*engine);
  9398. const auto instrumentBefore = engine->getChannelInstrument (0).get();
  9399. engine->capturePluginStates(); // as the wrapper page does
  9400. engine->editSong ([&] (lynx::Song& song) { option.change (song.channels[0].plugin); });
  9401. const auto after = play (*engine);
  9402. const auto sameInstance = engine->getChannelInstrument (0).get() == instrumentBefore;
  9403. // the counts differ between phases (how many blocks the note spans, how many instances the phase made):
  9404. // what matters is whether each kind of event is there at all
  9405. auto shape = [] (const juce::String& seen) {
  9406. juce::String out;
  9407. for (const auto& token : juce::StringArray::fromTokens (seen, " ", {}))
  9408. out << token.upToFirstOccurrenceOf ("=", false, false) << (token.fromFirstOccurrenceOf ("=", false, false).getIntValue() > 0 ? "=yes " : "=no ");
  9409. return out;
  9410. };
  9411. auto instances = [] (const std::vector<Event>& events) {
  9412. std::set<juce::String> made;
  9413. for (const auto& e : events)
  9414. made.insert (e.instance);
  9415. return (int) made.size();
  9416. };
  9417. const auto a = option.seen (control) + " instances=" + juce::String (instances (control)),
  9418. b = option.seen (before) + " instances=" + juce::String (instances (before)),
  9419. c = option.seen (after) + " instances=" + juce::String (instances (after));
  9420. const auto visible = shape (option.seen (control)) != shape (option.seen (before));
  9421. const auto works = shape (option.seen (after)) == shape (option.seen (control));
  9422. report << option.name << ": control " << a << " | before " << b << " | after the change " << c << " | same_instance=" << (int) sameInstance
  9423. << " | test_sees_the_option=" << (int) visible << " | " << (! visible ? "NOT PROVEN" : works ? "acts on the plugin" : "DEAD until re-created") << "\n";
  9424. ok = ok && visible && works;
  9425. }
  9426. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  9427. juce::File (reportPath).replaceWithText (report);
  9428. setApplicationReturnValue (ok ? 0 : 1);
  9429. quit();
  9430. }
  9431. // LYNX.exe --wrappershot "LYNX Test Drums.dll" <folder> (round 188d): the wrapper's Processing tab drawn offscreen
  9432. // (no window, no focus) for the FL | LYNX review: wrap-default.png (a fresh plugin), wrap-automap.png (Auto map
  9433. // outputs, output 3 off: FL's shot b23), wrap-settings.png. Scale 1.5 (FL's shots are at 150 %).
  9434. void runWrapperShot (const juce::String& pluginPath, const juce::String& folderPath)
  9435. {
  9436. const juce::File folder (folderPath);
  9437. folder.createDirectory();
  9438. auto ok = false;
  9439. lynx::AudioEngine engine (false);
  9440. engine.getPluginHost().addPluginFile (juce::File (pluginPath));
  9441. std::optional<juce::PluginDescription> vst2;
  9442. for (const auto& type : engine.getPluginHost().getKnownPlugins().getTypes())
  9443. if (type.pluginFormatName == "VST" && juce::File (type.fileOrIdentifier) == juce::File (pluginPath))
  9444. vst2 = type; // (the profile may know other test plugins)
  9445. if (vst2 && ! vst2->isInstrument)
  9446. {
  9447. // an effect (round 188d): on insert 1, with insert 2 routed there as a sidechain (FL's k65 / k78 shots):
  9448. // wrap-fx-default.png, wrap-fx-automap.png (Auto map inputs and outputs)
  9449. auto song = lynx::Song::makeDefault();
  9450. if (song.mixer.size() < 4)
  9451. song.mixer.resize (4);
  9452. auto slot = lynx::makeEffectSlot (lynx::EffectKind::plugin);
  9453. slot.plugin.id = vst2->createIdentifierString().toStdString();
  9454. slot.plugin.name = vst2->name.toStdString();
  9455. song.mixer[1].effects = { slot };
  9456. lynx::mixerops::sidechainTo (song, 2, 1);
  9457. engine.setSong (song);
  9458. engine.renderOffline (0.05, 48000.0);
  9459. if (auto fx = std::dynamic_pointer_cast<lynx::PluginEffect> (engine.getEffect (1, 0)))
  9460. {
  9461. auto find = [] (lynx::Song& s) -> lynx::PluginRef* {
  9462. return s.mixer.size() < 2 || s.mixer[1].effects.empty() ? nullptr : &s.mixer[1].effects[0].plugin;
  9463. };
  9464. auto save = [&] (const char* name) {
  9465. const auto image = lynx::wrapperSettingsSnapshot (engine, find, fx->getInstance(), false, 1, 1.5f, 1, 0);
  9466. juce::FileOutputStream out (folder.getChildFile (name));
  9467. out.setPosition (0);
  9468. out.truncate();
  9469. return out.openedOk() && juce::PNGImageFormat().writeImageToStream (image, out);
  9470. };
  9471. ok = save ("wrap-fx-default.png");
  9472. engine.editSong ([] (lynx::Song& s) {
  9473. lynx::autoMapOutputs (s.mixer[1].effects[0].plugin.inputs, 2);
  9474. lynx::autoMapOutputs (s.mixer[1].effects[0].plugin.outputs, 2);
  9475. s.mixer[1].effects[0].sidechain = lynx::mixerops::sidechainIndexSource (s, 1, 1);
  9476. });
  9477. ok = ok && save ("wrap-fx-automap.png") && engine.getSong().mixer[1].effects[0].sidechain == 2;
  9478. }
  9479. }
  9480. else if (vst2)
  9481. {
  9482. auto song = lynx::Song::makeDefault();
  9483. auto& channel = song.channels[0];
  9484. channel.instrument = lynx::InstrumentKind::plugin;
  9485. channel.plugin = {};
  9486. channel.plugin.id = vst2->createIdentifierString().toStdString();
  9487. channel.plugin.name = vst2->name.toStdString();
  9488. channel.mixerTrack = 5;
  9489. engine.setSong (song);
  9490. engine.renderOffline (0.05, 48000.0); // (the plugin is hosted by then)
  9491. if (auto instrument = std::dynamic_pointer_cast<lynx::PluginInstrument> (engine.getChannelInstrument (0)))
  9492. {
  9493. auto find = [] (lynx::Song& s) -> lynx::PluginRef* { return s.channels.empty() ? nullptr : &s.channels[0].plugin; };
  9494. auto save = [&] (const char* name, int tab) {
  9495. const auto image = lynx::wrapperSettingsSnapshot (engine, find, instrument->getInstance(), true, tab, 1.5f);
  9496. juce::FileOutputStream out (folder.getChildFile (name));
  9497. out.setPosition (0);
  9498. out.truncate();
  9499. return out.openedOk() && juce::PNGImageFormat().writeImageToStream (image, out);
  9500. };
  9501. ok = save ("wrap-default.png", 1) && save ("wrap-settings.png", 0);
  9502. engine.editSong ([] (lynx::Song& s) {
  9503. lynx::autoMapOutputs (s.channels[0].plugin.outputs, 8);
  9504. s.channels[0].plugin.outputs.resize (8);
  9505. s.channels[0].plugin.outputs[2].active = 0;
  9506. s.channels[0].plugin.processInactive = false; // (as an LED click does, FL's b23)
  9507. });
  9508. ok = ok && save ("wrap-automap.png", 1);
  9509. }
  9510. }
  9511. setApplicationReturnValue (ok ? 0 : 1);
  9512. quit();
  9513. }
  9514. // LYNX.exe --multiouttest "LYNX Test Drums.dll" report.txt (round 188d, issue #114): a multi-output VST2
  9515. // (tools/testplugin/lynx_test_drums_vst2.c: key 36 = output 1 at 110 Hz, key 37 = output 2 at 220 Hz) on a
  9516. // channel routed to insert 1; the wrapper's Processing › Connections as FL plays them [EXEC fl188d]: every output
  9517. // on the channel's insert by default, an offset to another insert, an inactive output silent, the channel's
  9518. // volume on all of them. Measured on the master with insert 1 muted or not.
  9519. void runMultiOutTest (const juce::String& pluginPath, const juce::String& reportPath)
  9520. {
  9521. juce::String report;
  9522. auto ok = true;
  9523. lynx::AudioEngine scanner (false);
  9524. report << "plugins_in_file=" << scanner.getPluginHost().addPluginFile (juce::File (pluginPath)) << "\n";
  9525. std::optional<juce::PluginDescription> vst2;
  9526. for (const auto& type : scanner.getPluginHost().getKnownPlugins().getTypes())
  9527. if (type.pluginFormatName == "VST" && juce::File (type.fileOrIdentifier) == juce::File (pluginPath))
  9528. vst2 = type; // (the profile may know other test plugins)
  9529. struct Case
  9530. {
  9531. const char* name;
  9532. std::vector<lynx::PluginOutputRoute> routes;
  9533. bool muteInsert1;
  9534. float volume;
  9535. bool kick, snare; // expected on the master
  9536. };
  9537. const Case cases[] = {
  9538. { "defaults", {}, false, -1.0f, true, true },
  9539. { "defaults, insert 1 muted", {}, true, -1.0f, false, false },
  9540. { "auto map, insert 1 muted", { { 0, 1 }, { 1, 1 } }, true, -1.0f, false, true },
  9541. { "auto map", { { 0, 1 }, { 1, 1 } }, false, -1.0f, true, true },
  9542. { "output 2 inactive", { { 0, 1 }, { 1, 0 } }, false, -1.0f, true, false },
  9543. { "output 1 inactive", { { 0, 0 } }, false, -1.0f, false, true },
  9544. { "auto map, channel volume 0", { { 0, 1 }, { 1, 1 } }, false, 0.0f, false, false },
  9545. { "output 2 inactive, Process inactive inputs and outputs on", { { 0, 1 }, { 1, 0 } }, false, -1.0f, true, true },
  9546. };
  9547. auto tone = [] (const std::vector<float>& x, double hz) {
  9548. // Goertzel magnitude over the buffer (normalised to a sine's amplitude)
  9549. const auto w = 2.0 * juce::MathConstants<double>::pi * hz / 48000.0;
  9550. double s1 = 0.0, s2 = 0.0;
  9551. for (const auto v : x)
  9552. {
  9553. const auto s0 = v + 2.0 * std::cos (w) * s1 - s2;
  9554. s2 = s1;
  9555. s1 = s0;
  9556. }
  9557. 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());
  9558. };
  9559. if (! vst2)
  9560. ok = false;
  9561. else
  9562. for (const auto& c : cases)
  9563. {
  9564. lynx::AudioEngine engine (false);
  9565. engine.getPluginHost().addPluginFile (juce::File (pluginPath));
  9566. auto song = lynx::Song::makeDefault();
  9567. auto& channel = song.channels[0];
  9568. channel.instrument = lynx::InstrumentKind::plugin;
  9569. channel.plugin = {};
  9570. channel.plugin.id = vst2->createIdentifierString().toStdString();
  9571. channel.plugin.name = vst2->name.toStdString();
  9572. channel.plugin.outputs = c.routes;
  9573. // (FL's "Process inactive inputs and outputs" plays an inactive output: off but for the case named so)
  9574. channel.plugin.processInactive = juce::String (c.name).contains ("Process inactive");
  9575. channel.mixerTrack = 1;
  9576. if (c.volume >= 0.0f)
  9577. channel.volume = c.volume;
  9578. for (std::size_t k = 1; k < song.channels.size(); ++k)
  9579. song.channels[k].muted = true;
  9580. if (song.mixer.size() < 4)
  9581. song.mixer.resize (4);
  9582. song.mixer[1].muted = c.muteInsert1;
  9583. song.patterns[0].notes.clear();
  9584. for (const auto key : { 36, 37 })
  9585. {
  9586. lynx::Note note;
  9587. note.start = 0;
  9588. note.length = lynx::ppq;
  9589. note.channel = 0;
  9590. note.key = key;
  9591. note.velocity = 1.0f;
  9592. song.patterns[0].notes.push_back (note);
  9593. }
  9594. engine.setSong (song);
  9595. std::vector<float> master;
  9596. lynx::AudioEngine::RenderOptions options;
  9597. options.seconds = 0.25;
  9598. options.sampleRate = 48000.0;
  9599. options.capture = [&master] (const float* l, const float*, int n) { master.insert (master.end(), l, l + n); };
  9600. engine.renderOffline (options);
  9601. const auto kick = tone (master, 110.0), snare = tone (master, 220.0);
  9602. const auto pass = (kick > 0.01) == c.kick && (snare > 0.01) == c.snare;
  9603. report << c.name << ": kick_110Hz=" << juce::String (kick, 4) << " snare_220Hz=" << juce::String (snare, 4) << " expected kick="
  9604. << (int) c.kick << " snare=" << (int) c.snare << (pass ? " OK" : " FAILED") << "\n";
  9605. ok = ok && pass;
  9606. if (auto instrument = std::dynamic_pointer_cast<lynx::PluginInstrument> (engine.getChannelInstrument (0)))
  9607. if (&c == &cases[0])
  9608. {
  9609. report << "outputs=" << (int) instrument->outputs().size();
  9610. for (const auto& o : instrument->outputs())
  9611. report << " [" << o.name << " ch" << o.channel << "x" << o.channels << "]";
  9612. report << "\n";
  9613. ok = ok && instrument->outputs().size() == 8 && instrument->outputs()[1].name == "Snare";
  9614. }
  9615. }
  9616. // round 189j: "LYNX Test SC.dll" next to it (tools/testplugin/lynx_test_sc_vst2.c) as an effect on insert 1
  9617. const auto sc = juce::File (pluginPath).getSiblingFile ("LYNX Test SC.dll");
  9618. if (sc.existsAsFile())
  9619. ok = runEffectConnectionsTest (sc, report) && ok;
  9620. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  9621. juce::File (reportPath).replaceWithText (report);
  9622. setApplicationReturnValue (ok ? 0 : 1);
  9623. quit();
  9624. }
  9625. // Round 189j: a hosted effect's Processing › Connections against FL 2026's own renders of the same projects
  9626. // [EXEC fxconn189j: FL /R renders of LYNX's .flp exports, docs/analise/REA_rodada189j.md]. Insert 1: a 440 Hz
  9627. // sampler and "LYNX Test SC" (output 1 = input 1, output 2 = input 2); inserts 2 (1000 Hz) and 3 (1500 Hz) routed
  9628. // to insert 1 at level 0 only; insert 4 a 2500 Hz reference on the Master; insert 1 routed to the Master and at
  9629. // level 0 to inserts 5 (panned left) and 6 (right). Each tone's level per side, in dB from the reference's, must be
  9630. // FL's within 0.5 dB (absent: 50 dB under it).
  9631. bool runEffectConnectionsTest (const juce::File& scFile, juce::String& report)
  9632. {
  9633. lynx::AudioEngine scanner (false);
  9634. scanner.getPluginHost().addPluginFile (scFile);
  9635. std::optional<juce::PluginDescription> sc;
  9636. for (const auto& type : scanner.getPluginHost().getKnownPlugins().getTypes())
  9637. if (type.pluginFormatName == "VST" && juce::File (type.fileOrIdentifier) == scFile)
  9638. sc = type;
  9639. report << "effect_plugin=" << (sc ? sc->name : juce::String ("not found")) << "\n";
  9640. if (! sc)
  9641. return false;
  9642. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-fxconn189j");
  9643. dir.createDirectory();
  9644. const double tones[] = { 440.0, 1000.0, 1500.0, 2500.0 };
  9645. for (const auto hz : tones)
  9646. {
  9647. const auto wav = dir.getChildFile ("sine" + juce::String ((int) hz) + ".wav");
  9648. if (wav.existsAsFile())
  9649. continue;
  9650. juce::AudioBuffer<float> sine (1, 44100 * 3);
  9651. for (int i = 0; i < sine.getNumSamples(); ++i)
  9652. sine.setSample (0, i, 0.25f * (float) std::sin (2.0 * juce::MathConstants<double>::pi * hz * i / 44100.0));
  9653. juce::WavAudioFormat format;
  9654. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  9655. if (auto* w = format.createWriterFor (out.get(), 44100.0, 1, 16, {}, 0))
  9656. {
  9657. out.release();
  9658. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  9659. writer->writeFromAudioSampleBuffer (sine, 0, sine.getNumSamples());
  9660. }
  9661. }
  9662. using Route = lynx::PluginOutputRoute;
  9663. constexpr float none = -999.0f;
  9664. struct Case
  9665. {
  9666. const char* name;
  9667. std::vector<Route> inputs, outputs;
  9668. int tweak; // 1 no Master route, 2 insert 1 fader at 0.4, 3 Process inactive off, 4 Master route level 0, 5 route
  9669. // to 7 too, 6 insert 2 fader at 0.4, 7 insert 2 muted, 8 insert 2 panned left
  9670. float level[3][2]; // 440 / 1000 / 1500 Hz, left / right: dB from the reference, FL's
  9671. };
  9672. const Route d { 0, 1 };
  9673. const Case cases[] = {
  9674. { "e00 FL defaults", { d, d }, {}, 0, { { 6.1f, 6.1f }, { none, none }, { none, none } } },
  9675. { "e01 input 1 at 1", { { 1, 1 } }, {}, 0, { { 0, 0 }, { 0, 0 }, { none, none } } },
  9676. { "e02 input 1 at 2", { { 2, 1 } }, {}, 0, { { 0, 0 }, { none, none }, { 0, 0 } } },
  9677. { "e03 input 2 at 1", { d, { 1, 1 } }, {}, 0, { { 0, 0 }, { 0, 0 }, { none, none } } },
  9678. { "e04 output 2 at 1 (Master)", { d, { 1, 1 } }, { d, { 1, 1 } }, 0, { { 0, 0 }, { 0, 0 }, { none, none } } },
  9679. { "e05 output 2 at 2 (insert 5)", { d, { 1, 1 } }, { d, { 2, 1 } }, 0, { { 0, 0 }, { 3.0f, none }, { none, none } } },
  9680. { "e06 output 1 at 1", {}, { { 1, 1 } }, 0, { { 6.1f, 6.1f }, { none, none }, { none, none } } },
  9681. { "e07 output 2 at 5 (past the list)", { d, { 1, 1 } }, { d, { 5, 1 } }, 0, { { 0, 0 }, { none, 3.0f }, { none, none } } },
  9682. { "e08 inputs 1 and 2 at 1", { { 1, 1 }, { 1, 1 } }, {}, 0, { { none, none }, { 6.1f, 6.1f }, { none, none } } },
  9683. { "e09 output 2 inactive", { d, { 1, 1 } }, { d, { 0, 0 } }, 0, { { 0, 0 }, { 0, 0 }, { none, none } } },
  9684. { "e10 input 1 at 5 (past the list)", { { 5, 1 } }, {}, 0, { { 6.1f, 6.1f }, { none, none }, { none, none } } },
  9685. { "e11 output 2 at 3 (insert 6)", { d, { 1, 1 } }, { d, { 3, 1 } }, 0, { { 0, 0 }, { none, 3.0f }, { none, none } } },
  9686. { "e13 no Master route, output 2 at 1", { d, { 1, 1 } }, { d, { 1, 1 } }, 1, { { none, none }, { 3.0f, none }, { none, none } } },
  9687. { "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 } } },
  9688. { "e15 input 2 inactive", { d, { 1, 0 } }, { d, d }, 3, { { 0, 0 }, { none, none }, { none, none } } },
  9689. { "e16 output 2 inactive", { d, { 1, 1 } }, { d, { 0, 0 } }, 3, { { 0, 0 }, { none, none }, { none, none } } },
  9690. { "e18 route to 7 too, output 2 at 3", { d, { 1, 1 } }, { d, { 3, 1 } }, 5, { { 0, 0 }, { none, 3.0f }, { none, none } } },
  9691. { "e19 Master route at 0, output 2 at 1", { d, { 1, 1 } }, { d, { 1, 1 } }, 4, { { none, none }, { 0, 0 }, { none, none } } },
  9692. { "e22 input 1 at 1 inactive", { { 1, 0 } }, {}, 3, { { 0, 0 }, { none, none }, { none, none } } },
  9693. { "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 } } },
  9694. { "e24 input 1 at 1, insert 2 fader 0.4", { { 1, 1 } }, {}, 6, { { 0, 0 }, { -12.7f, -12.7f }, { none, none } } },
  9695. { "e25 input 1 at 1, insert 2 muted", { { 1, 1 } }, {}, 7, { { 0, 0 }, { none, none }, { none, none } } },
  9696. { "e26 input 1 at 1, insert 2 panned left", { { 1, 1 } }, {}, 8, { { 0, 0 }, { 3.0f, none }, { none, none } } },
  9697. };
  9698. auto goertzel = [] (const std::vector<float>& x, double hz) {
  9699. const auto w = 2.0 * juce::MathConstants<double>::pi * hz / 44100.0;
  9700. double s1 = 0.0, s2 = 0.0;
  9701. for (const auto v : x)
  9702. {
  9703. const auto s0 = v + 2.0 * std::cos (w) * s1 - s2;
  9704. s2 = s1;
  9705. s1 = s0;
  9706. }
  9707. 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());
  9708. return a > 1e-7 ? 20.0 * std::log10 (a) : -140.0;
  9709. };
  9710. auto ok = true;
  9711. for (const auto& c : cases)
  9712. {
  9713. lynx::AudioEngine engine (false);
  9714. engine.getPluginHost().addPluginFile (scFile);
  9715. auto song = lynx::Song::makeDefault();
  9716. song.bpm = 120.0;
  9717. song.channels.clear();
  9718. song.automations.clear();
  9719. for (auto& p : song.patterns)
  9720. p.notes.clear();
  9721. for (int k = 0; k < 4; ++k)
  9722. {
  9723. lynx::ChannelDef ch;
  9724. ch.name = "S" + std::to_string ((int) tones[k]);
  9725. ch.instrument = lynx::InstrumentKind::sampler;
  9726. ch.samplePath = dir.getChildFile ("sine" + juce::String ((int) tones[k]) + ".wav").getFullPathName().toStdString();
  9727. ch.mixerTrack = k + 1;
  9728. song.channels.push_back (ch);
  9729. lynx::Note note;
  9730. note.start = 0;
  9731. note.length = 8 * lynx::ppq;
  9732. note.channel = k;
  9733. note.key = 60;
  9734. note.velocity = 0.78f;
  9735. song.patterns[0].notes.push_back (note);
  9736. }
  9737. if (song.mixer.size() < 10)
  9738. song.mixer.resize (10);
  9739. for (auto& t : song.mixer)
  9740. {
  9741. t.effects.clear();
  9742. t.sends.clear();
  9743. t.toMaster = true;
  9744. }
  9745. lynx::EffectSlot fx;
  9746. fx.kind = lynx::EffectKind::plugin;
  9747. fx.plugin.id = sc->createIdentifierString().toStdString();
  9748. fx.plugin.name = sc->name.toStdString();
  9749. fx.plugin.inputs = c.inputs;
  9750. fx.plugin.outputs = c.outputs;
  9751. fx.plugin.processInactive = c.tweak != 3;
  9752. auto& one = song.mixer[1];
  9753. one.effects.push_back (fx);
  9754. one.sends = { { 5, 0.0f }, { 6, 0.0f } };
  9755. for (const int t : { 2, 3 })
  9756. {
  9757. song.mixer[(std::size_t) t].toMaster = false;
  9758. song.mixer[(std::size_t) t].sends = { { 1, 0.0f } };
  9759. }
  9760. song.mixer[5].pan = -1.0f;
  9761. song.mixer[6].pan = 1.0f;
  9762. one.toMaster = c.tweak != 1;
  9763. if (c.tweak == 2)
  9764. one.volume = 0.4f;
  9765. if (c.tweak == 4)
  9766. one.masterLevel = 0.0f;
  9767. if (c.tweak == 6)
  9768. song.mixer[2].volume = 0.4f;
  9769. song.mixer[2].muted = c.tweak == 7;
  9770. song.mixer[2].pan = c.tweak == 8 ? -1.0f : 0.0f;
  9771. if (c.tweak == 5)
  9772. {
  9773. one.sends = { { 7, 0.0f }, { 5, 0.0f }, { 6, 0.0f } };
  9774. song.mixer[7].pan = 0.5f;
  9775. }
  9776. // (input 2's index sets the slot's side input source, as the Connections page and the import do)
  9777. if (c.inputs.size() > 1 && c.inputs[1].offset > 0)
  9778. one.effects[0].sidechain = lynx::mixerops::sidechainIndexSource (song, 1, c.inputs[1].offset);
  9779. engine.setSong (song);
  9780. std::vector<float> left, right;
  9781. lynx::AudioEngine::RenderOptions options;
  9782. options.seconds = 1.2;
  9783. options.sampleRate = 44100.0;
  9784. options.capture = [&] (const float* l, const float* r, int n) {
  9785. left.insert (left.end(), l, l + n);
  9786. right.insert (right.end(), r, r + n);
  9787. };
  9788. engine.renderOffline (options);
  9789. const auto from = (std::size_t) 22050, to = (std::size_t) 44100;
  9790. if (right.size() < to)
  9791. {
  9792. report << c.name << ": rendered " << (int) right.size() << " samples FAILED\n";
  9793. ok = false;
  9794. continue;
  9795. }
  9796. const std::vector<float> l (left.begin() + (std::ptrdiff_t) from, left.begin() + (std::ptrdiff_t) to);
  9797. const std::vector<float> r (right.begin() + (std::ptrdiff_t) from, right.begin() + (std::ptrdiff_t) to);
  9798. const auto ref = 0.5 * (goertzel (l, 2500.0) + goertzel (r, 2500.0));
  9799. auto pass = ref > -60.0;
  9800. report << c.name << ": ref=" << juce::String (ref, 1);
  9801. for (int k = 0; k < 3; ++k)
  9802. for (int side = 0; side < 2; ++side)
  9803. {
  9804. const auto got = goertzel (side == 0 ? l : r, tones[k]) - ref;
  9805. const auto want = c.level[k][side];
  9806. const auto good = want == none ? got < -50.0 : std::abs (got - want) < 0.5;
  9807. pass = pass && good;
  9808. report << " " << (int) tones[k] << (side == 0 ? "L" : "R") << "=" << (got < -50.0 ? juce::String ("-") : juce::String (got, 1))
  9809. << (good ? "" : "(FL " + (want == none ? juce::String ("-") : juce::String (want, 1)) + ")");
  9810. }
  9811. report << (pass ? " OK" : " FAILED") << "\n";
  9812. ok = ok && pass;
  9813. }
  9814. return ok;
  9815. }
  9816. // LYNX.exe --wrappertest plugin.vst3 report.txt: builds a VST3 state the way FL's Fruity
  9817. // Wrapper stores it (REA_rodada5 §3.2), runs it through the import (adoptFlPlugins) and checks
  9818. // that the plugin comes back with the changed parameter.
  9819. void runWrapperTest (const juce::String& pluginPath, const juce::String& reportPath)
  9820. {
  9821. juce::String report;
  9822. bool ok = false;
  9823. {
  9824. lynx::AudioEngine offline (false);
  9825. auto& host = offline.getPluginHost();
  9826. host.addPluginFile (juce::File (pluginPath));
  9827. const juce::PluginDescription* vst3 = nullptr;
  9828. const auto types = host.getKnownPlugins().getTypes(); // copy: the pointer below points into it
  9829. for (const auto& type : types)
  9830. if (type.pluginFormatName == "VST3" && type.isInstrument)
  9831. vst3 = &type;
  9832. if (vst3 != nullptr)
  9833. {
  9834. juce::String error;
  9835. auto plugin = host.getFormats().createPluginInstance (*vst3, 48000.0, 512, error);
  9836. auto* parameter = plugin != nullptr && ! plugin->getParameters().isEmpty() ? plugin->getParameters()[0] : nullptr;
  9837. if (parameter != nullptr)
  9838. {
  9839. const auto target = parameter->getValue() > 0.5f ? 0.13f : 0.87f;
  9840. parameter->setValueNotifyingHost (target);
  9841. juce::MemoryBlock juceState;
  9842. plugin->getStateInformation (juceState);
  9843. report << "parameter=" << parameter->getName (64) << " target=" << target << "\n";
  9844. // JUCE state -> FL container: u32 1 + records 1 (flags), 3 (component), 2 (controller)
  9845. std::vector<std::uint8_t> flState;
  9846. auto put32 = [&] (std::uint32_t v) { for (int b = 0; b < 4; ++b) flState.push_back ((std::uint8_t) (v >> (8 * b))); };
  9847. auto record = [&] (std::uint32_t id, const juce::MemoryBlock& data) {
  9848. put32 (id);
  9849. put32 ((std::uint32_t) data.getSize());
  9850. put32 (0);
  9851. flState.insert (flState.end(), (const std::uint8_t*) data.getData(), (const std::uint8_t*) data.getData() + data.getSize());
  9852. };
  9853. put32 (1);
  9854. record (1, juce::MemoryBlock (64, true));
  9855. // record 4 (REA_rodada22 §2.3): slots 0/1 hold the ParamIDs of parameters 2 and 0, so FL's
  9856. // automations k = 0, 1, 2 mean positions 2, 0 and 1 (the first parameter without a slot)
  9857. juce::MemoryBlock slots;
  9858. const auto paramId = [&] (int i) {
  9859. const auto* hosted = dynamic_cast<const juce::HostedAudioProcessorParameter*> (plugin->getParameters()[i]);
  9860. return hosted != nullptr ? (std::uint32_t) hosted->getParameterID().getLargeIntValue() : 0u;
  9861. };
  9862. const bool reorder = plugin->getParameters().size() >= 3;
  9863. if (reorder)
  9864. {
  9865. for (auto v : { 2u, paramId (2), paramId (0) })
  9866. slots.append (&v, 4);
  9867. report << "slot_param_ids=" << (juce::int64) paramId (2) << "," << (juce::int64) paramId (0) << "\n";
  9868. }
  9869. if (auto xml = juce::AudioProcessor::getXmlFromBinary (juceState.getData(), (int) juceState.getSize()))
  9870. for (auto [tag, id] : { std::pair { "IComponent", 3u }, { "IEditController", 2u } })
  9871. if (auto* child = xml->getChildByName (tag))
  9872. {
  9873. juce::MemoryBlock data;
  9874. data.fromBase64Encoding (child->getAllSubText());
  9875. record (id, data);
  9876. report << tag << "_bytes=" << (int) data.getSize() << "\n";
  9877. }
  9878. if (reorder)
  9879. record (4, slots);
  9880. plugin.reset();
  9881. auto song = lynx::Song::makeDefault();
  9882. auto& f = song.channels[4].plugin.foreign;
  9883. f.format = lynx::ForeignPlugin::Format::vst3;
  9884. f.name = vst3->name.toStdString(); // no class ID: find it by name (fallback)
  9885. f.state = flState;
  9886. {
  9887. std::vector<std::uint8_t> comp, ctrl;
  9888. report << "split=" << (int) lynx::splitFlVst3State (flState, comp, ctrl) << " component=" << (int) comp.size()
  9889. << " saved_slots=" << (int) lynx::flVst3ParamSlots (flState).size() << "\n";
  9890. }
  9891. for (int k = 0; k < 3; ++k)
  9892. {
  9893. lynx::Automation a;
  9894. a.target = { lynx::AutomationTargetKind::channelParam, 4, 0, k };
  9895. song.automations.push_back (a);
  9896. }
  9897. const auto adopted = host.adoptFlPlugins (song);
  9898. report << "adopted=" << adopted << "\n";
  9899. juce::String mapped;
  9900. for (const auto& a : song.automations)
  9901. if (a.target.kind == lynx::AutomationTargetKind::channelParam && a.target.index == 4)
  9902. mapped << (mapped.isEmpty() ? "" : ",") << a.target.param;
  9903. report << "slot_positions=" << mapped << "\n";
  9904. const auto slotsOk = ! reorder || mapped == "2,0,1";
  9905. offline.setSong (song);
  9906. if (auto* loaded = dynamic_cast<lynx::PluginInstrument*> (offline.getChannelInstrument (4).get()))
  9907. {
  9908. const auto value = loaded->getInstance().getParameters()[0]->getValue();
  9909. report << "restored_value=" << value << "\n";
  9910. ok = adopted == 1 && std::abs (value - target) < 0.02f && slotsOk;
  9911. }
  9912. }
  9913. }
  9914. }
  9915. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  9916. juce::File (reportPath).replaceWithText (report);
  9917. setApplicationReturnValue (ok ? 0 : 1);
  9918. quit();
  9919. }
  9920. void runDemoSongs (const juce::String& folderPath)
  9921. {
  9922. const juce::File folder (folderPath);
  9923. folder.createDirectory();
  9924. bool ok = true;
  9925. for (int d = 1; d < lynx::demos::count; ++d)
  9926. {
  9927. juce::String error;
  9928. ok = lynx::ProjectFile::save (lynx::demos::make (d), folder.getChildFile (lynx::demos::fileName (d)), error) && ok;
  9929. }
  9930. setApplicationReturnValue (ok ? 0 : 1);
  9931. quit();
  9932. }
  9933. void runShowcase (const juce::String& outputPath, int currentPattern)
  9934. {
  9935. const auto song = lynx::makeShowcaseSong (currentPattern);
  9936. juce::String error;
  9937. const auto ok = lynx::ProjectFile::save (song, juce::File (outputPath), error);
  9938. setApplicationReturnValue (ok ? 0 : 1);
  9939. quit();
  9940. }
  9941. // LYNX.exe --sandboxtest plugin.vst3 report.txt: opens the instrument in a separate process, plays a
  9942. // note, changes a parameter, checks the state (back in an in-process plugin) and makes the child hang
  9943. // to check that LYNX keeps going (silence, without waiting longer than the timeout).
  9944. // --sandboxtest: plays an instrument (a note) or an effect (a 440 Hz tone through it); render() adds into l / r
  9945. struct TestVoice
  9946. {
  9947. explicit TestVoice (std::unique_ptr<juce::AudioPluginInstance> p)
  9948. {
  9949. if (p->acceptsMidi() && p->getTotalNumInputChannels() == 0)
  9950. instrument = std::make_unique<lynx::PluginInstrument> (std::move (p), 512);
  9951. else
  9952. effect = std::move (p);
  9953. }
  9954. void noteOn()
  9955. {
  9956. if (instrument != nullptr)
  9957. instrument->noteOn (60, 0.9f);
  9958. }
  9959. void render (float* l, float* r, int n, float gainLeft, float gainRight)
  9960. {
  9961. if (instrument != nullptr)
  9962. {
  9963. instrument->render (l, r, n, gainLeft, gainRight);
  9964. return;
  9965. }
  9966. const auto channels = juce::jmax (2, effect->getTotalNumInputChannels(), effect->getTotalNumOutputChannels());
  9967. juce::AudioBuffer<float> block (channels, 512);
  9968. juce::MidiBuffer midi;
  9969. for (int done = 0; done < n; done += 512)
  9970. {
  9971. const auto k = juce::jmin (512, n - done);
  9972. block.setSize (channels, k, false, false, true);
  9973. for (int i = 0; i < k; ++i)
  9974. {
  9975. const auto v = 0.25f * (float) std::sin (phase);
  9976. phase += 2.0 * juce::MathConstants<double>::pi * 440.0 / 48000.0;
  9977. for (int c = 0; c < channels; ++c)
  9978. block.setSample (c, i, v);
  9979. }
  9980. effect->processBlock (block, midi);
  9981. for (int i = 0; i < k; ++i)
  9982. {
  9983. l[done + i] += gainLeft * block.getSample (0, i);
  9984. r[done + i] += gainRight * block.getSample (1, i);
  9985. }
  9986. }
  9987. }
  9988. void release()
  9989. {
  9990. instrument.reset();
  9991. effect.reset();
  9992. }
  9993. std::unique_ptr<lynx::PluginInstrument> instrument;
  9994. std::unique_ptr<juce::AudioPluginInstance> effect;
  9995. double phase = 0.0;
  9996. };
  9997. void runSandboxTest (const juce::String& pluginPath, const juce::String& reportPath)
  9998. {
  9999. juce::String report;
  10000. bool ok = false;
  10001. lynx::setPluginSandboxAlerts (false);
  10002. const juce::File log (reportPath + ".log");
  10003. auto step = [&] (const char* what) { log.appendText (juce::String (what) + "\n"); };
  10004. log.deleteFile();
  10005. {
  10006. lynx::PluginHost host (false);
  10007. host.addPluginFile (juce::File (pluginPath));
  10008. const auto types = host.getKnownPlugins().getTypes(); // getTypes() returns a copy
  10009. // the file's instrument, else its first effect (round 161: effects too, e.g. a Windows effect through yabridge)
  10010. const juce::PluginDescription* instrument = nullptr;
  10011. for (const auto& type : types)
  10012. if (type.isInstrument)
  10013. instrument = &type;
  10014. for (const auto& type : types)
  10015. if (instrument == nullptr && ! type.isInstrument)
  10016. instrument = &type;
  10017. step ("host");
  10018. juce::String error;
  10019. auto remote = instrument != nullptr ? lynx::createSandboxedPlugin (*instrument, 48000.0, 512, {}, error) : nullptr;
  10020. report << "opened=" << (remote != nullptr ? 1 : 0) << " error=" << error << "\n";
  10021. step ("created");
  10022. if (remote != nullptr)
  10023. {
  10024. auto& proxy = *remote;
  10025. TestVoice voice (std::move (remote));
  10026. std::vector<float> l (48000), r (48000);
  10027. auto peakOf = [&] {
  10028. float peak = 0.0f;
  10029. for (std::size_t k = 0; k < l.size(); ++k)
  10030. peak = std::max ({ peak, std::abs (l[k]), std::abs (r[k]) });
  10031. return peak;
  10032. };
  10033. const auto start = juce::Time::getMillisecondCounterHiRes();
  10034. voice.noteOn();
  10035. voice.render (l.data(), r.data(), 48000, 1.0f, 1.0f);
  10036. const auto renderMs = juce::Time::getMillisecondCounterHiRes() - start;
  10037. const auto peak = peakOf();
  10038. step ("played");
  10039. if (juce::JUCEApplication::getCommandLineParameters().contains ("--expect-crash"))
  10040. {
  10041. // a plugin that crashes while playing (round 161 test plugin): LYNX notices, mutes it and keeps running
  10042. const auto dead = lynx::isSandboxedPluginDead (proxy);
  10043. std::fill (l.begin(), l.end(), 0.0f);
  10044. std::fill (r.begin(), r.end(), 0.0f);
  10045. voice.render (l.data(), r.data(), 4096, 1.0f, 1.0f);
  10046. report << "peak=" << peak << " render_1s_ms=" << renderMs << " dead=" << (dead ? 1 : 0) << " peak_after=" << peakOf() << "\n";
  10047. ok = dead && peak > 1e-4f && renderMs < 2000.0 && peakOf() == 0.0f;
  10048. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  10049. juce::File (reportPath).replaceWithText (report);
  10050. setApplicationReturnValue (ok ? 0 : 1);
  10051. quit();
  10052. return;
  10053. }
  10054. report << "plugin=" << proxy.getName() << (instrument->isInstrument ? " (instrument)" : " (effect)") << " parameters="
  10055. << proxy.getParameters().size() << " peak=" << peak << " render_1s_ms=" << renderMs << "\n";
  10056. if (juce::JUCEApplication::getCommandLineParameters().contains ("--editor") && proxy.hasEditor())
  10057. {
  10058. // the plugin's own window, opened by the child process (4 s on screen); the child must stay responsive
  10059. std::unique_ptr<juce::AudioProcessorEditor> editor (proxy.createEditorIfNeeded());
  10060. juce::Thread::sleep (4000);
  10061. juce::MemoryBlock state;
  10062. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  10063. proxy.getStateInformation (state);
  10064. report << "editor_shown=1 state_with_editor_ms=" << (juce::Time::getMillisecondCounterHiRes() - t0) << " dead=" << (lynx::isSandboxedPluginDead (proxy) ? 1 : 0) << "\n";
  10065. editor.reset();
  10066. }
  10067. // parameter -> state -> in-process plugin
  10068. bool stateOk = false;
  10069. if (! proxy.getParameters().isEmpty())
  10070. {
  10071. auto* p = proxy.getParameters()[0];
  10072. const auto target = p->getValue() > 0.5f ? 0.13f : 0.87f;
  10073. p->setValue (target);
  10074. std::fill (l.begin(), l.end(), 0.0f);
  10075. voice.render (l.data(), r.data(), 512, 1.0f, 1.0f); // carries the change to the child
  10076. juce::MemoryBlock state;
  10077. proxy.getStateInformation (state);
  10078. if (auto local = host.getFormats().createPluginInstance (*instrument, 48000.0, 512, error))
  10079. {
  10080. local->setStateInformation (state.getData(), (int) state.getSize());
  10081. const auto back = local->getParameters()[0]->getValue();
  10082. // the same steps without the sandbox: some plugins quantise the value or keep it out of their state
  10083. auto control = target;
  10084. if (auto a = host.getFormats().createPluginInstance (*instrument, 48000.0, 512, error))
  10085. {
  10086. a->enableAllBuses();
  10087. a->prepareToPlay (48000.0, 512);
  10088. a->getParameters()[0]->setValue (target);
  10089. juce::AudioBuffer<float> block (juce::jmax (2, a->getTotalNumInputChannels(), a->getTotalNumOutputChannels()), 512);
  10090. block.clear();
  10091. juce::MidiBuffer none;
  10092. a->processBlock (block, none);
  10093. juce::MemoryBlock direct;
  10094. a->getStateInformation (direct);
  10095. if (auto b = host.getFormats().createPluginInstance (*instrument, 48000.0, 512, error))
  10096. {
  10097. b->setStateInformation (direct.getData(), (int) direct.getSize());
  10098. control = b->getParameters()[0]->getValue();
  10099. }
  10100. a->releaseResources();
  10101. }
  10102. report << "state_bytes=" << (int) state.getSize() << " target=" << target << " in_process=" << back << " in_process_control=" << control << "\n";
  10103. stateOk = std::abs (back - control) < 0.02f;
  10104. }
  10105. }
  10106. step ("state");
  10107. // hung child: the block returns in ~0.5 s, muted, and the plugin is marked dead
  10108. lynx::hangSandboxedPluginForTest (proxy);
  10109. juce::Thread::sleep (200);
  10110. std::fill (l.begin(), l.end(), 1.0f);
  10111. std::fill (r.begin(), r.end(), 1.0f);
  10112. const auto hangStart = juce::Time::getMillisecondCounterHiRes();
  10113. voice.render (l.data(), r.data(), 4096, 0.0f, 0.0f);
  10114. std::fill (l.begin(), l.end(), 0.0f);
  10115. std::fill (r.begin(), r.end(), 0.0f);
  10116. voice.render (l.data(), r.data(), 4096, 1.0f, 1.0f);
  10117. const auto hangMs = juce::Time::getMillisecondCounterHiRes() - hangStart;
  10118. const auto dead = lynx::isSandboxedPluginDead (proxy);
  10119. const auto hangPeak = peakOf();
  10120. report << "hung_ms=" << hangMs << " dead=" << (dead ? 1 : 0) << " peak_after=" << hangPeak << "\n";
  10121. // crashed child (round 161): a second instance aborts; LYNX notices, mutes it and keeps running
  10122. bool crashOk = false;
  10123. if (auto second = lynx::createSandboxedPlugin (*instrument, 48000.0, 512, {}, error))
  10124. {
  10125. auto& proxy2 = *second;
  10126. TestVoice voice2 (std::move (second));
  10127. voice2.noteOn();
  10128. voice2.render (l.data(), r.data(), 512, 1.0f, 1.0f);
  10129. lynx::crashSandboxedPluginForTest (proxy2);
  10130. const auto crashStart = juce::Time::getMillisecondCounterHiRes();
  10131. while (! lynx::isSandboxedPluginDead (proxy2) && juce::Time::getMillisecondCounterHiRes() - crashStart < 5000.0)
  10132. {
  10133. voice2.render (l.data(), r.data(), 512, 1.0f, 1.0f);
  10134. juce::Thread::sleep (5);
  10135. }
  10136. const auto crashMs = juce::Time::getMillisecondCounterHiRes() - crashStart;
  10137. std::fill (l.begin(), l.end(), 0.0f);
  10138. std::fill (r.begin(), r.end(), 0.0f);
  10139. voice2.render (l.data(), r.data(), 4096, 1.0f, 1.0f);
  10140. const auto crashDead = lynx::isSandboxedPluginDead (proxy2);
  10141. report << "crash_ms=" << crashMs << " crash_dead=" << (crashDead ? 1 : 0) << " crash_peak_after=" << peakOf() << "\n";
  10142. crashOk = crashDead && crashMs < 3000.0;
  10143. // issue #159: freeing the crashed plugin doesn't wait on its pipe (JUCE waited up to 10 s there for
  10144. // the gone child, on the message thread when the rack freed it); its teardown ends on its own
  10145. const auto freeStart = juce::Time::getMillisecondCounterHiRes();
  10146. voice2.release();
  10147. const auto freeMs = juce::Time::getMillisecondCounterHiRes() - freeStart;
  10148. const auto endedAll = lynx::finishSandboxTeardowns (15000);
  10149. report << "crashed_free_ms=" << freeMs << " teardown_done=" << (endedAll ? 1 : 0) << "\n";
  10150. crashOk = crashOk && freeMs < 250.0 && endedAll;
  10151. }
  10152. step ("crash");
  10153. ok = peak > 1e-4f && stateOk && dead && hangMs < 1500.0 && hangPeak == 0.0f && crashOk;
  10154. }
  10155. }
  10156. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  10157. juce::File (reportPath).replaceWithText (report);
  10158. setApplicationReturnValue (ok ? 0 : 1);
  10159. quit();
  10160. }
  10161. // --timertest (round 174f): a view's polling timer follows the view and its parents, and survives a minimised window
  10162. void runTimerTest (const juce::File& report)
  10163. {
  10164. struct Ticks final : juce::Timer
  10165. {
  10166. void timerCallback() override {}
  10167. } timer;
  10168. juce::Component top, parent, view;
  10169. parent.addChildComponent (view);
  10170. top.addChildComponent (parent);
  10171. top.setSize (320, 200);
  10172. lynx::ui::TimerWhileShowing watch (view, timer, 30);
  10173. juce::String text;
  10174. auto failures = 0;
  10175. auto expect = [&] (const char* step, bool running) {
  10176. const auto ok = timer.isTimerRunning() == running;
  10177. failures += ok ? 0 : 1;
  10178. text << step << ": timer " << (timer.isTimerRunning() ? "running" : "stopped") << (ok ? "" : " FAIL") << "\n";
  10179. };
  10180. expect ("never shown", false);
  10181. view.setVisible (true);
  10182. parent.setVisible (true);
  10183. expect ("view and parent visible, not on the desktop", false);
  10184. top.addToDesktop (juce::ComponentPeer::windowHasTitleBar);
  10185. top.setVisible (true);
  10186. expect ("window shown", true);
  10187. parent.setVisible (false);
  10188. expect ("parent hidden", false);
  10189. parent.setVisible (true);
  10190. expect ("parent shown", true);
  10191. view.setVisible (false);
  10192. expect ("view hidden", false);
  10193. top.getPeer()->setMinimised (true);
  10194. view.setVisible (true);
  10195. expect ("view shown while minimised", true);
  10196. top.getPeer()->setMinimised (false);
  10197. expect ("window restored", true);
  10198. top.setVisible (false);
  10199. expect ("window hidden", false);
  10200. top.setVisible (true);
  10201. expect ("window shown again", true);
  10202. top.removeFromDesktop();
  10203. text << "failures: " << failures << "\nresult=" << (failures == 0 ? "OK" : "FAIL") << "\n";
  10204. report.replaceWithText (text);
  10205. setApplicationReturnValue (failures == 0 ? 0 : 1);
  10206. quit();
  10207. }
  10208. // --cachetest (round 174f): PlaylistComponent::cacheSelfTest on the project, the Playlist off screen at 1466 x 930
  10209. void runCacheTest (const juce::File& project, const juce::File& report)
  10210. {
  10211. engine = std::make_unique<lynx::AudioEngine>();
  10212. juce::String error;
  10213. auto ok = false;
  10214. if (project.hasFileExtension ("flp"))
  10215. ok = engine->importFlpFile (project, error);
  10216. else if (auto song = lynx::ProjectFile::load (project, error))
  10217. {
  10218. engine->setSong (std::move (*song));
  10219. ok = true;
  10220. }
  10221. juce::String text = "project: " + project.getFullPathName() + "\n";
  10222. if (ok)
  10223. {
  10224. auto playlist = std::make_unique<lynx::PlaylistComponent> (*engine);
  10225. playlist->setBounds (0, 0, 1466, 930);
  10226. playlist->setVisible (true);
  10227. text << playlist->cacheSelfTest ([] { lynx::ui::WaveformCache::getInstance()->waitUntilIdle (60000); }, report.getParentDirectory());
  10228. }
  10229. else
  10230. text << "result=ERROR " << error << "\n";
  10231. report.replaceWithText (text);
  10232. setApplicationReturnValue (ok && text.contains ("result=OK") ? 0 : 1);
  10233. quit();
  10234. }
  10235. // --picturetest (round 190bm): ui/PictureCheck.h on the Playlist and the Mixer, at a window's usual size, at a 4K
  10236. // screen's, and wider than a GPU bitmap can be (16384 px)
  10237. void runPictureTest (const juce::File& report, const juce::File& project)
  10238. {
  10239. engine = std::make_unique<lynx::AudioEngine>();
  10240. juce::String error, text;
  10241. if (project != juce::File())
  10242. {
  10243. auto ok = false;
  10244. if (project.hasFileExtension ("flp"))
  10245. ok = engine->importFlpFile (project, error);
  10246. else if (auto song = lynx::ProjectFile::load (project, error))
  10247. {
  10248. engine->setSong (std::move (*song));
  10249. ok = true;
  10250. }
  10251. text << "project: " << project.getFullPathName() << (ok ? "" : " (not loaded: " + error + ")") << "\n";
  10252. }
  10253. #if JUCE_WINDOWS
  10254. text << "native image: " << juce::NativeImageType().create (juce::Image::RGB, 8, 8, true)->createType()->getTypeID()
  10255. << " (software = " << juce::SoftwareImageType().getTypeID() << ")\n";
  10256. #endif
  10257. auto failures = 0;
  10258. struct Size
  10259. {
  10260. int width, height;
  10261. std::vector<float> scales;
  10262. };
  10263. const auto folder = report.getParentDirectory();
  10264. 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 } } })
  10265. {
  10266. const auto label = [&size] (const char* name) { return juce::String (name) + " " + juce::String (size.width) + " x " + juce::String (size.height); };
  10267. {
  10268. auto playlist = std::make_unique<lynx::PlaylistComponent> (*engine);
  10269. playlist->setBounds (0, 0, size.width, size.height);
  10270. playlist->setVisible (true);
  10271. {
  10272. juce::Image warm (juce::Image::RGB, 64, 64, true); // (one paint asks for the waveforms, then they are waited for)
  10273. juce::Graphics g (warm);
  10274. playlist->paintEntireComponent (g, true);
  10275. }
  10276. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (60000);
  10277. text << lynx::ui::picturecheck::run (*playlist, label ("Playlist"), size.scales, failures, folder);
  10278. }
  10279. {
  10280. auto mixer = std::make_unique<lynx::MixerComponent> (*engine);
  10281. mixer->setBounds (0, 0, size.width, juce::jmin (size.height, 700));
  10282. mixer->setVisible (true);
  10283. text << lynx::ui::picturecheck::run (*mixer, label ("Mixer"), size.scales, failures, folder);
  10284. }
  10285. }
  10286. text << "failures: " << failures << "\nresult=" << (failures == 0 ? "OK" : "FAIL") << "\n";
  10287. report.replaceWithText (text);
  10288. setApplicationReturnValue (failures == 0 ? 0 : 1);
  10289. quit();
  10290. }
  10291. // --uiperf (round 161): opens the project in the normal window, plays it, and drives the heavy UI cases of round 151
  10292. // through the window's own event path — the default layout, the Mixer maximised (meters while playing, then
  10293. // scrolled), the Playlist maximised (scroll down, scroll sideways, zoom in and out) and the Channel rack scrolled.
  10294. // Every frame is painted right after its event (ComponentPeer::performAnyPendingRepaintsNow) and timed; the report
  10295. // has, per case, the time to show it and the frames' mean / p95 / max, how many took longer than 16 ms, and the
  10296. // process CPU. The same on every OS, so Linux (X11, XWayland) and Windows numbers can be put side by side.
  10297. void runUiPerf (const juce::File& project, const juce::File& report)
  10298. {
  10299. if (const auto profile = juce::SystemStats::getEnvironmentVariable ("LYNX_PROFILE_MAIN", {}); profile.isNotEmpty())
  10300. lynx::crashguard::startMainProfiler (profile.toStdString()); // (stopped in shutdown)
  10301. startupOptions = lynx::StartupOptions::load();
  10302. engine = std::make_unique<lynx::AudioEngine>();
  10303. lynx::videoview::install (*engine); // (Fruity Video Player channels: their sound tracks)
  10304. crashEngine = engine.get();
  10305. createMainWindow();
  10306. mainWindow->reveal();
  10307. // LYNX_UIPERF_SIZE=WxH, LYNX_UIPERF_SCALE=<percent> (round 179a): a large window, a HiDPI desktop's scale
  10308. if (const auto scale = juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_SCALE", {}).getIntValue(); scale > 0)
  10309. juce::Desktop::getInstance().setGlobalScaleFactor ((float) scale / 100.0f);
  10310. if (const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_SIZE", {}), "x", ""); size.size() == 2)
  10311. mainWindow->setBounds (0, 0, size[0].getIntValue(), size[1].getIntValue());
  10312. juce::String error;
  10313. auto ok = false;
  10314. const auto loadStart = juce::Time::getMillisecondCounterHiRes();
  10315. if (project.hasFileExtension ("flp;als;flm")) // (round 190gr: a Live set, its Session clips in the grid)
  10316. ok = engine->importFlpFile (project, error);
  10317. else if (auto song = lynx::ProjectFile::load (project, error))
  10318. {
  10319. engine->setSong (std::move (*song));
  10320. ok = true;
  10321. }
  10322. const auto loadMs = juce::Time::getMillisecondCounterHiRes() - loadStart;
  10323. if (! ok)
  10324. {
  10325. report.replaceWithText ("project: " + project.getFullPathName() + "\nresult=ERROR " + error + "\n");
  10326. setApplicationReturnValue (1);
  10327. quit();
  10328. return;
  10329. }
  10330. // LYNX_UIPERF_MUTE=1: the Master fader down (the meters of the inserts still move): a run on a desktop someone uses
  10331. if (juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_MUTE", {}) == "1")
  10332. engine->editSong ([] (lynx::Song& s) { if (! s.mixer.empty()) s.mixer[0].volume = 0.0f; }, false);
  10333. struct Step
  10334. {
  10335. juce::String name;
  10336. std::function<void()> setup;
  10337. std::function<void (int)> action; // per frame; none: the step watches the window for `frames` ms
  10338. int frames;
  10339. std::function<juce::String()> finish = {}; // round 173f: after the step, its own lines for the report
  10340. };
  10341. struct UiPerf final : juce::Timer
  10342. {
  10343. LynxApplication& app;
  10344. juce::File report;
  10345. juce::String text;
  10346. std::vector<Step> steps;
  10347. std::size_t step = 0;
  10348. int frame = -1;
  10349. std::vector<double> times, rendered; // whole frames (event + paint + blit, when this timer paints) / the window's paints
  10350. std::vector<double> frames; // round 173f: the time of every frame the window painted (ui/FrameProbe.h)
  10351. double paintedPixels = 0.0; // round 190ge: the dirty area of those frames, summed (overdraw / repaint storms)
  10352. double setupMs = 0.0, wallStart = 0.0;
  10353. double cpuStart = 0.0; // process CPU seconds (std::clock is wall time on Windows)
  10354. double messageCpuStart = 0.0; // the message thread's CPU seconds
  10355. double audioLoadSum = 0.0; // the device's CPU use (AudioDeviceManager::getCpuUsage), summed per tick
  10356. int audioLoadTicks = 0;
  10357. UiPerf (LynxApplication& a, juce::File r) : app (a), report (std::move (r)) {}
  10358. juce::ComponentPeer* peer() const { return app.mainWindow != nullptr ? app.mainWindow->getPeer() : nullptr; }
  10359. double paintNow() const
  10360. {
  10361. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  10362. if (auto* p = peer())
  10363. p->performAnyPendingRepaintsNow();
  10364. return juce::Time::getMillisecondCounterHiRes() - t0;
  10365. }
  10366. void timerCallback() override
  10367. {
  10368. if (step >= steps.size())
  10369. {
  10370. stopTimer();
  10371. finish();
  10372. return;
  10373. }
  10374. auto& s = steps[step];
  10375. if (frame < 0)
  10376. {
  10377. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  10378. if (s.setup)
  10379. s.setup();
  10380. paintNow();
  10381. setupMs = juce::Time::getMillisecondCounterHiRes() - t0;
  10382. times.clear();
  10383. rendered.clear();
  10384. frames.clear();
  10385. paintedPixels = 0.0;
  10386. wallStart = juce::Time::getMillisecondCounterHiRes();
  10387. cpuStart = lynx::processCpuSeconds();
  10388. messageCpuStart = lynx::threadCpuSeconds();
  10389. audioLoadSum = 0.0;
  10390. audioLoadTicks = 0;
  10391. frame = 0;
  10392. return;
  10393. }
  10394. audioLoadSum += app.engine->getDeviceManager().getCpuUsage();
  10395. ++audioLoadTicks;
  10396. if (s.action)
  10397. s.action (frame);
  10398. if (const auto ms = paintNow(); ms > 0.25) // (nothing to paint: not a frame)
  10399. times.push_back (ms);
  10400. ++frame;
  10401. if (s.action ? frame < s.frames : juce::Time::getMillisecondCounterHiRes() - wallStart < (double) s.frames)
  10402. return;
  10403. const auto wall = juce::Time::getMillisecondCounterHiRes() - wallStart;
  10404. const auto cpu = 1000.0 * (lynx::processCpuSeconds() - cpuStart);
  10405. const auto messageCpu = 1000.0 * (lynx::threadCpuSeconds() - messageCpuStart);
  10406. text << s.name << ": show " << juce::String (setupMs, 1) << " ms\n"
  10407. << " painted frames: " << stats (rendered) << "\n"
  10408. << " timed here (event + paint + blit): " << stats (times)
  10409. << "\n window frames (probe): " << lynx::ui::FrameStats::of (frames, wall).describe()
  10410. << ", painted " << juce::String (wall > 0.0 ? paintedPixels / wall / 1000.0 : 0.0, 2) << " Mpx/s"
  10411. << "\n CPU " << juce::String (wall > 0.0 ? 100.0 * cpu / wall : 0.0, 0) << "% (process, " << juce::String (wall / 1000.0, 1) << " s), message thread "
  10412. << juce::String (wall > 0.0 ? 100.0 * messageCpu / wall : 0.0, 1) << "%, audio device "
  10413. << juce::String (audioLoadTicks > 0 ? 100.0 * audioLoadSum / audioLoadTicks : 0.0, 1) << "%\n";
  10414. if (s.finish)
  10415. text << s.finish();
  10416. juce::File (report).replaceWithText (text);
  10417. ++step;
  10418. frame = -1;
  10419. }
  10420. static juce::String stats (std::vector<double> sorted)
  10421. {
  10422. std::sort (sorted.begin(), sorted.end());
  10423. 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()))]; };
  10424. double sum = 0.0;
  10425. int over = 0;
  10426. for (auto t : sorted)
  10427. {
  10428. sum += t;
  10429. over += t > 16.0 ? 1 : 0;
  10430. }
  10431. return juce::String ((int) sorted.size()) + ", mean " + juce::String (sorted.empty() ? 0.0 : sum / (double) sorted.size(), 1)
  10432. + " ms, p95 " + juce::String (at (0.95), 1) + " ms, max " + juce::String (sorted.empty() ? 0.0 : sorted.back(), 1)
  10433. + " ms, >16 ms " + juce::String (over);
  10434. }
  10435. void finish()
  10436. {
  10437. // the cost of asking where the mouse is (X11: a round trip to the display server)
  10438. const auto q0 = juce::Time::getMillisecondCounterHiRes();
  10439. for (int i = 0; i < 100; ++i)
  10440. juce::ignoreUnused (juce::Desktop::getInstance().getMainMouseSource().getScreenPosition());
  10441. text << "mouse position query: " << juce::String ((juce::Time::getMillisecondCounterHiRes() - q0) / 100.0, 3) << " ms\n";
  10442. app.mainWindow->onFrame = nullptr;
  10443. app.mainWindow->watchFrames ({});
  10444. app.engine->stop();
  10445. text << "result=OK\n";
  10446. report.replaceWithText (text);
  10447. app.setApplicationReturnValue (0);
  10448. app.quit();
  10449. }
  10450. };
  10451. auto* ui = &mainWindow->getContent();
  10452. auto wheelAt = [this] (juce::Component& target, float dx, float dy, juce::ModifierKeys mods) {
  10453. auto* peer = mainWindow->getPeer();
  10454. if (peer == nullptr || ! target.isShowing())
  10455. return;
  10456. juce::ModifierKeys::currentModifiers = mods;
  10457. const auto local = peer->globalToLocal (target.localPointToGlobal (target.getLocalBounds().getCentre()).toFloat());
  10458. juce::MouseWheelDetails wheel { dx, dy, false, false, false };
  10459. peer->handleMouseWheel (juce::MouseInputSource::InputSourceType::mouse, local, juce::Time::currentTimeMillis(), wheel);
  10460. juce::ModifierKeys::currentModifiers = {};
  10461. };
  10462. auto run = std::make_unique<UiPerf> (*this, report);
  10463. mainWindow->onFrame = [r = run.get()] (double ms) { if (r->frame >= 0) r->rendered.push_back (ms); };
  10464. // round 173f: every frame the window paints; a fader drag's moves count as shown when a frame covers the fader
  10465. auto drag = std::make_shared<UiPerfDrag>();
  10466. mainWindow->watchFrames ([r = run.get(), drag] (double now, juce::Rectangle<int> area) {
  10467. if (r->frame >= 0)
  10468. {
  10469. r->frames.push_back (now);
  10470. r->paintedPixels += (double) area.getWidth() * (double) area.getHeight();
  10471. }
  10472. drag->framePainted (now, area);
  10473. });
  10474. run->text << "project: " << project.getFullPathName() << "\n"
  10475. << "LYNX " << getApplicationVersion() << ", " << juce::SystemStats::getOperatingSystemName() << ", "
  10476. << juce::SystemStats::getCpuModel() << ", window " << mainWindow->getWidth() << "x" << mainWindow->getHeight()
  10477. << ", scale " << juce::String (juce::Desktop::getInstance().getDisplays().getPrimaryDisplay() != nullptr
  10478. ? juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->scale : 1.0, 2)
  10479. << ", audio device " << (engine->getDeviceManager().getCurrentAudioDevice() != nullptr ? engine->getDeviceManager().getCurrentAudioDevice()->getName() : juce::String ("none")) << "\n"
  10480. << "load " << juce::String (loadMs / 1000.0, 2) << " s\n";
  10481. const auto none = juce::ModifierKeys();
  10482. // discussion #10 (round 173f): the reporter's screen — the Channel Rack and the Mixer open, the pattern playing —
  10483. // watched as it is, then insert 3's fader dragged up and down with the mouse (125 moves a second through the
  10484. // window's own mouse path, the frames painted as the window paints them)
  10485. const auto dragTrack = engine->getSong().mixer.size() > 3 ? 3 : 1;
  10486. run->steps.push_back ({ "rack + mixer, pattern playing", [this, ui] {
  10487. ui->showPanelsForSnapshot ({ lynx::workspace::Panel::channelRack, lynx::workspace::Panel::mixer });
  10488. engine->getTransport().songMode = false;
  10489. engine->rewind();
  10490. engine->play();
  10491. }, {}, 4000 });
  10492. run->steps.push_back ({ "fader drag by mouse, rack + mixer, pattern playing", [this, ui, drag, dragTrack] {
  10493. auto& strips = ui->getMixerForSnapshot().getStripsForSnapshot();
  10494. const auto rail = strips.faderRailForSnapshot (dragTrack);
  10495. drag->start (*mainWindow, strips, rail, engine.get(), dragTrack);
  10496. }, {}, 3000, [drag] { return drag->stop(); } });
  10497. run->steps.push_back ({ "song stopped during the drag", {}, {}, 500, [drag] { return drag->release(); } });
  10498. run->steps.push_back ({ "after the drag (released)", {}, {}, 600, [drag] { return drag->released(); } });
  10499. run->steps.push_back ({ "desktop, playing", [this, ui] { ui->showDesktopForSnapshot (false); engine->rewind(); engine->play(); }, {}, 3000 });
  10500. run->steps.push_back ({ "mixer maximised, playing", [ui] { ui->selectTabForSnapshot (3); }, {}, 3000 });
  10501. // round 177a: only the meters move, so the strips' picture must stay valid, also with a folded group's tab and VCA
  10502. // strips on screen (their levels are drawn over the picture, like the inserts' meters)
  10503. run->steps.push_back ({ "mixer meters over the picture, playing", [this, ui] {
  10504. ui->selectTabForSnapshot (3);
  10505. engine->getTransport().songMode = false;
  10506. engine->rewind();
  10507. engine->play();
  10508. ui->getMixerForSnapshot().getStripsForSnapshot().cacheCountersForPerf();
  10509. }, {}, 6000, [this, ui, report] {
  10510. const auto [spoiled, refills] = ui->getMixerForSnapshot().getStripsForSnapshot().cacheCountersForPerf();
  10511. if (juce::FileOutputStream out (report.withFileExtension ("png")); out.openedOk())
  10512. {
  10513. out.setPosition (0);
  10514. out.truncate();
  10515. juce::PNGImageFormat().writeImageToStream (mainWindow->createComponentSnapshot (mainWindow->getLocalBounds()), out);
  10516. }
  10517. return juce::String (" mixer picture: spoiled ") + juce::String (spoiled) + " times, drawn again " + juce::String (refills) + " times\n";
  10518. } });
  10519. run->steps.push_back ({ "mixer scroll", {}, [wheelAt, ui, none] (int f) { wheelAt (ui->getMixerForSnapshot(), 0.0f, f < 30 ? -0.25f : 0.25f, none); }, 60 });
  10520. // a fader dragged while the song plays (round 171c, discussion #10): 4 mouse moves per frame on insert 1's fader,
  10521. // through the old path (a whole snapshot per move) and through editLevels
  10522. auto faderMove = [this] (bool levels, int f) {
  10523. for (int k = 0; k < 4; ++k)
  10524. {
  10525. const auto v = 0.5f + 0.3f * std::sin ((float) (f * 4 + k) * 0.05f);
  10526. const auto edit = [v] (lynx::Song& s) { if (s.mixer.size() > 1) s.mixer[1].volume = v; };
  10527. if (levels)
  10528. engine->editLevels (edit, false); // (no undo step: in a real drag only the press saves one)
  10529. else
  10530. engine->editSong (edit, false);
  10531. }
  10532. };
  10533. run->steps.push_back ({ "mixer fader drag, playing, rebuild per move (before 171c)", {}, [faderMove] (int f) { faderMove (false, f); }, 60 });
  10534. run->steps.push_back ({ "mixer fader drag, playing, live levels (171c)", {}, [faderMove, this] (int f) { faderMove (true, f); if (f == 59) engine->flushLevels(); }, 60 });
  10535. // F8's Plugin picker (round 171c): opening it (the "show" time = building it + its first paint), its pictures
  10536. // loading while it stays open, pointing at the tiles, then closing it
  10537. run->steps.push_back ({ "plugin picker open (F8)", [ui] { ui->togglePluginPickerForSnapshot(); }, {}, 2500 });
  10538. run->steps.push_back ({ "plugin picker, pointing at tiles", {}, [ui] (int f) {
  10539. // (round 175b: the picker is its own window)
  10540. if (auto* picker = ui->pluginPickerForSnapshot(); picker != nullptr && picker->getPeer() != nullptr)
  10541. {
  10542. const auto p = picker->localPointToGlobal (juce::Point<int> (60 + (f * 37) % juce::jmax (1, picker->getWidth() - 120),
  10543. 90 + (f * 53) % juce::jmax (1, picker->getHeight() - 200)));
  10544. const auto local = picker->getPeer()->globalToLocal (p.toFloat());
  10545. picker->getPeer()->handleMouseEvent (juce::MouseInputSource::InputSourceType::mouse, local, {}, 0.0f, 0.0f,
  10546. juce::Time::currentTimeMillis());
  10547. }
  10548. }, 60 });
  10549. run->steps.push_back ({ "plugin picker close", [ui] { ui->togglePluginPickerForSnapshot(); }, {}, 300 });
  10550. run->steps.push_back ({ "playlist maximised, playing", [ui] { ui->selectTabForSnapshot (2); }, {}, 3000 });
  10551. run->steps.push_back ({ "playlist scroll down/up", [this] { engine->stop(); },
  10552. [wheelAt, ui, none] (int f) { wheelAt (ui->getPlaylistForSnapshot(), 0.0f, f < 40 ? -0.15f : 0.15f, none); }, 80 });
  10553. run->steps.push_back ({ "playlist scroll sideways", {},
  10554. [wheelAt, ui, none] (int f) { wheelAt (ui->getPlaylistForSnapshot(), f < 40 ? -0.15f : 0.15f, 0.0f, none); }, 80 });
  10555. // round 174f: Ctrl+wheel zoom, a notch every third frame (~20 a second), three in then three out, as dupmon drives it
  10556. run->steps.push_back ({ "playlist zoom (Ctrl+wheel)", {},
  10557. [wheelAt, ui] (int f) {
  10558. if (f % 3 == 0)
  10559. wheelAt (ui->getPlaylistForSnapshot(), 0.0f, (f / 9) % 2 == 0 ? 0.15f : -0.15f, juce::ModifierKeys (juce::ModifierKeys::ctrlModifier));
  10560. }, 120 });
  10561. run->steps.push_back ({ "playlist after the zoom (settles)", {}, {}, 500 });
  10562. run->steps.push_back ({ "whole window repainted", {}, [this] (int) { mainWindow->repaint(); }, 40 });
  10563. run->steps.push_back ({ "channel rack scroll", [ui] { ui->selectTabForSnapshot (0); },
  10564. [wheelAt, ui, none] (int f) { wheelAt (ui->getRackViewportForSnapshot(), 0.0f, f < 30 ? -0.25f : 0.25f, none); }, 60 });
  10565. // round 190ge: the other main views while the pattern plays, then every view with the transport stopped and
  10566. // nothing moving (an idle view should paint nothing: its frames and painted area are the repaint storms), then
  10567. // the Clip-launch grid playing
  10568. auto playPattern = [this] {
  10569. engine->getTransport().songMode = false;
  10570. engine->rewind();
  10571. engine->play();
  10572. };
  10573. run->steps.push_back ({ "piano roll maximised, pattern playing", [ui, playPattern] { ui->selectTabForSnapshot (1); playPattern(); }, {}, 3000 });
  10574. run->steps.push_back ({ "channel rack maximised, pattern playing", [ui, playPattern] { ui->selectTabForSnapshot (0); playPattern(); }, {}, 3000 });
  10575. const char* idleViews[] { "channel rack", "piano roll", "playlist", "mixer" };
  10576. for (int view = 0; view < 4; ++view)
  10577. run->steps.push_back ({ juce::String ("idle: ") + idleViews[view] + ", stopped", [this, ui, view] { engine->stop(); ui->selectTabForSnapshot (view); }, {}, 3000 });
  10578. run->steps.push_back ({ "idle: desktop, stopped", [this, ui] { engine->stop(); ui->showDesktopForSnapshot (false); }, {}, 3000 });
  10579. run->steps.push_back ({ "clip grid, song playing", [this, ui] {
  10580. ui->selectTabForSnapshot (2);
  10581. ui->setClipLaunchWorkflow (true);
  10582. ui->setClipGridView (lynx::PlaylistArea::GridView::grid);
  10583. engine->getTransport().songMode = true;
  10584. engine->rewind();
  10585. engine->play();
  10586. }, {}, 3000 });
  10587. // round 190gr: the grid's clips launched (every scene that has clips, one after the other: the playing cells'
  10588. // progress bars move, the launches blink until their grid point)
  10589. run->steps.push_back ({ "clip grid, clips launched", [this] {
  10590. engine->getTransport().songMode = true;
  10591. if (const auto& grid = engine->getSong().clipGrid)
  10592. for (int scene = 0; scene < juce::jmin (8, (int) grid->scenes.size()); ++scene)
  10593. engine->launcherCommand ({ lynx::launcher::Command::Type::launchScene, 0, scene });
  10594. }, {}, 3000, [this] {
  10595. int playing = 0;
  10596. if (const auto* state = engine->launcherState())
  10597. for (const auto& t : state->tracks)
  10598. playing += t.playing.load() >= 0 ? 1 : 0;
  10599. engine->launcherCommand ({ lynx::launcher::Command::Type::stopAll });
  10600. return " tracks playing a clip: " + juce::String (playing) + "\n";
  10601. } });
  10602. run->steps.push_back ({ "idle: clip grid, stopped", [this] { engine->stop(); }, {}, 3000, [ui] { ui->setClipLaunchWorkflow (false); return juce::String(); } });
  10603. // LYNX_UIPERF_ONLY=text: only the steps whose name has that text
  10604. if (const auto only = juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_ONLY", {}); only.isNotEmpty())
  10605. 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());
  10606. // let the window draw the project first
  10607. perf = std::move (run);
  10608. juce::Timer::callAfterDelay (1500, [this] { if (perf != nullptr) perf->startTimer (16); });
  10609. }
  10610. // --rtstress: opens the project in the normal window with the saved audio device, plays it from the start for
  10611. // `seconds` and writes the real-time statistics (deadline misses, late device calls, load histogram, heaviest units)
  10612. // --rtstress --backuptest N (round 177d): while the project plays, a device's MIDI clock (10/s) and active sensing
  10613. // (3/s) arrive, and the project counts as changed. N > 0 also forces a backup every N seconds on top of the timed ones.
  10614. // The report tells how many backups were written, when, and what the MIDI counters did.
  10615. struct BackupTest final : juce::Timer
  10616. {
  10617. lynx::AudioEngine* engine = nullptr;
  10618. lynx::MainComponent* ui = nullptr;
  10619. double everyMs = 0.0, startMs = 0.0, lastForcedMs = 0.0, longestCallMs = 0.0;
  10620. int ticks = 0, forced = 0;
  10621. std::uint64_t seenOver = 0, seenNear = 0;
  10622. juce::String misses; // each callback over (or near) its deadline: how long after the last forced backup
  10623. void timerCallback() override
  10624. {
  10625. engine->injectMidiInput (juce::MidiMessage (0xf8));
  10626. if (++ticks % 3 == 0)
  10627. engine->injectMidiInput (juce::MidiMessage (0xfe));
  10628. const auto now = juce::Time::getMillisecondCounterHiRes();
  10629. const auto s = engine->getRtStats().snapshot();
  10630. if (s.overBudget != seenOver || s.nearBudget != seenNear)
  10631. {
  10632. misses << " +" << juce::String ((now - lastForcedMs) / 1000.0, 1) << " s after the last forced backup (or the start): over +"
  10633. << (juce::int64) (s.overBudget - seenOver) << ", near +" << (juce::int64) (s.nearBudget - seenNear) << "\n";
  10634. seenOver = s.overBudget;
  10635. seenNear = s.nearBudget;
  10636. }
  10637. if (everyMs > 0.0 && now - lastForcedMs >= everyMs)
  10638. {
  10639. lastForcedMs = now;
  10640. ++forced;
  10641. ui->backupNowForTest();
  10642. longestCallMs = juce::jmax (longestCallMs, juce::Time::getMillisecondCounterHiRes() - now);
  10643. }
  10644. }
  10645. };
  10646. std::unique_ptr<BackupTest> backupTest;
  10647. void startBackupTest()
  10648. {
  10649. const auto& cli = juce::JUCEApplication::getCommandLineParameterArray();
  10650. const auto at = cli.indexOf ("--backuptest");
  10651. auto* ui = mainWindow != nullptr ? dynamic_cast<lynx::MainComponent*> (mainWindow->getContentComponent()) : nullptr;
  10652. if (at < 0 || ui == nullptr)
  10653. return;
  10654. backupTest = std::make_unique<BackupTest>();
  10655. backupTest->engine = engine.get();
  10656. backupTest->ui = ui;
  10657. backupTest->everyMs = cli[at + 1].getDoubleValue() * 1000.0;
  10658. backupTest->startMs = backupTest->lastForcedMs = juce::Time::getMillisecondCounterHiRes();
  10659. // (the project counts as changed, so a backup has something to write; the Master's fader is down, so a long run
  10660. // makes no sound: everything else is processed as usual)
  10661. engine->editSong ([] (lynx::Song& s) {
  10662. if (! s.mixer.empty())
  10663. s.mixer[0].volume = 0.0f;
  10664. });
  10665. backupTest->startTimer (100);
  10666. }
  10667. juce::String finishBackupTest()
  10668. {
  10669. if (backupTest == nullptr)
  10670. return {};
  10671. backupTest->stopTimer();
  10672. juce::String text;
  10673. const auto played = engine->getMidiPlayed();
  10674. text << " backup test: MIDI light count " << (int) engine->getMidiActivity() << ", played count " << (int) played << " (clock and active sensing only)\n";
  10675. text << " backup test: " << backupTest->forced << " forced, longest forced call on the message thread "
  10676. << juce::String (backupTest->longestCallMs, 1) << " ms\n";
  10677. if (backupTest->misses.isNotEmpty())
  10678. text << " backup test: callbacks over or near the deadline (seen within 100 ms):\n" << backupTest->misses;
  10679. auto files = lynx::autosaveFolder().findChildFiles (juce::File::findFiles, false, "*.lynx");
  10680. text << " backup test: " << files.size() << " file(s) in the backup folder:\n";
  10681. for (const auto& f : files)
  10682. text << " " << juce::String ((f.getLastModificationTime().toMilliseconds() - juce::Time::getCurrentTime().toMilliseconds()) / 1000) << " s before the end: "
  10683. << f.getFileName() << " (" << f.getSize() << " bytes)\n";
  10684. engine->injectMidiInput (juce::MidiMessage::noteOn (1, 60, (juce::uint8) 1));
  10685. engine->injectMidiInput (juce::MidiMessage::noteOff (1, 60));
  10686. text << " backup test: after a played note, played count " << (int) engine->getMidiPlayed() << "\n";
  10687. backupTest.reset();
  10688. return text;
  10689. }
  10690. void runRealtimeStress (const juce::File& project, const juce::File& report, double seconds, int bufferSize,
  10691. const juce::String& deviceType, const juce::String& deviceName, const juce::String& recordTo = {})
  10692. {
  10693. startupOptions = lynx::StartupOptions::load();
  10694. engine = std::make_unique<lynx::AudioEngine>();
  10695. lynx::videoview::install (*engine); // (Fruity Video Player channels: their sound tracks)
  10696. crashEngine = engine.get();
  10697. // the user's saved device stays as it was: this run's choices are undone before quitting
  10698. savedDeviceState = engine->getDeviceManager().createStateXml();
  10699. auto& devices = engine->getDeviceManager();
  10700. const auto driverFile = addDriverFileDeviceType();
  10701. const auto type = deviceType.isEmpty() && driverFile ? juce::String (lynx::dllAsioTypeName) : deviceType;
  10702. if (type.isNotEmpty() && devices.getCurrentAudioDeviceType() != type)
  10703. devices.setCurrentAudioDeviceType (type, true);
  10704. if (bufferSize > 0 || deviceName.isNotEmpty())
  10705. {
  10706. auto setup = devices.getAudioDeviceSetup();
  10707. if (bufferSize > 0)
  10708. setup.bufferSize = bufferSize;
  10709. if (deviceName.isNotEmpty())
  10710. setup.outputDeviceName = deviceName;
  10711. const auto error = devices.setAudioDeviceSetup (setup, true);
  10712. if (error.isNotEmpty())
  10713. report.replaceWithText ("device error: " + error + "\n");
  10714. }
  10715. createMainWindow();
  10716. if (! juce::JUCEApplication::getCommandLineParameters().contains ("--no-window")) // --no-window: is it the UI?
  10717. mainWindow->reveal();
  10718. juce::String error;
  10719. auto ok = false;
  10720. const auto loadStart = juce::Time::getMillisecondCounterHiRes();
  10721. if (project.hasFileExtension ("flp"))
  10722. ok = engine->importFlpFile (project, error);
  10723. else if (auto song = lynx::ProjectFile::load (project, error))
  10724. {
  10725. engine->setSong (std::move (*song));
  10726. ok = true;
  10727. }
  10728. const auto loadMs = juce::Time::getMillisecondCounterHiRes() - loadStart;
  10729. if (! ok)
  10730. {
  10731. report.replaceWithText ("project: " + project.getFullPathName() + "\nresult=ERROR " + error + "\n");
  10732. restoreSavedDeviceState();
  10733. setApplicationReturnValue (1);
  10734. quit();
  10735. return;
  10736. }
  10737. if (recordTo.isNotEmpty())
  10738. engine->setAudioRecordingArmed (true); // opens the input of the driver
  10739. // let the window draw the project, then play from the start with fresh statistics
  10740. juce::Timer::callAfterDelay (1500, [this, project, report, seconds, loadMs, recordTo] {
  10741. if (engine == nullptr)
  10742. return;
  10743. engine->stop();
  10744. engine->rewind();
  10745. engine->getRtStats().reset();
  10746. engine->takeUiPulse();
  10747. if (recordTo.isNotEmpty())
  10748. engine->setRecording (true);
  10749. // --log folder: the audio logger records what the Master plays during the run (realtime vs export checks)
  10750. const auto& cli = juce::JUCEApplication::getCommandLineParameterArray();
  10751. if (const auto at = cli.indexOf ("--log"); at >= 0 && at + 1 < cli.size())
  10752. engine->getAudioLogger().start (juce::File (cli[at + 1].unquoted()), engine->getDeviceManager().getCurrentAudioDevice() != nullptr
  10753. ? engine->getDeviceManager().getCurrentAudioDevice()->getCurrentSampleRate() : 44100.0);
  10754. engine->play();
  10755. startBackupTest();
  10756. juce::Timer::callAfterDelay ((int) (seconds * 1000.0), [this, project, report, seconds, loadMs, recordTo] {
  10757. if (engine == nullptr)
  10758. return;
  10759. const auto backupReport = finishBackupTest();
  10760. engine->stop();
  10761. juce::String recording;
  10762. if (engine->getAudioLogger().isLogging())
  10763. {
  10764. recording << " logged: " << engine->getAudioLogger().currentFile().getFullPathName() << "\n";
  10765. engine->getAudioLogger().stop();
  10766. }
  10767. if (recordTo.isNotEmpty())
  10768. recording = finishStressTake (juce::File (recordTo), seconds);
  10769. const auto& cli = juce::JUCEApplication::getCommandLineParameterArray();
  10770. const auto s = engine->getRtStats().snapshot();
  10771. juce::String text;
  10772. text << "project: " << project.getFullPathName() << "\n"
  10773. << "LYNX " << getApplicationVersion() << ", " << juce::SystemStats::getOperatingSystemName() << ", "
  10774. << juce::SystemStats::getNumCpus() << " logical CPUs (" << juce::SystemStats::getNumPhysicalCpus() << " cores), "
  10775. << juce::SystemStats::getCpuModel() << "\n"
  10776. << "load " << juce::String (loadMs / 1000.0, 1) << " s, played " << juce::String (seconds, 0) << " s\n"
  10777. << engine->describeRealtime();
  10778. const auto pulse = engine->takeUiPulse();
  10779. text << " UI: the 30 Hz engine timer ran " << pulse.calls << " times (" << juce::String (pulse.calls / seconds, 1)
  10780. << "/s), longest gap " << juce::String (pulse.maxGapMs, 0) << " ms" << (mainWindow == nullptr || ! mainWindow->isVisible() ? " (window hidden)" : "") << "\n";
  10781. text << " load histogram (share of the deadline: callbacks):";
  10782. for (std::size_t b = 0; b < s.histogram.size(); ++b)
  10783. if (s.histogram[b] > 0)
  10784. text << " " << (int) (b * 10) << (b + 1 == s.histogram.size() ? juce::String ("+") : "-" + juce::String ((int) (b * 10 + 10))) << "%:" << (juce::int64) s.histogram[b];
  10785. text << "\n";
  10786. text << recording << backupReport;
  10787. // --settingsshot file.png (round 161): Options > Audio settings of this run's device, as a picture
  10788. if (const auto at = cli.indexOf ("--settingsshot"); at >= 0 && at + 1 < cli.size())
  10789. {
  10790. auto page = lynx::makeSettingsPanel (*engine, lynx::SettingsPage::audio);
  10791. juce::Image image (juce::Image::ARGB, page->getWidth(), page->getHeight(), true);
  10792. {
  10793. juce::Graphics g (image);
  10794. g.fillAll (lynx::theme::panel);
  10795. page->paintEntireComponent (g, false);
  10796. }
  10797. const juce::File shot (cli[at + 1].unquoted());
  10798. shot.deleteFile();
  10799. if (auto out = shot.createOutputStream())
  10800. juce::PNGImageFormat().writeImageToStream (image, *out);
  10801. }
  10802. text << "result=" << (s.callbacks == 0 ? "ERROR no audio callbacks" : s.overBudget == 0 && s.lateCalls == 0 ? "OK" : "GLITCHES") << "\n";
  10803. report.replaceWithText (text);
  10804. restoreSavedDeviceState();
  10805. setApplicationReturnValue (s.callbacks == 0 ? 1 : 0);
  10806. quit();
  10807. });
  10808. });
  10809. }
  10810. // --bendrectest (round 167a): see the command line above
  10811. void runBendRecordTest (const juce::File& report, bool songMode)
  10812. {
  10813. engine = std::make_unique<lynx::AudioEngine>();
  10814. auto text = std::make_shared<juce::String>();
  10815. auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
  10816. auto finish = [this] (int code) {
  10817. setApplicationReturnValue (code);
  10818. quit();
  10819. };
  10820. auto* device = engine->getDeviceManager().getCurrentAudioDevice();
  10821. if (device == nullptr)
  10822. {
  10823. step ("result=ERROR no audio device");
  10824. finish (1);
  10825. return;
  10826. }
  10827. step ("device=" + device->getTypeName() + " | " + device->getName() + " | mode " + (songMode ? "song" : "pattern"));
  10828. auto song = lynx::Song::makeDefault();
  10829. song.bpm = 120.0;
  10830. song.mode = songMode ? lynx::PlayMode::song : lynx::PlayMode::pattern;
  10831. engine->setSong (std::move (song));
  10832. auto o = engine->getRecordOptions();
  10833. o.mode = lynx::RecordMode::overdub;
  10834. o.recordNotes = true;
  10835. o.recordAutomation = true;
  10836. o.countInBars = 0;
  10837. o.waitForInput = false;
  10838. o.quantiseAutomation = false;
  10839. o.punchLoopRegion = false;
  10840. o.preRollBars = o.postRollBars = 0;
  10841. engine->setRecordOptions (o);
  10842. engine->stop();
  10843. engine->rewind();
  10844. engine->setRecording (true);
  10845. engine->startPlayback();
  10846. // 2 s of wheel at ~100 messages a second: 0 → +1 (0.5 s), +1 → −1 (1 s), −1 → 0 (0.5 s)
  10847. auto sent = std::make_shared<std::vector<std::pair<double, float>>>();
  10848. auto t0 = std::make_shared<double> (juce::Time::getMillisecondCounterHiRes());
  10849. engine->injectMidiInput (juce::MidiMessage::noteOn (1, 60, (juce::uint8) 100));
  10850. auto tick = std::make_shared<std::function<void()>>();
  10851. *tick = [this, sent, t0, tick, step, finish, songMode] {
  10852. if (engine == nullptr)
  10853. return;
  10854. const auto ms = juce::Time::getMillisecondCounterHiRes() - *t0;
  10855. if (ms < 2000.0)
  10856. {
  10857. const auto x = ms / 1000.0;
  10858. 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);
  10859. const auto wheel = juce::jlimit (0, 16383, 8192 + juce::roundToInt (v * 8191.0f));
  10860. engine->injectMidiInput (juce::MidiMessage::pitchWheel (1, wheel));
  10861. sent->push_back ({ ms, (float) (wheel - 8192) / 8192.0f });
  10862. juce::Timer::callAfterDelay (10, *tick);
  10863. return;
  10864. }
  10865. engine->injectMidiInput (juce::MidiMessage::pitchWheel (1, 8192));
  10866. engine->injectMidiInput (juce::MidiMessage::noteOff (1, 60));
  10867. juce::Timer::callAfterDelay (400, [this, sent, step, finish, songMode] {
  10868. if (engine == nullptr)
  10869. return;
  10870. engine->stop();
  10871. juce::Timer::callAfterDelay (600, [this, sent, step, finish, songMode] {
  10872. if (engine == nullptr)
  10873. return;
  10874. engine->setRecording (false);
  10875. const auto& s = engine->getSong();
  10876. // the channel's pitch bend (MIDI channel 1), recorded as a lane or a clip
  10877. std::vector<std::pair<std::int64_t, float>> got;
  10878. juce::String where = "nothing";
  10879. for (const auto& a : s.automations)
  10880. if (a.target.kind == lynx::AutomationTargetKind::channelParam && lynx::midictl::isPitchBend (a.target.param))
  10881. {
  10882. where = "automation clip \"" + juce::String (a.name) + "\"";
  10883. for (const auto& pt : a.points)
  10884. got.push_back ({ pt.tick, pt.value });
  10885. }
  10886. for (const auto& p : s.patterns)
  10887. for (const auto& lane : p.events)
  10888. if (lane.target.kind == lynx::AutomationTargetKind::channelParam && lynx::midictl::isPitchBend (lane.target.param))
  10889. {
  10890. where = "pattern \"" + juce::String (p.name) + "\" event lane";
  10891. for (const auto& e : lane.events)
  10892. got.push_back ({ e.tick, e.value });
  10893. }
  10894. int notes = 0;
  10895. for (const auto& p : s.patterns)
  10896. notes += (int) p.notes.size();
  10897. float lo = 1.0f, hi = 0.0f;
  10898. for (const auto& [t, v] : got)
  10899. lo = std::min (lo, v), hi = std::max (hi, v);
  10900. // ticks: in order, spread over the ~2 s sweep (8 beats of 96 ticks at 120 bpm ≈ 4 beats)
  10901. const auto span = got.empty() ? 0 : got.back().first - got.front().first;
  10902. const auto sorted = std::is_sorted (got.begin(), got.end(), [] (const auto& a, const auto& b) { return a.first < b.first; });
  10903. step ("sent=" + juce::String ((int) sent->size()) + " wheel messages over 2 s");
  10904. step ("recorded=" + juce::String ((int) got.size()) + " points in " + where + ", value " + juce::String (lo, 3) + " .. "
  10905. + juce::String (hi, 3) + " (0.5 = centre), ticks " + juce::String (span) + " apart, " + (sorted ? "in order" : "OUT OF ORDER")
  10906. + ", notes " + juce::String (notes));
  10907. if (! got.empty())
  10908. step ("last=" + juce::String (got.back().second, 3));
  10909. // song mode: a clip over the take, ending back at the centre. Pattern mode: the take loops the 1-bar pattern
  10910. // (4.6 beats of take), so the lane spans the bar and the last wheel message (the centre) lands inside it
  10911. const auto centred = std::any_of (got.begin(), got.end(), [] (const auto& p) { return std::abs (p.second - 0.5f) < 0.02f; });
  10912. const auto ok = got.size() >= 20 && hi > 0.97f && lo < 0.03f && sorted && notes >= 1
  10913. && (songMode ? span > lynx::ppq * 3 && span < lynx::ppq * 6 && std::abs (got.back().second - 0.5f) < 0.02f
  10914. : span > lynx::ppq * 2 && span <= lynx::ppq * 4 && centred);
  10915. step (ok ? "result=OK" : "result=FAILED");
  10916. finish (ok ? 0 : 1);
  10917. });
  10918. });
  10919. };
  10920. juce::Timer::callAfterDelay (300, *tick);
  10921. }
  10922. // --countinrectest (round 170d): see the command line above.
  10923. void runCountInRecordTest (const juce::File& report)
  10924. {
  10925. engine = std::make_unique<lynx::AudioEngine>();
  10926. engine->getDeviceManager().closeAudioDevice(); // the engine's callback is driven by hand below
  10927. struct StandIn final : juce::AudioIODevice
  10928. {
  10929. StandIn() : juce::AudioIODevice ("countin", "test") {}
  10930. juce::StringArray getOutputChannelNames() override { return { "L", "R" }; }
  10931. juce::StringArray getInputChannelNames() override { return {}; }
  10932. juce::Array<double> getAvailableSampleRates() override { return { 48000.0 }; }
  10933. juce::Array<int> getAvailableBufferSizes() override { return { 512 }; }
  10934. int getDefaultBufferSize() override { return 512; }
  10935. juce::String open (const juce::BigInteger&, const juce::BigInteger&, double, int) override { return {}; }
  10936. void close() override {}
  10937. bool isOpen() override { return true; }
  10938. void start (juce::AudioIODeviceCallback*) override {}
  10939. void stop() override {}
  10940. bool isPlaying() override { return true; }
  10941. juce::String getLastError() override { return {}; }
  10942. int getCurrentBufferSizeSamples() override { return 512; }
  10943. double getCurrentSampleRate() override { return 48000.0; }
  10944. int getCurrentBitDepth() override { return 32; }
  10945. juce::BigInteger getActiveOutputChannels() const override
  10946. {
  10947. juce::BigInteger b;
  10948. b.setRange (0, 2, true);
  10949. return b;
  10950. }
  10951. juce::BigInteger getActiveInputChannels() const override { return {}; }
  10952. int getOutputLatencyInSamples() override { return 256; }
  10953. int getInputLatencyInSamples() override { return 0; }
  10954. };
  10955. auto device = std::make_shared<StandIn>();
  10956. auto text = std::make_shared<juce::String>();
  10957. auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
  10958. auto finish = [this] (int code) {
  10959. setApplicationReturnValue (code);
  10960. quit();
  10961. };
  10962. constexpr std::int64_t bar = 4 * lynx::ppq; // 120 BPM, 4/4
  10963. lynx::Song song; // (as --cliplooptest: one synth channel on insert 1, an empty pattern)
  10964. song.bpm = 120.0;
  10965. song.mixer = lynx::Song::defaultMixer (2);
  10966. song.channels.resize (1);
  10967. song.channels[0].mixerTrack = 1;
  10968. song.patterns.emplace_back();
  10969. song.mode = lynx::PlayMode::song;
  10970. song.currentPattern = 0;
  10971. engine->setSong (song);
  10972. engine->getTransport().metronome.store (true);
  10973. auto o = engine->getRecordOptions();
  10974. o.mode = lynx::RecordMode::overdub;
  10975. o.countInBars = 1;
  10976. o.catchWindow = lynx::ppq / 4;
  10977. o.compensateOutput = true;
  10978. o.recordNotes = true;
  10979. o.recordAudio = false;
  10980. o.recordAutomation = false;
  10981. o.waitForInput = false;
  10982. o.quantise = 0;
  10983. o.placeSongClip = true;
  10984. o.recordingMarkers = false;
  10985. o.punchLoopRegion = false;
  10986. o.preRollBars = o.postRollBars = 0;
  10987. engine->setRecordOptions (o);
  10988. engine->deviceCallback().audioDeviceAboutToStart (device.get());
  10989. 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");
  10990. // an event heard at output sample `heard` (counted from the first block after Play), sent as MIDI input
  10991. struct Event
  10992. {
  10993. std::int64_t heard;
  10994. juce::MidiMessage message;
  10995. };
  10996. struct Pass
  10997. {
  10998. std::vector<float> out;
  10999. std::vector<Event> events;
  11000. std::int64_t playingAt = -1; // the first sample of the block the song started in
  11001. int block = 0, blocks = 0;
  11002. std::function<void()> done;
  11003. };
  11004. constexpr int n = 512;
  11005. constexpr double rate = 48000.0;
  11006. // one pass: the take recorded from bar 3, `blocks` blocks driven by hand, 8 at a time between the engine's timer
  11007. // ticks (the take is committed there); then stopped and its results left to the timer
  11008. auto runPass = std::make_shared<std::function<void (std::shared_ptr<Pass>)>>();
  11009. *runPass = [this] (std::shared_ptr<Pass> pass) {
  11010. auto& cb = engine->deviceCallback();
  11011. std::vector<float> l (n), r (n);
  11012. float* outs[] = { l.data(), r.data() };
  11013. juce::AudioIODeviceCallbackContext context;
  11014. if (pass->block == 0)
  11015. {
  11016. engine->stop();
  11017. engine->seek ((double) (2 * bar));
  11018. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, n, context); // (the seek, stopped)
  11019. engine->setRecording (true);
  11020. engine->startPlayback(); // the count-in starts
  11021. }
  11022. for (int k = 0; k < 8 && pass->block < pass->blocks; ++k, ++pass->block)
  11023. {
  11024. // the events heard in this block: stamped the way the engine's clock maps time to heard samples
  11025. const auto blockStart = (std::int64_t) pass->block * n;
  11026. const auto clock = engine->liveClock();
  11027. const auto compMs = 1000.0 * (n + 256) / rate;
  11028. for (auto& e : pass->events)
  11029. if (e.heard >= blockStart && e.heard < blockStart + n)
  11030. {
  11031. auto m = e.message;
  11032. m.setTimeStamp ((clock.timeMs + compMs + (double) (e.heard - blockStart) * 1000.0 / rate) * 0.001);
  11033. engine->injectMidiInput (m);
  11034. }
  11035. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, n, context);
  11036. pass->out.insert (pass->out.end(), l.begin(), l.end());
  11037. if (pass->playingAt < 0 && engine->getTransport().playing.load())
  11038. pass->playingAt = blockStart;
  11039. }
  11040. };
  11041. // (the recursion through the message loop; written out so each step lets the engine's timer run)
  11042. auto drive = std::make_shared<std::function<void (std::shared_ptr<Pass>)>>();
  11043. *drive = [this, runPass, drive, device] (std::shared_ptr<Pass> pass) { // (the stand-in lives while the passes run)
  11044. if (engine == nullptr)
  11045. return;
  11046. (*runPass) (pass);
  11047. if (pass->block < pass->blocks)
  11048. {
  11049. juce::Timer::callAfterDelay (40, [pass, drive] { (*drive) (pass); });
  11050. return;
  11051. }
  11052. engine->stop();
  11053. juce::Timer::callAfterDelay (300, [this, pass] {
  11054. if (engine == nullptr)
  11055. return;
  11056. engine->setRecording (false);
  11057. juce::Timer::callAfterDelay (200, [pass] { pass->done(); });
  11058. });
  11059. };
  11060. auto onsets = [] (const std::vector<float>& out) {
  11061. std::vector<std::int64_t> at;
  11062. std::int64_t last = -100000;
  11063. for (std::size_t i = 0; i < out.size(); ++i)
  11064. if (std::abs (out[i]) > 0.02f && (std::int64_t) i - last > 4000)
  11065. {
  11066. at.push_back ((std::int64_t) i);
  11067. last = (std::int64_t) i;
  11068. }
  11069. else if (std::abs (out[i]) > 0.02f)
  11070. last = (std::int64_t) i;
  11071. return at;
  11072. };
  11073. // the graph is (re)built on the message thread: start once it has settled
  11074. juce::Timer::callAfterDelay (1500, [this, step, finish, drive, onsets] {
  11075. if (engine == nullptr)
  11076. return;
  11077. auto first = std::make_shared<Pass>();
  11078. first->blocks = (int) (rate * 18.0 / n); // count-in + 8 bars
  11079. first->done = [this, first, step, finish, drive, onsets] {
  11080. const auto clicks = onsets (first->out);
  11081. juce::String list;
  11082. for (std::size_t i = 0; i < std::min<std::size_t> (clicks.size(), 8); ++i)
  11083. list << clicks[i] << " ";
  11084. step ("pass 1: clicks heard at samples " + list + "…, the song started in the block at " + juce::String (first->playingAt));
  11085. // the bar-3 downbeat: the click at the block the song started in
  11086. std::int64_t down = -1;
  11087. for (auto c : clicks)
  11088. if (std::abs (c - first->playingAt) < n)
  11089. down = c;
  11090. if (down < 0 || engine->getSong().patterns[0].notes.size() != 0)
  11091. {
  11092. step ("result=FAILED no downbeat click found (or notes recorded without input)");
  11093. finish (1);
  11094. return;
  11095. }
  11096. const auto ms = [down] (double t) { return down + (std::int64_t) std::llround (t * rate / 1000.0); };
  11097. auto second = std::make_shared<Pass>();
  11098. second->blocks = first->blocks;
  11099. auto add = [&second] (std::int64_t at, int key, bool on) {
  11100. second->events.push_back ({ at, on ? juce::MidiMessage::noteOn (1, key, (juce::uint8) 100) : juce::MidiMessage::noteOff (1, key) });
  11101. };
  11102. for (int key : { 60, 64, 67 }) // the chord, 15 ms early, held half a second
  11103. {
  11104. add (ms (-15.0), key, true);
  11105. add (ms (500.0), key, false);
  11106. }
  11107. add (ms (-1500.0), 62, true); // beat 2 of the count-in bar (bar 2)
  11108. add (ms (-1250.0), 62, false);
  11109. add (ms (503.0), 77, true); // 3 ms after beat 2
  11110. add (ms (603.0), 77, false);
  11111. for (int b = 1; b <= 6; ++b) // a note a bar ("it stopped after two bars")
  11112. {
  11113. add (ms (b * 2000.0), 70 + b, true);
  11114. add (ms (b * 2000.0 + 250.0), 70 + b, false);
  11115. }
  11116. second->done = [this, step, finish] {
  11117. const auto& s = engine->getSong();
  11118. const auto& p = s.patterns[0];
  11119. const lynx::Clip* clip = nullptr;
  11120. for (const auto& c : s.playlist)
  11121. if (c.kind == lynx::ClipKind::pattern && c.pattern == 0)
  11122. clip = &c;
  11123. const auto origin = clip != nullptr ? clip->start - clip->offset : -1;
  11124. step ("pass 2: " + juce::String ((int) p.notes.size()) + " notes recorded, clip at " + juce::String (clip != nullptr ? clip->start : -1));
  11125. auto ok = clip != nullptr && origin == bar && p.notes.size() == 11;
  11126. // where each one was heard (song ticks): 0.5 ms = ~1 tick
  11127. const std::vector<std::pair<int, double>> want = { { 60, 2.0 * bar }, { 64, 2.0 * bar }, { 67, 2.0 * bar },
  11128. { 62, 2.0 * bar - 3 * lynx::ppq }, { 77, 2.0 * bar + lynx::ppq + 3.0 * 1.92 },
  11129. { 71, 3.0 * bar }, { 72, 4.0 * bar }, { 73, 5.0 * bar },
  11130. { 74, 6.0 * bar }, { 75, 7.0 * bar }, { 76, 8.0 * bar } };
  11131. for (const auto& [key, tick] : want)
  11132. {
  11133. const lynx::Note* found = nullptr;
  11134. for (const auto& note : p.notes)
  11135. if (note.key == key)
  11136. found = &note;
  11137. const auto at = found != nullptr ? (double) (origin + found->start) : -1.0;
  11138. const auto good = found != nullptr && std::abs (at - tick) <= 2.0;
  11139. ok = ok && good;
  11140. step ("key " + juce::String (key) + ": heard at tick " + juce::String (tick, 2) + ", recorded at " + juce::String (at, 0)
  11141. + (good ? " ok" : " WRONG"));
  11142. }
  11143. const auto* chord = [&p] () -> const lynx::Note* {
  11144. for (const auto& note : p.notes)
  11145. if (note.key == 60)
  11146. return &note;
  11147. return nullptr;
  11148. }();
  11149. if (chord != nullptr)
  11150. step ("chord length " + juce::String (chord->length) + " ticks (caught 15 ms early, released 500 ms after bar 3: 960)");
  11151. step (ok ? "result=OK" : "result=FAILED");
  11152. finish (ok ? 0 : 1);
  11153. };
  11154. (*drive) (second);
  11155. };
  11156. (*drive) (first);
  11157. });
  11158. }
  11159. // --cliplooptest (round 167q): see the command line above.
  11160. // --slicexedittest (round 190aj): see the command line above
  11161. void runSlicexEditTest (const juce::File& project, const juce::File& script, const juce::File& report, const juce::String& prefix)
  11162. {
  11163. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  11164. juce::StringArray lines;
  11165. {
  11166. lynx::AudioEngine offline (false);
  11167. lynx::MainComponent ui (offline, false);
  11168. ui.setSize (1280, 720);
  11169. ui.openFile (project);
  11170. offline.dispatchPendingMessages();
  11171. int channel = -1;
  11172. for (int c = 0; c < (int) offline.getSong().channels.size() && channel < 0; ++c)
  11173. if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::slicex)
  11174. channel = c;
  11175. if (channel < 0)
  11176. lines.add ("no Slicex channel in " + project.getFullPathName());
  11177. else
  11178. {
  11179. auto panel = lynx::makeChannelSettingsPanel (offline, channel);
  11180. juce::Component frame;
  11181. frame.setSize (panel->getWidth(), panel->getHeight());
  11182. frame.setOpaque (true);
  11183. frame.addAndMakeVisible (*panel);
  11184. panel->setTopLeftPosition (0, 0);
  11185. offline.dispatchPendingMessages();
  11186. juce::StringArray commands;
  11187. script.readLines (commands);
  11188. for (const auto& raw : commands)
  11189. {
  11190. const auto command = raw.trim();
  11191. if (command.isEmpty() || command.startsWith ("#"))
  11192. {
  11193. lines.add (command);
  11194. continue;
  11195. }
  11196. if (command.startsWith ("shot "))
  11197. {
  11198. frame.setSize (panel->getWidth(), panel->getHeight()); // (round 190hg: the display modes resize the editor)
  11199. juce::Image image (juce::Image::ARGB, frame.getWidth(), frame.getHeight(), true);
  11200. {
  11201. juce::Graphics g (image);
  11202. g.fillAll (lynx::theme::panel);
  11203. frame.paintEntireComponent (g, false);
  11204. }
  11205. const juce::File file (prefix + command.fromFirstOccurrenceOf (" ", false, false).trim() + ".png");
  11206. file.deleteFile();
  11207. juce::PNGImageFormat png;
  11208. if (auto out = file.createOutputStream())
  11209. png.writeImageToStream (image, *out);
  11210. lines.add (command + " -> " + file.getFileName());
  11211. continue;
  11212. }
  11213. const auto result = lynx::slicexEditorTest (*panel, command);
  11214. offline.dispatchPendingMessages();
  11215. lines.add (command + " -> " + result);
  11216. }
  11217. }
  11218. }
  11219. report.replaceWithText (lines.joinIntoString ("\n") + "\nresult=DONE\n");
  11220. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  11221. quit();
  11222. }
  11223. // --slicexkeytest (round 190ac): see the command line above
  11224. void runSlicexKeyTest (const juce::File& report)
  11225. {
  11226. engine = std::make_unique<lynx::AudioEngine>();
  11227. engine->getDeviceManager().closeAudioDevice(); // the engine's callback is driven by hand below
  11228. struct StandIn final : juce::AudioIODevice
  11229. {
  11230. StandIn() : juce::AudioIODevice ("slicexkey", "test") {}
  11231. juce::StringArray getOutputChannelNames() override { return { "L", "R" }; }
  11232. juce::StringArray getInputChannelNames() override { return {}; }
  11233. juce::Array<double> getAvailableSampleRates() override { return { 48000.0 }; }
  11234. juce::Array<int> getAvailableBufferSizes() override { return { 512 }; }
  11235. int getDefaultBufferSize() override { return 512; }
  11236. juce::String open (const juce::BigInteger&, const juce::BigInteger&, double, int) override { return {}; }
  11237. void close() override {}
  11238. bool isOpen() override { return true; }
  11239. void start (juce::AudioIODeviceCallback*) override {}
  11240. void stop() override {}
  11241. bool isPlaying() override { return true; }
  11242. juce::String getLastError() override { return {}; }
  11243. int getCurrentBufferSizeSamples() override { return 512; }
  11244. double getCurrentSampleRate() override { return 48000.0; }
  11245. int getCurrentBitDepth() override { return 32; }
  11246. juce::BigInteger getActiveOutputChannels() const override
  11247. {
  11248. juce::BigInteger b;
  11249. b.setRange (0, 2, true);
  11250. return b;
  11251. }
  11252. juce::BigInteger getActiveInputChannels() const override { return {}; }
  11253. int getOutputLatencyInSamples() override { return 0; }
  11254. int getInputLatencyInSamples() override { return 0; }
  11255. };
  11256. auto device = std::make_shared<StandIn>();
  11257. auto text = std::make_shared<juce::String>();
  11258. auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
  11259. // 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
  11260. // × region number), so the region a key played can be read from the output
  11261. constexpr int rate = 48000, regionFrames = rate / 4;
  11262. const auto wavFile = report.getSiblingFile ("slicexkey-deck.wav");
  11263. {
  11264. juce::MemoryOutputStream w;
  11265. auto chunk = [&w] (const char* id, const juce::MemoryBlock& body) {
  11266. w.write (id, 4);
  11267. w.writeInt ((int) body.getSize());
  11268. w.write (body.getData(), body.getSize());
  11269. };
  11270. juce::MemoryOutputStream fmt, data, cue;
  11271. fmt.writeShort (1);
  11272. fmt.writeShort (1);
  11273. fmt.writeInt (rate);
  11274. fmt.writeInt (rate * 2);
  11275. fmt.writeShort (2);
  11276. fmt.writeShort (16);
  11277. for (int i = 0; i < 4 * regionFrames; ++i)
  11278. data.writeShort ((short) std::lround (12000.0 * std::sin (juce::MathConstants<double>::twoPi * 200.0 * (double) (i / regionFrames + 1) * (double) i / rate)));
  11279. cue.writeInt (4);
  11280. for (int k = 0; k < 4; ++k)
  11281. {
  11282. cue.writeInt (k + 1);
  11283. cue.writeInt (k * regionFrames);
  11284. cue.write ("data", 4);
  11285. cue.writeInt (0);
  11286. cue.writeInt (0);
  11287. cue.writeInt (k * regionFrames);
  11288. }
  11289. juce::MemoryOutputStream riff;
  11290. riff.write ("WAVE", 4);
  11291. w.reset();
  11292. chunk ("fmt ", fmt.getMemoryBlock());
  11293. chunk ("data", data.getMemoryBlock());
  11294. chunk ("cue ", cue.getMemoryBlock());
  11295. riff.write (w.getData(), w.getDataSize());
  11296. juce::MemoryOutputStream file;
  11297. file.write ("RIFF", 4);
  11298. file.writeInt ((int) riff.getDataSize());
  11299. file.write (riff.getData(), riff.getDataSize());
  11300. wavFile.replaceWithData (file.getData(), file.getDataSize());
  11301. }
  11302. lynx::Song song;
  11303. song.bpm = 120.0;
  11304. song.mixer = lynx::Song::defaultMixer (2);
  11305. song.channels.resize (1);
  11306. auto& channel = song.channels[0];
  11307. channel.instrument = lynx::InstrumentKind::slicex;
  11308. channel.mixerTrack = 1;
  11309. channel.samplePath = wavFile.getFullPathName().toStdString();
  11310. {
  11311. auto state = lynx::slicex::fresh();
  11312. lynx::slicex::setDeckFile (state, 0, channel.samplePath, 4);
  11313. lynx::slicex::setDeckBeats (state, 0, 0.0, 2.0);
  11314. channel.pluginState = lynx::slicex::write (state);
  11315. }
  11316. song.patterns.emplace_back();
  11317. engine->setSong (song);
  11318. auto& callback = engine->deviceCallback();
  11319. callback.audioDeviceAboutToStart (device.get());
  11320. 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");
  11321. juce::Timer::callAfterDelay (2000, [this, device, step] {
  11322. if (engine == nullptr)
  11323. return;
  11324. auto& cb = engine->deviceCallback();
  11325. auto pump = [&cb] (int blocks) {
  11326. std::vector<float> l (512), r (512), out;
  11327. float* outs[] = { l.data(), r.data() };
  11328. juce::AudioIODeviceCallbackContext context;
  11329. for (int k = 0; k < blocks; ++k)
  11330. {
  11331. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, 512, context);
  11332. out.insert (out.end(), l.begin(), l.end());
  11333. }
  11334. return out;
  11335. };
  11336. auto rms = [] (const std::vector<float>& x, int from, int count) {
  11337. double sum = 0.0;
  11338. for (int i = from; i < from + count && i < (int) x.size(); ++i)
  11339. sum += (double) x[(std::size_t) i] * x[(std::size_t) i];
  11340. return std::sqrt (sum / juce::jmax (1, count));
  11341. };
  11342. // the tone's frequency from its rising zero crossings over a stretch
  11343. auto hertz = [] (const std::vector<float>& x, int from, int count) {
  11344. int crossings = 0, first = -1, last = -1;
  11345. for (int i = from + 1; i < from + count && i < (int) x.size(); ++i)
  11346. if (x[(std::size_t) i - 1] < 0.0f && x[(std::size_t) i] >= 0.0f)
  11347. {
  11348. first = first < 0 ? i : first;
  11349. last = i;
  11350. ++crossings;
  11351. }
  11352. return crossings > 1 ? 48000.0 * (double) (crossings - 1) / (double) (last - first) : 0.0;
  11353. };
  11354. bool ok = true;
  11355. auto check = [&ok, step] (bool good, const juce::String& what) {
  11356. ok = ok && good;
  11357. step ((good ? "ok " : "FAIL ") + what);
  11358. };
  11359. const auto idle = pump (20);
  11360. engine->getMeters().takePeak (1, 0);
  11361. check (rms (idle, 0, (int) idle.size()) < 1.0e-6, "idle: rms " + juce::String (rms (idle, 0, (int) idle.size()), 9));
  11362. // 4 regions map to keys 60…63 (FL's automatic map); the editor's click: velocity 100 / 128
  11363. engine->sendLiveNote (0, 60, 0.78125f, true);
  11364. const auto first = pump (16); // 8192 frames = 171 ms, inside region 1 (250 ms)
  11365. const auto meter = engine->getMeters().takePeak (1, 0);
  11366. 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");
  11367. check (std::abs (hertz (first, 1024, 6000) - 200.0) < 4.0, "key 60 plays region 1 (200 Hz)");
  11368. check (meter > 0.01f, "mixer track 1 meter peak " + juce::String (meter, 6));
  11369. engine->sendLiveNote (0, 60, 0.0f, false);
  11370. const auto tail = pump (60);
  11371. 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));
  11372. engine->sendLiveNote (0, 62, 0.78125f, true);
  11373. const auto third = pump (16);
  11374. check (rms (third, 1024, 6000) > 0.01 && std::abs (hertz (third, 1024, 6000) - 600.0) < 8.0,
  11375. "key 62 plays region 3 (600 Hz): rms " + juce::String (rms (third, 1024, 6000), 6) + ", " + juce::String (hertz (third, 1024, 6000), 1) + " Hz");
  11376. engine->sendLiveNote (0, 62, 0.0f, false);
  11377. engine->sendLiveNote (0, 72, 0.78125f, true); // a key without a region
  11378. const auto none = pump (60);
  11379. 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));
  11380. engine->sendLiveNote (0, 72, 0.0f, false);
  11381. step (ok ? "result=OK" : "result=FAILED");
  11382. setApplicationReturnValue (ok ? 0 : 1);
  11383. quit();
  11384. });
  11385. }
  11386. // --renderaheadtest (round 190gq): see the command line above
  11387. void runRenderAheadTest (const juce::File& report, const juce::StringArray& projects, int block, double seconds)
  11388. {
  11389. struct StandIn final : juce::AudioIODevice
  11390. {
  11391. explicit StandIn (int b) : juce::AudioIODevice ("renderahead", "test"), block (b) {}
  11392. const int block;
  11393. juce::StringArray getOutputChannelNames() override { return { "L", "R" }; }
  11394. juce::StringArray getInputChannelNames() override { return {}; }
  11395. juce::Array<double> getAvailableSampleRates() override { return { 48000.0 }; }
  11396. juce::Array<int> getAvailableBufferSizes() override { return { block }; }
  11397. int getDefaultBufferSize() override { return block; }
  11398. juce::String open (const juce::BigInteger&, const juce::BigInteger&, double, int) override { return {}; }
  11399. void close() override {}
  11400. bool isOpen() override { return true; }
  11401. void start (juce::AudioIODeviceCallback*) override {}
  11402. void stop() override {}
  11403. bool isPlaying() override { return true; }
  11404. juce::String getLastError() override { return {}; }
  11405. int getCurrentBufferSizeSamples() override { return block; }
  11406. double getCurrentSampleRate() override { return 48000.0; }
  11407. int getCurrentBitDepth() override { return 32; }
  11408. juce::BigInteger getActiveOutputChannels() const override
  11409. {
  11410. juce::BigInteger b;
  11411. b.setRange (0, 2, true);
  11412. return b;
  11413. }
  11414. juce::BigInteger getActiveInputChannels() const override { return {}; }
  11415. int getOutputLatencyInSamples() override { return 0; }
  11416. int getInputLatencyInSamples() override { return 0; }
  11417. };
  11418. struct Scenario
  11419. {
  11420. juce::String name;
  11421. juce::File file; // a project, or none: the showcase song
  11422. int mode = 0; // 0 Song mode from the start, 1 a loop region, 2 Pattern mode
  11423. };
  11424. auto scenarios = std::make_shared<std::vector<Scenario>>();
  11425. scenarios->push_back ({ "showcase, Song mode", {}, 0 });
  11426. scenarios->push_back ({ "showcase, a loop region wrapping mid-block", {}, 1 });
  11427. scenarios->push_back ({ "showcase, Pattern mode", {}, 2 });
  11428. for (const auto& p : projects)
  11429. scenarios->push_back ({ juce::File (p).getFileName(), juce::File (p), 0 });
  11430. auto text = std::make_shared<juce::String>();
  11431. auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
  11432. step ("render-ahead test: blocks of " + juce::String (block) + " at 48 kHz, " + juce::String (seconds, 1) + " s per run");
  11433. auto outputs = std::make_shared<std::vector<std::vector<float>>>();
  11434. auto ok = std::make_shared<bool> (true);
  11435. auto run = std::make_shared<std::function<void (std::size_t, int)>>();
  11436. *run = [this, scenarios, step, outputs, ok, run, block, seconds, report] (std::size_t index, int pass) {
  11437. if (index >= scenarios->size())
  11438. {
  11439. lynx::renderAheadOption().store (true);
  11440. step (juce::String ("result=") + (*ok ? "OK" : "FAIL"));
  11441. setApplicationReturnValue (*ok ? 0 : 1);
  11442. engine.reset();
  11443. quit();
  11444. return;
  11445. }
  11446. const auto& sc = (*scenarios)[index];
  11447. lynx::renderAheadOption().store (pass == 1);
  11448. engine = std::make_unique<lynx::AudioEngine>();
  11449. engine->getDeviceManager().closeAudioDevice(); // the engine's callback is driven by hand below
  11450. engine->setRenderAheadAlways (true); // (the showcase song is light: the app would leave it real-time)
  11451. juce::String error;
  11452. auto loaded = true;
  11453. if (sc.file == juce::File())
  11454. {
  11455. auto song = lynx::makeShowcaseSong (0);
  11456. if (sc.mode == 1)
  11457. {
  11458. song.loopStart = 4 * lynx::ppq * song.beatsPerBar + 37; // (not on a block boundary)
  11459. song.loopEnd = 6 * lynx::ppq * song.beatsPerBar + 211;
  11460. song.loopOff = false;
  11461. }
  11462. if (sc.mode == 2)
  11463. song.mode = lynx::PlayMode::pattern;
  11464. engine->setSong (std::move (song));
  11465. }
  11466. else if (sc.file.hasFileExtension ("flp"))
  11467. loaded = engine->importFlpFile (sc.file, error);
  11468. else if (auto song = lynx::ProjectFile::load (sc.file, error))
  11469. engine->setSong (std::move (*song));
  11470. else
  11471. loaded = false;
  11472. if (! loaded)
  11473. {
  11474. step ("FAIL " + sc.name + ": " + error);
  11475. *ok = false;
  11476. (*run) (index + 1, 0);
  11477. return;
  11478. }
  11479. auto device = std::make_shared<StandIn> (block);
  11480. engine->deviceCallback().audioDeviceAboutToStart (device.get());
  11481. // the graph is (re)built on the message thread: the run starts once it has settled
  11482. juce::Timer::callAfterDelay (1500, [this, scenarios, step, outputs, ok, run, block, seconds, index, pass, device] {
  11483. if (engine == nullptr)
  11484. return;
  11485. const auto& sc = (*scenarios)[index];
  11486. auto& cb = engine->deviceCallback();
  11487. std::vector<float> l ((std::size_t) block), r ((std::size_t) block), out;
  11488. float* outs[] = { l.data(), r.data() };
  11489. juce::AudioIODeviceCallbackContext context;
  11490. engine->stop();
  11491. engine->seek (0.0);
  11492. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, block, context); // (the seek, stopped)
  11493. engine->play();
  11494. const auto blocks = (int) (seconds * 48000.0 / block);
  11495. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  11496. for (int k = 0; k < blocks; ++k)
  11497. {
  11498. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, block, context);
  11499. out.insert (out.end(), l.begin(), l.end());
  11500. out.insert (out.end(), r.begin(), r.end());
  11501. // (about the device's pace at the start of each second, so the render-ahead thread gets ahead)
  11502. if (k % (48000 / block) < 48000 / block / 2)
  11503. std::this_thread::sleep_for (std::chrono::microseconds ((int) (block * 1.0e6 / 48000.0 * 0.6)));
  11504. }
  11505. const auto ms = juce::Time::getMillisecondCounterHiRes() - t0;
  11506. engine->stop();
  11507. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, block, context);
  11508. const auto* st = engine->renderAheadStats();
  11509. auto n = [] (const std::atomic<std::uint64_t>& v) { return (juce::int64) v.load(); };
  11510. juce::String line = sc.name + (pass == 1 ? ", render ahead on: " : ", render ahead off: ") + juce::String (ms / 1000.0, 1) + " s";
  11511. if (st != nullptr && pass == 1)
  11512. line << "; blocks " << n (st->blocks) << ", from the ring " << n (st->fromRing) << ", waited " << n (st->waited) << ", in the callback "
  11513. << n (st->inline_) << ", dropped " << n (st->flushes) << ", drained " << n (st->drains) << ", started " << n (st->engagements)
  11514. << ", boundary mismatches " << n (st->splitMismatches) << "; ahead " << st->aheadChannels.load() << " channels / "
  11515. << st->aheadTracks.load() << " inserts, boundary " << st->boundary.load() << ", window " << st->window.load();
  11516. step (" " + line);
  11517. if (pass == 0)
  11518. {
  11519. outputs->assign (1, std::move (out));
  11520. (*run) (index, 1);
  11521. return;
  11522. }
  11523. const auto& off = outputs->front();
  11524. std::size_t first = off.size() == out.size() ? off.size() : 0;
  11525. for (std::size_t s = 0; s < std::min (off.size(), out.size()); ++s)
  11526. if (std::memcmp (&off[s], &out[s], sizeof (float)) != 0)
  11527. {
  11528. first = s;
  11529. break;
  11530. }
  11531. const auto same = off.size() == out.size() && first == off.size();
  11532. const auto clean = st != nullptr && st->flushes.load() == 0 && st->splitMismatches.load() == 0 && st->engagements.load() >= 1
  11533. && st->fromRing.load() > st->blocks.load() / 4;
  11534. *ok = *ok && same && clean;
  11535. step (juce::String (same && clean ? "ok " : "FAIL ") + sc.name + ": " + (same ? "bit-identical" : "differs from sample " + juce::String ((juce::int64) first / 2 % block) + " of block " + juce::String ((juce::int64) first / 2 / block))
  11536. + (clean ? "" : ", render-ahead counters off (see above)"));
  11537. (*run) (index + 1, 0);
  11538. });
  11539. };
  11540. (*run) (0, 0);
  11541. }
  11542. void runClipLoopTest (const juce::File& report, const juce::File& wavFile)
  11543. {
  11544. engine = std::make_unique<lynx::AudioEngine>();
  11545. engine->getDeviceManager().closeAudioDevice(); // the engine's callback is driven by hand below
  11546. struct StandIn final : juce::AudioIODevice
  11547. {
  11548. StandIn() : juce::AudioIODevice ("cliploop", "test") {}
  11549. juce::StringArray getOutputChannelNames() override { return { "L", "R" }; }
  11550. juce::StringArray getInputChannelNames() override { return {}; }
  11551. juce::Array<double> getAvailableSampleRates() override { return { 48000.0 }; }
  11552. juce::Array<int> getAvailableBufferSizes() override { return { 512 }; }
  11553. int getDefaultBufferSize() override { return 512; }
  11554. juce::String open (const juce::BigInteger&, const juce::BigInteger&, double, int) override { return {}; }
  11555. void close() override {}
  11556. bool isOpen() override { return true; }
  11557. void start (juce::AudioIODeviceCallback*) override {}
  11558. void stop() override {}
  11559. bool isPlaying() override { return true; }
  11560. juce::String getLastError() override { return {}; }
  11561. int getCurrentBufferSizeSamples() override { return 512; }
  11562. double getCurrentSampleRate() override { return 48000.0; }
  11563. int getCurrentBitDepth() override { return 32; }
  11564. juce::BigInteger getActiveOutputChannels() const override
  11565. {
  11566. juce::BigInteger b;
  11567. b.setRange (0, 2, true);
  11568. return b;
  11569. }
  11570. juce::BigInteger getActiveInputChannels() const override { return {}; }
  11571. int getOutputLatencyInSamples() override { return 0; }
  11572. int getInputLatencyInSamples() override { return 0; }
  11573. };
  11574. auto device = std::make_shared<StandIn>();
  11575. auto text = std::make_shared<juce::String>();
  11576. auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
  11577. constexpr int bar = 96000, beat = bar / 4; // 120 BPM, 48 kHz
  11578. const auto ppq = (double) lynx::ppq;
  11579. lynx::Song song;
  11580. song.bpm = 120.0;
  11581. song.mixer = lynx::Song::defaultMixer (2);
  11582. song.channels.resize (1); // the synth of a new channel: deterministic
  11583. song.channels[0].mixerTrack = 1;
  11584. auto& pattern = song.patterns.emplace_back(); // 1 bar: C5 on beat 0, C6 on beat 2
  11585. for (auto [b, key] : { std::pair { 0, 60 }, std::pair { 2, 72 } })
  11586. {
  11587. lynx::Note n;
  11588. n.start = b * lynx::ppq;
  11589. n.length = lynx::ppq / 4;
  11590. n.key = key;
  11591. pattern.notes.push_back (n);
  11592. }
  11593. lynx::Clip clip;
  11594. clip.pattern = 0;
  11595. clip.length = 16 * lynx::ppq; // stretched to 4 bars
  11596. song.playlist.push_back (clip);
  11597. song.mode = lynx::PlayMode::song;
  11598. {
  11599. // the Windows GUI check's project: the same song with a 1-bar clip, to stretch with the mouse
  11600. auto gui = song;
  11601. gui.playlist[0].length = 4 * lynx::ppq;
  11602. juce::String error;
  11603. lynx::ProjectFile::save (gui, report.getSiblingFile ("cliploop-gui.lynx"), error);
  11604. }
  11605. engine->setSong (song);
  11606. auto& callback = engine->deviceCallback();
  11607. callback.audioDeviceAboutToStart (device.get());
  11608. step ("song=1-bar synth pattern, clip stretched to 4 bars, 120 BPM, 48 kHz, blocks of 512");
  11609. // the graph is (re)built on the message thread: the scenarios run once it has settled
  11610. juce::Timer::callAfterDelay (1500, [this, device, step, wavFile, ppq] {
  11611. if (engine == nullptr)
  11612. return;
  11613. auto& cb = engine->deviceCallback();
  11614. // plays `samples` from tick `from` through the device callback; `between` runs after each block (block index)
  11615. auto play = [this, &cb] (double from, int samples, const std::function<void (int)>& between = {}) {
  11616. engine->stop();
  11617. engine->seek (from);
  11618. std::vector<float> l (512), r (512), out;
  11619. float* outs[] = { l.data(), r.data() };
  11620. juce::AudioIODeviceCallbackContext context;
  11621. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, 512, context); // (the seek, stopped)
  11622. engine->play();
  11623. for (int k = 0; (int) out.size() < samples; ++k)
  11624. {
  11625. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, 512, context);
  11626. out.insert (out.end(), l.begin(), l.end());
  11627. if (between)
  11628. between (k);
  11629. }
  11630. engine->stop();
  11631. for (int k = 0; k < 400; ++k) // the tails of the scenario die out
  11632. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, 512, context);
  11633. out.resize ((std::size_t) samples);
  11634. return out;
  11635. };
  11636. auto rms = [] (const std::vector<float>& x, int from, int count) {
  11637. double sum = 0.0;
  11638. for (int i = from; i < from + count && i < (int) x.size(); ++i)
  11639. sum += (double) x[(std::size_t) i] * x[(std::size_t) i];
  11640. return std::sqrt (sum / juce::jmax (1, count));
  11641. };
  11642. auto diff = [] (const std::vector<float>& a, int aFrom, const std::vector<float>& b, int bFrom, int count) {
  11643. double m = 0.0;
  11644. for (int i = 0; i < count && aFrom + i < (int) a.size() && bFrom + i < (int) b.size(); ++i)
  11645. m = juce::jmax (m, (double) std::abs (a[(std::size_t) (aFrom + i)] - b[(std::size_t) (bFrom + i)]));
  11646. return m;
  11647. };
  11648. auto num = [] (double v) { return juce::String (v, 6); };
  11649. bool ok = true;
  11650. auto check = [&ok, step] (bool good, const juce::String& what) {
  11651. ok = ok && good;
  11652. step ((good ? "ok " : "FAIL ") + what);
  11653. };
  11654. lynx::setStretchedClipsLoop (true);
  11655. const auto a = play (0.0, 4 * bar);
  11656. const auto bar1 = rms (a, 0, bar);
  11657. check (bar1 > 0.01, "play from the start: bar 1 RMS " + num (bar1));
  11658. for (int k = 1; k < 4; ++k)
  11659. {
  11660. const auto rk = rms (a, k * bar, bar), d = diff (a, k * bar, a, 0, bar);
  11661. check (std::abs (rk / bar1 - 1.0) < 1.0e-3 && d < 1.0e-4,
  11662. "bar " + juce::String (k + 1) + " RMS " + num (rk) + " (x" + num (rk / bar1) + " of bar 1), max |bar - bar 1| " + juce::String (d, 9));
  11663. }
  11664. {
  11665. const auto x = play (10 * ppq, bar + bar / 2);
  11666. const auto d = juce::jmax (diff (x, 0, a, 2 * beat, bar / 2), diff (x, bar / 2, a, 0, bar));
  11667. check (rms (x, 0, bar / 2) > 0.01 && d < 1.0e-4,
  11668. "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));
  11669. }
  11670. {
  11671. // a seek while playing, after 6.99 beats, to bar 4 beat 3 (a ruler click)
  11672. const auto jumpBlock = 7 * beat / 512 - 1;
  11673. const auto x = play (0.0, 2 * bar, [this, jumpBlock, ppq] (int k) {
  11674. if (k == jumpBlock)
  11675. engine->seek (14 * ppq);
  11676. });
  11677. // (the best of 0-2 samples late: anything but 0 fails)
  11678. const auto at = (jumpBlock + 1) * 512;
  11679. int lag = 0;
  11680. auto d = 1.0e9;
  11681. for (int l = 0; l <= 2; ++l)
  11682. if (const auto dl = diff (x, at + l, a, 2 * beat, beat - 2); dl < d)
  11683. d = dl, lag = l;
  11684. d = lag == 0 ? d : 1.0;
  11685. const auto ratio = rms (x, at, beat) / rms (a, 2 * beat, beat);
  11686. check (std::abs (ratio - 1.0) < 1.0e-3 && d < 1.0e-4,
  11687. "jump mid-clip to bar 4 beat 3: RMS " + num (rms (x, at, beat)) + " (x" + num (ratio) + " of bar 1 beat 3), max diff "
  11688. + juce::String (d, 9) + " (" + juce::String (lag) + " sample(s) late)");
  11689. }
  11690. {
  11691. engine->editSong ([ppq] (lynx::Song& s) {
  11692. s.loopStart = (std::int64_t) (4 * ppq);
  11693. s.loopEnd = (std::int64_t) (12 * ppq);
  11694. }, false);
  11695. const auto x = play (0.0, 7 * bar);
  11696. double d = 0.0;
  11697. juce::String lags;
  11698. for (int k = 1; k < 7; ++k) // (the best of 0-2 samples late after a wrap, as after a jump)
  11699. {
  11700. auto best = 1.0e9;
  11701. int lag = 0;
  11702. for (int l = 0; l <= 2; ++l)
  11703. if (const auto dl = diff (x, k * bar + l, a, 0, bar - 2); dl < best)
  11704. best = dl, lag = l;
  11705. d = juce::jmax (d, lag == 0 ? best : 1.0); // a sample gained at a wrap fails (round 167q loopwrap)
  11706. lags << (k > 1 ? "," : "") << lag;
  11707. }
  11708. const auto r = rms (x, bar, 6 * bar);
  11709. check (std::abs (r / bar1 - 1.0) < 1.0e-3 && d < 1.0e-4,
  11710. "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)
  11711. + " (samples late, bars 2-7: " + lags + ")");
  11712. engine->editSong ([] (lynx::Song& s) { s.loopStart = s.loopEnd = 0; }, false);
  11713. }
  11714. {
  11715. // 100 wraps of a 1-bar loop region (bar 2): every pass on its sample, none gained (round 167q loopwrap: each
  11716. // wrap used to play one sample more)
  11717. engine->editSong ([ppq] (lynx::Song& s) {
  11718. s.loopStart = (std::int64_t) (4 * ppq);
  11719. s.loopEnd = (std::int64_t) (8 * ppq);
  11720. }, false);
  11721. const auto x = play (0.0, 101 * bar);
  11722. double d = 0.0;
  11723. int worst = 0;
  11724. for (int k = 1; k <= 100; ++k)
  11725. if (const auto dk = diff (x, k * bar, a, 0, bar); dk > d)
  11726. d = dk, worst = k + 1;
  11727. check (d < 1.0e-4, "loop region bar 2, 100 wraps: max diff of every pass vs bar 1 " + juce::String (d, 9)
  11728. + (d < 1.0e-4 ? juce::String() : " (worst: bar " + juce::String (worst) + ")"));
  11729. engine->editSong ([] (lynx::Song& s) { s.loopStart = s.loopEnd = 0; }, false);
  11730. }
  11731. lynx::setStretchedClipsLoop (false);
  11732. {
  11733. const auto x = play (0.0, 4 * bar);
  11734. const auto r = juce::jmax (rms (x, bar, bar), juce::jmax (rms (x, 2 * bar, bar), rms (x, 3 * bar, bar)));
  11735. 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));
  11736. }
  11737. lynx::setStretchedClipsLoop (true);
  11738. cb.audioDeviceStopped();
  11739. // the export: a WAV of the 4 bars, read back from the file
  11740. if (wavFile != juce::File())
  11741. {
  11742. for (const auto loops : { true, false })
  11743. {
  11744. lynx::setStretchedClipsLoop (loops);
  11745. const auto file = loops ? wavFile : wavFile.getSiblingFile (wavFile.getFileNameWithoutExtension() + "-off.wav");
  11746. file.deleteFile();
  11747. {
  11748. juce::WavAudioFormat wav;
  11749. std::unique_ptr<juce::AudioFormatWriter> writer (wav.createWriterFor (file.createOutputStream().release(), 48000.0, 2, 32, {}, 0));
  11750. engine->stop();
  11751. engine->seek (0.0);
  11752. lynx::AudioEngine::RenderOptions o;
  11753. o.seconds = 8.0;
  11754. o.sampleRate = 48000.0;
  11755. o.output = writer.get();
  11756. engine->renderOffline (o);
  11757. }
  11758. juce::WavAudioFormat wav;
  11759. std::unique_ptr<juce::AudioFormatReader> reader (wav.createReaderFor (file.createInputStream().release(), true));
  11760. std::vector<float> x;
  11761. if (reader != nullptr)
  11762. {
  11763. juce::AudioBuffer<float> buffer (2, (int) reader->lengthInSamples);
  11764. reader->read (&buffer, 0, (int) reader->lengthInSamples, 0, true, true);
  11765. x.assign (buffer.getReadPointer (0), buffer.getReadPointer (0) + buffer.getNumSamples());
  11766. }
  11767. const auto b1 = rms (x, 0, bar);
  11768. juce::String line = juce::String (loops ? "export" : "export, option off") + " (" + file.getFileName() + ", " + juce::String ((int) x.size()) + " samples): bar 1 RMS " + num (b1);
  11769. bool good = x.size() >= (std::size_t) 4 * bar && b1 > 0.01;
  11770. for (int k = 1; k < 4; ++k)
  11771. {
  11772. const auto rk = rms (x, k * bar, bar);
  11773. line << ", bar " << (k + 1) << " " << num (rk);
  11774. 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);
  11775. }
  11776. if (loops)
  11777. 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);
  11778. check (good, line);
  11779. }
  11780. lynx::setStretchedClipsLoop (true);
  11781. }
  11782. step (ok ? "result=OK" : "result=FAILED");
  11783. setApplicationReturnValue (ok ? 0 : 1);
  11784. quit();
  11785. });
  11786. }
  11787. // --rectest (round 163): see the command line above. Writes report lines step by step (a driver that ends the
  11788. // process leaves what was done).
  11789. void runRecordTest (const juce::File& report, double seconds, const juce::String& deviceType, const juce::String& deviceName,
  11790. const juce::String& inputName, int mode, int pdcSamples, int bufferSize)
  11791. {
  11792. engine = std::make_unique<lynx::AudioEngine>();
  11793. lynx::videoview::install (*engine); // (Fruity Video Player channels: their sound tracks)
  11794. savedDeviceState = engine->getDeviceManager().createStateXml();
  11795. auto text = std::make_shared<juce::String>();
  11796. auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
  11797. auto finish = [this, step] (int code) {
  11798. restoreSavedDeviceState();
  11799. setApplicationReturnValue (code);
  11800. quit();
  11801. };
  11802. auto& devices = engine->getDeviceManager();
  11803. if (deviceType.isNotEmpty() && devices.getCurrentAudioDeviceType() != deviceType)
  11804. devices.setCurrentAudioDeviceType (deviceType, true);
  11805. {
  11806. auto setup = devices.getAudioDeviceSetup();
  11807. if (deviceName.isNotEmpty())
  11808. setup.outputDeviceName = deviceName;
  11809. if (bufferSize > 0)
  11810. setup.bufferSize = bufferSize;
  11811. if (const auto error = devices.setAudioDeviceSetup (setup, true); error.isNotEmpty())
  11812. step ("device_error=" + error);
  11813. }
  11814. if (const auto r = engine->openAudioInput (inputName.isNotEmpty() ? inputName : deviceName); r.issue != lynx::AudioEngine::InputIssue::none)
  11815. step ("input_error=" + juce::String ((int) r.issue) + " " + r.detail);
  11816. // takes go next to the report, not into the user's recordings folder
  11817. engine->setRecordingTarget (report.getSiblingFile (report.getFileNameWithoutExtension() + "-takes"), {});
  11818. auto* device = devices.getCurrentAudioDevice();
  11819. if (device == nullptr || engine->getInputChannelNames().empty())
  11820. {
  11821. step ("result=ERROR no device / no input");
  11822. finish (1);
  11823. return;
  11824. }
  11825. const auto rate = device->getCurrentSampleRate();
  11826. step ("device=" + device->getTypeName() + " | " + device->getName() + " | " + juce::String (rate) + " Hz | block " + juce::String (device->getCurrentBufferSizeSamples())
  11827. + " | driver latency in " + juce::String (device->getInputLatencyInSamples()) + " out " + juce::String (device->getOutputLatencyInSamples()));
  11828. // a click (the ping's pulse) on every beat at 120 bpm: beat k at sample k * rate / 2
  11829. const auto beats = (int) std::ceil (seconds * 2.0) + 8;
  11830. const auto clickFile = report.getSiblingFile (report.getFileNameWithoutExtension() + "-clicks.wav");
  11831. {
  11832. lynx::takes::WavTakeWriter w;
  11833. w.open (clickFile.getFullPathName().toStdString(), rate, 1, lynx::takes::SampleFormat::float32);
  11834. const auto total = (juce::int64) std::llround ((double) beats * rate / 2.0);
  11835. std::vector<float> block (4096);
  11836. for (juce::int64 at = 0; at < total; at += (juce::int64) block.size())
  11837. {
  11838. std::fill (block.begin(), block.end(), 0.0f);
  11839. for (int k = 0; k < (int) block.size(); ++k)
  11840. {
  11841. const auto f = at + k;
  11842. const auto beat = (juce::int64) std::floor ((double) f / (rate / 2.0));
  11843. const auto rel = f - (juce::int64) std::llround ((double) beat * rate / 2.0);
  11844. static constexpr float shape[] { 0.25f, 0.75f, 1.0f, 0.75f, 0.25f };
  11845. if (rel >= 0 && rel < 5)
  11846. block[(std::size_t) k] = 0.5f * shape[rel];
  11847. }
  11848. const float* d[] { block.data() };
  11849. w.write (d, (int) std::min<juce::int64> ((juce::int64) block.size(), total - at));
  11850. }
  11851. w.close();
  11852. }
  11853. lynx::Song song = lynx::Song::makeDefault();
  11854. song.bpm = 120.0;
  11855. song.mode = lynx::PlayMode::song;
  11856. song.playlist.clear();
  11857. lynx::ChannelDef c;
  11858. c.name = "Clicks";
  11859. c.instrument = lynx::InstrumentKind::audioClip;
  11860. c.samplePath = clickFile.getFullPathName().toStdString();
  11861. c.mixerTrack = 0;
  11862. c.volume = 1.0f;
  11863. song.channels.push_back (c);
  11864. lynx::Clip clip;
  11865. clip.kind = lynx::ClipKind::audio;
  11866. clip.channel = (int) song.channels.size() - 1;
  11867. clip.track = 0;
  11868. clip.start = 0;
  11869. clip.length = (std::int64_t) beats * lynx::ppq;
  11870. song.playlist.push_back (clip);
  11871. if (mode == 1) // loop recording, bars 2-4
  11872. {
  11873. song.loopStart = 4 * lynx::ppq;
  11874. song.loopEnd = 16 * lynx::ppq;
  11875. }
  11876. else if (mode == 2) // punch in/out, bars 3-4
  11877. {
  11878. song.loopStart = 8 * lynx::ppq;
  11879. song.loopEnd = 16 * lynx::ppq;
  11880. }
  11881. if (song.mixer.size() > 1)
  11882. {
  11883. song.mixer[1].name = "Loop In";
  11884. song.mixer[1].monitor = lynx::InputMonitor::off; // (the loopback must not hear itself)
  11885. }
  11886. engine->setSong (std::move (song));
  11887. engine->setInsertInput (1, 0, false);
  11888. juce::ignoreUnused (pdcSamples);
  11889. // 1) the ping
  11890. if (const auto error = engine->startLatencyPing(); error.isNotEmpty())
  11891. step ("ping_error=" + error);
  11892. juce::Timer::callAfterDelay (3500, [this, step, finish, seconds, rate, report, mode] {
  11893. if (engine == nullptr)
  11894. return;
  11895. if (engine->isPinging())
  11896. engine->cancelLatencyPing();
  11897. const auto r = engine->finishLatencyPing();
  11898. step ("ping=" + juce::String (r.ok ? "ok" : "FAILED " + juce::String (r.problem)) + " samples " + juce::String (r.samples) + " spread " + juce::String (r.spread)
  11899. + " found " + juce::String (r.found) + "/" + juce::String (r.sent) + " peak " + juce::String (juce::Decibels::gainToDecibels (r.peak, -150.0f), 1) + " dB");
  11900. const auto l = engine->currentLatency();
  11901. step ("compensation=" + juce::String (l.total()) + " (round trip " + juce::String (l.roundTrip()) + ", manual " + juce::String (l.manual) + ", pdc " + juce::String (l.pdc) + ")");
  11902. // 2) record
  11903. engine->setInsertArmed (1, true);
  11904. auto o = engine->getRecordOptions();
  11905. o.recordAudio = true;
  11906. o.countInBars = 0;
  11907. o.waitForInput = false;
  11908. o.punchLoopRegion = mode == 2;
  11909. o.preRollBars = mode == 2 ? 1 : 0;
  11910. o.postRollBars = mode == 2 ? 1 : 0;
  11911. // (round 177c: LYNX_RECTEST_BLEND_OFF=1: Blend off; LYNX_RECTEST_LAST_PASS=1: "only the last pass plays")
  11912. o.mode = juce::SystemStats::getEnvironmentVariable ("LYNX_RECTEST_BLEND_OFF", {}) == "1" ? lynx::RecordMode::replace
  11913. : lynx::RecordMode::overdub;
  11914. o.lastLoopPassPlays = juce::SystemStats::getEnvironmentVariable ("LYNX_RECTEST_LAST_PASS", {}) == "1";
  11915. engine->setRecordOptions (o);
  11916. engine->stop();
  11917. engine->rewind();
  11918. engine->setRecording (true);
  11919. juce::Timer::callAfterDelay (300, [this, step, finish, seconds, rate, report, mode] {
  11920. if (engine == nullptr)
  11921. return;
  11922. engine->startPlayback(); // (as the Play button: pre-roll / punch)
  11923. juce::Timer::callAfterDelay ((int) (seconds * 1000.0), [this, step, finish, seconds, rate, report, mode] {
  11924. if (engine == nullptr)
  11925. return;
  11926. if (mode == 2)
  11927. step (juce::String ("stopped_by_post_roll=") + (engine->getTransport().playing.load() ? "no" : "yes"));
  11928. engine->stop();
  11929. juce::Timer::callAfterDelay (500, [this, step, finish, seconds, rate, report, mode] {
  11930. if (engine == nullptr)
  11931. return;
  11932. engine->setRecording (false);
  11933. const auto& s = engine->getSong();
  11934. const auto tps = 120.0 * lynx::ppq / (60.0 * rate);
  11935. int take = -1;
  11936. for (int ch = 0; ch < (int) s.channels.size(); ++ch)
  11937. if (s.channels[(std::size_t) ch].instrument == lynx::InstrumentKind::audioClip && s.channels[(std::size_t) ch].name != "Clicks")
  11938. take = ch;
  11939. if (take < 0)
  11940. {
  11941. step ("result=ERROR no take (" + engine->getLastRecordingError() + ")");
  11942. finish (1);
  11943. return;
  11944. }
  11945. std::vector<std::vector<float>> audio;
  11946. double takeRate = 0.0;
  11947. const auto& path = s.channels[(std::size_t) take].samplePath;
  11948. lynx::takes::readWav (path, audio, &takeRate);
  11949. const auto frames = audio.empty() ? (juce::int64) 0 : (juce::int64) audio[0].size();
  11950. step ("take=" + juce::String::fromUTF8 (path.c_str()) + " frames " + juce::String (frames) + " (" + juce::String ((double) frames / rate, 3)
  11951. + " s of " + juce::String (seconds, 1) + " s played) lost " + juce::String (engine->getLostRecordingFrames()));
  11952. // the clicks in the file (peaks above -12 dBFS, one per 1/8 s at most)
  11953. std::vector<juce::int64> peaks;
  11954. if (! audio.empty())
  11955. for (juce::int64 f = 1; f + 1 < frames; ++f)
  11956. {
  11957. const auto x = std::abs (audio[0][(std::size_t) f]);
  11958. if (x > 0.25f && x >= std::abs (audio[0][(std::size_t) f - 1]) && x > std::abs (audio[0][(std::size_t) f + 1])
  11959. && (peaks.empty() || f - peaks.back() > (juce::int64) (rate / 8)))
  11960. peaks.push_back (f);
  11961. }
  11962. // every clip of the take: each click inside it against the nearest beat
  11963. int clips = 0, checked = 0, muted = 0;
  11964. double worst = 0.0, sum = 0.0;
  11965. for (const auto& c : s.playlist)
  11966. {
  11967. if (c.kind != lynx::ClipKind::audio || c.channel != take)
  11968. continue;
  11969. ++clips;
  11970. muted += c.muted ? 1 : 0;
  11971. const auto skip = ((double) c.offset + (double) c.offsetFraction) / tps; // file samples before the clip start
  11972. for (const auto f : peaks)
  11973. {
  11974. const auto intoClip = (double) f - skip;
  11975. if (intoClip < 0.0 || intoClip * tps >= (double) c.length)
  11976. continue;
  11977. const auto songTick = (double) c.start + intoClip * tps - 2.0 * tps; // (the pulse's peak is its 3rd sample)
  11978. const auto beat = std::round (songTick / lynx::ppq) * lynx::ppq;
  11979. const auto error = (songTick - beat) / tps;
  11980. worst = std::max (worst, std::abs (error));
  11981. sum += error;
  11982. ++checked;
  11983. }
  11984. step ("clip track " + juce::String (c.track) + " start " + juce::String ((juce::int64) c.start) + " length " + juce::String ((juce::int64) c.length)
  11985. + " offset " + juce::String ((juce::int64) c.offset) + juce::String (c.offsetFraction >= 0.0f ? "+" : "") + juce::String (c.offsetFraction, 4)
  11986. + (c.muted ? " (muted lane)" : ""));
  11987. }
  11988. step ("clicks_in_file=" + juce::String ((int) peaks.size()) + " checked=" + juce::String (checked) + " clips=" + juce::String (clips)
  11989. + " muted_lanes=" + juce::String (muted));
  11990. step ("placement_error_samples=max " + juce::String (worst, 3) + " mean " + juce::String (checked > 0 ? sum / checked : 0.0, 3));
  11991. auto ok = checked > 0 && worst <= 1.0 && engine->getLostRecordingFrames() == 0;
  11992. if (mode == 2) // one clip, exactly the punch range, its 8 beats
  11993. {
  11994. const auto& sp = engine->getSong();
  11995. bool exact = false;
  11996. for (const auto& c : sp.playlist)
  11997. if (c.kind == lynx::ClipKind::audio && c.channel == take)
  11998. exact = c.start == sp.loopStart && c.start + c.length == sp.loopEnd;
  11999. step (juce::String ("punch_clip_matches_range=") + (exact ? "yes" : "no"));
  12000. ok = ok && clips == 1 && exact && checked == 8;
  12001. }
  12002. report.getSiblingFile (report.getFileNameWithoutExtension() + "-project.lynx").replaceWithText (lynx::ProjectFile::toJson (engine->getSong()));
  12003. step (juce::String ("result=") + (ok ? "OK" : "FAILED"));
  12004. finish (ok ? 0 : 1);
  12005. });
  12006. });
  12007. });
  12008. });
  12009. }
  12010. // --hwinserttest (round 164d): see the command line above.
  12011. void runHwInsertTest (const juce::File& report, double seconds, const juce::String& deviceType, const juce::String& deviceName,
  12012. const juce::String& inputName, int bufferSize, bool inPatcher = false, juce::File bounceFile = {})
  12013. {
  12014. engine = std::make_unique<lynx::AudioEngine>();
  12015. lynx::videoview::install (*engine); // (Fruity Video Player channels: their sound tracks)
  12016. savedDeviceState = engine->getDeviceManager().createStateXml();
  12017. auto text = std::make_shared<juce::String>();
  12018. auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
  12019. auto finish = [this] (int code) {
  12020. if (engine != nullptr)
  12021. engine->getMeters().capture.setSource (lynx::AudioCapture::off);
  12022. restoreSavedDeviceState();
  12023. setApplicationReturnValue (code);
  12024. quit();
  12025. };
  12026. auto& devices = engine->getDeviceManager();
  12027. if (deviceType.isNotEmpty() && devices.getCurrentAudioDeviceType() != deviceType)
  12028. devices.setCurrentAudioDeviceType (deviceType, true);
  12029. {
  12030. auto setup = devices.getAudioDeviceSetup();
  12031. if (deviceName.isNotEmpty())
  12032. setup.outputDeviceName = deviceName;
  12033. if (bufferSize > 0)
  12034. setup.bufferSize = bufferSize;
  12035. if (const auto error = devices.setAudioDeviceSetup (setup, true); error.isNotEmpty())
  12036. step ("device_error=" + error);
  12037. }
  12038. if (const auto r = engine->openAudioInput (inputName.isNotEmpty() ? inputName : deviceName); r.issue != lynx::AudioEngine::InputIssue::none)
  12039. step ("input_error=" + juce::String ((int) r.issue) + " " + r.detail);
  12040. auto* device = devices.getCurrentAudioDevice();
  12041. if (device == nullptr || engine->getInputChannelNames().empty())
  12042. {
  12043. step ("result=ERROR no device / no input");
  12044. finish (1);
  12045. return;
  12046. }
  12047. const auto rate = device->getCurrentSampleRate();
  12048. step ("device=" + device->getTypeName() + " | " + device->getName() + " | " + juce::String (rate) + " Hz | block " + juce::String (device->getCurrentBufferSizeSamples()));
  12049. // the click track: the ping's pulse on every beat at 120 bpm
  12050. const auto beats = (int) std::ceil (seconds * 2.0) + 8;
  12051. const auto clickFile = report.getSiblingFile (report.getFileNameWithoutExtension() + "-clicks.wav");
  12052. {
  12053. lynx::takes::WavTakeWriter w;
  12054. w.open (clickFile.getFullPathName().toStdString(), rate, 1, lynx::takes::SampleFormat::float32);
  12055. const auto total = (juce::int64) std::llround ((double) beats * rate / 2.0);
  12056. std::vector<float> block (4096);
  12057. for (juce::int64 at = 0; at < total; at += (juce::int64) block.size())
  12058. {
  12059. std::fill (block.begin(), block.end(), 0.0f);
  12060. for (int k = 0; k < (int) block.size(); ++k)
  12061. {
  12062. const auto f = at + k;
  12063. const auto beat = (juce::int64) std::floor ((double) f / (rate / 2.0));
  12064. const auto rel = f - (juce::int64) std::llround ((double) beat * rate / 2.0);
  12065. static constexpr float shape[] { 0.25f, 0.75f, 1.0f, 0.75f, 0.25f };
  12066. if (rel >= 0 && rel < 5)
  12067. block[(std::size_t) k] = 0.5f * shape[rel];
  12068. }
  12069. const float* d[] { block.data() };
  12070. w.write (d, (int) std::min<juce::int64> ((juce::int64) block.size(), total - at));
  12071. }
  12072. w.close();
  12073. }
  12074. lynx::Song song = lynx::Song::makeDefault();
  12075. song.bpm = 120.0;
  12076. song.mode = lynx::PlayMode::song;
  12077. song.playlist.clear();
  12078. song.channels.clear();
  12079. for (int k = 0; k < 2; ++k)
  12080. {
  12081. lynx::ChannelDef c;
  12082. c.name = k == 0 ? "Wet" : "Dry";
  12083. c.instrument = lynx::InstrumentKind::audioClip;
  12084. c.samplePath = clickFile.getFullPathName().toStdString();
  12085. c.mixerTrack = k + 1;
  12086. c.volume = 1.0f;
  12087. song.channels.push_back (c);
  12088. lynx::Clip clip;
  12089. clip.kind = lynx::ClipKind::audio;
  12090. clip.channel = k;
  12091. clip.track = k;
  12092. clip.start = 0;
  12093. clip.length = (std::int64_t) beats * lynx::ppq;
  12094. song.playlist.push_back (clip);
  12095. }
  12096. song.mixer[0].outputChannel = lynx::outputNone; // (the cable carries the send only)
  12097. for (auto& fx : song.mixer[0].effects) // (no Master effects: the default limiter's PDC would hide nothing, but keep it plain)
  12098. fx.enabled = false;
  12099. song.mixer[1].pan = -1.0f;
  12100. song.mixer[2].pan = 1.0f;
  12101. auto hw = lynx::makeEffectSlot (lynx::EffectKind::hardwareInsert);
  12102. hw.params[lynx::hwinsert::output] = lynx::hwinsert::channelValue (0);
  12103. hw.params[lynx::hwinsert::input] = lynx::hwinsert::channelValue (0);
  12104. hw.params[lynx::hwinsert::inputStereo] = 1.0f;
  12105. song.mixer[1].effects.clear();
  12106. lynx::AudioEngine::HardwareInsertRef ref { false, 1, 0, {} };
  12107. if (inPatcher) // (round 165c) From LYNX -> Hardware Insert -> To LYNX
  12108. {
  12109. auto slot = lynx::makeEffectSlot (lynx::EffectKind::patcher);
  12110. lynx::PatchNode node;
  12111. node.effect = hw;
  12112. slot.patcher.nodes = { node };
  12113. lynx::PatchWire in, out;
  12114. in.from = lynx::patchFromHost;
  12115. in.to = 0;
  12116. out.from = 0;
  12117. out.to = lynx::patchToHost;
  12118. slot.patcher.wires = { in, out };
  12119. song.mixer[1].effects.push_back (slot);
  12120. ref.nodes = { 0 };
  12121. }
  12122. else
  12123. song.mixer[1].effects.push_back (hw);
  12124. engine->setSong (std::move (song));
  12125. step (juce::String ("insert=") + (inPatcher ? "inside a Patcher on Insert 1" : "Insert 1 slot 1"));
  12126. const auto meter = [this, ref] (int output) {
  12127. const auto fx = engine->runningHardwareInsert (ref);
  12128. return fx != nullptr ? fx->controlOutput (output) : 0.0f;
  12129. };
  12130. // 1) the insert's ping (as its Ping button: a momentary value flipped)
  12131. juce::Timer::callAfterDelay (500, [this, report, step, finish, seconds, rate, meter, ref, inPatcher, bounceFile] {
  12132. if (engine == nullptr)
  12133. return;
  12134. engine->pingHardwareInserts ({ ref });
  12135. juce::Timer::callAfterDelay (3500, [this, report, step, finish, seconds, rate, meter, ref, inPatcher, bounceFile] {
  12136. if (engine == nullptr)
  12137. return;
  12138. // (round 165c) the engine makes a ping's result the slot's round trip with the device setup it belongs to; the
  12139. // new round trip rebuilds the insert (its latency), so the result is read from the slot
  12140. const auto* slot = lynx::AudioEngine::locateHardwareInsert (const_cast<lynx::Song&> (engine->getSong()), ref);
  12141. const auto samples = slot != nullptr ? lynx::hwinsert::roundTripOf (slot->params[lynx::hwinsert::roundTrip]) : 0;
  12142. const auto setup = slot != nullptr ? lynx::hwinsert::measuredSetup (*slot) : std::string();
  12143. const auto state = meter (lynx::hwinsert::pingState);
  12144. const auto ok = samples > 0 && setup == engine->currentSetupKey();
  12145. step ("ping_round_trip=" + juce::String (samples) + " measured_setup=" + juce::String (setup) + (ok ? " (ok)" : " (FAILED)")
  12146. + " live_ping_state=" + juce::String (state, 3) + " status_flags=" + juce::String (juce::roundToInt (meter (lynx::hwinsert::status) * 16.0f)));
  12147. if (! ok)
  12148. {
  12149. step ("result=FAILED ping");
  12150. finish (1);
  12151. return;
  12152. }
  12153. // a stale setup is noticed: another setup key on the slot gives the notice, the real one none
  12154. step ("stale_now=" + juce::String ((int) engine->staleHardwareInserts().size()));
  12155. // 2) play, capturing the Master
  12156. juce::Timer::callAfterDelay (500, [this, report, step, finish, seconds, rate, samples, ref, inPatcher, bounceFile] {
  12157. if (engine == nullptr)
  12158. return;
  12159. step ("pdc_total=" + juce::String (engine->getLatencySamples()) + " (expected " + juce::String (samples) + ")");
  12160. // saved in the project: the slot comes back the same (routing, round trip), and its latency with it — also an
  12161. // odd round trip (12345 samples: the project keeps it to the sample)
  12162. if (! inPatcher)
  12163. {
  12164. auto odd = engine->getSong();
  12165. odd.mixer[1].effects[0].params[lynx::hwinsert::roundTrip] = lynx::hwinsert::roundTripValue (12345);
  12166. juce::String error;
  12167. auto same = true;
  12168. for (const auto* song : { &engine->getSong(), (const lynx::Song*) &odd })
  12169. {
  12170. const auto file = report.getSiblingFile (report.getFileNameWithoutExtension() + (song == &odd ? "-odd.lynx" : ".lynx"));
  12171. const auto saved = lynx::ProjectFile::save (*song, file, error);
  12172. const auto loaded = saved ? lynx::ProjectFile::load (file, error) : std::nullopt;
  12173. same = same && loaded && loaded->mixer.size() > 1 && ! loaded->mixer[1].effects.empty()
  12174. && loaded->mixer[1].effects[0].kind == lynx::EffectKind::hardwareInsert
  12175. && loaded->mixer[1].effects[0].params == song->mixer[1].effects[0].params
  12176. && lynx::makeEffect (loaded->mixer[1].effects[0])->latencySamples() == (song == &odd ? 12345 : samples);
  12177. }
  12178. const auto file = report.getSiblingFile (report.getFileNameWithoutExtension() + ".lynx");
  12179. step (juce::String ("project_round_trip=") + (same ? "same" : "DIFFERENT " + error) + " (" + file.getFileName() + ")");
  12180. if (! same)
  12181. {
  12182. step ("result=FAILED project");
  12183. finish (1);
  12184. return;
  12185. }
  12186. }
  12187. auto left = std::make_shared<std::vector<float>>(), right = std::make_shared<std::vector<float>>();
  12188. engine->stop();
  12189. engine->rewind();
  12190. engine->getMeters().capture.setSource (0);
  12191. engine->play();
  12192. auto pulls = std::make_shared<int> ((int) (seconds * 5.0));
  12193. auto pull = std::make_shared<std::function<void()>>();
  12194. *pull = [this, report, step, finish, seconds, rate, samples, left, right, pulls, pull, ref, inPatcher, bounceFile] {
  12195. if (engine == nullptr)
  12196. return;
  12197. engine->getMeters().capture.pull (*left, *right);
  12198. if (*pulls == 10) // the insert's editor while it plays (next to the report)
  12199. for (const auto scale : { 1.0f, 1.5f })
  12200. {
  12201. auto editor = inPatcher ? lynx::makeNodeEffectEditor (
  12202. *engine, [ref] (lynx::Song& s) { return lynx::AudioEngine::locateHardwareInsert (s, ref); },
  12203. [this, ref] { return engine->runningHardwareInsert (ref); }, "Insert 1 (Patcher)", scale)
  12204. : lynx::makeNativeEffectEditor (*engine, 1, 0, scale, 0);
  12205. juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
  12206. {
  12207. juce::Graphics g (image);
  12208. g.fillAll (lynx::theme::panel);
  12209. editor->paintEntireComponent (g, false);
  12210. }
  12211. const auto file = report.getSiblingFile (report.getFileNameWithoutExtension() + (scale > 1.0f ? "-editor150.png" : "-editor.png"));
  12212. file.deleteFile();
  12213. juce::PNGImageFormat png;
  12214. if (auto stream = file.createOutputStream())
  12215. png.writeImageToStream (image, *stream);
  12216. }
  12217. if (--*pulls > 0)
  12218. {
  12219. juce::Timer::callAfterDelay (200, *pull);
  12220. return;
  12221. }
  12222. engine->stop();
  12223. const auto dropped = engine->getMeters().capture.droppedFrames();
  12224. engine->getMeters().capture.setSource (lynx::AudioCapture::off);
  12225. // the clicks of each side (peaks above -12 dBFS, one per 1/8 s at most)
  12226. auto peaksOf = [rate] (const std::vector<float>& x) {
  12227. std::vector<juce::int64> peaks;
  12228. for (std::size_t f = 1; f + 1 < x.size(); ++f)
  12229. 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])
  12230. && (peaks.empty() || (juce::int64) f - peaks.back() > (juce::int64) (rate / 8)))
  12231. peaks.push_back ((juce::int64) f);
  12232. return peaks;
  12233. };
  12234. const auto wet = peaksOf (*left), dry = peaksOf (*right);
  12235. int pairs = 0;
  12236. juce::int64 worst = 0;
  12237. double gainSum = 0.0, residual = 0.0, energy = 0.0;
  12238. for (const auto w : wet)
  12239. {
  12240. 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); });
  12241. if (best == dry.end() || std::abs (*best - w) > (juce::int64) (rate / 8))
  12242. continue;
  12243. ++pairs;
  12244. worst = std::max (worst, std::abs (*best - w));
  12245. gainSum += (*left)[(std::size_t) w] / (*right)[(std::size_t) *best];
  12246. }
  12247. const auto gain = pairs > 0 ? gainSum / pairs : 1.0;
  12248. // dry clicks with no wet click beside them (a dropout of the cable / device), listed
  12249. juce::String unmatched;
  12250. for (const auto d : dry)
  12251. if (std::none_of (wet.begin(), wet.end(), [d, rate] (juce::int64 w) { return std::abs (w - d) <= (juce::int64) (rate / 8); }))
  12252. unmatched << " " << (juce::int64) d << " (" << juce::String ((*left)[(std::size_t) d], 3) << ")";
  12253. if (unmatched.isNotEmpty())
  12254. step ("dry_clicks_without_wet=" + unmatched);
  12255. // the null test: left − gain · right around each click (both sides aligned → only the cable's colour remains)
  12256. for (const auto w : wet)
  12257. for (juce::int64 f = std::max<juce::int64> (0, w - 16); f < std::min<juce::int64> ((juce::int64) left->size(), w + 16); ++f)
  12258. {
  12259. const auto d = (double) (*left)[(std::size_t) f] - gain * (double) (*right)[(std::size_t) f];
  12260. residual += d * d;
  12261. energy += (double) (*left)[(std::size_t) f] * (*left)[(std::size_t) f];
  12262. }
  12263. const auto nullDb = energy > 0.0 ? 10.0 * std::log10 (std::max (1e-30, residual / energy)) : 0.0;
  12264. step ("captured=" + juce::String ((int) left->size()) + " frames dropped=" + juce::String (dropped) + " wet_clicks=" + juce::String ((int) wet.size())
  12265. + " dry_clicks=" + juce::String ((int) dry.size()) + " pairs=" + juce::String (pairs));
  12266. step ("alignment_error_samples=max " + juce::String ((int) worst) + " cable_gain=" + juce::String (gain, 4) + " null_residual_db=" + juce::String (nullDb, 1));
  12267. auto* dev = engine->getDeviceManager().getCurrentAudioDevice();
  12268. const auto xruns = dev != nullptr ? dev->getXRunCount() : -1;
  12269. step ("device_xruns=" + juce::String (xruns) + " (a dropout loses what was on the cable then: its clicks are excused)");
  12270. const auto excused = xruns > 0 ? 2 * xruns : 0;
  12271. const auto ok = pairs >= (int) (seconds * 2.0) - 2 - excused && worst == 0 && dropped == 0 && engine->getLatencySamples() == samples;
  12272. step (juce::String ("result=") + (ok ? "OK" : "FAILED"));
  12273. // (round 165c) then the re-ping notice after a buffer size change
  12274. auto then = [this, ref, step, finish] (int code) {
  12275. if (code != 0)
  12276. finish (code);
  12277. else
  12278. runRepingCheck (ref, step, finish);
  12279. };
  12280. if (! ok)
  12281. {
  12282. finish (1);
  12283. return;
  12284. }
  12285. if (bounceFile == juce::File())
  12286. then (0);
  12287. else
  12288. runBounceCheck (bounceFile, step, then);
  12289. };
  12290. juce::Timer::callAfterDelay (200, *pull);
  12291. });
  12292. });
  12293. });
  12294. }
  12295. // --hwinserttest --bounce (round 165c): Export › "Render through the hardware in real time" of the test song next to
  12296. // the offline export of the same song. Through the loopback cable (gain 1) the return is the send delayed by the
  12297. // pinged round trip, so the real-time file must equal the offline one (which passes the dry signal at that delay)
  12298. // to float rounding, with the wet clicks (left) on the dry clicks' samples (right).
  12299. // --hwinserttest (round 165c): the buffer size changes (another round trip on the device): the engine notices the
  12300. // insert measured for the old setup (the app's "Ping now?" prompt), "Ping now" measures it again for the new one
  12301. void runRepingCheck (lynx::AudioEngine::HardwareInsertRef ref, std::function<void (const juce::String&)> step, std::function<void (int)> finish)
  12302. {
  12303. auto& devices = engine->getDeviceManager();
  12304. auto setup = devices.getAudioDeviceSetup();
  12305. const auto before = setup.bufferSize;
  12306. setup.bufferSize = before == 512 ? 256 : 512;
  12307. if (const auto error = devices.setAudioDeviceSetup (setup, true); error.isNotEmpty())
  12308. step ("reping_device_error=" + error);
  12309. engine->takeHardwareInsertNotice(); // (whatever was pending before the change)
  12310. juce::Timer::callAfterDelay (1500, [this, ref, step, finish, before] {
  12311. if (engine == nullptr)
  12312. return;
  12313. auto* device = engine->getDeviceManager().getCurrentAudioDevice();
  12314. const auto block = device != nullptr ? device->getCurrentBufferSizeSamples() : 0;
  12315. const auto notice = engine->takeHardwareInsertNotice();
  12316. step ("reping_buffer=" + juce::String (before) + "->" + juce::String (block) + " notice=" + juce::String ((int) notice.size())
  12317. + " stale=" + juce::String ((int) engine->staleHardwareInserts().size()));
  12318. if (notice.size() != 1 || ! (notice[0] == ref))
  12319. {
  12320. step ("result_reping=FAILED (no notice)");
  12321. finish (1);
  12322. return;
  12323. }
  12324. engine->pingHardwareInserts (notice); // ("Ping now")
  12325. juce::Timer::callAfterDelay (3500, [this, ref, step, finish, block] {
  12326. if (engine == nullptr)
  12327. return;
  12328. const auto* slot = lynx::AudioEngine::locateHardwareInsert (const_cast<lynx::Song&> (engine->getSong()), ref);
  12329. const auto samples = slot != nullptr ? lynx::hwinsert::roundTripOf (slot->params[lynx::hwinsert::roundTrip]) : 0;
  12330. const auto stale = (int) engine->staleHardwareInserts().size();
  12331. step ("reping_round_trip=" + juce::String (samples) + " pdc_total=" + juce::String (engine->getLatencySamples()) + " stale=" + juce::String (stale));
  12332. const auto ok = stale == 0 && samples > 0 && engine->getLatencySamples() == samples;
  12333. step (juce::String ("result_reping=") + (ok ? "OK" : "FAILED") + " (device block " + juce::String (block) + ")");
  12334. finish (ok ? 0 : 1);
  12335. });
  12336. });
  12337. }
  12338. void runBounceCheck (const juce::File& bounceFile, std::function<void (const juce::String&)> step, std::function<void (int)> finish)
  12339. {
  12340. // the Export window as the user sees it with the real-time option ticked (next to the report)
  12341. lynx::showExportDialog (*engine, bounceFile.getParentDirectory(), "bounce", 0);
  12342. for (int k = 0; k < juce::TopLevelWindow::getNumTopLevelWindows(); ++k)
  12343. if (auto* w = juce::TopLevelWindow::getTopLevelWindow (k))
  12344. {
  12345. std::function<juce::ToggleButton* (juce::Component&)> find = [&find] (juce::Component& c) -> juce::ToggleButton* {
  12346. if (auto* t = dynamic_cast<juce::ToggleButton*> (&c); t != nullptr && t->getButtonText() == lynx::tr ("Render through the hardware in real time"))
  12347. return t;
  12348. for (auto* child : c.getChildren())
  12349. if (auto* t = find (*child))
  12350. return t;
  12351. return nullptr;
  12352. };
  12353. if (auto* toggle = find (*w))
  12354. {
  12355. step (juce::String ("export_option_visible=") + (toggle->isVisible() ? "yes" : "NO"));
  12356. toggle->setToggleState (true, juce::sendNotificationSync); // (calls its onClick, as a click)
  12357. auto* c = dynamic_cast<juce::DocumentWindow*> (w) != nullptr ? static_cast<juce::DocumentWindow*> (w)->getContentComponent() : w;
  12358. if (c != nullptr)
  12359. {
  12360. const auto file = bounceFile.getSiblingFile (bounceFile.getFileNameWithoutExtension() + "-export.png");
  12361. file.deleteFile();
  12362. juce::FileOutputStream out (file);
  12363. juce::PNGImageFormat png;
  12364. if (out.openedOk())
  12365. png.writeImageToStream (c->createComponentSnapshot (c->getLocalBounds()), out);
  12366. }
  12367. delete w;
  12368. break;
  12369. }
  12370. }
  12371. lynx::exportopts::Options o;
  12372. o.format = lynx::exportopts::Format::wav;
  12373. o.wavBits = 32;
  12374. o.dither = lynx::exportopts::DitherMode::none;
  12375. o.tail = lynx::exportopts::TailMode::cut;
  12376. o.range = lynx::exportopts::Range::song;
  12377. o.trimPdc = true;
  12378. o.hqAllPlugins = false;
  12379. o.pluginWarmUp = false;
  12380. const auto offlineFile = bounceFile.getSiblingFile (bounceFile.getFileNameWithoutExtension() + "-offline.wav");
  12381. auto realtimeJob = std::make_shared<lynx::ExportJob> (*engine, o, bounceFile);
  12382. o.sampleRate = engine->getTransport().sampleRate.load();
  12383. auto offlineJob = std::make_shared<lynx::ExportJob> (engine->getSong(), o, offlineFile);
  12384. struct Shared
  12385. {
  12386. std::atomic<int> done { 0 };
  12387. bool okRealtime = false, okOffline = false;
  12388. juce::String errorRealtime, errorOffline;
  12389. double lastProgress = 0.0;
  12390. double started = juce::Time::getMillisecondCounterHiRes();
  12391. };
  12392. auto shared = std::make_shared<Shared>();
  12393. // (the jobs stay owned by the message thread's poll below: they are destroyed there)
  12394. juce::Thread::launch ([rt = realtimeJob.get(), off = offlineJob.get(), shared] {
  12395. shared->okRealtime = rt->run ([shared] (double p) { shared->lastProgress = p; return true; }, shared->errorRealtime);
  12396. shared->okOffline = off->run ({}, shared->errorOffline);
  12397. shared->done.store (1);
  12398. });
  12399. auto poll = std::make_shared<std::function<void()>>();
  12400. *poll = [this, poll, shared, realtimeJob, offlineJob, bounceFile, offlineFile, step, finish] {
  12401. if (shared->done.load() == 0)
  12402. {
  12403. juce::Timer::callAfterDelay (100, *poll);
  12404. return;
  12405. }
  12406. const auto seconds = (juce::Time::getMillisecondCounterHiRes() - shared->started) / 1000.0;
  12407. step ("bounce_realtime=" + juce::String (shared->okRealtime ? "ok" : "FAILED " + shared->errorRealtime) + " offline="
  12408. + juce::String (shared->okOffline ? "ok" : "FAILED " + shared->errorOffline) + " took=" + juce::String (seconds, 1) + " s (music "
  12409. + juce::String (realtimeJob->getMusicSeconds(), 1) + " s)" + (realtimeJob->getNotice().isNotEmpty() ? " notice=" + realtimeJob->getNotice() : juce::String()));
  12410. juce::AudioFormatManager formats;
  12411. formats.registerBasicFormats();
  12412. std::unique_ptr<juce::AudioFormatReader> a (formats.createReaderFor (bounceFile)), b (formats.createReaderFor (offlineFile));
  12413. if (! shared->okRealtime || ! shared->okOffline || a == nullptr || b == nullptr)
  12414. {
  12415. step ("result=FAILED bounce");
  12416. finish (1);
  12417. return;
  12418. }
  12419. const auto frames = (int) std::min (a->lengthInSamples, b->lengthInSamples);
  12420. juce::AudioBuffer<float> x (2, frames), y (2, frames);
  12421. a->read (&x, 0, frames, 0, true, true);
  12422. b->read (&y, 0, frames, 0, true, true);
  12423. double residual = 0.0, energy = 0.0, wetDry = 0.0;
  12424. for (int ch = 0; ch < 2; ++ch)
  12425. for (int i = 0; i < frames; ++i)
  12426. {
  12427. const double d = x.getSample (ch, i) - y.getSample (ch, i);
  12428. residual += d * d;
  12429. energy += (double) y.getSample (ch, i) * y.getSample (ch, i);
  12430. }
  12431. for (int i = 0; i < frames; ++i) // the wet side against the dry side of the real-time file
  12432. wetDry += std::pow ((double) x.getSample (0, i) - x.getSample (1, i), 2.0);
  12433. const auto db = [energy] (double r) { return energy > 0.0 ? 10.0 * std::log10 (std::max (1e-30, r / energy)) : 0.0; };
  12434. step ("bounce_frames=" + juce::String ((juce::int64) a->lengthInSamples) + " offline_frames=" + juce::String ((juce::int64) b->lengthInSamples)
  12435. + " rate=" + juce::String (a->sampleRate) + " bounce_vs_offline_db=" + juce::String (db (residual), 1)
  12436. + " wet_vs_dry_db=" + juce::String (db (2.0 * wetDry), 1) + " peak=" + juce::String (realtimeJob->getPeak(), 3));
  12437. const auto ok = std::abs (a->lengthInSamples - b->lengthInSamples) <= 1 && db (residual) < -100.0 && realtimeJob->getPeak() > 0.1f;
  12438. step (juce::String ("result_bounce=") + (ok ? "OK" : "FAILED"));
  12439. finish (ok ? 0 : 1);
  12440. };
  12441. juce::Timer::callAfterDelay (100, *poll);
  12442. }
  12443. // --rtstress --record: stops recording (the take becomes a clip of the song, as in the app), moves the take's WAV to
  12444. // `target` and describes it: length against the time played, channels, peak, the latencies the driver reported.
  12445. juce::String finishStressTake (const juce::File& target, double seconds)
  12446. {
  12447. juce::String text;
  12448. auto* device = engine->getDeviceManager().getCurrentAudioDevice();
  12449. text << " recording: input " << (device != nullptr ? device->getActiveInputChannels().countNumberOfSetBits() : 0) << " channel(s)";
  12450. if (device != nullptr)
  12451. text << ", input latency " << device->getInputLatencyInSamples() << " + output latency " << device->getOutputLatencyInSamples() << " samples";
  12452. engine->setRecording (false); // closes the take: a clip of the song
  12453. juce::File take;
  12454. for (const auto& c : engine->getSong().channels)
  12455. if (c.instrument == lynx::InstrumentKind::audioClip)
  12456. take = juce::File (juce::String::fromUTF8 (c.samplePath.c_str()));
  12457. if (! take.existsAsFile())
  12458. return text + "\n recording: no take (" + engine->getLastRecordingError() + ")\n";
  12459. target.deleteFile();
  12460. if (! take.moveFileTo (target))
  12461. take.copyFileTo (target);
  12462. juce::AudioFormatManager formats;
  12463. formats.registerBasicFormats();
  12464. if (std::unique_ptr<juce::AudioFormatReader> reader (formats.createReaderFor (target)); reader != nullptr)
  12465. {
  12466. juce::AudioBuffer<float> audio ((int) reader->numChannels, (int) reader->lengthInSamples);
  12467. reader->read (&audio, 0, (int) reader->lengthInSamples, 0, true, true);
  12468. const auto peak = audio.getMagnitude (0, audio.getNumSamples());
  12469. const auto length = (double) reader->lengthInSamples / reader->sampleRate;
  12470. text << "\n recording: take " << juce::String (length, 3) << " s of " << juce::String (seconds, 0) << " s played, "
  12471. << (int) reader->numChannels << " ch @ " << (int) reader->sampleRate << " Hz, peak "
  12472. << juce::String (juce::Decibels::gainToDecibels (peak, -150.0f), 1) << " dBFS -> " << target.getFullPathName() << "\n";
  12473. }
  12474. else
  12475. text << "\n recording: take unreadable (" << target.getFullPathName() << ")\n";
  12476. return text;
  12477. }
  12478. // LYNX.exe --render project.(flp|lynx) output.wav [seconds]
  12479. // Exports the current pattern to 24-bit WAV (for an imported .flp, the one with the most notes).
  12480. void runRender (const juce::String& inputPath, const juce::String& outputPath, double seconds)
  12481. {
  12482. lynx::AudioEngine offline (false);
  12483. const juce::File input (inputPath);
  12484. juce::String error, report;
  12485. bool ok = false;
  12486. if (input.hasFileExtension ("flp;als;flm;songtmpl"))
  12487. ok = offline.importFlpFile (input, error);
  12488. else if (auto song = lynx::ProjectFile::load (input, error))
  12489. {
  12490. offline.setSong (std::move (*song));
  12491. ok = true;
  12492. }
  12493. int samplers = 0, samplersLoaded = 0;
  12494. if (ok)
  12495. {
  12496. for (const auto& c : offline.getSong().channels)
  12497. if (c.instrument == lynx::InstrumentKind::sampler || c.instrument == lynx::InstrumentKind::audioClip)
  12498. {
  12499. ++samplers;
  12500. samplersLoaded += offline.getSampleLibrary().load (juce::String::fromUTF8 (c.samplePath.c_str())) != nullptr;
  12501. }
  12502. const juce::File output (outputPath);
  12503. output.deleteFile();
  12504. juce::WavAudioFormat wav;
  12505. std::unique_ptr<juce::AudioFormatWriter> writer (
  12506. wav.createWriterFor (output.createOutputStream().release(), 44100.0, 2, 24, {}, 0));
  12507. if (writer == nullptr)
  12508. {
  12509. ok = false;
  12510. error = lynx::utf8 ("could not create ") + outputPath;
  12511. }
  12512. else
  12513. {
  12514. const auto peak = offline.renderOffline (seconds > 0.0 ? seconds : 10.0, 44100.0, writer.get());
  12515. report << "peak=" << peak << "\n";
  12516. ok = peak > 0.001f;
  12517. }
  12518. }
  12519. report << "samples=" << samplersLoaded << "/" << samplers << "\n"
  12520. << "result=" << (ok ? "OK" : "ERROR " + error) << "\n";
  12521. juce::File (outputPath + ".txt").replaceWithText (report);
  12522. setApplicationReturnValue (ok ? 0 : 1);
  12523. quit();
  12524. }
  12525. // LYNX.exe --export-flp project.(lynx|flp|als) output.(flp|zip) [--substitute] (round 171e): File › Export › FL Studio
  12526. // project without the window (option A unless --substitute; the renders next to a .flp in "<name> audio"); the
  12527. // report goes to output.txt
  12528. void runAlsExport (const juce::String& inputPath, const juce::String& folderPath, bool live11, bool reference)
  12529. {
  12530. juce::String error;
  12531. juce::StringArray notes;
  12532. juce::File als;
  12533. {
  12534. lynx::AudioEngine loader (false);
  12535. const juce::File input (inputPath);
  12536. bool ok = false;
  12537. // --scan: the targeted plugin scan an open runs first (child processes), so the set's plugins load
  12538. if (juce::JUCEApplication::getCommandLineParameterArray().contains ("--scan") && input.hasFileExtension ("flp;als;flm;songtmpl"))
  12539. {
  12540. juce::MemoryBlock data;
  12541. if (input.loadFileAsData (data))
  12542. {
  12543. const std::vector<std::uint8_t> bytes (static_cast<const std::uint8_t*> (data.getData()),
  12544. static_cast<const std::uint8_t*> (data.getData()) + data.getSize());
  12545. try
  12546. {
  12547. const auto uses = input.hasFileExtension ("als") ? lynx::alsForeignPlugins (bytes)
  12548. : lynx::flpForeignPlugins (flp::parseProject ({ bytes.data(), bytes.size() }));
  12549. loader.getPluginHost().scanFiles (loader.getPluginHost().filesToScanFor (uses), {});
  12550. }
  12551. catch (const std::exception&)
  12552. {
  12553. }
  12554. }
  12555. }
  12556. if (input.hasFileExtension ("flp;als;flm;songtmpl"))
  12557. ok = loader.importFlpFile (input, error);
  12558. else if (auto song = lynx::ProjectFile::load (input, error))
  12559. {
  12560. loader.setSong (std::move (*song));
  12561. ok = true;
  12562. }
  12563. if (ok)
  12564. {
  12565. loader.capturePluginStates();
  12566. const juce::File folder (folderPath);
  12567. folder.createDirectory();
  12568. als = lynx::writeAlsProject (loader.getSong(), &loader.getPluginHost(), live11 ? lynx::AlsVersion::live11 : lynx::AlsVersion::live12, ! reference, folder,
  12569. input.getFileNameWithoutExtension(), notes, error);
  12570. }
  12571. }
  12572. juce::String report;
  12573. report << (als != juce::File() ? "ok " + als.getFullPathName() : "error=" + error) << "\n" << notes.joinIntoString ("\n") << "\n";
  12574. juce::File (folderPath).getChildFile ("export-als.txt").replaceWithText (report);
  12575. setApplicationReturnValue (als != juce::File() ? 0 : 1);
  12576. quit();
  12577. }
  12578. // --versionsshot <prefix> (round 190ap): everything the round adds, offscreen (no window on the desktop):
  12579. // -versions.png / -versions-unsaved.png the Versions panel (a project with versions, backups and labels; a new one)
  12580. // -menu-file.png / -menu-file-pluginsoff.png the File menu, and as it is while the plugins are off
  12581. // -pluginsoff-window.png / -pluginsoff-mixer.png a project opened without its third-party plugins (the tags)
  12582. // -pluginsoff-panel.png / -pluginsoff-panel-one.png the list, all off, then after "Switch on" for one
  12583. // -export-default.png / -export.png the Export window as it opens, and with the additions in use
  12584. bool runLinkShot (const juce::String& prefix)
  12585. {
  12586. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  12587. juce::StringArray report;
  12588. bool allOk = true;
  12589. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  12590. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  12591. allOk = allOk && ok;
  12592. };
  12593. const auto shoot = [&prefix] (juce::Component& c, const char* name) {
  12594. savePng (c.createComponentSnapshot (c.getLocalBounds()), prefix + "-" + name + ".png");
  12595. };
  12596. using lynx::AutomationTarget;
  12597. using lynx::AutomationTargetKind;
  12598. using lynx::MidiLink;
  12599. lynx::AudioEngine engine (false);
  12600. const AutomationTarget volume { AutomationTargetKind::channelVolume, 0 }, pan { AutomationTargetKind::channelPan, 0 },
  12601. insert { AutomationTargetKind::mixerVolume, 1 };
  12602. // ---- the window as it opens on a control with no link (FL's defaults)
  12603. {
  12604. auto panel = lynx::makeRemoteControlPanel (engine, { volume }, false);
  12605. shoot (*panel, "remote-default");
  12606. check ("default_state", lynx::remoteControlPanelState (*panel).startsWith ("-1|1|-1|Input|"), lynx::remoteControlPanelState (*panel));
  12607. // Auto detect: the controller that sends next fills the fields
  12608. engine.injectControllerForTest (74, 2, 100, 5);
  12609. lynx::remoteControlPanelPoll (*panel);
  12610. check ("auto_detect", lynx::remoteControlPanelState (*panel).startsWith ("5|3|74|"), lynx::remoteControlPanelState (*panel));
  12611. // a formula preset, smoothing; Accept writes the link
  12612. lynx::remoteControlPanelSetController (*panel, -1, 1, 7);
  12613. lynx::remoteControlPanelSetFormula (*panel, "Tension(Input,10)");
  12614. lynx::remoteControlPanelSetSmoothing (*panel, true, 469);
  12615. shoot (*panel, "remote-formula-smoothing");
  12616. lynx::remoteControlPanelPress (*panel, 2);
  12617. const auto& links = engine.getSong().midiLinks;
  12618. check ("accept_writes_link", links.size() == 1 && links[0].cc == 7 && links[0].channel == 0 && links[0].port == -1
  12619. && links[0].formula == "Tension(Input,10)" && links[0].smooth && links[0].target == volume);
  12620. }
  12621. // ---- a broken formula: the message, the red text
  12622. {
  12623. auto panel = lynx::makeRemoteControlPanel (engine, { volume }, false);
  12624. lynx::remoteControlPanelSetFormula (*panel, "Min(Input*2,");
  12625. shoot (*panel, "remote-formula-error");
  12626. check ("formula_error_shown", ! lynx::remoteControlPanelState (*panel).contains ("Compiled ok."), lynx::remoteControlPanelState (*panel));
  12627. }
  12628. // ---- the engine: formula, port, conflicts, omni
  12629. {
  12630. engine.editSong ([&] (lynx::Song& s) {
  12631. s.midiLinks.clear();
  12632. MidiLink inverted { 20, 0, volume };
  12633. inverted.formula = "1-Input";
  12634. MidiLink ported { 21, 0, pan };
  12635. ported.port = 3;
  12636. s.midiLinks = { inverted, ported };
  12637. });
  12638. engine.injectControllerForTest (20, 0, 127);
  12639. check ("formula_inverts", std::abs (engine.currentTargetValue (volume)) < 0.01f, juce::String (engine.currentTargetValue (volume)));
  12640. engine.injectControllerForTest (20, 0, 0);
  12641. check ("formula_inverts_back", std::abs (engine.currentTargetValue (volume) - 1.0f) < 0.01f, juce::String (engine.currentTargetValue (volume)));
  12642. const auto panBefore = engine.currentTargetValue (pan);
  12643. engine.injectControllerForTest (21, 0, 127); // no port: not this link's device
  12644. check ("port_must_match", std::abs (engine.currentTargetValue (pan) - panBefore) < 0.001f);
  12645. engine.injectControllerForTest (21, 0, 127, 3);
  12646. check ("port_matches", std::abs (engine.currentTargetValue (pan) - 1.0f) < 0.01f, juce::String (engine.currentTargetValue (pan)));
  12647. // the window on a control whose controller another control uses: Remove conflicts in red; Accept removes it
  12648. auto panel = lynx::makeRemoteControlPanel (engine, { insert }, false);
  12649. lynx::remoteControlPanelSetController (*panel, -1, 1, 20);
  12650. shoot (*panel, "remote-conflict");
  12651. check ("conflict_counted", lynx::remoteControlPanelState (*panel).contains ("|1|"), lynx::remoteControlPanelState (*panel));
  12652. lynx::remoteControlPanelPress (*panel, 2);
  12653. const auto& links = engine.getSong().midiLinks;
  12654. check ("conflict_removed", links.size() == 2
  12655. && std::none_of (links.begin(), links.end(), [&] (const MidiLink& l) { return l.target == volume; })
  12656. && std::any_of (links.begin(), links.end(), [&] (const MidiLink& l) { return l.target == insert && l.cc == 20; }));
  12657. engine.undo();
  12658. check ("accept_is_one_undo_step", engine.getSong().midiLinks.size() == 2 && engine.getSong().midiLinks[0].target == volume);
  12659. }
  12660. // ---- an existing link opened again: "Link 1" / "New link"
  12661. {
  12662. auto panel = lynx::makeRemoteControlPanel (engine, { volume }, false);
  12663. shoot (*panel, "remote-existing-link");
  12664. check ("existing_link_loaded", lynx::remoteControlPanelState (*panel).startsWith ("-1|1|20|1-Input|"), lynx::remoteControlPanelState (*panel));
  12665. // Reset, then Accept: a link without a controller is removed
  12666. lynx::remoteControlPanelPress (*panel, 0);
  12667. check ("reset_state", lynx::remoteControlPanelState (*panel).startsWith ("-1|1|-1|Input|"), lynx::remoteControlPanelState (*panel));
  12668. lynx::remoteControlPanelPress (*panel, 2);
  12669. const auto& links = engine.getSong().midiLinks;
  12670. check ("reset_accept_unlinks", std::none_of (links.begin(), links.end(), [&] (const MidiLink& l) { return l.target == volume; }));
  12671. }
  12672. // ---- several controls ("Link to controllers..."): Accept and Skip step through them
  12673. {
  12674. auto panel = lynx::makeRemoteControlPanel (engine, { volume, pan, insert }, false, [] {});
  12675. shoot (*panel, "remote-multilink");
  12676. const auto parameter = [&panel] { return juce::StringArray::fromTokens (lynx::remoteControlPanelState (*panel), "|", "")[6]; };
  12677. const auto first = parameter();
  12678. check ("multilink_caption_and_skip", first.startsWith ("1/3") && first.contains (lynx::tr ("Channel volume"))
  12679. && lynx::remoteControlPanelState (*panel).contains ("S|omni"),
  12680. lynx::remoteControlPanelState (*panel));
  12681. lynx::remoteControlPanelSetController (*panel, -1, 1, 30);
  12682. lynx::remoteControlPanelPress (*panel, 2); // Accept: volume linked, on to pan
  12683. const auto second = parameter();
  12684. lynx::remoteControlPanelPress (*panel, 1); // Skip: pan untouched, on to the insert
  12685. const auto third = parameter();
  12686. const auto beforeLast = lynx::remoteControlPanelFinished (*panel);
  12687. lynx::remoteControlPanelPress (*panel, 1); // Skip on the last one: done
  12688. const auto closed = ! beforeLast && lynx::remoteControlPanelFinished (*panel);
  12689. const auto& links = engine.getSong().midiLinks;
  12690. check ("multilink_steps", first != second && second != third && closed
  12691. && std::any_of (links.begin(), links.end(), [&] (const MidiLink& l) { return l.target == volume && l.cc == 30; }),
  12692. first + " > " + second + " > " + third);
  12693. }
  12694. // ---- Global link settings
  12695. {
  12696. auto panel = lynx::makeRemoteControlPanel (engine, { volume }, true);
  12697. shoot (*panel, "global-default");
  12698. lynx::remoteControlPanelSetController (*panel, 2, 1, 11);
  12699. lynx::remoteControlPanelSetFormula (*panel, "Input*0.5");
  12700. lynx::remoteControlPanelPress (*panel, 2);
  12701. const auto global = engine.globalLinkOf (volume);
  12702. check ("global_link_written", global && global->cc == 11 && global->port == 2 && global->formula == "Input*0.5");
  12703. const auto text = engine.getMidiPrefs().toText();
  12704. const auto back = lynx::prefs::MidiPrefs::fromText (text);
  12705. check ("global_link_settings_round_trip", back.globalLinks == engine.getMidiPrefs().globalLinks && text.find ("linkset=2|0|469|Input*0.5") != std::string::npos);
  12706. auto again = lynx::makeRemoteControlPanel (engine, { volume }, true);
  12707. shoot (*again, "global-existing-link");
  12708. engine.setGlobalLink (volume, std::nullopt);
  12709. check ("global_link_removed", ! engine.globalLinkOf (volume));
  12710. }
  12711. // ---- the project file: links with settings come back; a project of an older version loads the same
  12712. {
  12713. lynx::Song song = engine.getSong();
  12714. MidiLink plain { 7, -1, volume };
  12715. MidiLink rich { 74, 2, pan };
  12716. rich.port = 4;
  12717. rich.formula = "Min(Input*1.1,0.5)+Max(Input*1.1,0.6)-0.6";
  12718. rich.smooth = true;
  12719. rich.smoothing = -300;
  12720. rich.omni = true;
  12721. song.midiLinks = { plain, rich };
  12722. juce::String error;
  12723. const auto json = lynx::ProjectFile::toJson (song);
  12724. const auto back = lynx::ProjectFile::fromJson (json, error);
  12725. check ("project_round_trip", back && back->midiLinks == song.midiLinks, error);
  12726. // without settings the file holds only the list older versions wrote
  12727. song.midiLinks = { plain };
  12728. const auto plainJson = lynx::ProjectFile::toJson (song);
  12729. check ("plain_links_write_the_old_form", ! plainJson.contains ("midiLinkSettings") && plainJson.contains ("midiLinks"));
  12730. const auto plainBack = lynx::ProjectFile::fromJson (plainJson, error);
  12731. check ("old_project_loads_the_same", plainBack && plainBack->midiLinks.size() == 1 && plainBack->midiLinks[0] == plain
  12732. && ! plainBack->midiLinks[0].hasSettings());
  12733. // what an older version does with a new file: it reads "midiLinks" alone, so the links stay (plain)
  12734. auto parsed = juce::JSON::parse (json);
  12735. if (auto* o = parsed.getDynamicObject())
  12736. o->removeProperty ("midiLinkSettings");
  12737. const auto stripped = lynx::ProjectFile::fromJson (juce::JSON::toString (parsed), error);
  12738. check ("older_version_keeps_the_links", stripped && stripped->midiLinks.size() == 2 && stripped->midiLinks[1].cc == 74
  12739. && ! stripped->midiLinks[1].hasSettings());
  12740. }
  12741. // ---- round 190cs: FL's live answers (live check 190cq) and the note / button link modes
  12742. {
  12743. const auto state = [] (juce::Component& p) { return lynx::remoteControlPanelState (p); };
  12744. engine.editSong ([] (lynx::Song& s) { s.midiLinks.clear(); });
  12745. // the layout FL shows: no assignment list without a link, no Skip outside Multilink, no internal
  12746. // controller group without a controller in the project; the parameter caption in FL's words
  12747. auto fresh = lynx::makeRemoteControlPanel (engine, { volume }, false);
  12748. shoot (*fresh, "cs-remote-default");
  12749. check ("cs_layout_without_link", state (*fresh).contains ("|" + lynx::tr ("Channel volume") + "|") && state (*fresh).contains ("|shown=POC|"), state (*fresh));
  12750. // Omni: enabled on a mixer track's volume (FL: "Insert 1 - Volume"), greyed on the tempo
  12751. auto onInsert = lynx::makeRemoteControlPanel (engine, { insert }, false);
  12752. auto onTempo = lynx::makeRemoteControlPanel (engine, { AutomationTarget { AutomationTargetKind::tempo, 0 } }, false);
  12753. shoot (*onInsert, "cs-remote-omni-insert");
  12754. check ("cs_omni_mixer_track", state (*onInsert).contains ("|omni=on|") && state (*onTempo).contains ("|omni=off|"),
  12755. state (*onInsert) + " / " + state (*onTempo));
  12756. // the formula compiles on Enter only; FL's messages and colours
  12757. lynx::remoteControlPanelSetFormula (*fresh, "1-Input^2", false);
  12758. check ("cs_no_compile_while_typing", state (*fresh).contains ("|" + lynx::tr ("(default 1:1 mapping)") + "|"), state (*fresh));
  12759. lynx::remoteControlPanelSetFormula (*fresh, "-Input^2");
  12760. shoot (*fresh, "cs-remote-compiled");
  12761. check ("cs_compiled_on_enter", state (*fresh).contains ("|" + lynx::tr ("Compiled ok.") + "|"), state (*fresh));
  12762. const std::pair<const char*, const char*> errors[] { { "Input*", "Syntax error: function or operand" },
  12763. { "foo(Input)", "Invalid identifier: foo" },
  12764. { "Sin(Input", "Unequal brackets" },
  12765. { "Input 2", "input two space limited" } };
  12766. for (const auto& [text, expected] : errors)
  12767. {
  12768. lynx::remoteControlPanelSetFormula (*fresh, text);
  12769. check ("cs_fl_error_text", state (*fresh).contains (expected), state (*fresh));
  12770. }
  12771. lynx::remoteControlPanelSetFormula (*fresh, "foo(Input)");
  12772. shoot (*fresh, "cs-remote-error");
  12773. // Accept with that formula: the link is made, the formula is not kept (FL reopens it as "Input")
  12774. lynx::remoteControlPanelSetController (*fresh, -1, 1, 7);
  12775. lynx::remoteControlPanelPress (*fresh, 2);
  12776. check ("cs_bad_formula_accept_is_input", engine.getSong().midiLinks.size() == 1 && engine.getSong().midiLinks[0].cc == 7
  12777. && engine.getSong().midiLinks[0].formula.empty());
  12778. auto reopened = lynx::makeRemoteControlPanel (engine, { volume }, false);
  12779. shoot (*reopened, "cs-remote-reopened");
  12780. check ("cs_reopened_shows_input_and_link_list", state (*reopened).startsWith ("-1|1|7|Input|" + lynx::tr ("(default 1:1 mapping)") + "|")
  12781. && state (*reopened).contains ("|shown=PAOC|"),
  12782. state (*reopened));
  12783. // the internal controller group appears with a controller in the project, with "Record automation"
  12784. engine.editSong ([] (lynx::Song& s) {
  12785. lynx::EffectSlot peak;
  12786. peak.kind = lynx::EffectKind::peakController;
  12787. s.mixer[0].effects.push_back (peak);
  12788. });
  12789. auto withController = lynx::makeRemoteControlPanel (engine, { volume }, false);
  12790. lynx::remoteControlPanelSetInternal (*withController, 1, true);
  12791. shoot (*withController, "cs-remote-internal");
  12792. check ("cs_internal_group_shown", state (*withController).contains ("|shown=PAIOC|") && state (*withController).startsWith ("-1|1|-1|"),
  12793. state (*withController));
  12794. lynx::remoteControlPanelPress (*withController, 2);
  12795. const auto& autos = engine.getSong().automations;
  12796. check ("cs_record_automation_kept", std::any_of (autos.begin(), autos.end(), [&] (const lynx::Automation& a) {
  12797. return a.isLive() && a.target == volume && a.recordLive;
  12798. }));
  12799. engine.editSong ([] (lynx::Song& s) {
  12800. s.mixer[0].effects.pop_back();
  12801. s.automations.clear();
  12802. s.midiLinks.clear();
  12803. });
  12804. // the global window: no parameter list, Omni, Remove conflicts or Skip; Mode is there
  12805. auto globalPanel = lynx::makeRemoteControlPanel (engine, { volume }, true);
  12806. shoot (*globalPanel, "cs-global-default");
  12807. check ("cs_global_layout", state (*globalPanel).contains ("|shown=|"), state (*globalPanel));
  12808. // a key link in each Mode: note 60 = FL's controller number 256 + 60
  12809. const auto key = lynx::linkNoteBase + 60;
  12810. auto modePanel = lynx::makeRemoteControlPanel (engine, { volume }, false);
  12811. lynx::remoteControlPanelSetController (*modePanel, -1, 1, key);
  12812. lynx::remoteControlPanelSetMode (*modePanel, 2);
  12813. shoot (*modePanel, "cs-remote-note-latch");
  12814. lynx::remoteControlPanelPress (*modePanel, 2);
  12815. check ("cs_note_link_written", engine.getSong().midiLinks.size() == 1 && engine.getSong().midiLinks[0].cc == key
  12816. && engine.getSong().midiLinks[0].mode == 2);
  12817. const auto play = [&engine, key, volume] (int velocity) {
  12818. engine.injectControllerForTest (key, 0, velocity);
  12819. return engine.currentTargetValue (volume);
  12820. };
  12821. const auto setMode = [&engine] (int mode) {
  12822. engine.editSong ([mode] (lynx::Song& s) { s.midiLinks[0].mode = mode; });
  12823. engine.editSong ([] (lynx::Song& s) { s.setTargetValue ({ AutomationTargetKind::channelVolume, 0 }, 0.25f); });
  12824. };
  12825. setMode (2); // Latch: press switches, release does nothing
  12826. const auto l1 = play (100), l1off = play (0), l2 = play (90), l2off = play (0);
  12827. check ("cs_mode_latch", std::abs (l1 - 1.0f) < 1e-4f && std::abs (l1off - 1.0f) < 1e-4f && l2 < 1e-4f && l2off < 1e-4f,
  12828. juce::String (l1) + " " + juce::String (l1off) + " " + juce::String (l2) + " " + juce::String (l2off));
  12829. setMode (1); // Hold: the velocity while held, back to 0 on release
  12830. const auto h1 = play (100), h1off = play (0);
  12831. check ("cs_mode_hold", std::abs (h1 - 100.0f / 127.0f) < 1e-4f && h1off < 1e-4f, juce::String (h1) + " " + juce::String (h1off));
  12832. setMode (0); // Default: as Hold for a key
  12833. const auto d1 = play (64), d1off = play (0);
  12834. check ("cs_mode_default", std::abs (d1 - 64.0f / 127.0f) < 1e-4f && d1off < 1e-4f, juce::String (d1) + " " + juce::String (d1off));
  12835. setMode (3); // Inc: each press adds 1/128
  12836. const auto i1 = play (100), i1off = play (0), i2 = play (20);
  12837. check ("cs_mode_inc", std::abs (i1 - (0.25f + 1.0f / 128.0f)) < 1e-4f && std::abs (i1off - i1) < 1e-6f
  12838. && std::abs (i2 - (0.25f + 2.0f / 128.0f)) < 1e-4f,
  12839. juce::String (i1) + " " + juce::String (i2));
  12840. setMode (4); // Stay: the velocity, kept after the release
  12841. const auto s1 = play (100), s1off = play (0);
  12842. 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));
  12843. // the project file keeps the key link and its mode; an older reader skips it
  12844. lynx::Song song = engine.getSong();
  12845. song.midiLinks[0].mode = 2;
  12846. MidiLink cc7 { 7, 0, pan };
  12847. cc7.mode = 4;
  12848. song.midiLinks.insert (song.midiLinks.begin(), cc7);
  12849. juce::String error;
  12850. const auto json = lynx::ProjectFile::toJson (song);
  12851. const auto back = lynx::ProjectFile::fromJson (json, error);
  12852. check ("cs_note_link_round_trip", back && back->midiLinks == song.midiLinks && json.contains ("midiNoteLinks"), error);
  12853. auto parsed = juce::JSON::parse (json);
  12854. if (auto* o = parsed.getDynamicObject())
  12855. {
  12856. o->removeProperty ("midiNoteLinks");
  12857. o->removeProperty ("midiLinkSettings");
  12858. }
  12859. const auto older = lynx::ProjectFile::fromJson (juce::JSON::toString (parsed), error);
  12860. check ("cs_older_reader_keeps_cc_links_only", older && older->midiLinks.size() == 1 && older->midiLinks[0].cc == 7);
  12861. // "Record automation" of an internal-controller link, saved only when on
  12862. lynx::Automation live;
  12863. live.target = volume;
  12864. live.source.track = 0;
  12865. live.recordLive = true;
  12866. song.automations = { live };
  12867. const auto withLive = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  12868. live.recordLive = false;
  12869. song.automations = { live };
  12870. check ("cs_record_automation_round_trip", withLive && withLive->automations.size() == 1 && withLive->automations[0].recordLive
  12871. && ! lynx::ProjectFile::toJson (song).contains ("recordLive"));
  12872. engine.editSong ([] (lynx::Song& s) { s.midiLinks.clear(); });
  12873. }
  12874. // ---- menus: the control menu, the formula presets, the controller list, the Multilink items
  12875. {
  12876. juce::PopupMenu control;
  12877. lynx::addAutomationItem (control, engine, volume, true);
  12878. engine.setMultilink (true);
  12879. engine.noteTweaked (volume);
  12880. engine.noteTweaked (pan);
  12881. juce::PopupMenu multilink;
  12882. lynx::addMultilinkControlsItems (multilink, engine);
  12883. check ("multilink_queue", engine.multilinkTargets().size() == 2);
  12884. engine.setMultilink (false);
  12885. saveMenus (juce::StringArray { "Control menu", "Formula presets", "Multilink" },
  12886. std::vector<juce::PopupMenu> { control, lynx::remoteControlFormulaMenu ([] (const juce::String&) {}), multilink },
  12887. prefix + "-menus.png");
  12888. saveMenus (juce::StringArray { "Ctrl menu" }, std::vector<juce::PopupMenu> { lynx::remoteControlControllerMenu ([] (int) {}) },
  12889. prefix + "-ctrl-menu.png");
  12890. // the Mode list as its box pops it up (round 190cs)
  12891. juce::PopupMenu modes;
  12892. for (const char* m : { "Default", "Hold", "Latch", "Inc", "Stay" })
  12893. modes.addItem (lynx::tr (m), true, juce::String (m) == "Default", [] {});
  12894. saveMenus (juce::StringArray { "Mode" }, std::vector<juce::PopupMenu> { modes }, prefix + "-mode-menu.png");
  12895. }
  12896. // ---- Settings > MIDI: the input's Port box, the link list with a link's settings
  12897. {
  12898. engine.editSong ([&] (lynx::Song& s) {
  12899. MidiLink l { 74, 2, pan };
  12900. l.port = 4;
  12901. l.formula = "1-Input";
  12902. l.smooth = true;
  12903. s.midiLinks = { MidiLink { 7, 0, volume }, l };
  12904. });
  12905. auto page = lynx::makeMidiPage (engine, {}, false);
  12906. page->setSize (760, 900);
  12907. shoot (*page, "settings-midi");
  12908. }
  12909. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\nresult=" + (allOk ? "OK" : "FAIL") + "\n");
  12910. return allOk;
  12911. }
  12912. // A stand-in hosted plugin for the shot route: three parameters, its state = their values
  12913. struct FlCtlShotPlugin final : juce::AudioPluginInstance
  12914. {
  12915. FlCtlShotPlugin()
  12916. {
  12917. for (const char* n : { "Cutoff", "Resonance", "Drive" })
  12918. addHostedParameter (std::make_unique<juce::AudioParameterFloat> (juce::ParameterID (n, 1), n, 0.0f, 1.0f, 0.5f));
  12919. }
  12920. const juce::String getName() const override { return "Shot plugin"; }
  12921. void prepareToPlay (double, int) override {}
  12922. void releaseResources() override {}
  12923. void processBlock (juce::AudioBuffer<float>&, juce::MidiBuffer&) override {}
  12924. double getTailLengthSeconds() const override { return 0.0; }
  12925. bool acceptsMidi() const override { return false; }
  12926. bool producesMidi() const override { return false; }
  12927. juce::AudioProcessorEditor* createEditor() override { return nullptr; }
  12928. bool hasEditor() const override { return false; }
  12929. int getNumPrograms() override { return 1; }
  12930. int getCurrentProgram() override { return 0; }
  12931. void setCurrentProgram (int) override {}
  12932. const juce::String getProgramName (int) override { return {}; }
  12933. void changeProgramName (int, const juce::String&) override {}
  12934. void getStateInformation (juce::MemoryBlock& b) override
  12935. {
  12936. for (auto* p : getParameters())
  12937. {
  12938. const float v = static_cast<juce::AudioParameterFloat*> (p)->get();
  12939. b.append (&v, sizeof (float));
  12940. }
  12941. }
  12942. void setStateInformation (const void* data, int size) override
  12943. {
  12944. const auto& list = getParameters();
  12945. for (int i = 0; i < list.size() && (i + 1) * (int) sizeof (float) <= size; ++i)
  12946. *static_cast<juce::AudioParameterFloat*> (list[i]) = static_cast<const float*> (data)[i];
  12947. }
  12948. void fillInPluginDescription (juce::PluginDescription& d) const override
  12949. {
  12950. d.name = getName();
  12951. d.pluginFormatName = "Shot";
  12952. d.fileOrIdentifier = "shot";
  12953. }
  12954. };
  12955. static juce::File writeShotSample (const juce::File& file, double hz)
  12956. {
  12957. juce::AudioBuffer<float> buffer (1, 22050);
  12958. for (int i = 0; i < buffer.getNumSamples(); ++i)
  12959. buffer.setSample (0, i, (float) (std::sin (juce::MathConstants<double>::twoPi * hz * i / 44100.0) * std::exp (-i / 6000.0)));
  12960. file.deleteFile();
  12961. juce::WavAudioFormat wav;
  12962. if (auto out = std::unique_ptr<juce::AudioFormatWriter> (wav.createWriterFor (file.createOutputStream().release(), 44100.0, 1, 16, {}, 0)))
  12963. out->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
  12964. return file;
  12965. }
  12966. static bool clickMenuItem (const juce::PopupMenu& menu, const juce::String& text)
  12967. {
  12968. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  12969. if (it.getItem().text == text && it.getItem().isEnabled && it.getItem().action != nullptr)
  12970. {
  12971. it.getItem().action();
  12972. return true;
  12973. }
  12974. return false;
  12975. }
  12976. // --samplerpageshot <prefix> (round 190dh): FL's Sampler page offscreen — the page as FL's shot (dock188a) shows it,
  12977. // the legacy effects, a small window, a zoomed waveform — and its laws turned as a user would; prefix-checks.txt
  12978. bool runSamplerPageShot (const juce::String& prefix)
  12979. {
  12980. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  12981. juce::StringArray report;
  12982. bool allOk = true;
  12983. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  12984. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  12985. allOk = allOk && ok;
  12986. };
  12987. const auto shoot = [&prefix] (juce::Component& c, const char* name) {
  12988. savePng (c.createComponentSnapshot (c.getLocalBounds()), prefix + "-" + name + ".png");
  12989. };
  12990. lynx::AudioEngine engine (false);
  12991. const auto folder = juce::File (prefix).getParentDirectory().getChildFile ("sampler-samples");
  12992. folder.createDirectory();
  12993. // an 808-like kick, 1 s (FL's shot: "Basic 808 Kick.wav")
  12994. const auto kick = folder.getChildFile ("Basic 808 Kick.wav");
  12995. {
  12996. juce::AudioBuffer<float> buffer (1, 44100);
  12997. double phase = 0.0;
  12998. for (int i = 0; i < buffer.getNumSamples(); ++i)
  12999. {
  13000. const auto t = i / 44100.0;
  13001. phase += juce::MathConstants<double>::twoPi * (48.0 + 90.0 * std::exp (-t * 30.0)) / 44100.0;
  13002. buffer.setSample (0, i, (float) (0.9 * std::sin (phase) * std::exp (-t * 3.2)));
  13003. }
  13004. kick.deleteFile();
  13005. juce::WavAudioFormat wav;
  13006. if (auto out = std::unique_ptr<juce::AudioFormatWriter> (wav.createWriterFor (kick.createOutputStream().release(), 44100.0, 1, 16, {}, 0)))
  13007. out->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
  13008. }
  13009. engine.editSong ([&] (lynx::Song& s) {
  13010. if (s.channels.empty())
  13011. s.channels.resize (1);
  13012. lynx::audioclips::loadSampleInto (s.channels[0], kick.getFullPathName().toStdString(), "808 Kick");
  13013. // FL's shot: Resample and Load regions on, Use loop points on, declicking "Out only (no bleeding)"
  13014. s.channels[0].sampler.resampleOnLoad = true;
  13015. });
  13016. const auto sampler = [&engine] { return engine.getSong().channels[0].sampler; };
  13017. auto frame = lynx::makeChannelFrame (engine, 0, 0);
  13018. frame->setSize (frame->getWidth() > 0 ? frame->getWidth() : 700, frame->getHeight() > 0 ? frame->getHeight() : 720);
  13019. frame->createComponentSnapshot (frame->getLocalBounds()); // (starts the waveform's analysis)
  13020. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (8000);
  13021. shoot (*frame, "sampler-page");
  13022. report.add ("page size " + juce::String (frame->getWidth()) + "x" + juce::String (frame->getHeight()));
  13023. // ---- the laws, turned on the page
  13024. auto& f = *frame;
  13025. lynx::samplerPageTurn (f, "pingPong", 1.0);
  13026. check ("ping_pong", sampler().precompute.pingPong);
  13027. lynx::samplerPageTurn (f, "pingPong", 0.0);
  13028. lynx::samplerPageTurn (f, "loopStart", 5000.0);
  13029. check ("loop_start", sampler().loopStart == 5000 && sampler().loopEnd == 5001, juce::String (sampler().loopStart) + "/" + juce::String (sampler().loopEnd));
  13030. lynx::samplerPageTurn (f, "loopEnd", 15000.0);
  13031. check ("loop_end", sampler().loopStart == 5000 && sampler().loopEnd == 15000);
  13032. lynx::samplerPageTurn (f, "loopStart", 20000.0, true); // Shift: the loop moves
  13033. check ("loop_shift_moves", sampler().loopStart == 20000 && sampler().loopEnd == 30000, juce::String (sampler().loopStart) + "/" + juce::String (sampler().loopEnd));
  13034. check ("keep_on_disk_greyed_with_loop", lynx::samplerPageQuery (f, "keepOnDisk") == "0");
  13035. lynx::samplerPageTurn (f, "useLoops", 0.0);
  13036. check ("keep_on_disk_back", lynx::samplerPageQuery (f, "keepOnDisk") == "1" && ! sampler().useLoopPoints);
  13037. check ("not_cut_yet", ! lynx::channelCutsItself (engine.getSong().channels[0]));
  13038. lynx::samplerPageTurn (f, "useLoops", 1.0);
  13039. check ("use_loops_cuts_itself", sampler().useLoopPoints && lynx::channelCutsItself (engine.getSong().channels[0]));
  13040. engine.editSong ([] (lynx::Song& s) {
  13041. lynx::setChannelCutsItself (s.channels[0], 0, false);
  13042. s.channels[0].sampler.useLoopPoints = false;
  13043. });
  13044. lynx::samplerPageTurn (f, "crossfade", 300.0); // (Use loop points off: the crossfade switches it on)
  13045. check ("crossfade_switches_loops_on", sampler().precompute.crossfade == 300 && sampler().useLoopPoints);
  13046. lynx::samplerPageTurn (f, "crossfade", 0.0);
  13047. lynx::samplerPageTurn (f, "pitch", 300.0); // (Resample: FL switches to Auto)
  13048. check ("pitch_resample_to_auto", sampler().keepPitch && sampler().flStretchMode == 5 && sampler().flStretchPitch == 300
  13049. && lynx::samplerPageQuery (f, "mode") == lynx::tr ("General"),
  13050. lynx::samplerPageQuery (f, "mode") + " " + juce::String (sampler().pitch));
  13051. lynx::samplerPageTurn (f, "pitch", 0.0);
  13052. lynx::samplerPageTurn (f, "mode", 1.0); // Resample
  13053. check ("mode_resample", ! sampler().keepPitch && std::abs (sampler().pitch) < 1.0e-4f);
  13054. lynx::samplerPageTurn (f, "time", 4.0);
  13055. lynx::samplerPageTurn (f, "mul", 10000.0);
  13056. check ("time_mul", std::abs (sampler().stretchBeats - 8.0f) < 1.0e-3f && sampler().stretchMul == 10000, juce::String (sampler().stretchBeats));
  13057. lynx::samplerPageTurn (f, "mul", 0.0);
  13058. lynx::samplerPageTurn (f, "time", 0.0);
  13059. lynx::samplerPageTurn (f, "length", 0.5);
  13060. lynx::samplerPageTurn (f, "smpStart", 0.5);
  13061. check ("smp_start_keeps_length", std::abs (sampler().regionStart - 0.5f) < 1.0e-3f && std::abs (sampler().regionEnd - 0.75f) < 1.0e-3f,
  13062. juce::String (sampler().regionStart) + "-" + juce::String (sampler().regionEnd));
  13063. lynx::samplerPageTurn (f, "smpStart", 0.0);
  13064. lynx::samplerPageTurn (f, "length", 1.0);
  13065. lynx::samplerPageTurn (f, "declick", 4.0);
  13066. check ("declick_mode", sampler().declickMode == 4);
  13067. lynx::samplerPageTurn (f, "declick", 0.0);
  13068. // ---- the .lynx keeps what the page set
  13069. {
  13070. lynx::samplerPageTurn (f, "mul", -5000.0);
  13071. lynx::samplerPageTurn (f, "keepOnDisk", 1.0);
  13072. juce::String error;
  13073. const auto json = lynx::ProjectFile::toJson (engine.getSong(), false);
  13074. const auto back = lynx::ProjectFile::fromJson (json, error);
  13075. check ("lynx_round_trip", back.has_value() && back->channels[0].sampler == engine.getSong().channels[0].sampler, error);
  13076. lynx::samplerPageTurn (f, "mul", 0.0);
  13077. lynx::samplerPageTurn (f, "keepOnDisk", 0.0);
  13078. }
  13079. // ---- shots: FL's state again (loop points from the file: none), the legacy panel, a zoom, a small window
  13080. engine.editSong ([] (lynx::Song& s) {
  13081. auto& ch = s.channels[0];
  13082. ch.sampler.loopStart = ch.sampler.loopEnd = -1;
  13083. ch.sampler.useLoopPoints = true;
  13084. ch.sampler.precompute = {};
  13085. });
  13086. lynx::samplerPageTurn (f, "show", 0.0); // (no control: the page shows the channel again)
  13087. frame->createComponentSnapshot (frame->getLocalBounds());
  13088. shoot (*frame, "sampler-page-fl-state");
  13089. lynx::samplerPageTurn (f, "legacy", 1.0);
  13090. check ("legacy_panel", lynx::samplerPageQuery (f, "legacy") == "1");
  13091. shoot (*frame, "sampler-page-legacy");
  13092. lynx::samplerPageTurn (f, "legacy", 0.0);
  13093. lynx::samplerPageTurn (f, "zoom", 0.25);
  13094. check ("zoom_scroll", lynx::samplerPageQuery (f, "scroll") == "0.250", lynx::samplerPageQuery (f, "scroll"));
  13095. shoot (*frame, "sampler-page-zoom");
  13096. lynx::samplerPageTurn (f, "zoom", 1.0);
  13097. frame->setSize (520, 470);
  13098. frame->createComponentSnapshot (frame->getLocalBounds());
  13099. shoot (*frame, "sampler-page-small");
  13100. report.add (juce::String ("result=") + (allOk ? "OK" : "FAIL"));
  13101. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\n");
  13102. return allOk;
  13103. }
  13104. bool runFlCtlShot (const juce::String& prefix)
  13105. {
  13106. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  13107. juce::StringArray report;
  13108. bool allOk = true;
  13109. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  13110. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  13111. allOk = allOk && ok;
  13112. };
  13113. const auto shoot = [&prefix] (juce::Component& c, const char* name) {
  13114. savePng (c.createComponentSnapshot (c.getLocalBounds()), prefix + "-" + name + ".png");
  13115. };
  13116. using lynx::AutomationTarget;
  13117. using lynx::AutomationTargetKind;
  13118. lynx::AudioEngine engine (false);
  13119. engine.editSong ([] (lynx::Song& s) {
  13120. if (s.channels.size() < 3)
  13121. s.channels.resize (3);
  13122. if (s.patterns.empty())
  13123. s.patterns.resize (1);
  13124. s.currentPattern = 0;
  13125. });
  13126. const AutomationTarget volume { AutomationTargetKind::channelVolume, 0 }, pan { AutomationTargetKind::channelPan, 0 };
  13127. // ---- FL's multilink menu: on with two queued controls, off with the last tweaked parameters
  13128. {
  13129. engine.setMultilink (true);
  13130. engine.noteTweaked (volume);
  13131. engine.noteTweaked (pan);
  13132. auto on = lynx::multilinkButtonMenu (engine);
  13133. juce::PopupMenu::MenuItemIterator first (on);
  13134. first.next();
  13135. check ("ml_caption_on", first.getItem().isSectionHeader && first.getItem().text == lynx::tr ("{0} parameters selected", { "2" }), first.getItem().text);
  13136. // Init pattern: the values at the pattern's start; ends multilink
  13137. const auto v0 = engine.currentTargetValue (volume);
  13138. lynx::runMultilinkAction (engine, lynx::mlmenu::Action::initPattern, engine.multilinkTargets(), 0);
  13139. const auto& lanes = engine.getSong().patterns[0].events;
  13140. check ("ml_init_pattern", lanes.size() == 2 && ! lanes[0].events.empty() && lanes[0].events[0].tick == 0
  13141. && std::abs (lanes[0].events[0].value - v0) < 1.0e-6f && ! engine.isMultilinkOn());
  13142. // Randomize keeps multilink on; Humanize moves at most an eighth
  13143. engine.setMultilink (true);
  13144. engine.noteTweaked (volume);
  13145. engine.noteTweaked (pan);
  13146. lynx::runMultilinkAction (engine, lynx::mlmenu::Action::randomize, engine.multilinkTargets(), 1234);
  13147. check ("ml_randomize_keeps_queue", engine.isMultilinkOn() && engine.multilinkTargets().size() == 2);
  13148. const auto before = engine.currentTargetValue (volume);
  13149. lynx::runMultilinkAction (engine, lynx::mlmenu::Action::humanize, engine.multilinkTargets(), 99);
  13150. check ("ml_humanize_small", std::abs (engine.currentTargetValue (volume) - before) <= 0.1251f && engine.isMultilinkOn(),
  13151. juce::String (before) + " -> " + juce::String (engine.currentTargetValue (volume)));
  13152. lynx::runMultilinkAction (engine, lynx::mlmenu::Action::initSong, engine.multilinkTargets(), 0);
  13153. check ("ml_init_song", engine.getSong().findInitialValue (volume) >= 0 && ! engine.isMultilinkOn());
  13154. // off: the last two tweaked parameters, no Cancel
  13155. auto off = lynx::multilinkButtonMenu (engine);
  13156. bool hasCancel = false;
  13157. for (juce::PopupMenu::MenuItemIterator it (off); it.next();)
  13158. hasCancel = hasCancel || it.getItem().text == lynx::tr ("Cancel");
  13159. juce::PopupMenu::MenuItemIterator offFirst (off);
  13160. offFirst.next();
  13161. check ("ml_off_caption", offFirst.getItem().text == lynx::tr ("Last 2 tweaked parameters") && ! hasCancel, offFirst.getItem().text);
  13162. // LYNX's own one-step items stay, after FL's items below a line (greyed while multilink is off)
  13163. juce::String last;
  13164. bool lineBefore = false, prevLine = false;
  13165. for (juce::PopupMenu::MenuItemIterator it (on); it.next();)
  13166. {
  13167. if (it.getItem().text == lynx::tr ("Link to controller"))
  13168. lineBefore = prevLine;
  13169. prevLine = it.getItem().isSeparator;
  13170. last = it.getItem().text;
  13171. }
  13172. check ("ml_lynx_items_after_fl", lineBefore && last == lynx::tr ("Override global links"), last);
  13173. saveMenus (juce::StringArray { "Multilink on (2 queued)", "Multilink off" }, std::vector<juce::PopupMenu> { on, off },
  13174. prefix + "-multilink-menu.png");
  13175. }
  13176. // ---- the plugin menu's spare state and Parameters > Link all parameters...
  13177. {
  13178. FlCtlShotPlugin plugin;
  13179. juce::PopupMenu menu;
  13180. lynx::addPluginWrapperItems (menu, engine, plugin, { AutomationTargetKind::channelParam, 1, 0, 0 });
  13181. saveMenus (juce::StringArray { "Plugin menu: spare state and parameters" }, std::vector<juce::PopupMenu> { menu }, prefix + "-plugin-menu.png");
  13182. const auto targets = lynx::allPluginParameterTargets (plugin, { AutomationTargetKind::channelParam, 1, 0, 0 });
  13183. check ("link_all_parameters", targets.size() == 3 && targets[2].param == 2 && targets[2].index == 1);
  13184. auto* cutoff = static_cast<juce::AudioParameterFloat*> (plugin.getParameters()[0]);
  13185. *cutoff = 0.2f;
  13186. check ("spare_store", clickMenuItem (menu, lynx::tr ("Store in spare state")));
  13187. *cutoff = 0.9f;
  13188. juce::PopupMenu again;
  13189. lynx::addPluginWrapperItems (again, engine, plugin, { AutomationTargetKind::channelParam, 1, 0, 0 });
  13190. check ("spare_flip", clickMenuItem (again, lynx::tr ("Flip with spare state")) && std::abs (cutoff->get() - 0.2f) < 1.0e-6f, juce::String (cutoff->get()));
  13191. 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()));
  13192. lynx::sparestate::shared().forget (&plugin);
  13193. }
  13194. // ---- the sampler's File row: Load (history menu, wheel), Locate, Remove
  13195. {
  13196. const auto folder = juce::File (prefix).getParentDirectory().getChildFile ("flctl-samples");
  13197. folder.createDirectory();
  13198. const auto a = writeShotSample (folder.getChildFile ("Kick 1.wav"), 60.0), b = writeShotSample (folder.getChildFile ("Snare 2.wav"), 200.0),
  13199. c = writeShotSample (folder.getChildFile ("Hat 3.wav"), 900.0);
  13200. lynx::samplehistory::list().clear();
  13201. engine.editSong ([&] (lynx::Song& s) {
  13202. for (const auto& f : { c, b, a }) // (each load goes into the history, newest first)
  13203. lynx::audioclips::loadSampleInto (s.channels[1], f.getFullPathName().toStdString(), f.getFileNameWithoutExtension().toStdString());
  13204. });
  13205. check ("history_order", lynx::samplehistory::list().size() == 3 && lynx::samplehistory::list().front() == a.getFullPathName().toStdString());
  13206. juce::File located;
  13207. lynx::locateInBrowserHandler() = [&located] (const juce::File& f) { located = f; };
  13208. auto frame = lynx::makeChannelFrame (engine, 1, 0);
  13209. frame->setSize (frame->getWidth() > 0 ? frame->getWidth() : 600, frame->getHeight() > 0 ? frame->getHeight() : 820);
  13210. frame->createComponentSnapshot (frame->getLocalBounds()); // (starts the waveform's analysis)
  13211. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (8000);
  13212. shoot (*frame, "sampler-file-row");
  13213. const auto history = lynx::samplerHistoryMenu (*frame);
  13214. check ("history_menu", history.has_value() && history->getNumItems() == 4); // (caption + three samples)
  13215. if (history)
  13216. saveMenus (juce::StringArray { "Load: Sample history" }, std::vector<juce::PopupMenu> { *history }, prefix + "-sample-history.png");
  13217. lynx::samplerFileRowPress (*frame, 0); // wheel down: the next (older) sample
  13218. check ("wheel_down", engine.getSong().channels[1].samplePath == b.getFullPathName().toStdString(), juce::String (engine.getSong().channels[1].samplePath));
  13219. lynx::samplerFileRowPress (*frame, 1); // wheel up: back
  13220. check ("wheel_up", engine.getSong().channels[1].samplePath == a.getFullPathName().toStdString());
  13221. lynx::samplerFileRowPress (*frame, 2);
  13222. check ("locate", located == a, located.getFullPathName());
  13223. lynx::samplerFileRowPress (*frame, 3);
  13224. check ("remove", engine.getSong().channels[1].samplePath.empty());
  13225. engine.undo();
  13226. check ("remove_undo", engine.getSong().channels[1].samplePath == a.getFullPathName().toStdString());
  13227. lynx::locateInBrowserHandler() = nullptr;
  13228. }
  13229. // ---- a sampler running FL's voice: FL's Envelope / instrument page with the tensions, the predelay and presets
  13230. {
  13231. engine.editSong ([] (lynx::Song& s) {
  13232. auto& ch = s.channels[2];
  13233. ch.instrument = lynx::InstrumentKind::sampler;
  13234. ch.name = "FL sampler";
  13235. const auto snap = lynx::flvp::defaultSnapshot();
  13236. ch.sampler.flChannel.assign (90, 0);
  13237. std::memcpy (ch.sampler.flChannel.data(), snap.data(), 85 * 4);
  13238. std::memcpy (&ch.sampler.flChannel[85], snap.data() + 0x15c, 4);
  13239. std::memcpy (&ch.sampler.flChannel[86], snap.data() + 0x160, 4);
  13240. std::memcpy (&ch.sampler.flChannel[87], snap.data() + 0x168, 4);
  13241. ch.sampler.flChannel[88] = 96;
  13242. ch.sampler.flChannel[89] = 0;
  13243. auto& vol = ch.sampler.flChannel; // the volume envelope on, bent
  13244. vol[17 + 1] = -1;
  13245. vol[17 + 2] = 4000; // predelay
  13246. vol[17 + 14] = -70; // attack tension
  13247. vol[17 + 15] = 60; // decay tension
  13248. vol[17 + 16] = -40; // release tension
  13249. });
  13250. auto frame = lynx::makeChannelFrame (engine, 2, 1);
  13251. frame->setSize (frame->getWidth() > 0 ? frame->getWidth() : 600, frame->getHeight() > 0 ? frame->getHeight() : 560);
  13252. shoot (*frame, "sampler-fl-envelope");
  13253. check ("fl_page_shown", lynx::flVoicePresetsMenu (*frame).has_value());
  13254. lynx::flVoicePresetFolder().deleteRecursively();
  13255. check ("preset_save", lynx::flVoiceSavePreset (*frame, "Bent volume")
  13256. && lynx::flVoicePresetFolder().getChildFile ("Bent volume.CHENV").getSize() == 68);
  13257. if (const auto menu = lynx::flVoicePresetsMenu (*frame))
  13258. saveMenus (juce::StringArray { "Channel envelope presets" }, std::vector<juce::PopupMenu> { *menu }, prefix + "-envelope-presets.png");
  13259. // the preset into the pitch target: its record becomes the saved one
  13260. lynx::showFlVoiceTarget (*frame, lynx::flvoice::pitch);
  13261. const auto loaded = lynx::flVoiceLoadPreset (*frame, lynx::flVoicePresetFolder().getChildFile ("Bent volume.CHENV"));
  13262. const auto& fl = engine.getSong().channels[2].sampler.flChannel;
  13263. check ("preset_load", loaded && fl.size() == 90 && fl[68 + 2] == 4000 && fl[68 + 14] == -70 && fl[68 + 16] == -40 && fl[88] == 96);
  13264. engine.undo();
  13265. check ("preset_load_undo", engine.getSong().channels[2].sampler.flChannel[68 + 14] != -70);
  13266. }
  13267. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\nresult=" + (allOk ? "OK" : "FAIL") + "\n");
  13268. return allOk;
  13269. }
  13270. // --flplshot (round 190dx): see the dispatch above
  13271. bool runHdrShot190ft (const juce::String& prefix)
  13272. {
  13273. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  13274. juce::StringArray report;
  13275. bool allOk = true;
  13276. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  13277. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  13278. allOk = allOk && ok;
  13279. };
  13280. const auto list = [] (const std::vector<int>& v) {
  13281. juce::StringArray out;
  13282. for (auto i : v)
  13283. out.add (juce::String (i));
  13284. return out.joinIntoString (",");
  13285. };
  13286. lynx::AudioEngine engine (false);
  13287. lynx::MainComponent ui (engine, false);
  13288. ui.setSize (1600, 900);
  13289. {
  13290. auto song = lynx::Song::makeDefault();
  13291. song.playlist.clear();
  13292. for (int t = 0; t < 6; ++t)
  13293. {
  13294. if ((int) song.playlistTracks.size() <= t)
  13295. song.playlistTracks.resize ((std::size_t) t + 1);
  13296. song.playlistTracks[(std::size_t) t].name = juce::String ("Track " + juce::String (t + 1)).toStdString();
  13297. for (int k = 0; k < 2; ++k)
  13298. {
  13299. lynx::Clip c;
  13300. c.kind = lynx::ClipKind::pattern;
  13301. c.pattern = 0;
  13302. c.track = t;
  13303. c.start = (std::int64_t) (k * 4 + t % 3) * lynx::ppq;
  13304. c.length = 2 * lynx::ppq;
  13305. song.playlist.push_back (c);
  13306. }
  13307. }
  13308. if (song.mixer.size() < 4)
  13309. song.mixer.resize (4);
  13310. song.playlistTracks[2].mode = lynx::PlaylistTrackMode::audio; // an audio track linked to mixer track 3
  13311. song.playlistTracks[2].mixerTrack = 3;
  13312. song.playlistTracks[2].name = "Vox";
  13313. engine.setSong (std::move (song));
  13314. }
  13315. engine.dispatchPendingMessages();
  13316. ui.selectTabForSnapshot (2);
  13317. engine.dispatchPendingMessages();
  13318. auto& pl = ui.getPlaylistForSnapshot();
  13319. pl.setSize (juce::jmax (pl.getWidth(), 900), juce::jmax (pl.getHeight(), 600));
  13320. auto source = juce::Desktop::getInstance().getMainMouseSource();
  13321. const auto now = juce::Time::getCurrentTime();
  13322. const juce::ModifierKeys left (juce::ModifierKeys::leftButtonModifier);
  13323. const int ctrl = juce::ModifierKeys::commandModifier; // (FL's Ctrl: Cmd on a Mac)
  13324. const int shift = juce::ModifierKeys::shiftModifier;
  13325. const int alt = juce::ModifierKeys::altModifier;
  13326. const auto event = [&] (juce::Component& c, juce::Point<int> p, juce::ModifierKeys mods, juce::Point<int> down, int clicks, bool dragged) {
  13327. return juce::MouseEvent (source, p.toFloat(), mods, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, &c, &c, now, down.toFloat(), now, clicks, dragged);
  13328. };
  13329. // a press (and release) at p with the modifiers; `to`: a drag there before the release
  13330. const auto press = [&] (juce::Component& c, juce::Point<int> p, juce::ModifierKeys mods, std::optional<juce::Point<int>> to = {}, int clicks = 1) {
  13331. const auto down = mods.withFlags (juce::ModifierKeys::leftButtonModifier);
  13332. c.mouseMove (event (c, p, mods, p, 1, false));
  13333. c.mouseDown (event (c, p, down, p, clicks, false));
  13334. if (to)
  13335. c.mouseDrag (event (c, *to, down, p, clicks, true));
  13336. c.mouseUp (event (c, to ? *to : p, mods, p, clicks, to.has_value()));
  13337. };
  13338. const auto headerPoint = [&] (int track) { const auto r = pl.trackRowForSnapshot (track); return juce::Point<int> (40, r.getY() + juce::jmin (10, r.getHeight() / 3)); };
  13339. const auto bandPoint = [&] (int track) { const auto r = pl.trackRowForSnapshot (track); return juce::Point<int> (40, r.getBottom() - 2); };
  13340. const auto clipsOn = [&] (const std::vector<int>& tracks) {
  13341. std::vector<int> out;
  13342. const auto& song = engine.getSong();
  13343. for (int i = 0; i < (int) song.playlist.size(); ++i)
  13344. if (std::find (tracks.begin(), tracks.end(), song.playlist[(std::size_t) i].track) != tracks.end())
  13345. out.push_back (i);
  13346. return out;
  13347. };
  13348. const auto sortedClips = [&] { auto v = pl.getSelectedClips(); std::sort (v.begin(), v.end()); return v; };
  13349. const auto headerShot = [&] (const juce::String& name, int rows) {
  13350. const auto bottom = pl.trackRowForSnapshot (rows).getY();
  13351. savePng (pl.createComponentSnapshot ({ 0, 0, juce::jmin (pl.getWidth(), 760), juce::jmin (pl.getHeight(), bottom + 12) }), prefix + name);
  13352. };
  13353. // ---- 1. selection (AUTracksPanelMouseDown / FUN_012e83e0)
  13354. press (pl, headerPoint (1), {});
  13355. check ("click_selects_alone", pl.selectedTracksForSnapshot() == std::vector<int> { 1 }, list (pl.selectedTracksForSnapshot()));
  13356. pl.selectClipsForSnapshot ({});
  13357. // LYNX extra (issue #163): Ctrl+click adds / removes one track, its clips follow
  13358. press (pl, headerPoint (3), ctrl);
  13359. check ("ctrl_click_adds_lynx", pl.selectedTracksForSnapshot() == std::vector<int> { 1, 3 } && sortedClips() == clipsOn ({ 3 }),
  13360. list (pl.selectedTracksForSnapshot()) + " clips " + list (sortedClips()));
  13361. press (pl, headerPoint (5), ctrl);
  13362. press (pl, headerPoint (1), ctrl);
  13363. check ("ctrl_click_removes_lynx", pl.selectedTracksForSnapshot() == std::vector<int> { 3, 5 } && sortedClips() == clipsOn ({ 3, 5 }),
  13364. list (pl.selectedTracksForSnapshot()) + " clips " + list (sortedClips()));
  13365. // FL's own toggle: Ctrl+Shift+click (its clips are added)
  13366. press (pl, headerPoint (1), ctrl | shift);
  13367. check ("ctrl_shift_click_adds", pl.selectedTracksForSnapshot() == std::vector<int> { 1, 3, 5 }, list (pl.selectedTracksForSnapshot()));
  13368. check ("ctrl_shift_click_adds_clips", sortedClips() == clipsOn ({ 1, 3, 5 }), list (sortedClips()));
  13369. press (pl, headerPoint (3), ctrl | shift);
  13370. check ("ctrl_shift_click_removes", pl.selectedTracksForSnapshot() == std::vector<int> { 1, 5 }, list (pl.selectedTracksForSnapshot()));
  13371. press (pl, headerPoint (3), ctrl | shift);
  13372. check ("ctrl_shift_click_adds_again", pl.selectedTracksForSnapshot() == std::vector<int> { 1, 3, 5 }, list (pl.selectedTracksForSnapshot()));
  13373. pl.selectClipsForSnapshot ({});
  13374. headerShot ("-ctrl-multiselect.png", 6);
  13375. press (pl, headerPoint (0), ctrl, headerPoint (2));
  13376. check ("ctrl_drag_range_with_clips", pl.selectedTracksForSnapshot() == std::vector<int> { 0, 1, 2 } && sortedClips() == clipsOn ({ 0, 1, 2 }),
  13377. list (pl.selectedTracksForSnapshot()) + " clips " + list (sortedClips()));
  13378. press (pl, headerPoint (1), shift); // LYNX's own Shift+click range (from the last clicked track, 0)
  13379. check ("lynx_shift_range_kept", pl.selectedTracksForSnapshot() == std::vector<int> { 0, 1 }, list (pl.selectedTracksForSnapshot()));
  13380. {
  13381. int linked = -1;
  13382. auto old = pl.onLinkedMixerTrack;
  13383. pl.onLinkedMixerTrack = [&linked] (int insert) { linked = insert; };
  13384. press (pl, headerPoint (2), {});
  13385. check ("audio_track_click_links_mixer_track", linked == 3, juce::String (linked));
  13386. pl.onLinkedMixerTrack = old;
  13387. }
  13388. // ---- 2. the resize band (FUN_00ea93a0, AUTracksPanelMouseMove)
  13389. const auto heightOf = [&] (int t) { return pl.trackRowForSnapshot (t).getHeight(); };
  13390. const auto& tracks = [&]() -> const std::vector<lynx::PlaylistTrack>& { return engine.getSong().playlistTracks; };
  13391. press (pl, headerPoint (4), {}); // (track 4 alone selected)
  13392. {
  13393. const auto start = bandPoint (4);
  13394. press (pl, start, {}, start + juce::Point<int> (0, 41));
  13395. check ("drag_resizes", tracks()[4].height == 88 && heightOf (4) == 88, juce::String (tracks()[4].height) + " / " + juce::String (heightOf (4))); // (190gw: from FL's 48 px row)
  13396. headerShot ("-resized.png", 6);
  13397. const auto again = bandPoint (4);
  13398. press (pl, again, {}, again + juce::Point<int> (0, -100)); // (above the row's top, but less than 32 px)
  13399. check ("drag_stops_at_16", heightOf (4) == 16, juce::String (heightOf (4)));
  13400. press (pl, bandPoint (4), alt);
  13401. check ("alt_click_resets", tracks()[4].height == 0 && tracks()[4].lockedHeight == -1 && heightOf (4) == 48, juce::String (heightOf (4)));
  13402. press (pl, bandPoint (4), {}, {}, 2); // the second press of a double click
  13403. check ("double_click_locks_small", tracks()[4].lockedHeight == 1 && heightOf (4) == 16, juce::String (tracks()[4].lockedHeight));
  13404. press (pl, bandPoint (4), {});
  13405. check ("click_on_locked_band_unlocks", tracks()[4].lockedHeight == -1 && heightOf (4) == 48, juce::String (tracks()[4].lockedHeight));
  13406. const auto top = pl.trackRowForSnapshot (4).getY();
  13407. const auto b = bandPoint (4);
  13408. press (pl, b, {}, juce::Point<int> (b.x, top - 40));
  13409. check ("drag_past_the_top_groups", tracks()[4].grouped && tracks()[4].height == 0, juce::String ((int) tracks()[4].grouped));
  13410. const auto b2 = bandPoint (4);
  13411. press (pl, b2, {}, juce::Point<int> (b2.x, pl.trackRowForSnapshot (4).getY() - 40));
  13412. check ("again_ungroups", ! tracks()[4].grouped, juce::String ((int) tracks()[4].grouped));
  13413. }
  13414. {
  13415. // every selected track: the same height, from the first one's top to the mouse
  13416. press (pl, headerPoint (1), {});
  13417. press (pl, headerPoint (2), ctrl | shift);
  13418. press (pl, headerPoint (3), ctrl | shift);
  13419. const auto top = pl.trackRowForSnapshot (1).getY();
  13420. const auto b = bandPoint (2);
  13421. press (pl, b, {}, juce::Point<int> (b.x, top + 2 * 50));
  13422. check ("selected_tracks_share_the_height", tracks()[1].height == 50 && tracks()[2].height == 50 && tracks()[3].height == 50,
  13423. juce::String (tracks()[1].height) + "," + juce::String (tracks()[2].height) + "," + juce::String (tracks()[3].height));
  13424. headerShot ("-selected-resized.png", 6);
  13425. }
  13426. // ---- 3. saved: .lynx round trip and the .flp size factor
  13427. {
  13428. engine.editSong ([] (lynx::Song& s) { s.playlistTracks[5].height = 300; s.playlistTracks[0].lockedHeight = 60; });
  13429. const auto json = lynx::ProjectFile::toJson (engine.getSong());
  13430. juce::String error;
  13431. const auto back = lynx::ProjectFile::fromJson (json, error);
  13432. check ("lynx_round_trip", back && back->playlistTracks.size() > 5 && back->playlistTracks[5].height == 300 && back->playlistTracks[1].height == 50
  13433. && back->playlistTracks[0].lockedHeight == 60, error);
  13434. lynx::flpexport::Options options;
  13435. lynx::flpexport::Report flpReport;
  13436. const auto project = flp::parseProject (lynx::flpexport::exportFlp (engine.getSong(), options, flpReport));
  13437. float size5 = -1.0f, size1 = -1.0f;
  13438. for (const auto& arrangement : project.arrangements)
  13439. for (const auto& t : arrangement.tracks)
  13440. {
  13441. if (t.index == 5) size5 = t.heightScale;
  13442. if (t.index == 1) size1 = t.heightScale;
  13443. }
  13444. check ("flp_size_factor", std::abs (size5 - lynx::polish::flSizeForHeight (300, 48)) < 1.0e-4f && std::abs (size1 - lynx::polish::flSizeForHeight (50, 48)) < 1.0e-4f,
  13445. juce::String (size5) + " " + juce::String (size1));
  13446. }
  13447. // ---- 4. the mixer strips (round 170b's FL rules): Ctrl+click alone, Ctrl+Shift+click adds / removes
  13448. {
  13449. ui.selectTabForSnapshot (3);
  13450. engine.editSong ([] (lynx::Song& s) { if (s.mixer.size() < 9) s.mixer.resize (9); });
  13451. engine.dispatchPendingMessages();
  13452. auto& mixer = ui.getMixerForSnapshot();
  13453. mixer.setSize (1400, 640);
  13454. auto& strips = mixer.getStripsForSnapshot();
  13455. strips.setSize (juce::jmax (strips.getWidth(), 1300), juce::jmax (strips.getHeight(), 560));
  13456. const auto at = [&] (int t) { return juce::Point<int> (strips.stripLeft (t) + 8, strips.getHeight() / 2 + 40); };
  13457. press (strips, at (2), {});
  13458. check ("mixer_click_alone", strips.getSelection() == std::vector<int> { 2 }, list (strips.getSelection()));
  13459. // LYNX extra (issue #163): Ctrl+click adds / removes one insert
  13460. press (strips, at (4), ctrl);
  13461. press (strips, at (6), ctrl);
  13462. check ("mixer_ctrl_click_adds_lynx", strips.getSelection() == std::vector<int> { 2, 4, 6 }, list (strips.getSelection()));
  13463. press (strips, at (4), ctrl);
  13464. check ("mixer_ctrl_click_removes_lynx", strips.getSelection() == std::vector<int> { 2, 6 }, list (strips.getSelection()));
  13465. // FL: Ctrl+Shift+click adds / removes too
  13466. press (strips, at (5), ctrl | shift);
  13467. check ("mixer_ctrl_shift_click_adds", strips.getSelection() == std::vector<int> { 2, 5, 6 }, list (strips.getSelection()));
  13468. savePng (mixer.createComponentSnapshot ({ 0, 0, juce::jmin (mixer.getWidth(), 900), mixer.getHeight() }), prefix + "-mixer-ctrl-multiselect.png");
  13469. // FL: Ctrl+drag across the strips = the range from the press, alone
  13470. press (strips, at (3), ctrl, at (4));
  13471. check ("mixer_ctrl_drag_range", strips.getSelection() == std::vector<int> { 3, 4 }, list (strips.getSelection()));
  13472. }
  13473. // ---- 5. round 190gw (live check 190gu B1): FL's default row, the left lock strip, the right selection strip
  13474. {
  13475. ui.selectTabForSnapshot (2);
  13476. auto song = lynx::Song::makeDefault();
  13477. song.playlist.clear();
  13478. song.playlistTracks.assign (6, {});
  13479. for (int t = 0; t < 6; ++t)
  13480. song.playlistTracks[(std::size_t) t].name = juce::String ("Track " + juce::String (t + 1)).toStdString();
  13481. engine.setSong (std::move (song));
  13482. engine.dispatchPendingMessages();
  13483. pl.setSize (juce::jmax (pl.getWidth(), 900), juce::jmax (pl.getHeight(), 600));
  13484. check ("gw_default_row_48", heightOf (0) == 48 && heightOf (5) == 48, juce::String (heightOf (0)));
  13485. const auto rowMid = [&] (int t) { const auto r = pl.trackRowForSnapshot (t); return r.getY() + r.getHeight() / 2 - 4; };
  13486. const auto stripX = lynx::PlaylistComponent::flHeaderWidth - 4;
  13487. // the left strip (x < 10): the row flips to the smallest size and back; nothing selects
  13488. press (pl, { 2, rowMid (2) }, {});
  13489. check ("gw_left_strip_smallest", heightOf (2) == 16 && tracks()[2].lockedHeight == 1, juce::String (heightOf (2)));
  13490. press (pl, { 2, rowMid (2) }, {});
  13491. check ("gw_left_strip_back", heightOf (2) == 48 && tracks()[2].lockedHeight == -1, juce::String (heightOf (2)));
  13492. // the right strip: click = alone, Shift+click toggles, right-click toggles with no menu
  13493. press (pl, { stripX, rowMid (0) }, {});
  13494. check ("gw_strip_click_alone", pl.selectedTracksForSnapshot() == std::vector<int> { 0 }, list (pl.selectedTracksForSnapshot()));
  13495. press (pl, { stripX, rowMid (1) }, shift);
  13496. check ("gw_strip_shift_click_adds", pl.selectedTracksForSnapshot() == std::vector<int> { 0, 1 }, list (pl.selectedTracksForSnapshot()));
  13497. headerShot ("-gw-strip-two-selected.png", 6);
  13498. press (pl, { stripX, rowMid (0) }, shift);
  13499. check ("gw_strip_shift_click_removes", pl.selectedTracksForSnapshot() == std::vector<int> { 1 }, list (pl.selectedTracksForSnapshot()));
  13500. {
  13501. const juce::Point<int> p { stripX, rowMid (4) };
  13502. const juce::ModifierKeys right (juce::ModifierKeys::rightButtonModifier);
  13503. pl.mouseDown (event (pl, p, right, p, 1, false));
  13504. pl.mouseUp (event (pl, p, {}, p, 1, false));
  13505. }
  13506. check ("gw_strip_right_click_adds", pl.selectedTracksForSnapshot() == std::vector<int> { 1, 4 }, list (pl.selectedTracksForSnapshot()));
  13507. // a drag down the strip: the tracks crossed join (FUN_012e8740)
  13508. press (pl, { stripX, rowMid (0) }, {}, juce::Point<int> (stripX, rowMid (4)));
  13509. check ("gw_strip_drag_range", pl.selectedTracksForSnapshot() == std::vector<int> { 0, 1, 2, 3, 4 }, list (pl.selectedTracksForSnapshot()));
  13510. headerShot ("-gw-strip-range.png", 6);
  13511. // a double click: the track alone <-> every track
  13512. press (pl, { stripX, rowMid (2) }, {});
  13513. press (pl, { stripX, rowMid (2) }, {}, {}, 2);
  13514. check ("gw_strip_double_click_all", (int) pl.selectedTracksForSnapshot().size() == pl.numTracksForSnapshot(), list (pl.selectedTracksForSnapshot()));
  13515. press (pl, { stripX, rowMid (1) }, {});
  13516. // .lynx: the new default row is saved; a project from before (no key) keeps LYNX's old 38 px row
  13517. juce::String error;
  13518. const auto json = lynx::ProjectFile::toJson (engine.getSong());
  13519. const auto back = lynx::ProjectFile::fromJson (json, error);
  13520. check ("gw_lynx_row_saved", back && back->playlistRowHeight == 48, error);
  13521. auto parsed = juce::JSON::parse (json);
  13522. if (auto* o = parsed.getDynamicObject())
  13523. o->removeProperty ("playlistRowHeight");
  13524. const auto old = lynx::ProjectFile::fromJson (juce::JSON::toString (parsed), error);
  13525. check ("gw_old_lynx_keeps_38", old && old->playlistRowHeight == 38, error);
  13526. engine.setSong (*old);
  13527. engine.dispatchPendingMessages();
  13528. check ("gw_old_lynx_rows_38", heightOf (0) == 38, juce::String (heightOf (0)));
  13529. // an automation clip with two target links (Crossfade with) comes back with its links and formulas
  13530. auto linked = lynx::Song::makeDefault();
  13531. linked.channels.resize (2);
  13532. lynx::Automation a;
  13533. a.links = { { { lynx::AutomationTargetKind::channelAdjust, 0, 0, lynx::leveladjust::volume }, lynx::clipops::crossfadeOutFormula },
  13534. { { lynx::AutomationTargetKind::channelAdjust, 1, 0, lynx::leveladjust::volume }, lynx::clipops::crossfadeInFormula } };
  13535. a.target = a.links[0].target;
  13536. a.points = { { 0, 1.0f, 0.0f }, { 384, 0.0f, 0.0f } };
  13537. linked.automations.push_back (a);
  13538. const auto linkedBack = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (linked), error);
  13539. check ("gw_lynx_links_round_trip", linkedBack && linkedBack->automations.size() == linked.automations.size()
  13540. && linkedBack->automations.back().links == a.links && linkedBack->automations.back().target == a.target, error);
  13541. // Sampler › Open in new Fruity Slicer / Slicex channel: named after the sample, " #n" when taken
  13542. const auto wav = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-190gw").getChildFile ("Basic 808 Clap.wav");
  13543. wav.getParentDirectory().createDirectory();
  13544. {
  13545. juce::AudioBuffer<float> b (1, 4410);
  13546. for (int i = 0; i < b.getNumSamples(); ++i)
  13547. b.setSample (0, i, 0.5f * std::sin ((float) i * 0.2f) * (1.0f - (float) i / (float) b.getNumSamples()));
  13548. wav.deleteFile();
  13549. juce::WavAudioFormat format;
  13550. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream());
  13551. if (auto* w = format.createWriterFor (out.get(), 44100.0, 1, 16, {}, 0))
  13552. {
  13553. out.release();
  13554. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  13555. writer->writeFromAudioSampleBuffer (b, 0, b.getNumSamples());
  13556. }
  13557. }
  13558. engine.editSong ([] (lynx::Song& s) {
  13559. s.channels.resize (1);
  13560. s.channels[0] = {};
  13561. s.channels[0].name = "Basic 808 Clap";
  13562. });
  13563. engine.dispatchPendingMessages();
  13564. if (lynx::openInNewChannelHandler())
  13565. {
  13566. lynx::openInNewChannelHandler() (wav, lynx::InstrumentKind::fruityslicer);
  13567. lynx::openInNewChannelHandler() (wav, lynx::InstrumentKind::slicex);
  13568. }
  13569. engine.dispatchPendingMessages();
  13570. const auto& ch = engine.getSong().channels;
  13571. check ("gw_open_in_new_named_after_sample", ch.size() >= 3 && ch[1].name == "Basic 808 Clap #2" && ch[2].name == "Basic 808 Clap #3"
  13572. && ch[1].instrument == lynx::InstrumentKind::fruityslicer && ch[2].instrument == lynx::InstrumentKind::slicex,
  13573. ch.size() >= 3 ? juce::String::fromUTF8 (ch[1].name.c_str()) + " | " + juce::String::fromUTF8 (ch[2].name.c_str()) : juce::String ((int) ch.size()));
  13574. wav.getParentDirectory().deleteRecursively();
  13575. // the mixer's two boxes (live check 190gu B4): "Insert multiple..." asks "Number of tracks to add" (1),
  13576. // "Add multiple..." "Enter the number of mixer tracks to add" (10)
  13577. for (const auto adding : { false, true })
  13578. {
  13579. auto box = lynx::MixerStrips::makeInsertMultipleBox (adding);
  13580. const auto text = box->getTextEditorContents ("count");
  13581. check (adding ? "gw_add_multiple_box" : "gw_insert_multiple_box", text == (adding ? "10" : "1"), text);
  13582. if (box->getWidth() > 0 && box->getHeight() > 0)
  13583. savePng (box->createComponentSnapshot (box->getLocalBounds()), prefix + (adding ? "-gw-add-multiple-box.png" : "-gw-insert-multiple-box.png"));
  13584. }
  13585. }
  13586. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\nresult=" + (allOk ? "OK" : "FAIL") + "\n");
  13587. return allOk;
  13588. }
  13589. // --userfixshot190ib (round 190ib): see the dispatch above
  13590. bool runUserFixShot190ib (const juce::String& prefix)
  13591. {
  13592. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  13593. juce::StringArray report;
  13594. bool allOk = true;
  13595. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  13596. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  13597. allOk = allOk && ok;
  13598. };
  13599. lynx::AudioEngine engine (false);
  13600. lynx::MainComponent ui (engine, false);
  13601. ui.setSize (1600, 900);
  13602. engine.dispatchPendingMessages();
  13603. // ---- #182: a real JUCE popup menu inside a host component, keys sent to its window as the keyboard would
  13604. juce::Component host;
  13605. host.setSize (560, 900);
  13606. const auto typeInto = [&host] (const juce::String& text) {
  13607. auto* menuWindow = host.getNumChildComponents() > 0 ? host.getChildComponent (host.getNumChildComponents() - 1) : nullptr;
  13608. for (auto c : text)
  13609. if (menuWindow != nullptr)
  13610. menuWindow->keyPressed (juce::KeyPress ((int) juce::CharacterFunctions::toLowerCase (c), 0, c));
  13611. return menuWindow != nullptr;
  13612. };
  13613. const auto shotMenu = [&host, &prefix] (const juce::String& name) {
  13614. savePng (host.createComponentSnapshot (host.getLocalBounds()), prefix + name);
  13615. };
  13616. {
  13617. auto& pl = ui.getPlaylistForSnapshot();
  13618. pl.editMenu().showMenuAsync (juce::PopupMenu::Options().withParentComponent (&host).withTargetScreenArea ({ 8, 8, 1, 1 }));
  13619. check ("menu_shown", host.getNumChildComponents() > 0, juce::String (host.getNumChildComponents()));
  13620. shotMenu ("-menu-0.png");
  13621. typeInto ("d");
  13622. shotMenu ("-menu-d.png"); // the first item starting with D
  13623. typeInto ("d");
  13624. shotMenu ("-menu-dd.png"); // D again: the next one
  13625. juce::Time::waitForMillisecondCounter (juce::Time::getMillisecondCounter() + 1100); // (a pause: a new prefix)
  13626. typeInto ("drop a");
  13627. shotMenu ("-menu-drop-a.png"); // "Drop audio on track headers"
  13628. juce::PopupMenu::dismissAllActiveMenus();
  13629. }
  13630. {
  13631. auto& pr = ui.getPianoRollForSnapshot();
  13632. pr.moreMenuForSnapshot().showMenuAsync (juce::PopupMenu::Options().withParentComponent (&host).withTargetScreenArea ({ 8, 8, 1, 1 }));
  13633. juce::Time::waitForMillisecondCounter (juce::Time::getMillisecondCounter() + 1100);
  13634. typeInto ("preview");
  13635. shotMenu ("-pianoroll-preview.png"); // #183's item, reached by typing its name
  13636. juce::PopupMenu::dismissAllActiveMenus();
  13637. check ("preview_while_playing_off_by_default", ! lynx::PianoRollComponent::previewWhilePlaying);
  13638. }
  13639. // ---- #181: Ctrl+, (Cmd+, on macOS) through the main window's key handling opens Settings, again closes it
  13640. const auto ctrlComma = juce::KeyPress (',', juce::ModifierKeys::commandModifier, ',');
  13641. check ("settings_closed_first", lynx::shownSettingsPage() < 0);
  13642. ui.keyPressed (ctrlComma);
  13643. check ("ctrl_comma_opens_settings", lynx::shownSettingsPage() == (int) lynx::SettingsPage::general, juce::String (lynx::shownSettingsPage()));
  13644. ui.keyPressed (ctrlComma);
  13645. check ("ctrl_comma_again_closes_it", lynx::shownSettingsPage() < 0, juce::String (lynx::shownSettingsPage()));
  13646. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\nresult=" + (allOk ? "OK" : "FAIL") + "\n");
  13647. return allOk;
  13648. }
  13649. // --trackautoshot190gz (round 190gz): see the dispatch above
  13650. bool runTrackAutoShot190gz (const juce::String& prefix)
  13651. {
  13652. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  13653. juce::StringArray report;
  13654. bool allOk = true;
  13655. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  13656. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  13657. allOk = allOk && ok;
  13658. };
  13659. lynx::AudioEngine engine (false);
  13660. lynx::MainComponent ui (engine, false);
  13661. ui.setSize (1600, 900);
  13662. {
  13663. // a small song in FL's shape: Kick and Synth patterns, a drum loop, a vocal on its prepared insert, a mixed beat
  13664. using namespace lynx;
  13665. auto song = Song::makeDefault();
  13666. song.playlist.clear();
  13667. song.patterns.clear();
  13668. for (auto& c : song.channels)
  13669. c.mixerTrack = 0; // (FL's new channels play on the Master)
  13670. song.channels[4].mixerTrack = 9; // the Synth on a bus the user made
  13671. song.mixer[9].name = "Synth bus";
  13672. const auto audio = [&song] (const char* name, int mixer) {
  13673. ChannelDef c;
  13674. c.name = name;
  13675. c.instrument = InstrumentKind::audioClip;
  13676. c.samplePath = std::string ("/shots/") + name + ".wav";
  13677. c.mixerTrack = mixer;
  13678. song.channels.push_back (c);
  13679. return (int) song.channels.size() - 1;
  13680. };
  13681. const auto loop = audio ("Drum loop", 0);
  13682. const auto vox = audio ("Lead vocal", 12);
  13683. song.mixer[12].name = "Vox chain";
  13684. song.mixer[12].colour = 0xFF3C8DD8;
  13685. song.mixer[12].effects.push_back (makeEffectSlot (EffectKind::parametricEq));
  13686. const auto pattern = [&song] (const char* name, std::vector<int> channels, std::uint32_t colour) {
  13687. auto& p = song.patterns.emplace_back();
  13688. p.name = name;
  13689. p.colour = colour;
  13690. for (const auto c : channels)
  13691. for (int step : { 0, 4, 8, 12 })
  13692. p.toggleStep (c, step);
  13693. return (int) song.patterns.size() - 1;
  13694. };
  13695. const auto kick = pattern ("Kick", { 0 }, 0xFFD85A3C);
  13696. const auto lead = pattern ("Lead", { 4 }, 0xFF8A5CD8);
  13697. const auto beat = pattern ("Beat", { 1, 2, 3 }, 0xFF5CB85C);
  13698. const auto clip = [&song] (int track, ClipKind kind, int source, int bar, int bars) {
  13699. Clip c;
  13700. c.kind = kind;
  13701. c.track = track;
  13702. c.start = (std::int64_t) bar * 4 * ppq;
  13703. c.length = (std::int64_t) bars * 4 * ppq;
  13704. (kind == ClipKind::pattern ? c.pattern : c.channel) = source;
  13705. song.playlist.push_back (c);
  13706. };
  13707. for (int bar = 0; bar < 8; bar += 2)
  13708. {
  13709. clip (0, ClipKind::pattern, kick, bar, 2);
  13710. clip (2, ClipKind::pattern, beat, bar, 2);
  13711. }
  13712. clip (1, ClipKind::audio, loop, 0, 8);
  13713. clip (3, ClipKind::pattern, lead, 2, 4);
  13714. clip (4, ClipKind::audio, vox, 4, 4);
  13715. clip (6, ClipKind::pattern, kick, 4, 2); // (round 190ib: Track 7 only repeats Track 1's Kick)
  13716. song.playlistTracks.resize (8);
  13717. engine.setSong (std::move (song));
  13718. }
  13719. engine.dispatchPendingMessages();
  13720. ui.selectTabForSnapshot (2);
  13721. engine.dispatchPendingMessages();
  13722. auto& pl = ui.getPlaylistForSnapshot();
  13723. pl.setSize (juce::jmax (pl.getWidth(), 1000), juce::jmax (pl.getHeight(), 640));
  13724. pl.setViewForSnapshot (120.0, 1, 0);
  13725. const auto shotRows = [&] (const juce::String& name, int rows) {
  13726. const auto bottom = pl.trackRowForSnapshot (rows).getY();
  13727. savePng (pl.createComponentSnapshot ({ 0, 0, juce::jmin (pl.getWidth(), 820), juce::jmin (pl.getHeight(), bottom + 12) }), prefix + name);
  13728. };
  13729. const auto& song = [&]() -> const lynx::Song& { return engine.getSong(); };
  13730. const auto mode = [&] (int t) { return t < (int) song().playlistTracks.size() ? song().playlistTracks[(std::size_t) t].mode : lynx::PlaylistTrackMode::unassigned; };
  13731. const auto mixerOf = [&] (int t) { return t < (int) song().playlistTracks.size() ? song().playlistTracks[(std::size_t) t].mixerTrack : -1; };
  13732. // ---- 1. FL's default: tracks and inserts apart, FL's narrow headers
  13733. check ("off_by_default", ! song().linkTracksToMixer && pl.headerWidthForSnapshot() == lynx::PlaylistComponent::flHeaderWidth,
  13734. juce::String (pl.headerWidthForSnapshot()));
  13735. shotRows ("-off.png", 7);
  13736. // ---- 2. the switch (Playlist › Edit, Track mode, Settings › Project): it lists what it changes and asks (round
  13737. // 190ib: inserts move, channels are routed), then it is one undo step
  13738. lynx::autolink::Report plan;
  13739. bool asked = false;
  13740. lynx::PlaylistComponent::answerLinkConfirmation = [&] (const lynx::autolink::Report& r) {
  13741. plan = r;
  13742. asked = true;
  13743. return true;
  13744. };
  13745. {
  13746. const auto text = lynx::PlaylistComponent::describeLinkPlan (song(), lynx::autolink::planOn (song()));
  13747. juce::AlertWindow box (lynx::tr ("Link Playlist tracks to mixer tracks"), text, juce::MessageBoxIconType::QuestionIcon);
  13748. box.addButton (lynx::tr ("Link"), 1);
  13749. box.addButton (lynx::tr ("Cancel"), 0);
  13750. box.sendLookAndFeelChange();
  13751. savePng (lynx::shot::snapshot (box), prefix + "-confirm.png");
  13752. }
  13753. pl.runAction ("playlist.linkTracks");
  13754. engine.dispatchPendingMessages();
  13755. const auto moved = [&plan] (int from, int to) {
  13756. return std::any_of (plan.changes.begin(), plan.changes.end(), [=] (const lynx::autolink::Change& c) {
  13757. return c.kind == lynx::autolink::Change::Kind::moveInsert && c.from == from && c.to == to;
  13758. });
  13759. };
  13760. check ("asked_first_with_the_moves", asked && moved (9, 4) && moved (12, 5) && plan.repeats.size() == 1 && ! plan.changesSound(),
  13761. juce::String ((int) plan.changes.size()));
  13762. check ("switch_on", song().linkTracksToMixer && pl.headerWidthForSnapshot() == lynx::PlaylistComponent::linkedHeaderWidth,
  13763. juce::String (pl.headerWidthForSnapshot()));
  13764. check ("kick_instrument_track_insert_1", mode (0) == lynx::PlaylistTrackMode::instrument && mixerOf (0) == 1 && song().channels[0].mixerTrack == 1,
  13765. juce::String (mixerOf (0)));
  13766. check ("loop_audio_track_insert_2", mode (1) == lynx::PlaylistTrackMode::audio && mixerOf (1) == 2 && song().mixer[2].name == "Drum loop",
  13767. juce::String (mixerOf (1)));
  13768. // (round 190ib: Track N = insert N for every track with content of its own)
  13769. check ("beat_track_insert_3", mode (2) == lynx::PlaylistTrackMode::audio && mixerOf (2) == 3 && song().channels[1].mixerTrack == 3
  13770. && song().channels[2].mixerTrack == 3 && song().channels[3].mixerTrack == 3,
  13771. juce::String (mixerOf (2)));
  13772. check ("synth_bus_moves_to_insert_4", mode (3) == lynx::PlaylistTrackMode::instrument && song().channels[4].mixerTrack == 4
  13773. && song().mixer[4].name == "Synth bus" && song().playlistTracks[3].name == "Synth bus",
  13774. juce::String (song().channels[4].mixerTrack));
  13775. check ("vocal_chain_moves_to_insert_5", mode (4) == lynx::PlaylistTrackMode::audio && mixerOf (4) == 5 && song().mixer[5].effects.size() == 1
  13776. && song().mixer[5].name == "Vox chain",
  13777. juce::String (mixerOf (4)));
  13778. check ("empty_and_repeat_tracks_stay", mode (5) == lynx::PlaylistTrackMode::unassigned && mode (6) == lynx::PlaylistTrackMode::unassigned
  13779. && lynx::autolink::repeatedTracks (song())[6] == 0);
  13780. shotRows ("-on.png", 7);
  13781. // one undo step: Undo brings FL's tracks back, Redo the links
  13782. engine.undo();
  13783. engine.dispatchPendingMessages();
  13784. check ("undo_switch_on", ! song().linkTracksToMixer && mode (0) == lynx::PlaylistTrackMode::unassigned && mode (1) == lynx::PlaylistTrackMode::unassigned
  13785. && song().channels[0].mixerTrack == 0 && pl.headerWidthForSnapshot() == lynx::PlaylistComponent::flHeaderWidth);
  13786. engine.redo();
  13787. engine.dispatchPendingMessages();
  13788. check ("redo_switch_on", song().linkTracksToMixer && mixerOf (1) == 2 && pl.headerWidthForSnapshot() == lynx::PlaylistComponent::linkedHeaderWidth);
  13789. auto source = juce::Desktop::getInstance().getMainMouseSource();
  13790. const auto now = juce::Time::getCurrentTime();
  13791. const int ctrl = juce::ModifierKeys::commandModifier;
  13792. const auto event = [&] (juce::Point<int> p, juce::ModifierKeys mods, juce::Point<int> down, int clicks, bool dragged) {
  13793. return juce::MouseEvent (source, p.toFloat(), mods, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, &pl, &pl, now, down.toFloat(), now, clicks, dragged);
  13794. };
  13795. const auto press = [&] (juce::Point<int> p, juce::ModifierKeys mods, std::optional<juce::Point<int>> to = {}) {
  13796. const auto down = mods.withFlags (juce::ModifierKeys::leftButtonModifier);
  13797. pl.mouseMove (event (p, mods, p, 1, false));
  13798. pl.mouseDown (event (p, down, p, 1, false));
  13799. if (to)
  13800. pl.mouseDrag (event (*to, down, p, 1, true));
  13801. pl.mouseUp (event (to ? *to : p, mods, p, 1, to.has_value()));
  13802. engine.flushLevels();
  13803. engine.dispatchPendingMessages();
  13804. };
  13805. const auto doubleClick = [&] (juce::Point<int> p) {
  13806. const auto down = juce::ModifierKeys (juce::ModifierKeys::leftButtonModifier);
  13807. pl.mouseDown (event (p, down, p, 2, false));
  13808. pl.mouseDoubleClick (event (p, down, p, 2, false));
  13809. pl.mouseUp (event (p, {}, p, 2, false));
  13810. engine.flushLevels();
  13811. engine.dispatchPendingMessages();
  13812. };
  13813. // the controls are found where they are drawn: M right of the plate, S left of it, the volume bar and the pan knob
  13814. // under them (the same geometry the header paints with)
  13815. const auto row = [&] (int t) { return pl.trackRowForSnapshot (t); };
  13816. const int w = pl.headerWidthForSnapshot();
  13817. const auto mAt = [&] (int t) { const auto r = row (t); return juce::Point<int> (w - 13 - 9, r.getY() + 11); }; // (meter column 9 px)
  13818. const auto sAt = [&] (int t) { return mAt (t) - juce::Point<int> (20, 0); };
  13819. const auto volumeAt = [&] (int t, float fraction) {
  13820. const auto r = row (t);
  13821. const auto left = 8, width = w - 9 - 2 - 32;
  13822. return juce::Point<int> (left + juce::roundToInt (fraction * (float) width), r.getY() + 26);
  13823. };
  13824. const auto panAt = [&] (int t) { const auto r = row (t); return juce::Point<int> (w - 9 - 6 - 7, r.getY() + 26); };
  13825. const auto& insert2 = [&]() -> const lynx::MixerTrack& { return song().mixer[2]; };
  13826. // ---- 3. the linked headers' controls act on the track's mixer track
  13827. press (mAt (1), {});
  13828. check ("m_mutes_the_insert", insert2().muted, juce::String ((int) insert2().muted));
  13829. press (mAt (1), {});
  13830. check ("m_again_unmutes", ! insert2().muted);
  13831. press (sAt (1), {});
  13832. check ("s_solos_the_insert", insert2().solo);
  13833. press (sAt (1), {});
  13834. press (volumeAt (1, 0.25f), {});
  13835. check ("volume_click_sets_the_level", std::abs (insert2().volume - 0.25f) < 0.03f, juce::String (insert2().volume, 3));
  13836. press (volumeAt (1, 0.25f), {}, volumeAt (1, 0.5f));
  13837. check ("volume_drag", std::abs (insert2().volume - 0.5f) < 0.03f, juce::String (insert2().volume, 3));
  13838. doubleClick (volumeAt (1, 0.5f));
  13839. check ("volume_double_click_0_db", insert2().volume == lynx::unityFader, juce::String (insert2().volume, 3));
  13840. press (panAt (1), {}, panAt (1) - juce::Point<int> (0, 40));
  13841. check ("pan_drag_up", std::abs (insert2().pan - 0.5f) < 0.02f, juce::String (insert2().pan, 3));
  13842. shotRows ("-controls.png", 7);
  13843. doubleClick (panAt (1));
  13844. check ("pan_double_click_centre", insert2().pan == 0.0f, juce::String (insert2().pan, 3));
  13845. // an instrument track's header acts on its channel's insert (Synth: insert 4 since round 190ib)
  13846. press (volumeAt (3, 0.4f), {});
  13847. check ("instrument_track_volume_on_its_insert", std::abs (song().mixer[4].volume - 0.4f) < 0.03f, juce::String (song().mixer[4].volume, 3));
  13848. engine.editSong ([] (lynx::Song& s) { s.mixer[4].volume = lynx::unityFader; });
  13849. // FL's track mute and solo stay on the Playlist track: Ctrl+click on M solos it, a muted track lights M and the
  13850. // first click unmutes it
  13851. press (mAt (1), ctrl);
  13852. check ("ctrl_m_solos_the_playlist_track", song().isTrackMuted (0) && ! song().isTrackMuted (1) && ! insert2().solo);
  13853. press (mAt (1), ctrl);
  13854. engine.editSong ([] (lynx::Song& s) {
  13855. for (auto& t : s.playlistTracks)
  13856. t.muted = false;
  13857. s.playlistTracks[1].muted = true;
  13858. });
  13859. press (mAt (1), {});
  13860. check ("m_unmutes_a_muted_playlist_track_first", ! song().isTrackMuted (1) && ! insert2().muted);
  13861. // a track that only repeats another keeps FL's LED (Track 7, Track 1's Kick): a click mutes the Playlist track
  13862. press (juce::Point<int> (w - 9 - 11, row (6).getCentreY()), {});
  13863. check ("unlinked_led_is_fl", song().isTrackMuted (6));
  13864. engine.editSong ([] (lynx::Song& s) { s.playlistTracks[6].muted = false; });
  13865. // round 190ib: a linked track and its insert keep one name, whichever is renamed
  13866. engine.editSong ([] (lynx::Song& s) { s.mixer[3].name = "Drums"; });
  13867. check ("insert_rename_renames_the_track", song().playlistTracks[2].name == "Drums");
  13868. engine.editSong ([] (lynx::Song& s) { s.playlistTracks[2].name = "Beat"; });
  13869. check ("track_rename_renames_the_insert", song().mixer[3].name == "Beat");
  13870. // ---- 4. new content follows: a sample on empty Track 6 makes it an audio track (insert 6)
  13871. engine.editSong ([] (lynx::Song& s) {
  13872. lynx::ChannelDef c;
  13873. c.name = "Guitar";
  13874. c.instrument = lynx::InstrumentKind::audioClip;
  13875. c.samplePath = "/shots/Guitar.wav";
  13876. s.channels.push_back (c);
  13877. lynx::Clip clip;
  13878. clip.kind = lynx::ClipKind::audio;
  13879. clip.channel = (int) s.channels.size() - 1;
  13880. clip.track = 5;
  13881. clip.start = 4 * 4 * lynx::ppq;
  13882. clip.length = 4 * 4 * lynx::ppq;
  13883. s.playlist.push_back (clip);
  13884. });
  13885. check ("new_sample_links_its_track", mode (5) == lynx::PlaylistTrackMode::audio && mixerOf (5) == 6 && song().channels.back().mixerTrack == 6,
  13886. juce::String (mixerOf (5)));
  13887. engine.undo();
  13888. check ("undo_takes_the_clip_and_the_link", mode (5) == lynx::PlaylistTrackMode::unassigned && song().channels.back().name != "Guitar");
  13889. // ---- 5. row heights (round 190ft): short rows keep M / S; from 34 px the volume and pan; tall rows the input
  13890. const auto heights = [&] (std::vector<std::pair<int, int>> rows) {
  13891. engine.editSong ([rows] (lynx::Song& s) {
  13892. for (const auto& [t, h] : rows)
  13893. s.playlistTracks[(std::size_t) t].height = h;
  13894. });
  13895. engine.dispatchPendingMessages();
  13896. };
  13897. heights ({ { 0, 16 }, { 1, 24 }, { 4, 80 } });
  13898. shotRows ("-heights.png", 7);
  13899. {
  13900. const auto r = row (1);
  13901. const auto before = insert2().volume;
  13902. press (juce::Point<int> (20, r.getY() + 12), {}); // (no volume bar on a 24 px row: the press selects)
  13903. check ("short_row_has_no_volume_bar", insert2().volume == before && pl.selectedTracksForSnapshot() == std::vector<int> { 1 });
  13904. press (juce::Point<int> (w - 22, r.getY() + 12), {});
  13905. check ("short_row_m_still_works", insert2().muted);
  13906. press (juce::Point<int> (w - 22, r.getY() + 12), {});
  13907. }
  13908. heights ({ { 0, 0 }, { 1, 0 }, { 4, 0 } });
  13909. // ---- 6. saved: .lynx keeps the switch; the links themselves are FL track modes
  13910. {
  13911. juce::String error;
  13912. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song()), error);
  13913. check ("lynx_round_trip", back && back->linkTracksToMixer && back->playlistTracks.size() > 4 && back->playlistTracks[1].mixerTrack == 2
  13914. && back->playlistTracks[0].mode == lynx::PlaylistTrackMode::instrument, error);
  13915. auto plain = song();
  13916. plain.linkTracksToMixer = false;
  13917. const auto json = lynx::ProjectFile::toJson (plain);
  13918. check ("off_not_saved", ! json.contains ("linkTracksToMixer"));
  13919. }
  13920. // ---- 7. off: FL's headers again (the links stay)
  13921. lynx::PlaylistComponent::answerLinkConfirmation = nullptr;
  13922. pl.runAction ("playlist.linkTracks");
  13923. engine.dispatchPendingMessages();
  13924. check ("switch_off_fl_headers", ! song().linkTracksToMixer && pl.headerWidthForSnapshot() == lynx::PlaylistComponent::flHeaderWidth
  13925. && mode (1) == lynx::PlaylistTrackMode::audio);
  13926. shotRows ("-off-after.png", 7);
  13927. // ---- 8. Settings › Project's switches
  13928. {
  13929. auto panel = lynx::makeSettingsPanel (engine, lynx::SettingsPage::project);
  13930. panel->setSize (760, 720);
  13931. savePng (lynx::shot::snapshot (*panel), prefix + "-settings-project.png");
  13932. }
  13933. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\nresult=" + (allOk ? "OK" : "FAIL") + "\n");
  13934. return allOk;
  13935. }
  13936. bool runFlPlShot (const juce::String& prefix)
  13937. {
  13938. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  13939. juce::StringArray report;
  13940. bool allOk = true;
  13941. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  13942. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  13943. allOk = allOk && ok;
  13944. };
  13945. const auto plain = [] (juce::String t) {
  13946. // (without the shortcut column and the mnemonic: the mark, or the " (K)" a translation without the letter gets)
  13947. t = t.upToFirstOccurrenceOf ("\t", false, false);
  13948. if (const auto at = t.indexOf (juce::String (" (") + juce::String::charToString (1)); at >= 0)
  13949. t = t.substring (0, at);
  13950. return t.removeCharacters (juce::String ("&_") + juce::String::charToString (1));
  13951. };
  13952. const auto findSub = [&plain] (const juce::PopupMenu& menu, const juce::String& text) -> const juce::PopupMenu* {
  13953. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  13954. if (it.getItem().subMenu != nullptr && plain (it.getItem().text) == plain (text))
  13955. return it.getItem().subMenu.get();
  13956. return nullptr;
  13957. };
  13958. const auto texts = [&plain] (const juce::PopupMenu& menu, int count) {
  13959. juce::StringArray out;
  13960. for (juce::PopupMenu::MenuItemIterator it (menu); it.next() && out.size() < count;)
  13961. out.add (it.getItem().isSeparator ? juce::String ("-") : it.getItem().isSectionHeader ? "[" + plain (it.getItem().text) + "]" : plain (it.getItem().text));
  13962. return out;
  13963. };
  13964. const auto modelTexts = [] (const std::vector<lynx::fltrackmenus::Entry>& model) {
  13965. juce::StringArray out;
  13966. for (const auto& e : model)
  13967. if (e.kind != lynx::fltrackmenus::Entry::Kind::list)
  13968. out.add (e.kind == lynx::fltrackmenus::Entry::Kind::separator ? juce::String ("-")
  13969. : e.kind == lynx::fltrackmenus::Entry::Kind::caption ? "[" + lynx::tr (e.text) + "]"
  13970. : lynx::tr (e.text));
  13971. return out;
  13972. };
  13973. const auto click = [&plain] (const juce::PopupMenu& menu, const juce::String& text) {
  13974. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  13975. if (plain (it.getItem().text) == plain (text) && it.getItem().isEnabled && it.getItem().action != nullptr)
  13976. {
  13977. it.getItem().action();
  13978. return true;
  13979. }
  13980. return false;
  13981. };
  13982. lynx::AudioEngine engine (false);
  13983. lynx::MainComponent ui (engine, false);
  13984. ui.setSize (1600, 900);
  13985. int vox = -1;
  13986. {
  13987. auto song = lynx::Song::makeDefault();
  13988. song.channels.push_back ({});
  13989. song.channels.back().name = "Vox";
  13990. song.channels.back().instrument = lynx::InstrumentKind::audioClip;
  13991. song.channels.back().volume = 0.6f;
  13992. song.channels.back().samplePath = writeShotSample (juce::File (prefix + "-vox.wav"), 330.0).getFullPathName().toStdString();
  13993. vox = (int) song.channels.size() - 1;
  13994. lynx::Clip c;
  13995. c.kind = lynx::ClipKind::audio;
  13996. c.channel = vox;
  13997. c.track = 3;
  13998. c.start = 4 * lynx::ppq;
  13999. c.length = 2 * lynx::ppq;
  14000. song.playlist.push_back (c);
  14001. engine.setSong (std::move (song));
  14002. }
  14003. engine.dispatchPendingMessages();
  14004. auto& playlist = ui.getPlaylistForSnapshot();
  14005. // ---- 1. the audio clip menu: Preview first, Automate › Panning / Volume
  14006. {
  14007. const auto menu = playlist.getClipMenuForSnapshot (0);
  14008. juce::PopupMenu::MenuItemIterator it (menu);
  14009. it.next(); // (the "Audio clip" title band)
  14010. it.next();
  14011. check ("clip_menu_preview_first", plain (it.getItem().text) == lynx::tr ("Preview"), it.getItem().text);
  14012. const auto* automate = findSub (menu, lynx::tr ("Automate"));
  14013. check ("clip_menu_automate", automate != nullptr && texts (*automate, 9) == modelTexts (lynx::fltrackmenus::automate()),
  14014. automate != nullptr ? texts (*automate, 9).joinIntoString ("|") : juce::String ("missing"));
  14015. saveMenus (juce::StringArray { "Audio clip menu", "Automate" }, std::vector<juce::PopupMenu> { menu, automate != nullptr ? *automate : juce::PopupMenu() },
  14016. prefix + "-clip-menu.png");
  14017. const auto before = engine.getSong().automations.size();
  14018. check ("automate_volume_runs", automate != nullptr && click (*automate, lynx::tr ("Volume")));
  14019. const auto& song = engine.getSong();
  14020. // (round 190dz: the Levels adjustment's volume multiplier, neutral = 0.5 of its 0…200 % travel)
  14021. const auto ok = song.automations.size() == before + 1 && song.automations.back().target.kind == lynx::AutomationTargetKind::channelAdjust
  14022. && song.automations.back().target.param == lynx::leveladjust::volume
  14023. && song.automations.back().target.index == vox && song.automations.back().points.size() == 2
  14024. && song.automations.back().points[1].tick == 2 * lynx::ppq && std::abs (song.automations.back().points[0].value - 0.5f) < 1.0e-6f;
  14025. const auto* clip = ok ? &song.playlist.back() : nullptr;
  14026. check ("automate_volume_clip", ok && clip->kind == lynx::ClipKind::automation && clip->track == 3 && clip->start == 4 * lynx::ppq
  14027. && clip->length == 2 * lynx::ppq,
  14028. ok ? juce::String::fromUTF8 (song.automations.back().name.c_str()) : juce::String());
  14029. engine.undo();
  14030. check ("automate_undo", engine.getSong().automations.size() == before);
  14031. // Preview: the clip's own audio (FL plays it through its channel); LYNX renders it for the preview output
  14032. const auto rendered = engine.renderClipAudio (0);
  14033. check ("preview_renders_the_clip", ! rendered.left.empty(), juce::String ((int) rendered.left.size()) + " frames");
  14034. }
  14035. // ---- 2. the Playlist's "+": its menu, a right click's audio track, the corner
  14036. {
  14037. const auto menu = playlist.getAddTrackMenuForSnapshot();
  14038. check ("add_menu_head", texts (menu, 5) == modelTexts (lynx::fltrackmenus::addTrack()), texts (menu, 5).joinIntoString ("|"));
  14039. saveMenus (juce::StringArray { "Playlist +" }, std::vector<juce::PopupMenu> { menu }, prefix + "-add-track-menu.png");
  14040. ui.selectTabForSnapshot (2);
  14041. engine.dispatchPendingMessages();
  14042. auto* button = playlist.getAddTrackButtonForSnapshot();
  14043. check ("add_button_in_corner", button != nullptr && button->isVisible() && button->getX() == 7 && button->getWidth() == 21 && button->getHeight() == 18
  14044. && button->getBottom() <= lynx::PlaylistComponent::headerHeight);
  14045. savePng (playlist.createComponentSnapshot (juce::Rectangle<int> (0, 0, juce::jmin (560, playlist.getWidth()), juce::jmin (260, playlist.getHeight()))),
  14046. prefix + "-playlist-corner.png");
  14047. const auto track = playlist.addAudioTrackNow();
  14048. const auto& song = engine.getSong();
  14049. check ("add_audio_track", track == 0 && song.playlistTracks.size() > 0 && song.playlistTracks[0].mode == lynx::PlaylistTrackMode::audio
  14050. && song.playlistTracks[0].mixerTrack > 0,
  14051. juce::String (track));
  14052. engine.undo();
  14053. }
  14054. // ---- 3. Track mode › Instrument track ›
  14055. {
  14056. const auto menu = playlist.getTrackMenuForSnapshot (5);
  14057. const auto* modes = findSub (menu, lynx::tr ("Track mode"));
  14058. const auto* instrument = modes != nullptr ? findSub (*modes, lynx::tr ("Instrument track")) : nullptr;
  14059. check ("instrument_track_head", instrument != nullptr && texts (*instrument, 4) == modelTexts (lynx::fltrackmenus::instrumentTrack()),
  14060. instrument != nullptr ? texts (*instrument, 4).joinIntoString ("|") : juce::String ("missing"));
  14061. const auto* existing = instrument != nullptr ? findSub (*instrument, lynx::tr ("Use existing channel")) : nullptr;
  14062. check ("use_existing_lists_generators", existing != nullptr && existing->getNumItems() == 5, existing != nullptr ? juce::String (existing->getNumItems()) : juce::String());
  14063. std::vector<juce::PopupMenu> menus { modes != nullptr ? *modes : juce::PopupMenu(), instrument != nullptr ? *instrument : juce::PopupMenu(),
  14064. existing != nullptr ? *existing : juce::PopupMenu() };
  14065. saveMenus (juce::StringArray { "Track mode", "Instrument track", "Use existing channel" }, menus, prefix + "-instrument-track-menu.png");
  14066. lynx::ChannelDef synth;
  14067. synth.name = "Lead";
  14068. synth.instrument = lynx::InstrumentKind::synth;
  14069. const auto channels = engine.getSong().channels.size();
  14070. int made = -1;
  14071. engine.editSong ([&] (lynx::Song& s) { made = lynx::trackmodes::addInstrumentTrack (s, synth, 5); });
  14072. check ("instrument_track_new_channel", made == (int) channels && engine.getSong().playlistTracks.size() > 5
  14073. && engine.getSong().playlistTracks[5].channel == made);
  14074. engine.undo();
  14075. }
  14076. // ---- 4. the Channel rack menu: Assign to new instrument track / Unassign
  14077. {
  14078. auto& rack = ui.getRackForSnapshot();
  14079. const auto menu = rack.getChannelMenuForSnapshot (1);
  14080. saveMenus (juce::StringArray { "Channel menu" }, std::vector<juce::PopupMenu> { menu }, prefix + "-channel-menu.png");
  14081. check ("assign_runs", click (menu, lynx::tr ("Assign to new instrument track")));
  14082. const auto tracks = lynx::trackmodes::instrumentTracksOf (engine.getSong(), 1);
  14083. check ("assign_first_free_track", tracks == std::vector<int> { 0 }, juce::String (tracks.empty() ? -1 : tracks.front()));
  14084. const auto again = rack.getChannelMenuForSnapshot (1);
  14085. check ("unassign_offered", click (again, lynx::tr ("Unassign from instrument track")) && lynx::trackmodes::instrumentTracksOf (engine.getSong(), 1).empty());
  14086. bool greyed = false;
  14087. const auto voxMenu = rack.getChannelMenuForSnapshot (vox);
  14088. for (juce::PopupMenu::MenuItemIterator it (voxMenu); it.next();)
  14089. if (plain (it.getItem().text) == plain (lynx::tr ("Assign to new instrument track")))
  14090. greyed = ! it.getItem().isEnabled;
  14091. check ("assign_greyed_for_audio_clip_channel", greyed);
  14092. }
  14093. // ---- 5. Tools › One-click audio recording
  14094. std::fprintf (stderr, "flplshot: tools\n");
  14095. {
  14096. const auto names = ui.getMenuNamesForSnapshot();
  14097. const auto tools = ui.getMenuForSnapshot (names.indexOf (lynx::tr ("Tools")));
  14098. const auto* oneClick = findSub (tools, lynx::tr ("One-click audio recording"));
  14099. check ("one_click_submenu", oneClick != nullptr && texts (*oneClick, 3) == modelTexts (lynx::fltrackmenus::oneClickRecording()),
  14100. oneClick != nullptr ? texts (*oneClick, 3).joinIntoString ("|") : juce::String ("missing"));
  14101. saveMenus (juce::StringArray { "Tools", "One-click audio recording" }, std::vector<juce::PopupMenu> { tools, oneClick != nullptr ? *oneClick : juce::PopupMenu() },
  14102. prefix + "-tools-one-click.png");
  14103. const auto plan = lynx::oneclick::plan (engine.getSong(), {}, 2, lynx::oneclick::Into::playlist);
  14104. check ("one_click_plan", plan.insert == 2 && plan.armInsert && plan.askInput && plan.songMode);
  14105. }
  14106. // ---- 6. Mixer › Disk recording › Latency compensation
  14107. {
  14108. auto& strips = ui.getMixerForSnapshot().getStripsForSnapshot();
  14109. const auto menu = strips.buildMenu (1);
  14110. const auto* disk = findSub (menu, lynx::tr ("Disk recording"));
  14111. int after = -1, at = -1, i = 0;
  14112. bool ticked = false;
  14113. if (disk != nullptr)
  14114. for (juce::PopupMenu::MenuItemIterator it (*disk); it.next(); ++i)
  14115. {
  14116. if (plain (it.getItem().text) == plain (lynx::tr ("Auto-create audio clip (the rendered files go on the Playlist)")))
  14117. after = i;
  14118. if (plain (it.getItem().text) == plain (lynx::tr ("Latency compensation")))
  14119. {
  14120. at = i;
  14121. ticked = it.getItem().isTicked;
  14122. }
  14123. }
  14124. check ("latency_comp_item", disk != nullptr && after >= 0 && at == after + 1 && ticked && engine.getRecordOptions().latencyCompensation,
  14125. juce::String (after) + " " + juce::String (at));
  14126. saveMenus (juce::StringArray { "Disk recording" }, std::vector<juce::PopupMenu> { disk != nullptr ? *disk : juce::PopupMenu() },
  14127. prefix + "-disk-recording.png");
  14128. check ("latency_comp_toggles", disk != nullptr && click (*disk, lynx::tr ("Latency compensation")) && ! engine.getRecordOptions().latencyCompensation);
  14129. }
  14130. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\nresult=" + (allOk ? "OK" : "FAIL") + "\n");
  14131. return allOk;
  14132. }
  14133. // --flclipshot (round 190dz): see the dispatch above
  14134. // a menu as JUCE lays it out with explicit column breaks (PopupMenu::addColumnBreak): the columns side by side on
  14135. // one menu background; custom items (the title band) are painted by their own component
  14136. static juce::Image columnMenuImage (const juce::PopupMenu& menu)
  14137. {
  14138. auto& lf = juce::LookAndFeel::getDefaultLookAndFeel();
  14139. const auto border = lf.getPopupMenuBorderSize();
  14140. struct Row
  14141. {
  14142. const juce::PopupMenu::Item* item;
  14143. int height;
  14144. };
  14145. std::vector<std::vector<Row>> columns (1);
  14146. std::vector<int> widths (1, 160);
  14147. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  14148. {
  14149. const auto& item = it.getItem();
  14150. int w = 0, h = 0;
  14151. if (item.customComponent != nullptr)
  14152. item.customComponent->getIdealSize (w, h);
  14153. else
  14154. {
  14155. lf.getIdealPopupMenuItemSize (item.text.upToFirstOccurrenceOf ("\t", false, false), item.isSeparator, item.isSectionHeader ? -1 : 0, w, h);
  14156. if (item.isSectionHeader)
  14157. h += h / 2; // as JUCE does
  14158. if (item.text.containsChar ('\t'))
  14159. w += 90;
  14160. }
  14161. columns.back().push_back ({ &item, h });
  14162. widths.back() = juce::jmax (widths.back(), w + 10);
  14163. if (item.shouldBreakAfter)
  14164. {
  14165. columns.emplace_back();
  14166. widths.push_back (160);
  14167. }
  14168. }
  14169. int width = 0, height = 0;
  14170. for (std::size_t c = 0; c < columns.size(); ++c)
  14171. {
  14172. width += widths[c];
  14173. int h = 2 * border;
  14174. for (const auto& row : columns[c])
  14175. h += row.height;
  14176. height = juce::jmax (height, h);
  14177. }
  14178. auto image = lynx::shot::canvas (width, height);
  14179. juce::Graphics g (image);
  14180. lynx::shot::logical (g);
  14181. lf.drawPopupMenuBackground (g, width, height);
  14182. int x = 0;
  14183. for (std::size_t c = 0; c < columns.size(); ++c)
  14184. {
  14185. int y = border;
  14186. for (const auto& row : columns[c])
  14187. {
  14188. const auto& item = *row.item;
  14189. const juce::Rectangle<int> r (x, y, widths[c], row.height);
  14190. if (item.customComponent != nullptr)
  14191. {
  14192. juce::Graphics::ScopedSaveState state (g);
  14193. g.setOrigin (r.getPosition());
  14194. item.customComponent->setSize (r.getWidth(), r.getHeight());
  14195. item.customComponent->paintEntireComponent (g, false);
  14196. }
  14197. else if (item.isSectionHeader)
  14198. lf.drawPopupMenuSectionHeader (g, r, item.text);
  14199. else
  14200. {
  14201. juce::Graphics::ScopedSaveState state (g);
  14202. g.setOrigin (r.getPosition());
  14203. lf.drawPopupMenuItem (g, r.withPosition (0, 0), item.isSeparator, item.isEnabled, false, item.isTicked, item.subMenu != nullptr,
  14204. item.text.upToFirstOccurrenceOf ("\t", false, false), item.text.fromFirstOccurrenceOf ("\t", false, false),
  14205. item.image.get(), nullptr);
  14206. }
  14207. y += row.height;
  14208. }
  14209. x += widths[c];
  14210. if (c + 1 < columns.size()) // (JUCE's column separator)
  14211. {
  14212. g.setColour (lf.findColour (juce::PopupMenu::textColourId).withAlpha (0.15f));
  14213. g.fillRect (x - 1, border, 1, height - 2 * border);
  14214. }
  14215. }
  14216. return image;
  14217. }
  14218. // --genpresetshot (round 190fs): see the dispatch above
  14219. bool runGenPresetShot (const juce::String& prefix)
  14220. {
  14221. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  14222. juce::StringArray report;
  14223. bool allOk = true;
  14224. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  14225. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  14226. allOk = allOk && ok;
  14227. };
  14228. const auto shoot = [&prefix] (juce::Component& c, const char* name) {
  14229. savePng (c.createComponentSnapshot (c.getLocalBounds()), prefix + "-" + name + ".png");
  14230. };
  14231. const auto plain = [] (juce::String t) { return t.upToFirstOccurrenceOf ("\t", false, false).removeCharacters ("&"); };
  14232. const auto texts = [&plain] (const juce::PopupMenu& menu) {
  14233. juce::StringArray out;
  14234. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  14235. out.add (it.getItem().isSeparator ? juce::String ("-") : it.getItem().isSectionHeader ? "[" + plain (it.getItem().text) + "]" : plain (it.getItem().text));
  14236. return out;
  14237. };
  14238. const auto click = [&plain] (const juce::PopupMenu& menu, const juce::String& text) {
  14239. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  14240. if (plain (it.getItem().text) == plain (text) && it.getItem().isEnabled && it.getItem().action != nullptr)
  14241. {
  14242. it.getItem().action();
  14243. return true;
  14244. }
  14245. return false;
  14246. };
  14247. const auto sameSound = [] (const lynx::ChannelDef& a, const lynx::ChannelDef& b) { return lynx::genpresets::sameSound (a, b); };
  14248. lynx::AudioEngine engine (false);
  14249. const auto& fl = lynx::flStudioAccess();
  14250. auto dx = lynx::natives::makeChannel (lynx::InstrumentKind::dx10, fl);
  14251. auto osc = lynx::natives::makeChannel (lynx::InstrumentKind::threeosc, fl);
  14252. check ("channels_made", dx.has_value() && osc.has_value());
  14253. if (! dx || ! osc)
  14254. {
  14255. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\n");
  14256. return false;
  14257. }
  14258. engine.editSong ([&] (lynx::Song& s) {
  14259. s.channels.clear();
  14260. s.channels.push_back (*dx);
  14261. s.channels.back().mixerTrack = 1;
  14262. s.channels.push_back (*osc);
  14263. s.channels.back().mixerTrack = 2;
  14264. lynx::ChannelDef synth;
  14265. synth.instrument = lynx::InstrumentKind::synth;
  14266. synth.name = "Synth";
  14267. synth.mixerTrack = 3;
  14268. s.channels.push_back (synth);
  14269. });
  14270. const auto channel = [&engine] (int i) { return engine.getSong().channels[(std::size_t) i]; };
  14271. // ---- 1. Fruity DX10: the preset box before and after "Save preset..."
  14272. {
  14273. auto frame = lynx::makeChannelFrame (engine, 0, 0);
  14274. frame->setSize (juce::jmax (500, frame->getWidth()), juce::jmax (300, frame->getHeight()));
  14275. auto menu = lynx::channelPresetMenu (*frame);
  14276. check ("dx10_menu", menu.has_value());
  14277. const auto before = menu ? texts (*menu) : juce::StringArray();
  14278. check ("dx10_menu_has_save", before.contains (lynx::tr ("Save preset...")) && before.contains (lynx::tr ("Show the presets folder"))
  14279. && ! before.contains ("[" + lynx::tr ("Your presets") + "]"), before.joinIntoString ("|"));
  14280. if (menu)
  14281. saveMenus (juce::StringArray { "Fruity DX10 presets" }, std::vector<juce::PopupMenu> { *menu }, prefix + "-dx10-menu-before.png");
  14282. // a sound of its own: the bank's 4th preset, then a knob moved (a sound no factory preset has)
  14283. const auto mine = [&] {
  14284. auto c = channel (0);
  14285. if (auto b = lynx::banks::withPreset (c, 3))
  14286. c = *b;
  14287. if (! c.pluginState.empty())
  14288. c.pluginState[c.pluginState.size() / 2] ^= 0x5a;
  14289. return c;
  14290. }();
  14291. engine.editSong ([&] (lynx::Song& s) { s.channels[0] = mine; });
  14292. check ("dx10_saved", lynx::channelPresetSave (*frame, "My FM Bell"));
  14293. const auto file = lynx::genpresetui::folderFor (lynx::InstrumentKind::dx10).getChildFile ("My FM Bell.lynxpreset");
  14294. check ("dx10_file", file.existsAsFile() && lynx::genpresetui::isPresetFile (file), file.getFullPathName());
  14295. check ("dx10_box_shows_it", lynx::channelPresetName (*frame) == "My FM Bell", lynx::channelPresetName (*frame));
  14296. menu = lynx::channelPresetMenu (*frame);
  14297. const auto after = menu ? texts (*menu) : juce::StringArray();
  14298. check ("dx10_menu_your_presets", after.contains ("[" + lynx::tr ("Your presets") + "]") && after.contains ("My FM Bell")
  14299. && after.contains (lynx::tr ("Delete preset \"{0}\"", { "My FM Bell" })), after.joinIntoString ("|"));
  14300. if (menu)
  14301. saveMenus (juce::StringArray { "Fruity DX10 presets" }, std::vector<juce::PopupMenu> { *menu }, prefix + "-dx10-menu.png");
  14302. shoot (*frame, "dx10-window");
  14303. // another sound, then the user's preset from the menu: the saved sound back, one undo step, project changed
  14304. if (auto other = lynx::banks::withPreset (channel (0), 0))
  14305. engine.editSong ([&] (lynx::Song& s) { s.channels[0] = *other; });
  14306. check ("dx10_other_sound", ! sameSound (channel (0), mine));
  14307. engine.markSaved();
  14308. menu = lynx::channelPresetMenu (*frame);
  14309. check ("dx10_load_click", menu.has_value() && click (*menu, "My FM Bell"));
  14310. check ("dx10_loaded_identical", sameSound (channel (0), mine) && channel (0).pluginState == mine.pluginState);
  14311. check ("dx10_loaded_name_and_insert", channel (0).name == "My FM Bell" && channel (0).mixerTrack == 1,
  14312. juce::String::fromUTF8 (channel (0).name.c_str()));
  14313. check ("dx10_project_changed", engine.isModified());
  14314. engine.undo();
  14315. check ("dx10_one_undo_step", ! sameSound (channel (0), mine));
  14316. engine.redo();
  14317. check ("dx10_redo", sameSound (channel (0), mine));
  14318. // the Browser: a new channel with the preset's generator, sound and name
  14319. juce::String error;
  14320. const auto count = engine.getSong().channels.size();
  14321. check ("browser_new_channel", lynx::genpresetui::addChannel (engine, file, error) && engine.getSong().channels.size() == count + 1, error);
  14322. const auto added = engine.getSong().channels.back();
  14323. check ("browser_channel_sound", added.instrument == lynx::InstrumentKind::dx10 && sameSound (added, mine) && added.name == "My FM Bell");
  14324. engine.undo();
  14325. check ("browser_channel_undo", engine.getSong().channels.size() == count);
  14326. }
  14327. // ---- 2. 3x Osc: save, the menu, delete
  14328. {
  14329. auto frame = lynx::makeChannelFrame (engine, 1, 0);
  14330. frame->setSize (juce::jmax (500, frame->getWidth()), juce::jmax (300, frame->getHeight()));
  14331. check ("3xosc_saved", lynx::channelPresetSave (*frame, "Wide Saw Lead") && lynx::channelPresetSave (*frame, "Sub Bass"));
  14332. auto menu = lynx::channelPresetMenu (*frame);
  14333. const auto items = menu ? texts (*menu) : juce::StringArray();
  14334. check ("3xosc_menu", items.contains ("Wide Saw Lead") && items.contains ("Sub Bass") && items.contains (lynx::tr ("Save preset...")),
  14335. items.joinIntoString ("|"));
  14336. if (menu)
  14337. saveMenus (juce::StringArray { "3x Osc presets" }, std::vector<juce::PopupMenu> { *menu }, prefix + "-3xosc-menu.png");
  14338. shoot (*frame, "3xosc-window");
  14339. check ("3xosc_delete", menu.has_value() && click (*menu, lynx::tr ("Delete preset \"{0}\"", { "Sub Bass" })));
  14340. check ("3xosc_deleted", lynx::genpresetui::userPresets (lynx::InstrumentKind::threeosc).size() == 1
  14341. && ! lynx::genpresetui::folderFor (lynx::InstrumentKind::threeosc).getChildFile ("Sub Bass.lynxpreset").exists());
  14342. menu = lynx::channelPresetMenu (*frame);
  14343. const auto left = menu ? texts (*menu) : juce::StringArray();
  14344. check ("3xosc_menu_after_delete", left.contains ("Wide Saw Lead") && ! left.contains ("Sub Bass"), left.joinIntoString ("|"));
  14345. }
  14346. // ---- 3. LYNX's synth: its "Presets..." box
  14347. {
  14348. engine.editSong ([] (lynx::Song& s) { s.channels[2].synth.cutoff = 777.0f; });
  14349. auto frame = lynx::makeChannelFrame (engine, 2, 0);
  14350. frame->setSize (juce::jmax (500, frame->getWidth()), juce::jmax (300, frame->getHeight()));
  14351. check ("synth_saved", lynx::channelPresetSave (*frame, "Dark Pad"));
  14352. const auto menu = lynx::channelPresetMenu (*frame);
  14353. const auto items = menu ? texts (*menu) : juce::StringArray();
  14354. check ("synth_menu", items.contains ("Dark Pad") && items.contains (lynx::tr ("Save preset...")) && items.contains (lynx::tr ("Show the presets folder")),
  14355. items.joinIntoString ("|"));
  14356. if (menu)
  14357. saveMenus (juce::StringArray { "Synth presets" }, std::vector<juce::PopupMenu> { *menu }, prefix + "-synth-menu.png");
  14358. const auto saved = lynx::genpresetui::read (lynx::genpresetui::folderFor (lynx::InstrumentKind::synth).getChildFile ("Dark Pad.lynxpreset"));
  14359. check ("synth_file", saved.has_value() && saved->sound.synth.cutoff == 777.0f);
  14360. }
  14361. // ---- 4. the name box (the hosted plugins' and the effects' "Save preset" box)
  14362. {
  14363. auto box = lynx::genpresetui::makeNameBox ("My FM Bell");
  14364. box->setSize (juce::jmax (360, box->getWidth()), juce::jmax (150, box->getHeight()));
  14365. shoot (*box, "save-name-box");
  14366. check ("name_box", box->getTextEditorContents ("name") == "My FM Bell");
  14367. }
  14368. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\n");
  14369. return allOk;
  14370. }
  14371. // --flfixshot (round 190ey): see the dispatch above
  14372. bool runFlFixShot (const juce::String& prefix)
  14373. {
  14374. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  14375. juce::StringArray report;
  14376. bool allOk = true;
  14377. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  14378. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  14379. allOk = allOk && ok;
  14380. };
  14381. const auto shoot = [&prefix] (juce::Component& c, const char* name) {
  14382. savePng (c.createComponentSnapshot (c.getLocalBounds()), prefix + "-" + name + ".png");
  14383. };
  14384. const auto plain = [] (juce::String t) {
  14385. t = t.upToFirstOccurrenceOf ("\t", false, false);
  14386. if (const auto at = t.indexOf (juce::String (" (") + juce::String::charToString (1)); at >= 0)
  14387. t = t.substring (0, at);
  14388. return t.removeCharacters (juce::String ("&_") + juce::String::charToString (1));
  14389. };
  14390. const auto texts = [&plain] (const juce::PopupMenu& menu) {
  14391. juce::StringArray out;
  14392. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  14393. out.add (it.getItem().isSeparator ? juce::String ("-") : it.getItem().isSectionHeader ? "[" + plain (it.getItem().text) + "]" : plain (it.getItem().text));
  14394. return out;
  14395. };
  14396. const auto findSub = [&plain] (const juce::PopupMenu& menu, const juce::String& text) -> const juce::PopupMenu* {
  14397. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  14398. if (it.getItem().subMenu != nullptr && plain (it.getItem().text) == plain (text))
  14399. return it.getItem().subMenu.get();
  14400. return nullptr;
  14401. };
  14402. const auto click = [&plain] (const juce::PopupMenu& menu, const juce::String& text) {
  14403. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  14404. if (plain (it.getItem().text) == plain (text) && it.getItem().isEnabled && it.getItem().action != nullptr)
  14405. {
  14406. it.getItem().action();
  14407. return true;
  14408. }
  14409. return false;
  14410. };
  14411. const auto folder = juce::File (prefix).getParentDirectory().getChildFile ("flfix-samples");
  14412. folder.createDirectory();
  14413. const auto writeWav = [] (const juce::File& file, double rate, int frames, double hz) {
  14414. juce::AudioBuffer<float> buffer (1, frames);
  14415. for (int i = 0; i < frames; ++i)
  14416. buffer.setSample (0, i, (float) (0.8 * std::sin (juce::MathConstants<double>::twoPi * hz * i / rate) * std::exp (-i / (rate * 0.12))));
  14417. file.deleteFile();
  14418. juce::WavAudioFormat wav;
  14419. if (auto out = std::unique_ptr<juce::AudioFormatWriter> (wav.createWriterFor (file.createOutputStream().release(), rate, 1, 16, {}, 0)))
  14420. out->writeFromAudioSampleBuffer (buffer, 0, frames);
  14421. return file;
  14422. };
  14423. // ---- 1. the Sampler page (SMP-1 / 4 / 5 / 7, CTL-4)
  14424. {
  14425. lynx::AudioEngine engine (false);
  14426. const auto clap = writeWav (folder.getChildFile ("Basic 808 Clap.wav"), 44100.0, 11600, 180.0);
  14427. const auto loop48 = writeWav (folder.getChildFile ("Loop 48k.wav"), 48000.0, 48000, 220.0);
  14428. engine.editSong ([&] (lynx::Song& s) {
  14429. if (s.channels.empty())
  14430. s.channels.resize (1);
  14431. lynx::audioclips::loadSampleInto (s.channels[0], clap.getFullPathName().toStdString(), "808 Clap");
  14432. });
  14433. const auto sampler = [&engine] { return engine.getSong().channels[0].sampler; };
  14434. auto frame = lynx::makeChannelFrame (engine, 0, 0);
  14435. frame->setSize (frame->getWidth() > 0 ? frame->getWidth() : 700, frame->getHeight() > 0 ? frame->getHeight() : 720);
  14436. frame->createComponentSnapshot (frame->getLocalBounds());
  14437. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (8000);
  14438. auto& f = *frame;
  14439. lynx::samplerPageTurn (f, "show", 0.0);
  14440. const auto rate = engine.getTransport().sampleRate.load();
  14441. check ("resample_greyed_at_project_rate", lynx::samplerPageQuery (f, "resample") == (std::abs (rate - 44100.0) < 0.5 ? "0" : "1"), juce::String (rate));
  14442. check ("load_regions_greyed_without_regions", lynx::samplerPageQuery (f, "loadRegions") == "0");
  14443. check ("load_markers_greyed_without_markers", lynx::samplerPageQuery (f, "loadMarkers") == "0");
  14444. check ("bit_depth_16", lynx::samplerPageQuery (f, "corner") == "16", lynx::samplerPageQuery (f, "corner"));
  14445. check ("wave_hint_summary", lynx::samplerPageQuery (f, "waveHint").startsWith ("44100Hz, 16Bit int mono, 0:263"), lynx::samplerPageQuery (f, "waveHint"));
  14446. shoot (f, "sampler-44k");
  14447. // SMP-5: MUL's text
  14448. lynx::samplerPageTurn (f, "mul", 800.0);
  14449. check ("mul_text", lynx::samplerPageQuery (f, "mulText") == "105.70%", lynx::samplerPageQuery (f, "mulText"));
  14450. lynx::samplerPageTurn (f, "mul", 0.0);
  14451. // SMP-4: CROSSFADE on a loopless sample: Use loop points on, the loop = the whole sample, the box reads 32
  14452. engine.editSong ([] (lynx::Song& s) { s.channels[0].sampler.useLoopPoints = false; });
  14453. lynx::samplerPageTurn (f, "crossfade", 120.0);
  14454. check ("crossfade_loops_whole_sample", sampler().useLoopPoints && sampler().loopStart == 0 && sampler().loopEnd == 11599,
  14455. juce::String (sampler().loopStart) + ".." + juce::String (sampler().loopEnd));
  14456. check ("bit_depth_32_precomputed", lynx::samplerPageQuery (f, "corner") == "32", lynx::samplerPageQuery (f, "corner"));
  14457. frame->createComponentSnapshot (frame->getLocalBounds());
  14458. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (8000);
  14459. shoot (f, "sampler-crossfade-red-loop");
  14460. lynx::samplerPageTurn (f, "crossfade", 0.0);
  14461. // SMP-3: a loop set with END alone, drawn red (FL: 0..276)
  14462. engine.editSong ([] (lynx::Song& s) {
  14463. s.channels[0].sampler.loopStart = 0;
  14464. s.channels[0].sampler.loopEnd = 2400;
  14465. });
  14466. lynx::samplerPageTurn (f, "show", 0.0);
  14467. shoot (f, "sampler-end-loop-red");
  14468. // round 190gw (live check 190gu B3): the waveform menu's Spectrum view / Multichannel waveform view, on a stereo
  14469. // clap-like noise burst (left and right differ) with no loop, as FL's shot
  14470. {
  14471. const auto noisy = folder.getChildFile ("Noise Clap.wav");
  14472. juce::AudioBuffer<float> b (2, 44100);
  14473. juce::Random random (190);
  14474. for (int i = 0; i < b.getNumSamples(); ++i)
  14475. for (int c = 0; c < 2; ++c)
  14476. b.setSample (c, i, (float) ((random.nextFloat() * 2.0f - 1.0f) * 0.9 * std::exp (-i / (44100.0 * (c == 0 ? 0.10 : 0.18)))
  14477. * (i > 1500 * c ? 1.0 : 0.15)));
  14478. noisy.deleteFile();
  14479. juce::WavAudioFormat wav;
  14480. if (auto out = std::unique_ptr<juce::AudioFormatWriter> (wav.createWriterFor (noisy.createOutputStream().release(), 44100.0, 2, 16, {}, 0)))
  14481. out->writeFromAudioSampleBuffer (b, 0, b.getNumSamples());
  14482. const auto before = engine.getSong().channels[0];
  14483. engine.editSong ([&] (lynx::Song& s) {
  14484. s.channels[0].samplePath = noisy.getFullPathName().toStdString();
  14485. s.channels[0].sampler.loopStart = s.channels[0].sampler.loopEnd = -1;
  14486. s.channels[0].sampler.useLoopPoints = false;
  14487. });
  14488. lynx::samplerPageTurn (f, "show", 0.0);
  14489. frame->createComponentSnapshot (frame->getLocalBounds()); // (starts the new file's waveform)
  14490. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (8000);
  14491. lynx::samplerpage::waveViews().spectrum = true;
  14492. lynx::samplerPageTurn (f, "show", 0.0);
  14493. shoot (f, "sampler-spectrum-view");
  14494. lynx::samplerpage::waveViews() = { false, true };
  14495. lynx::samplerPageTurn (f, "show", 0.0);
  14496. shoot (f, "sampler-multichannel-view");
  14497. lynx::samplerpage::waveViews() = {};
  14498. engine.editSong ([&before] (lynx::Song& s) { s.channels[0] = before; });
  14499. lynx::samplerPageTurn (f, "show", 0.0);
  14500. frame->createComponentSnapshot (frame->getLocalBounds());
  14501. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (8000);
  14502. }
  14503. // SMP-7: the waveform menu
  14504. const auto waveMenu = lynx::samplerWaveMenu (f);
  14505. juce::StringArray expected { lynx::tr ("Reload"), lynx::tr ("Save as..."), lynx::tr ("Locate file"), lynx::tr ("Copy audio to clipboard"),
  14506. lynx::tr ("Paste audio from clipboard"), "-", lynx::tr ("Edit in audio editor"),
  14507. lynx::tr ("Edit in pitch corrector"), lynx::tr ("Edit in time warper"), "-", // (round 190gw)
  14508. lynx::tr ("Open in new sampler channel"), lynx::tr ("Open in new Fruity Granulizer channel"),
  14509. lynx::tr ("Open in new Fruity Slicer channel"), lynx::tr ("Open in new Slicex channel"), "-", // (round 190gk)
  14510. lynx::tr ("Detect tempo") };
  14511. if (lynx::fileProperties) // (round 190gk: Windows only)
  14512. expected.add (lynx::tr ("Get properties"));
  14513. expected.addArray (juce::StringArray { "-", lynx::tr ("Spectrum view"), lynx::tr ("Multichannel waveform view") }); // (round 190gw)
  14514. check ("wave_menu_items", waveMenu.has_value() && texts (*waveMenu) == expected, waveMenu.has_value() ? texts (*waveMenu).joinIntoString ("|") : juce::String ("none"));
  14515. if (waveMenu.has_value())
  14516. saveMenus (juce::StringArray { "Sampler waveform" }, std::vector<juce::PopupMenu> { *waveMenu }, prefix + "-wave-menu.png");
  14517. check ("copy_audio_to_clipboard", waveMenu.has_value() && click (*waveMenu, lynx::tr ("Copy audio to clipboard"))
  14518. && lynx::audioclipboard::editor().frames() == 11600);
  14519. // SMP-1: a 48 kHz sample in this project: Resample enabled
  14520. lynx::samplerPageTurn (f, "show", 0.0);
  14521. engine.editSong ([&] (lynx::Song& s) { s.channels[0].samplePath = loop48.getFullPathName().toStdString(); });
  14522. lynx::samplerPageTurn (f, "show", 0.0);
  14523. check ("resample_enabled_48k", lynx::samplerPageQuery (f, "resample") == (std::abs (rate - 48000.0) < 0.5 ? "0" : "1"), juce::String (rate));
  14524. frame->createComponentSnapshot (frame->getLocalBounds()); // (starts the new file's waveform)
  14525. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (8000);
  14526. shoot (f, "sampler-48k");
  14527. // CTL-4: Remove sample renames the channel "Sampler"
  14528. lynx::samplerFileRowPress (f, 3);
  14529. check ("remove_sample_renames", engine.getSong().channels[0].name == "Sampler" && engine.getSong().channels[0].samplePath.empty(),
  14530. juce::String::fromUTF8 (engine.getSong().channels[0].name.c_str()));
  14531. lynx::samplerPageTurn (f, "show", 0.0);
  14532. check ("no_sample_content_greyed", lynx::samplerPageQuery (f, "keepOnDisk") == "0" && lynx::samplerPageQuery (f, "resample") == "0");
  14533. shoot (f, "sampler-removed");
  14534. }
  14535. // ---- 2. the Multilink button's menu with multilink off (CTL-1)
  14536. lynx::AudioEngine engine (false);
  14537. lynx::MainComponent ui (engine, false);
  14538. ui.setSize (1600, 900);
  14539. {
  14540. using lynx::AutomationTarget;
  14541. using lynx::AutomationTargetKind;
  14542. engine.editSong ([] (lynx::Song& s) {
  14543. if (s.channels.empty())
  14544. s.channels.resize (1);
  14545. s.channels[0].name = "808 Kick";
  14546. });
  14547. engine.setMultilink (false);
  14548. engine.noteTweaked ({ AutomationTargetKind::channelVolume, 0 });
  14549. engine.noteTweaked ({ AutomationTargetKind::channelPan, 0 });
  14550. const auto menu = ui.getMultilinkMenuForSnapshot();
  14551. juce::PopupMenu::MenuItemIterator first (menu);
  14552. first.next();
  14553. const auto caption = first.getItem().text;
  14554. bool columnBreak = false, lynxLines = false;
  14555. juce::String rightCaption;
  14556. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  14557. {
  14558. if (columnBreak && rightCaption.isEmpty() && it.getItem().isSectionHeader)
  14559. rightCaption = it.getItem().text;
  14560. columnBreak = columnBreak || it.getItem().shouldBreakAfter;
  14561. lynxLines = lynxLines || it.getItem().text == lynx::tr ("Link to controller");
  14562. }
  14563. check ("ml_off_left_column_named", first.getItem().isSectionHeader && caption == lynx::describeAutomationTarget (engine, { AutomationTargetKind::channelPan, 0 }), caption);
  14564. check ("ml_off_two_columns", columnBreak && rightCaption == lynx::tr ("Last 2 tweaked parameters"), rightCaption);
  14565. check ("ml_off_no_lynx_greyed_lines", ! lynxLines);
  14566. savePng (columnMenuImage (menu), prefix + "-multilink-off-menu.png");
  14567. }
  14568. // ---- 3. the Playlist (PL-1 / 2 / 3 / 6 / 7 / 8)
  14569. auto& playlist = ui.getPlaylistForSnapshot();
  14570. {
  14571. auto song = lynx::Song::makeDefault();
  14572. lynx::ChannelDef bass;
  14573. bass.name = "Amount Too - Bass";
  14574. bass.instrument = lynx::InstrumentKind::audioClip;
  14575. bass.samplePath = writeWav (folder.getChildFile ("bass.wav"), 44100.0, 88200, 82.0).getFullPathName().toStdString();
  14576. bass.misc.levels.volume = 1.468f;
  14577. song.channels.push_back (bass);
  14578. lynx::Clip c;
  14579. c.kind = lynx::ClipKind::audio;
  14580. c.channel = (int) song.channels.size() - 1;
  14581. c.track = 3;
  14582. c.start = 4 * lynx::ppq;
  14583. c.length = 2 * lynx::ppq;
  14584. song.playlist.push_back (c);
  14585. engine.setSong (std::move (song));
  14586. }
  14587. engine.dispatchPendingMessages();
  14588. const auto clipIndex = (int) engine.getSong().playlist.size() - 1;
  14589. {
  14590. const auto menu = playlist.getClipMenuForSnapshot (clipIndex);
  14591. const auto* automate = findSub (menu, lynx::tr ("Automate"));
  14592. check ("automate_volume_runs", automate != nullptr && click (*automate, lynx::tr ("Volume")));
  14593. const auto& song = engine.getSong();
  14594. const auto made = (int) song.automations.size() - 1;
  14595. check ("automate_makes_current_clip", made >= 0 && playlist.brush.kind == lynx::ClipKind::automation && playlist.brush.index == made,
  14596. juce::String (playlist.brush.index));
  14597. // (PL-2: Levels VOL 147 %, FL's clip plays unity)
  14598. check ("automate_volume_unity", made >= 0 && song.automations.back().points[0].value == 0.5f
  14599. && lynx::lasttweak::valueText (song, song.automations.back().target, song.automations.back().points[0].value) == "100% 0.0dB 1.00");
  14600. const auto again = playlist.getClipMenuForSnapshot (clipIndex);
  14601. const auto* automate2 = findSub (again, lynx::tr ("Automate"));
  14602. check ("automate_second_is_2", automate2 != nullptr && click (*automate2, lynx::tr ("Volume"))
  14603. && juce::String::fromUTF8 (engine.getSong().automations.back().name.c_str()).endsWith (" #2"),
  14604. juce::String::fromUTF8 (engine.getSong().automations.back().name.c_str()));
  14605. // PL-7: Fade in / out curve
  14606. const auto* fadeIn = findSub (menu, lynx::tr ("Fade in curve"));
  14607. const auto* fadeOut = findSub (menu, lynx::tr ("Fade out curve"));
  14608. const juce::StringArray curve { lynx::tr ("Reset"), lynx::tr ("Normalize"), lynx::tr ("Normalize selection as a group"), lynx::tr ("Create crossfade"),
  14609. lynx::tr ("Manual"), "[" + lynx::tr ("Declicker") + "]", lynx::tr ("Automatic"), lynx::tr ("Disabled"), lynx::tr ("Enabled"),
  14610. "[" + lynx::tr ("Curve shape") + "]", lynx::tr ("Smooth curve"), lynx::tr ("Single curve") };
  14611. check ("fade_curve_submenus", fadeIn != nullptr && fadeOut != nullptr && texts (*fadeIn) == curve && texts (*fadeOut) == curve,
  14612. fadeIn != nullptr ? texts (*fadeIn).joinIntoString ("|") : juce::String ("missing"));
  14613. if (fadeOut != nullptr)
  14614. saveMenus (juce::StringArray { "Audio clip menu", "Fade out curve" }, std::vector<juce::PopupMenu> { menu, *fadeOut }, prefix + "-fade-curve-menu.png");
  14615. // PL-8: Detect tempo is one item now
  14616. bool detectItem = false;
  14617. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  14618. if (plain (it.getItem().text) == plain (lynx::tr ("Detect tempo")))
  14619. detectItem = it.getItem().subMenu == nullptr && it.getItem().action != nullptr;
  14620. check ("detect_tempo_item", detectItem);
  14621. // PL-3: Preview through the channel; transport start ends it
  14622. check ("preview_through_channel", engine.previewClipThroughChannel ((std::size_t) clipIndex) && engine.isClipPreviewing());
  14623. engine.play();
  14624. check ("preview_stops_on_transport", ! engine.isClipPreviewing());
  14625. engine.stop();
  14626. check ("preview_again_then_stop", engine.previewClipThroughChannel ((std::size_t) clipIndex) && engine.isClipPreviewing());
  14627. engine.stop();
  14628. check ("preview_stops_on_stop", ! engine.isClipPreviewing());
  14629. }
  14630. // PL-8: the dialog
  14631. {
  14632. lynx::ui::TempoDetectionRequest r;
  14633. r.name = "Amount Too - Bass";
  14634. // (a drum-like loop at 117.5 BPM, 100 beats as in FL's dialog: clicks on every beat)
  14635. {
  14636. auto beats = std::make_shared<lynx::SampleData>();
  14637. beats->sampleRate = 44100.0;
  14638. const auto period = 44100.0 * 60.0 / 117.5;
  14639. beats->left.assign ((std::size_t) std::llround (period * 100.0), 0.0f);
  14640. for (int b = 0; b < 100; ++b)
  14641. for (int i = 0; i < 2000; ++i)
  14642. if (const auto at = (std::size_t) std::llround (b * period) + (std::size_t) i; at < beats->left.size())
  14643. beats->left[at] = (float) (0.9 * std::sin (i * 0.09) * std::exp (-i / 400.0));
  14644. r.sample = beats;
  14645. }
  14646. r.projectBpm = 100.0;
  14647. double applied = -1.0;
  14648. r.apply = [&applied] (double beats) { applied = beats; };
  14649. auto panel = lynx::ui::makeTempoDetectionPanel (r);
  14650. panel->setSize (panel->getWidth(), panel->getHeight());
  14651. shoot (*panel, "tempo-detection");
  14652. report.add ("tempo dialog title: " + lynx::ui::tempoDetectionTitle (r.name));
  14653. const auto project = lynx::ui::pressTempoDetectionButton (*panel, panel->getNumChildComponents() - 3);
  14654. const auto seconds = (double) r.sample->frames() / r.sample->sampleRate; // (100 beats at 117.5 BPM)
  14655. check ("tempo_project_button", std::abs (applied - seconds * 100.0 / 60.0) < 1.0e-6, project + " -> " + juce::String (applied));
  14656. const auto none = lynx::ui::pressTempoDetectionButton (*panel, panel->getNumChildComponents() - 2);
  14657. check ("tempo_no_tempo_button", applied == 0.0, none);
  14658. }
  14659. // ---- 4. issue #152's question (ISS152-1): FL's message with "Remember my choice"
  14660. {
  14661. auto box = lynx::makeFlMessageDialog ({ lynx::tr ("External input"),
  14662. 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?"),
  14663. { lynx::tr ("Yes"), lynx::tr ("No") }, true });
  14664. shoot (*box, "external-input-question");
  14665. bool listed = false;
  14666. for (const auto& m : lynx::messages::all())
  14667. listed = listed || juce::String (m.id) == "RecAutoSwitchExternalInput";
  14668. check ("external_input_in_manage_messages", listed);
  14669. }
  14670. // ---- 5. round 190gk: FL's Start in the render window; the Sampler's "Open in new Fruity Slicer / Slicex channel";
  14671. // a Gross Beat slot picked by MIDI becomes its parameter
  14672. {
  14673. lynx::AudioEngine engine (false);
  14674. auto panel = lynx::makeClipRenderPanel (engine);
  14675. panel->setSize (panel->getWidth() > 0 ? panel->getWidth() : 640, panel->getHeight() > 0 ? panel->getHeight() : 480);
  14676. juce::String button;
  14677. for (auto* c : panel->getChildren())
  14678. if (auto* b = dynamic_cast<juce::TextButton*> (c); b != nullptr && b->isVisible() && b->getTooltip() == lynx::tr ("Start rendering"))
  14679. button = b->getButtonText();
  14680. check ("render_button_start", button == lynx::trc ("@render button: Start") && button == "Start", button);
  14681. shoot (*panel, "fltails190gk-render-start");
  14682. const auto clap = writeWav (folder.getChildFile ("Slice me.wav"), 44100.0, 44100, 140.0);
  14683. engine.editSong ([] (lynx::Song& s) {
  14684. s.channels.resize (2);
  14685. s.channels[0] = {};
  14686. s.channels[0].instrument = lynx::InstrumentKind::fruityslicer;
  14687. s.channels[0].name = "Fruity Slicer";
  14688. s.channels[1] = {};
  14689. s.channels[1].instrument = lynx::InstrumentKind::slicex;
  14690. s.channels[1].name = "Slicex";
  14691. });
  14692. const auto locate = [] (int index) {
  14693. return [index] (lynx::Song& s) -> lynx::ChannelDef* { return index < (int) s.channels.size() ? &s.channels[(std::size_t) index] : nullptr; };
  14694. };
  14695. lynx::loadSampleWhenOpened (0, clap.getFullPathName());
  14696. auto slicer = lynx::makeFruitySlicerEditor (engine, locate (0), 0);
  14697. const auto& fs = engine.getSong().channels[0];
  14698. check ("open_in_new_fruity_slicer", fs.samplePath == clap.getFullPathName().toStdString() && ! fs.pluginState.empty(), juce::String (fs.samplePath));
  14699. lynx::loadSlicexSampleWhenOpened (1, clap.getFullPathName());
  14700. auto slicex = lynx::makeSlicexEditor (engine, locate (1), 1);
  14701. const auto& sx = engine.getSong().channels[1];
  14702. check ("open_in_new_slicex", sx.samplePath == clap.getFullPathName().toStdString() && ! sx.pluginState.empty(), juce::String (sx.samplePath));
  14703. auto again = lynx::makeSlicexEditor (engine, locate (1), 1); // (the request is used once)
  14704. check ("open_in_new_used_once", engine.getSong().channels[1].samplePath == sx.samplePath);
  14705. // Gross Beat on insert 1: two notes on its MIDI input, one block, the engine's timer step
  14706. engine.editSong ([] (lynx::Song& s) {
  14707. if (s.mixer.size() < 2)
  14708. s.mixer.resize (2);
  14709. s.mixer[1].effects = { lynx::makeEffectSlot (lynx::EffectKind::grossBeat) };
  14710. });
  14711. engine.dispatchPendingMessages();
  14712. auto fx = engine.getEffect (1, 0);
  14713. check ("gb_running", fx != nullptr);
  14714. if (fx != nullptr)
  14715. {
  14716. std::vector<float> l (512, 0.1f), r (512, 0.1f);
  14717. fx->prepare (44100.0);
  14718. fx->setSongPosition (0.0);
  14719. fx->midiNote (60 + 9, 100, 0);
  14720. fx->midiNote (24 + 3, 100, 0);
  14721. fx->process (l.data(), r.data(), 512, engine.getSong().mixer[1].effects[0].params, 120.0);
  14722. engine.pumpGrossBeatPicks();
  14723. const auto& p = engine.getSong().mixer[1].effects[0].params;
  14724. check ("gb_midi_pick_sets_parameters", lynx::grossbeat::rawFromParam (0, p[0]) == 9 && lynx::grossbeat::rawFromParam (1, p[1]) == 3,
  14725. juce::String (lynx::grossbeat::rawFromParam (0, p[0])) + " " + juce::String (lynx::grossbeat::rawFromParam (1, p[1])));
  14726. }
  14727. }
  14728. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\nresult=" + (allOk ? "OK" : "FAIL") + "\n");
  14729. return allOk;
  14730. }
  14731. // --grooveshot190fm (round 190fm): see the dispatch above
  14732. bool runGrooveShot190fm (const juce::String& prefix)
  14733. {
  14734. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  14735. juce::StringArray report;
  14736. bool allOk = true;
  14737. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  14738. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  14739. allOk = allOk && ok;
  14740. };
  14741. const auto plain = [] (juce::String t) {
  14742. t = t.upToFirstOccurrenceOf ("\t", false, false);
  14743. return t.removeCharacters (juce::String ("&_") + juce::String::charToString (1));
  14744. };
  14745. const auto sub = [&plain] (const juce::PopupMenu& menu, const juce::String& start) -> const juce::PopupMenu* {
  14746. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  14747. if (it.getItem().subMenu != nullptr && plain (it.getItem().text).startsWith (start))
  14748. return it.getItem().subMenu.get();
  14749. return nullptr;
  14750. };
  14751. const auto item = [&plain] (const juce::PopupMenu& menu, const juce::String& text) -> const juce::PopupMenu::Item* {
  14752. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  14753. if (plain (it.getItem().text) == text)
  14754. return &it.getItem();
  14755. return nullptr;
  14756. };
  14757. lynx::AudioEngine engine (false);
  14758. lynx::MainComponent ui (engine, false);
  14759. ui.setSize (1600, 900);
  14760. std::uint32_t classic = 0;
  14761. {
  14762. auto song = lynx::Song::makeDefault();
  14763. song.mode = lynx::PlayMode::song;
  14764. song.playlist.push_back ({ 0, 0, 0, 4 * lynx::ppq, 0 });
  14765. song.playlist.push_back ({ 0, 1, 4 * lynx::ppq, 4 * lynx::ppq, 0 });
  14766. for (const auto& e : lynx::groove::factoryBank())
  14767. if (juce::String (e.folder) == "Classic swing" && e.groove.base == lynx::GrooveBase::sixteenth
  14768. && (e.groove.name == "Swing 16ths 54 %" || e.groove.name == "Swing 16ths 58 %" || e.groove.name == "Swing 16ths 62 %"
  14769. || e.groove.name == "Swing 16ths 71 %"))
  14770. {
  14771. const auto id = lynx::groove::add (song.grooves, e.groove);
  14772. if (e.groove.name == "Swing 16ths 58 %")
  14773. classic = id;
  14774. }
  14775. song.playlist[0].groove = classic;
  14776. engine.setSong (std::move (song));
  14777. }
  14778. engine.dispatchPendingMessages();
  14779. auto& playlist = ui.getPlaylistForSnapshot();
  14780. const auto menu = playlist.getClipMenuForSnapshot (0);
  14781. const auto* chooser = sub (menu, lynx::tr ("Groove"));
  14782. check ("groove_chooser_in_clip_menu", chooser != nullptr);
  14783. const auto* add = chooser != nullptr ? sub (*chooser, lynx::tr ("Add a groove")) : nullptr;
  14784. const auto* folder = add != nullptr ? sub (*add, lynx::tr ("Classic swing")) : nullptr;
  14785. check ("classic_swing_folder", folder != nullptr && folder->getNumItems() == 27, folder != nullptr ? juce::String (folder->getNumItems()) : juce::String ("missing"));
  14786. const auto* commit = item (menu, lynx::tr ("Commit groove"));
  14787. check ("commit_enabled_with_a_groove", commit != nullptr && commit->isEnabled);
  14788. check ("extract_present", item (menu, lynx::tr ("Extract groove")) != nullptr);
  14789. {
  14790. juce::StringArray names { "Pattern clip menu" };
  14791. std::vector<juce::PopupMenu> menus { menu };
  14792. if (chooser != nullptr)
  14793. {
  14794. names.add ("Groove");
  14795. menus.push_back (*chooser);
  14796. }
  14797. if (add != nullptr)
  14798. {
  14799. names.add ("Add a groove");
  14800. menus.push_back (*add);
  14801. }
  14802. if (folder != nullptr)
  14803. {
  14804. names.add ("Classic swing");
  14805. menus.push_back (*folder);
  14806. }
  14807. saveMenus (names, menus, prefix + "-playlist-clip-menu.png");
  14808. }
  14809. // the second clip (no groove): Commit is off; choosing a groove from the menu sets it
  14810. {
  14811. const auto other = playlist.getClipMenuForSnapshot (1);
  14812. const auto* c2 = item (other, lynx::tr ("Commit groove"));
  14813. check ("commit_disabled_without_a_groove", c2 != nullptr && ! c2->isEnabled);
  14814. const auto* ch2 = sub (other, lynx::tr ("Groove"));
  14815. const auto* pick = ch2 != nullptr ? item (*ch2, "Swing 16ths 71 %") : nullptr;
  14816. if (pick != nullptr && pick->action != nullptr)
  14817. pick->action();
  14818. const auto& song = engine.getSong();
  14819. check ("chooser_sets_the_clip_groove", song.playlist.size() == 2 && lynx::groove::ofClip (song, song.playlist[1]) != nullptr
  14820. && lynx::groove::ofClip (song, song.playlist[1])->name == "Swing 16ths 71 %");
  14821. }
  14822. // the pool with the classic grooves
  14823. {
  14824. auto pool = lynx::makeGroovePool (engine);
  14825. pool->setSize (900, lynx::groovePoolHeight (engine));
  14826. savePng (pool->createComponentSnapshot (pool->getLocalBounds()), prefix + "-pool.png");
  14827. }
  14828. // .lynx: a Playlist clip's groove comes back; a project without one writes nothing new
  14829. {
  14830. juce::String error;
  14831. const auto& song = engine.getSong();
  14832. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  14833. check ("lynx_round_trip", back && back->playlist.size() == 2 && back->playlist[0].groove == song.playlist[0].groove
  14834. && back->playlist[1].groove == song.playlist[1].groove && back->grooves == song.grooves,
  14835. error);
  14836. auto old = lynx::Song::makeDefault();
  14837. old.playlist.push_back ({ 0, 0, 0, 4 * lynx::ppq, 0 });
  14838. const auto json = lynx::ProjectFile::toJson (old, false);
  14839. const auto reloaded = lynx::ProjectFile::fromJson (json, error);
  14840. check ("old_project_unchanged", reloaded && lynx::ProjectFile::toJson (*reloaded, false) == json && reloaded->playlist[0].groove == 0);
  14841. }
  14842. // Commit from the menu: the clip's pattern (shared with the second clip) is copied, the groove is off
  14843. {
  14844. const auto patterns = engine.getSong().patterns.size();
  14845. const auto again = playlist.getClipMenuForSnapshot (0);
  14846. if (const auto* c = item (again, lynx::tr ("Commit groove")); c != nullptr && c->action != nullptr)
  14847. c->action();
  14848. const auto& song = engine.getSong();
  14849. check ("commit_runs", song.playlist[0].groove == 0 && song.patterns.size() == patterns + 1 && song.playlist[0].pattern == (int) patterns);
  14850. }
  14851. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\n" + (allOk ? "ALL OK" : "SOME FAILED") + "\n");
  14852. return allOk;
  14853. }
  14854. bool runFlClipShot (const juce::String& prefix)
  14855. {
  14856. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  14857. juce::StringArray report;
  14858. bool allOk = true;
  14859. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  14860. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  14861. allOk = allOk && ok;
  14862. };
  14863. const auto plain = [] (juce::String t) {
  14864. t = t.upToFirstOccurrenceOf ("\t", false, false);
  14865. if (const auto at = t.indexOf (juce::String (" (") + juce::String::charToString (1)); at >= 0)
  14866. t = t.substring (0, at);
  14867. return t.removeCharacters (juce::String ("&_") + juce::String::charToString (1));
  14868. };
  14869. const auto find = [&plain] (const juce::PopupMenu& menu, const juce::String& text) -> const juce::PopupMenu::Item* {
  14870. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  14871. if (plain (it.getItem().text) == plain (text))
  14872. return &it.getItem();
  14873. return nullptr;
  14874. };
  14875. const auto click = [&find] (const juce::PopupMenu& menu, const juce::String& text) {
  14876. const auto* item = find (menu, text);
  14877. if (item == nullptr || ! item->isEnabled || item->action == nullptr)
  14878. return false;
  14879. item->action();
  14880. return true;
  14881. };
  14882. lynx::AudioEngine engine (false);
  14883. lynx::MainComponent ui (engine, false);
  14884. ui.setSize (1600, 900);
  14885. int vox = -1;
  14886. {
  14887. auto song = lynx::Song::makeDefault();
  14888. song.channels.push_back ({});
  14889. song.channels.back().name = "Vox";
  14890. song.channels.back().instrument = lynx::InstrumentKind::audioClip;
  14891. song.channels.back().samplePath = writeShotSample (juce::File (prefix + "-vox.wav"), 330.0).getFullPathName().toStdString();
  14892. vox = (int) song.channels.size() - 1;
  14893. lynx::Clip c;
  14894. c.kind = lynx::ClipKind::audio;
  14895. c.channel = vox;
  14896. c.track = 3;
  14897. c.start = 4 * lynx::ppq;
  14898. c.length = 2 * lynx::ppq;
  14899. c.fadeIn = lynx::ppq / 4;
  14900. song.playlist.push_back (c);
  14901. engine.setSong (std::move (song));
  14902. }
  14903. engine.dispatchPendingMessages();
  14904. auto& playlist = ui.getPlaylistForSnapshot();
  14905. // ---- 1. the audio clip menu: FL's order, sections and columns, then LYNX's own items
  14906. {
  14907. const auto menu = playlist.getClipMenuForSnapshot (0);
  14908. juce::StringArray got, want;
  14909. int breakAfter = -1;
  14910. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  14911. {
  14912. const auto& item = it.getItem();
  14913. got.add (item.customComponent != nullptr ? "[" + lynx::tr ("Audio clip") + "]"
  14914. : item.isSeparator ? juce::String ("-")
  14915. : item.isSectionHeader ? "[" + plain (item.text) + "]"
  14916. : plain (item.text));
  14917. if (item.shouldBreakAfter)
  14918. breakAfter = got.size() - 1;
  14919. }
  14920. for (const auto& e : lynx::flclipmenu::shown (true, false))
  14921. if (e.kind != lynx::flclipmenu::Entry::Kind::columnBreak)
  14922. want.add (e.kind == lynx::flclipmenu::Entry::Kind::separator ? juce::String ("-")
  14923. : e.kind == lynx::flclipmenu::Entry::Kind::header ? "[" + lynx::tr (e.text.c_str()) + "]"
  14924. : lynx::tr (e.text.c_str()));
  14925. want.add ("-");
  14926. want.add ("[" + lynx::tr ("LYNX extras") + "]"); // (round 190gi)
  14927. for (const auto& x : lynx::flclipmenu::lynxExtras())
  14928. want.add (lynx::tr (x.c_str()));
  14929. check ("clip_menu_fl_order", got == want, got.joinIntoString ("|"));
  14930. check ("clip_menu_two_columns", breakAfter >= 0 && got[breakAfter] == lynx::tr ("Chop") && got[breakAfter + 1] == "[" + lynx::tr ("Sample") + "]",
  14931. juce::String (breakAfter));
  14932. const auto* crossfade = find (menu, lynx::tr ("Crossfade with"));
  14933. check ("crossfade_with_greyed", crossfade != nullptr && ! crossfade->isEnabled);
  14934. const auto* region = find (menu, lynx::tr ("Select region"));
  14935. const auto* full = region != nullptr && region->subMenu != nullptr ? find (*region->subMenu, lynx::tr ("Full")) : nullptr;
  14936. check ("select_region_full_ticked", full != nullptr && full->isTicked);
  14937. const auto* chop = find (menu, lynx::tr ("Chop"));
  14938. check ("chop_time_based", chop != nullptr && chop->subMenu != nullptr && find (*chop->subMenu, lynx::tr ("Chop in 32nd beats")) != nullptr
  14939. && find (*chop->subMenu, lynx::tr ("Chop to grid")) != nullptr);
  14940. savePng (columnMenuImage (menu), prefix + "-clip-menu.png");
  14941. std::fprintf (stderr, "flclipshot: menu saved\n");
  14942. // Muted is a check; Reset fades clears the fades; Select all similar clips selects
  14943. check ("muted_toggles", click (menu, lynx::tr ("Muted")) && engine.getSong().playlist[0].muted);
  14944. const auto again = playlist.getClipMenuForSnapshot (0);
  14945. const auto* muted = find (again, lynx::tr ("Muted"));
  14946. check ("muted_ticked", muted != nullptr && muted->isTicked);
  14947. check ("reset_fades", click (again, lynx::tr ("Reset fades")) && engine.getSong().playlist[0].fadeIn == 0);
  14948. engine.undo();
  14949. engine.undo();
  14950. engine.dispatchPendingMessages();
  14951. std::fprintf (stderr, "flclipshot: automate\n");
  14952. // Automate › Volume / Panning: the clip channel's Levels adjustment (FL's channel parameters 0x11 / 0x10)
  14953. const auto fresh = playlist.getClipMenuForSnapshot (0);
  14954. const auto* automate = find (fresh, lynx::tr ("Automate"));
  14955. const auto before = engine.getSong().automations.size();
  14956. check ("automate_volume_runs", automate != nullptr && automate->subMenu != nullptr && click (*automate->subMenu, lynx::tr ("Volume")));
  14957. const auto& song = engine.getSong();
  14958. const auto ok = song.automations.size() == before + 1 && song.automations.back().target.kind == lynx::AutomationTargetKind::channelAdjust
  14959. && song.automations.back().target.param == lynx::leveladjust::volume && song.automations.back().target.index == vox
  14960. && std::abs (song.automations.back().points[0].value - 0.5f) < 1.0e-6f;
  14961. check ("automate_volume_is_level_adjust", ok, ok ? juce::String::fromUTF8 (song.automations.back().name.c_str()) : juce::String());
  14962. engine.undo();
  14963. engine.dispatchPendingMessages();
  14964. }
  14965. std::fprintf (stderr, "flclipshot: overlap\n");
  14966. // ---- 2. a second channel's clip overlapping: Crossfade with lists it and makes FL's crossfade clip (round 190gw)
  14967. {
  14968. engine.editSong ([vox] (lynx::Song& s) {
  14969. auto copy = s.playlist[0]; // (another audio clip channel's clip, at the same time)
  14970. s.channels.push_back (s.channels[(std::size_t) vox]);
  14971. s.channels.back().name = "Vox 2";
  14972. copy.channel = (int) s.channels.size() - 1;
  14973. copy.track = 4;
  14974. s.playlist.push_back (copy);
  14975. });
  14976. engine.dispatchPendingMessages();
  14977. const auto overlapped = playlist.getClipMenuForSnapshot (0);
  14978. const auto* with = find (overlapped, lynx::tr ("Crossfade with"));
  14979. check ("crossfade_with_lists_the_overlap", with != nullptr && with->isEnabled && with->subMenu != nullptr && find (*with->subMenu, "Vox 2") != nullptr);
  14980. const auto made = with != nullptr && with->subMenu != nullptr && click (*with->subMenu, "Vox 2");
  14981. engine.dispatchPendingMessages();
  14982. const auto& xsong = engine.getSong();
  14983. const auto xok = made && ! xsong.automations.empty() && xsong.automations.back().links.size() == 2
  14984. && juce::String::fromUTF8 (xsong.automations.back().name.c_str()).endsWith (" to Vox 2 crossfade");
  14985. check ("crossfade_with_makes_the_clip", xok, xok ? juce::String::fromUTF8 (xsong.automations.back().name.c_str()) : juce::String());
  14986. if (made)
  14987. engine.undo();
  14988. engine.undo();
  14989. engine.dispatchPendingMessages();
  14990. }
  14991. std::fprintf (stderr, "flclipshot: misc\n");
  14992. // ---- 3. the channel's Misc tab: Levels adjustment = the offsets (pan 0, volume 100 %, Mod X / Y 0 %)
  14993. {
  14994. engine.editSong ([vox] (lynx::Song& s) {
  14995. s.channels[(std::size_t) vox].misc.levels.volume = 0.5f;
  14996. s.channels[(std::size_t) vox].misc.levels.pan = -0.25f;
  14997. });
  14998. engine.dispatchPendingMessages();
  14999. auto frame = lynx::makeChannelFrame (engine, vox, -1);
  15000. frame->setSize (juce::jmax (frame->getWidth(), 800), juce::jmax (frame->getHeight(), 420));
  15001. savePng (frame->createComponentSnapshot (frame->getLocalBounds()), prefix + "-misc-levels.png");
  15002. auto synthFrame = lynx::makeChannelFrame (engine, 0, -1);
  15003. synthFrame->setSize (juce::jmax (synthFrame->getWidth(), 800), juce::jmax (synthFrame->getHeight(), 420));
  15004. savePng (synthFrame->createComponentSnapshot (synthFrame->getLocalBounds()), prefix + "-misc-levels-ch1.png");
  15005. std::fprintf (stderr, "flclipshot: round trip\n");
  15006. // the .lynx round trip of the adjustment and of an automation of it; an old project writes nothing new
  15007. juce::String error;
  15008. auto song = engine.getSong();
  15009. lynx::Automation a;
  15010. a.target = { lynx::AutomationTargetKind::channelAdjust, vox, 0, lynx::leveladjust::volume };
  15011. a.points = { { 0, 0.25f, 0.0f } };
  15012. song.automations.push_back (a);
  15013. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  15014. check ("lynx_round_trip", back && back->channels[(std::size_t) vox].misc.levels == song.channels[(std::size_t) vox].misc.levels
  15015. && back->automations.back().target == a.target,
  15016. error);
  15017. auto old = lynx::Song::makeDefault();
  15018. const auto json = lynx::ProjectFile::toJson (old, false);
  15019. const auto reloaded = lynx::ProjectFile::fromJson (json, error);
  15020. check ("old_project_unchanged", ! json.contains ("\"levels\"") && reloaded && lynx::ProjectFile::toJson (*reloaded, false) == json
  15021. && std::all_of (reloaded->channels.begin(), reloaded->channels.end(),
  15022. [] (const lynx::ChannelDef& c) { return c.misc.levels.neutral(); }));
  15023. }
  15024. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\nresult=" + (allOk ? "OK" : "FAIL") + "\n");
  15025. return allOk;
  15026. }
  15027. // --bandlabshot <prefix> (round 190ch): the Lyrics / Notes panel (Pattern and Simple layouts, and on its own), the
  15028. // Reference match window measured on a real render and a real file, "Start from", and Clean voice, off-screen; and
  15029. // <prefix>-report.txt with what each route did (ok / FAIL lines)
  15030. void runBandlabShot (const juce::String& prefix)
  15031. {
  15032. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  15033. lynx::AudioEngine offline (false);
  15034. lynx::MainComponent ui (offline, false);
  15035. ui.setSize (1600, 900);
  15036. // (each step is named on stderr as it starts: a run that stops says where)
  15037. const auto note = [] (const juce::String& what) { std::fprintf (stderr, "bandlabshot: %s\n", what.toRawUTF8()); };
  15038. const auto shoot = [&prefix, &note] (juce::Component& c, const char* name) {
  15039. note (name);
  15040. savePng (lynx::shot::snapshot (c), prefix + "-" + name + ".png");
  15041. };
  15042. juce::String report;
  15043. const auto check = [&report, &note] (const juce::String& what, bool ok) {
  15044. note ((ok ? "ok " : "FAIL ") + what);
  15045. report << (ok ? "ok " : "FAIL ") << what << "\n";
  15046. };
  15047. const auto bar = (double) lynx::ppq * 4.0;
  15048. // ---- 1. Lyrics / Notes: the project's Comments
  15049. {
  15050. auto song = lynx::makeShowcaseSong (0);
  15051. song.info.title = "Night Drive";
  15052. 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"
  15053. "I keep driving through the night\n\n[Chorus]\nNight drive, night drive\nNothing but the white line\n\n"
  15054. "Notes: double the chorus vocal, try the second verse an octave down.";
  15055. lynx::Marker chorus;
  15056. chorus.tick = (std::int64_t) (12.0 * bar);
  15057. chorus.name = "Chorus";
  15058. song.addMarker (chorus);
  15059. offline.setSong (std::move (song));
  15060. }
  15061. note ("song set");
  15062. offline.dispatchPendingMessages();
  15063. ui.selectTabForSnapshot (2);
  15064. note ("show lyrics");
  15065. ui.showLyrics (false);
  15066. note ("lyrics shown");
  15067. if (auto* panel = ui.getLyricsPanelForSnapshot())
  15068. {
  15069. panel->showForSnapshot ({}, 6.5 * bar); // the playhead inside bar 7: that line is the one playing
  15070. shoot (ui, "lyrics-pattern");
  15071. shoot (*panel, "lyrics-panel");
  15072. const auto markersBefore = offline.getSong().markers().size();
  15073. panel->setCaretLineForSnapshot (6); // "I keep driving through the night"
  15074. panel->markAtPlayheadForSnapshot (10.0 * bar + 2.0 * lynx::ppq);
  15075. offline.dispatchPendingMessages();
  15076. ui.commitSongNotes();
  15077. const auto& s = offline.getSong();
  15078. check ("Marker at playhead stamps the line [11.3] and adds one marker",
  15079. juce::String::fromUTF8 (s.info.comments.c_str()).contains ("[11.3] I keep driving") && s.markers().size() == markersBefore + 1);
  15080. // (no audio device here: the seek is the request the audio thread takes at its next block)
  15081. const auto& seek = offline.getTransport().seekRequest;
  15082. check ("clicking the stamped line moves the playhead to bar 7", panel->jumpToLineForSnapshot (4) && std::abs (seek.load() - 6.0 * bar) < 1.0);
  15083. check ("clicking [Chorus] (no position) goes to the marker of that name, bar 13",
  15084. panel->jumpToLineForSnapshot (8) && std::abs (seek.load() - 12.0 * bar) < 1.0);
  15085. check ("a line without a position does not jump", ! panel->jumpToLineForSnapshot (9));
  15086. panel->showForSnapshot ("night", 10.5 * bar);
  15087. shoot (*panel, "lyrics-search");
  15088. // the text travels in the project file, and old readers see it as the Comments they always had
  15089. juce::String error;
  15090. const auto json = lynx::ProjectFile::toJson (offline.getSong());
  15091. const auto back = lynx::ProjectFile::fromJson (json, error);
  15092. check ("lyrics round-trip through .lynx (the Comments field)", back.has_value() && back->info.comments == offline.getSong().info.comments);
  15093. const auto text = lynx::lyrics::exportText (offline.getSong(), lynx::lyrics::Stamps::times);
  15094. juce::File (prefix + "-lyrics-export.txt").replaceWithText (juce::String::fromUTF8 (text.c_str()));
  15095. check ("export as text with times", text.find ("[0:") != std::string::npos);
  15096. panel->showForSnapshot ({}, 6.5 * bar);
  15097. }
  15098. else
  15099. check ("the docked Lyrics panel exists", false);
  15100. {
  15101. const auto names = ui.getMenuNamesForSnapshot();
  15102. const auto view = names.indexOf (lynx::tr ("View"));
  15103. saveMenus (juce::StringArray { lynx::tr ("View") }, std::vector<juce::PopupMenu> { ui.getMenuForSnapshot (juce::jmax (0, view)) }, prefix + "-menu-view.png");
  15104. }
  15105. ui.showDesktopForSnapshot (false);
  15106. check ("the panel stays docked beside the Playlist in the default desktop", ui.isLyricsShowing());
  15107. shoot (ui, "lyrics-desktop");
  15108. // ---- the Simple layout: the Lyrics button in its title tools, the chooser's "Start from" link
  15109. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  15110. offline.dispatchPendingMessages();
  15111. ui.selectTabForSnapshot (2); // (the Playlist alone, as --simpleshot shows the layout)
  15112. auto* simple = ui.getSimpleWorkflowForSnapshot();
  15113. check ("the Simple workflow exists", simple != nullptr);
  15114. if (simple != nullptr)
  15115. {
  15116. simple->hideChooser();
  15117. if (! ui.isLyricsShowing())
  15118. ui.showLyrics (false);
  15119. shoot (ui, "lyrics-simple");
  15120. ui.hideLyrics();
  15121. check ("closing the panel keeps the text", juce::String::fromUTF8 (offline.getSong().info.comments.c_str()).contains ("Night drive, night drive"));
  15122. // ---- 4. Clean voice: on a voice track, from the track's menu
  15123. lynx::simpletracks::Result voice;
  15124. offline.editSongStructural ([&voice] (lynx::Song& s) {
  15125. lynx::simpletracks::Request q;
  15126. q.kind = lynx::simpletracks::Kind::voice;
  15127. q.name = "Lead vocal";
  15128. voice = lynx::simpletracks::addTrack (s, q);
  15129. });
  15130. offline.dispatchPendingMessages();
  15131. check ("a voice track was added", voice.insert > 0);
  15132. if (voice.insert > 0)
  15133. {
  15134. auto menu = ui.getPlaylistForSnapshot().getTrackMenuForSnapshot (voice.track);
  15135. juce::StringArray names { "Track" };
  15136. std::vector<juce::PopupMenu> menus { menu };
  15137. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  15138. if (it.getItem().subMenu != nullptr && it.getItem().text == lynx::tr ("Clean voice"))
  15139. {
  15140. names.add (lynx::tr ("Clean voice"));
  15141. menus.push_back (*it.getItem().subMenu);
  15142. }
  15143. check ("the Simple track menu has Clean voice", menus.size() == 2);
  15144. saveMenus (names, menus, prefix + "-cleanvoice-menu.png");
  15145. const auto before = offline.getSong().mixer[(std::size_t) voice.insert].effects.size();
  15146. check ("Clean voice applies", lynx::ui::applyCleanVoice (offline, voice.insert, false));
  15147. offline.dispatchPendingMessages();
  15148. const auto& fx = offline.getSong().mixer[(std::size_t) voice.insert].effects;
  15149. check ("four slots in front of the track's effects", fx.size() == before + 4 && lynx::cleanvoice::slotsOf (offline.getSong(), voice.insert).size() == 4
  15150. && fx[0].kind == lynx::EffectKind::facetEq);
  15151. check ("with noise reduction: five, none doubled", lynx::ui::applyCleanVoice (offline, voice.insert, true)
  15152. && offline.getSong().mixer[(std::size_t) voice.insert].effects.size() == before + 5);
  15153. offline.dispatchPendingMessages();
  15154. juce::String error;
  15155. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (offline.getSong()), error);
  15156. check ("the chain round-trips through .lynx and is still found", back.has_value() && lynx::cleanvoice::slotsOf (*back, voice.insert).size() == 5
  15157. && back->mixer[(std::size_t) voice.insert].effects == offline.getSong().mixer[(std::size_t) voice.insert].effects);
  15158. saveMenus (juce::StringArray { lynx::tr ("Clean voice") }, std::vector<juce::PopupMenu> { lynx::ui::cleanVoiceMenu (offline, voice.insert) },
  15159. prefix + "-cleanvoice-menu-on.png");
  15160. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
  15161. offline.dispatchPendingMessages();
  15162. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::mixer });
  15163. ui.selectMixerTrackForSnapshot (voice.insert);
  15164. shoot (ui, "cleanvoice-mixer");
  15165. offline.undo(); // the second chain
  15166. offline.dispatchPendingMessages();
  15167. check ("undo brings the first chain back", lynx::cleanvoice::slotsOf (offline.getSong(), voice.insert).size() == 4);
  15168. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  15169. offline.dispatchPendingMessages();
  15170. ui.selectTabForSnapshot (2); // (the Playlist alone, as --simpleshot shows the layout)
  15171. simple = ui.getSimpleWorkflowForSnapshot();
  15172. }
  15173. }
  15174. // ---- 2. Reference match: the song's Master render against a file (pink noise with more top, at about -14 LUFS)
  15175. {
  15176. const auto file = juce::File (prefix + "-reference.wav");
  15177. file.deleteFile();
  15178. const auto rate = 44100.0;
  15179. const auto frames = (int) (20.0 * rate);
  15180. juce::AudioBuffer<float> audio (2, frames);
  15181. juce::Random random (190);
  15182. for (int ch = 0; ch < 2; ++ch)
  15183. {
  15184. double b0 = 0, b1 = 0, b2 = 0, hp = 0;
  15185. for (int i = 0; i < frames; ++i)
  15186. {
  15187. const auto w = (double) random.nextFloat() * 2.0 - 1.0;
  15188. b0 = 0.99765 * b0 + w * 0.0990460;
  15189. b1 = 0.96300 * b1 + w * 0.2965164;
  15190. b2 = 0.57000 * b2 + w * 1.0526913;
  15191. const auto pink = (b0 + b1 + b2 + w * 0.1848) * 0.071; // (about -14 LUFS: a streaming master)
  15192. hp += 0.25 * (pink - hp); // a little more top than pink noise has
  15193. audio.setSample (ch, i, (float) (pink + 0.35 * (pink - hp)));
  15194. }
  15195. }
  15196. if (auto out = file.createOutputStream())
  15197. if (auto writer = std::unique_ptr<juce::AudioFormatWriter> (juce::WavAudioFormat().createWriterFor (out.get(), rate, 2, 24, {}, 0)))
  15198. {
  15199. out.release();
  15200. writer->writeFromAudioSampleBuffer (audio, 0, frames);
  15201. }
  15202. note ("measure reference");
  15203. const auto reference = lynx::ReferenceMatchPanel::measureFile (offline, file);
  15204. note ("measure song");
  15205. const auto song = lynx::ReferenceMatchPanel::measureSong (offline.getSong(), false);
  15206. check ("the reference file was measured", reference.valid);
  15207. check ("the song's Master render was measured", song.valid);
  15208. lynx::ReferenceMatchPanel panel (offline, {});
  15209. panel.setSize (lynx::ReferenceMatchPanel::defaultWidth, lynx::ReferenceMatchPanel::defaultHeight);
  15210. panel.showForSnapshot ("Reference.wav", song, reference, nullptr);
  15211. shoot (panel, "refmatch-measured");
  15212. const auto masterBefore = offline.getSong().mixer[0].effects.size();
  15213. check ("Match adds its two slots at the end of the Master", panel.matchForSnapshot() && offline.getSong().mixer[0].effects.size() == masterBefore + 2);
  15214. offline.dispatchPendingMessages();
  15215. const auto first = lynx::ReferenceMatchPanel::measureSong (offline.getSong(), true);
  15216. panel.showForSnapshot ("Reference.wav", song, reference, &first);
  15217. panel.refresh();
  15218. shoot (panel, "refmatch-matched");
  15219. report << " first Match: " << juce::String (first.lufs, 2) << " LUFS, " << juce::String (first.truePeakDb, 2) << " dBTP, EQ output "
  15220. << juce::String (lynx::facet::outputDb (offline.getSong().mixer[0].effects[masterBefore].params[(std::size_t) lynx::facet::outputParam]), 2) << " dB\n";
  15221. // a result more than 0.5 LU from the reference (a limiter that has to hold peaks back): Match again takes
  15222. // what is missing, as the window's note says
  15223. auto after = first;
  15224. const auto secondPass = std::abs (first.lufs - reference.lufs) > 0.5;
  15225. if (secondPass)
  15226. {
  15227. check ("Match again replaces the two slots (level corrected)", panel.matchForSnapshot() && offline.getSong().mixer[0].effects.size() == masterBefore + 2);
  15228. offline.dispatchPendingMessages();
  15229. after = lynx::ReferenceMatchPanel::measureSong (offline.getSong(), true);
  15230. panel.showForSnapshot ("Reference.wav", song, reference, &after);
  15231. panel.refresh();
  15232. shoot (panel, "refmatch-matched-again");
  15233. }
  15234. report << " " << (secondPass ? "a second Match was needed for the level" : "one Match was enough for the level") << "\n";
  15235. const auto& s = panel.suggestionForSnapshot();
  15236. report << " song " << juce::String (song.lufs, 2) << " LUFS, " << juce::String (song.truePeakDb, 2) << " dBTP, width " << juce::String (song.widthPercent(), 1)
  15237. << " % | reference " << juce::String (reference.lufs, 2) << " LUFS, " << juce::String (reference.truePeakDb, 2) << " dBTP, width "
  15238. << juce::String (reference.widthPercent(), 1) << " % | after " << juce::String (after.lufs, 2) << " LUFS, " << juce::String (after.truePeakDb, 2)
  15239. << " dBTP\n next suggestion: gain " << juce::String (s.gainDb, 2) << " dB, EQ fit error " << juce::String (s.fitErrorDb, 2) << " dB\n";
  15240. double before = 0.0, now = 0.0;
  15241. int counted = 0;
  15242. {
  15243. // tone only (each curve around its own mean), over the bands both hold
  15244. double ms = 0, mr = 0, ma = 0;
  15245. const auto used = juce::jmin (song.usedBands, reference.usedBands);
  15246. for (int k = 0; k < used; ++k)
  15247. ms += song.spectrumDb[(std::size_t) k], mr += reference.spectrumDb[(std::size_t) k], ma += after.spectrumDb[(std::size_t) k];
  15248. for (int k = 2; k < used; ++k, ++counted)
  15249. {
  15250. before += std::abs ((song.spectrumDb[(std::size_t) k] - ms / used) - (reference.spectrumDb[(std::size_t) k] - mr / used));
  15251. now += std::abs ((after.spectrumDb[(std::size_t) k] - ma / used) - (reference.spectrumDb[(std::size_t) k] - mr / used));
  15252. }
  15253. }
  15254. report << " mean tone difference to the reference: " << juce::String (before / juce::jmax (1, counted), 2) << " dB before, "
  15255. << juce::String (now / juce::jmax (1, counted), 2) << " dB after one Match (each band moves 6 dB at most)\n";
  15256. check ("after Match the tone is closer to the reference", after.valid && now < before);
  15257. check ("after Match the loudness is within 1 LU of the reference", std::abs (after.lufs - reference.lufs) < 1.0);
  15258. 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);
  15259. juce::String error;
  15260. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (offline.getSong()), error);
  15261. check ("the match round-trips through .lynx as two ordinary Master slots", back.has_value() && lynx::refmatch::present (*back)
  15262. && back->mixer[0].effects == offline.getSong().mixer[0].effects);
  15263. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
  15264. offline.dispatchPendingMessages();
  15265. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::mixer });
  15266. ui.selectMixerTrackForSnapshot (0);
  15267. shoot (ui, "refmatch-mixer");
  15268. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  15269. offline.dispatchPendingMessages();
  15270. ui.selectTabForSnapshot (2); // (the Playlist alone, as --simpleshot shows the layout)
  15271. simple = ui.getSimpleWorkflowForSnapshot();
  15272. if (simple != nullptr)
  15273. {
  15274. simple->hideChooser();
  15275. simple->showFinish();
  15276. shoot (ui, "finish-dock"); // "Match a reference track..." under the saving buttons
  15277. simple->hideFinish();
  15278. }
  15279. file.deleteFile();
  15280. }
  15281. // ---- 3. Start from: the chooser's link, the list, and opening an entry
  15282. if (simple != nullptr)
  15283. {
  15284. simple->showChooser();
  15285. shoot (ui, "chooser");
  15286. simple->hideChooser();
  15287. auto* panel = dynamic_cast<lynx::StartFromPanel*> (simple->startFromForSnapshot());
  15288. check ("the Start from list opens", panel != nullptr && simple->isStartFromShowing());
  15289. if (panel != nullptr)
  15290. {
  15291. shoot (ui, "startfrom");
  15292. auto list = lynx::startfrom::entries();
  15293. check ("it lists the demo song and the templates shipped", list.size() >= 3 && list[0].kind == lynx::startfrom::Entry::Kind::demo
  15294. && (int) list.size() == panel->entryCountForSnapshot());
  15295. for (auto& e : list)
  15296. report << " " << e.name << " | " << juce::String (e.bpm, 0) << " BPM, " << e.channels << " channels, " << e.bars << " bars"
  15297. << (e.playable ? ", preview" : "") << "\n";
  15298. if (const auto demo = lynx::startfrom::songOf (list[0]))
  15299. {
  15300. const auto wav = juce::File (prefix + "-preview.wav");
  15301. const auto ok = lynx::startfrom::renderPreview (*demo, wav);
  15302. check ("the demo's preview renders (" + juce::String (wav.getSize() / 1024) + " kB)", ok && wav.getSize() > 100000);
  15303. wav.deleteFile();
  15304. }
  15305. panel->selectForSnapshot (juce::jmin (2, panel->entryCountForSnapshot() - 1));
  15306. shoot (ui, "startfrom-selected");
  15307. offline.markSaved(); // (a project with changes asks first: Save / Don't save / Cancel)
  15308. const auto opened = panel->openForSnapshot (0);
  15309. offline.dispatchPendingMessages();
  15310. check ("opening the demo starts a new project from it and closes the list",
  15311. opened && ! simple->isStartFromShowing() && offline.getSong().info.comments.empty() && ! offline.getSong().channels.empty());
  15312. shoot (ui, "startfrom-opened");
  15313. }
  15314. }
  15315. juce::File (prefix + "-report.txt").replaceWithText (report);
  15316. }
  15317. void runVersionsShot (const juce::String& prefix)
  15318. {
  15319. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  15320. const auto shoot = [&prefix] (juce::Component& c, const char* name) {
  15321. savePng (lynx::shot::snapshot (c), prefix + "-" + name + ".png");
  15322. };
  15323. // ---- the Versions panel, on files in a temporary folder
  15324. const auto root = juce::File::getSpecialLocation (juce::File::tempDirectory)
  15325. .getChildFile ("lynx-versionsshot-" + juce::String::toHexString (juce::Random::getSystemRandom().nextInt64()));
  15326. const juce::ScopeGuard cleanUp { [&root] { root.deleteRecursively(); } };
  15327. const auto project = root.getChildFile ("Night Drive"), backup = root.getChildFile ("Backup");
  15328. project.createDirectory();
  15329. backup.createDirectory();
  15330. const auto now = juce::Time::getCurrentTime();
  15331. const auto put = [&now] (const juce::File& folder, const juce::String& name, const char* kind, int kilobytes, double hoursAgo) {
  15332. const auto time = now - juce::RelativeTime::hours (hoursAgo);
  15333. const auto file = folder.getChildFile (kind == nullptr ? name + ".lynx" : name + " (" + kind + " on " + time.formatted ("%Y-%m-%d at %Hh%M") + ").lynx");
  15334. juce::MemoryBlock data ((size_t) kilobytes * 1024, true);
  15335. file.replaceWithData (data.getData(), data.getSize());
  15336. file.setLastModificationTime (time);
  15337. };
  15338. put (project, "Night Drive", nullptr, 412, 26.0 * 24.0);
  15339. put (project, "Night Drive_2", nullptr, 688, 9.0 * 24.0);
  15340. put (project, "Night Drive_3", nullptr, 731, 2.0 * 24.0);
  15341. put (project, "Night Drive_4", nullptr, 905, 1.6);
  15342. put (backup, "Night Drive_4", "autosaved", 907, 0.07);
  15343. put (backup, "Night Drive_4", "autosaved", 906, 0.4);
  15344. put (backup, "Night Drive_4", "overwritten", 890, 1.6);
  15345. put (backup, "Night Drive_4", "autosaved", 884, 3.2);
  15346. put (backup, "Night Drive_3", "overwritten", 720, 2.0 * 24.0);
  15347. put (backup, "Night Drive_2", "autosaved", 690, 8.0 * 24.0);
  15348. const lynx::VersionsContext context { project.getChildFile ("Night Drive_4.lynx"), "Night Drive_4", backup, ".lynx" };
  15349. {
  15350. const auto entries = lynx::versionEntries (context);
  15351. const auto label = [&] (const juce::String& startsWith, const char* text) {
  15352. for (const auto& e : entries)
  15353. if (juce::String::fromUTF8 (e.name.c_str()).startsWith (startsWith))
  15354. {
  15355. lynx::setVersionLabel (context, e, text);
  15356. return;
  15357. }
  15358. };
  15359. label ("Night Drive_2", "first full arrangement");
  15360. label ("Night Drive_3", "sent to the singer");
  15361. label ("Night Drive_4 (autosaved", "new bass line");
  15362. }
  15363. {
  15364. lynx::VersionsActions actions;
  15365. actions.context = [context] { return context; };
  15366. auto panel = lynx::makeVersionsPanel (actions);
  15367. shoot (*panel, "versions");
  15368. lynx::VersionsActions fresh;
  15369. fresh.context = [backup] { return lynx::VersionsContext { juce::File(), "Untitled", backup, ".lynx" }; };
  15370. auto empty = lynx::makeVersionsPanel (fresh);
  15371. shoot (*empty, "versions-unsaved");
  15372. }
  15373. // ---- the window
  15374. lynx::AudioEngine offline (false);
  15375. lynx::MainComponent ui (offline, false);
  15376. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  15377. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  15378. const auto saveFileMenu = [&] (const char* name) {
  15379. const auto index = juce::jmax (0, ui.getMenuNamesForSnapshot().indexOf (lynx::tr ("File")));
  15380. saveMenus (juce::StringArray { lynx::tr ("File") }, std::vector<juce::PopupMenu> { ui.getMenuForSnapshot (index) }, prefix + "-" + name + ".png");
  15381. };
  15382. saveFileMenu ("menu-file");
  15383. // ---- a project opened without its third-party plugins (the plugins are not installed: nothing foreign runs)
  15384. {
  15385. const auto ref = [] (const char* id, const char* name) {
  15386. lynx::PluginRef r;
  15387. r.id = id;
  15388. r.name = name;
  15389. r.state = "c2V0dGluZ3M=";
  15390. return r;
  15391. };
  15392. auto song = lynx::Song::makeDefault();
  15393. while (song.channels.size() < 4)
  15394. song.channels.push_back (song.channels.front());
  15395. while (song.mixer.size() < 5)
  15396. song.mixer.push_back (song.mixer.back());
  15397. const char* names[] = { "Lead", "Pad" };
  15398. for (int c = 0; c < 2; ++c)
  15399. {
  15400. auto& channel = song.channels[(std::size_t) (c + 2)];
  15401. channel.instrument = lynx::InstrumentKind::plugin;
  15402. channel.plugin = ref ("VST3-ShotSynth-11111111-aaaaaaaa", "Shot Synth");
  15403. channel.name = names[c];
  15404. channel.mixerTrack = c + 1;
  15405. }
  15406. lynx::EffectSlot fx;
  15407. fx.kind = lynx::EffectKind::plugin;
  15408. fx.plugin = ref ("VST3-ShotVerb-22222222-bbbbbbbb", "Shot Verb");
  15409. song.mixer[1].effects.push_back (fx);
  15410. fx.plugin = ref ("VST3-ShotComp-33333333-cccccccc", "Shot Comp");
  15411. song.mixer[2].effects.push_back (fx);
  15412. song.mixer[0].effects.push_back (fx);
  15413. offline.setSongWithPluginsOff (std::move (song));
  15414. ui.showDesktopForSnapshot (false);
  15415. shoot (ui, "pluginsoff-window");
  15416. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::channelRack, lynx::workspace::Panel::mixer });
  15417. shoot (ui, "pluginsoff-mixer"); // (the rack's and the mixer's "off" tags together)
  15418. saveFileMenu ("menu-file-pluginsoff");
  15419. auto panel = lynx::makePluginsOffPanel (offline);
  15420. shoot (*panel, "pluginsoff-panel");
  15421. offline.switchPluginOn ("VST3-ShotVerb-22222222-bbbbbbbb"); // (not installed: "Did not load")
  15422. auto after = lynx::makePluginsOffPanel (offline);
  15423. shoot (*after, "pluginsoff-panel-one");
  15424. }
  15425. // ---- the Export window: as it opens, and with a preset chosen, sections on and a last export to repeat
  15426. {
  15427. auto song = lynx::Song::makeDefault();
  15428. const auto bar = song.barTicks();
  15429. song.mode = lynx::PlayMode::song;
  15430. song.playlist.clear();
  15431. lynx::Clip clip;
  15432. clip.length = 32 * bar;
  15433. song.playlist.push_back (clip);
  15434. const char* sections[] = { "Intro", "Verse", "Chorus", "Outro" };
  15435. for (int i = 0; i < 4; ++i)
  15436. {
  15437. lynx::Marker m;
  15438. m.tick = i * 8 * bar;
  15439. m.name = sections[i];
  15440. song.addMarker (m);
  15441. }
  15442. offline.setSong (std::move (song)); // (also ends the plugins-off mode)
  15443. auto plain = lynx::makeExportPanel (offline, 0);
  15444. shoot (*plain, "export-default");
  15445. auto additions = lynx::makeExportPanelWithAdditions (offline);
  15446. shoot (*additions, "export");
  15447. }
  15448. }
  15449. void runGamepadShot (const juce::String& prefix)
  15450. {
  15451. juce::String report;
  15452. int failures = 0;
  15453. {
  15454. lynx::AudioEngine engine (false);
  15455. auto hints = lynx::makeGamepadHints();
  15456. savePng (lynx::shot::snapshot (*hints), prefix + "-hints.png");
  15457. auto prefs = engine.getMidiPrefs();
  15458. prefs.gamepad = true;
  15459. engine.setMidiPrefs (prefs, false);
  15460. auto page = lynx::makeMidiPage (engine, {}, false);
  15461. page->setSize (760, 1400);
  15462. savePng (lynx::shot::snapshot (*page), prefix + "-settings.png");
  15463. // the poller with fake states: what the handler gets
  15464. using namespace lynx::gamepad;
  15465. std::vector<std::string> got;
  15466. lynx::GamepadInput input ([&got] (const Changes& c, const State&, double dt) {
  15467. for (int i = 0; i < c.pressedCount; ++i)
  15468. got.push_back (std::string ("press ") + buttonName (c.pressed[(std::size_t) i]));
  15469. for (int i = 0; i < c.releasedCount; ++i)
  15470. got.push_back (std::string ("release ") + buttonName (c.released[(std::size_t) i]));
  15471. for (int i = 0; i < c.controllerCount; ++i)
  15472. got.push_back ("cc " + std::to_string (c.controller[(std::size_t) i]) + "=" + std::to_string (c.value[(std::size_t) i]));
  15473. if (c.connectedChanged)
  15474. got.push_back ("connected changed");
  15475. got.push_back ("dt " + std::to_string ((int) std::lround (dt * 1000)));
  15476. });
  15477. State pad;
  15478. pad.connected = true;
  15479. input.inject (pad, 1.0 / 60.0);
  15480. pad.buttons = mask (Button::a);
  15481. pad.rightTrigger = 255;
  15482. input.inject (pad, 1.0 / 60.0);
  15483. pad.buttons = 0;
  15484. input.inject (pad, 1.0 / 60.0);
  15485. const std::vector<std::string> expected { "connected changed", "dt 17", "press A", "cc 102=127", "cc 21=127", "dt 17",
  15486. "release A", "cc 102=0", "dt 17" };
  15487. for (const auto& line : got)
  15488. report << line << "\n";
  15489. if (got != expected)
  15490. {
  15491. ++failures;
  15492. report << "FAILED: the poller's changes differ from the expected ones\n";
  15493. }
  15494. report << "xinput " << (input.available() ? "loaded" : "not available") << "\n";
  15495. }
  15496. report << (failures == 0 ? "gamepad OK" : "gamepad FAILED") << "\n";
  15497. juce::File (prefix + "-gamepad.txt").replaceWithText (report);
  15498. setApplicationReturnValue (failures == 0 ? 0 : 1);
  15499. quit();
  15500. }
  15501. void runBundleExport (const juce::String& inputPath, const juce::String& folderPath, bool zip, bool mixdown, const juce::String& shotPrefix)
  15502. {
  15503. juce::String error;
  15504. bool ok = false;
  15505. lynx::otherapps::Result result;
  15506. {
  15507. lynx::AudioEngine loader (false);
  15508. const juce::File input (inputPath);
  15509. if (input.hasFileExtension ("flp;als"))
  15510. ok = loader.importFlpFile (input, error);
  15511. else if (auto song = lynx::ProjectFile::load (input, error))
  15512. {
  15513. loader.setSong (std::move (*song));
  15514. ok = true;
  15515. }
  15516. if (ok)
  15517. {
  15518. loader.capturePluginStates();
  15519. lynx::otherapps::Context context;
  15520. context.host = &loader.getPluginHost();
  15521. context.flOptions = lynx::flstudio::optionsFor (context.host, lynx::flpexport::LynxOnly::renderAudio, loader.getSong());
  15522. context.render = [] (const lynx::Song& s, const lynx::exportopts::Options& o, const juce::File& file,
  15523. const std::function<bool (double)>& progress, juce::String& err) {
  15524. lynx::ExportJob job (s, o, file);
  15525. return job.run (progress, err);
  15526. };
  15527. context.onMessageThread = [] (std::function<void()> f) { f(); };
  15528. lynx::exportbundle::Options options;
  15529. options.zip = zip;
  15530. options.mixdown = mixdown;
  15531. const auto name = input.getFileNameWithoutExtension();
  15532. const auto shot = [&shotPrefix] (juce::Component& c, const juce::String& suffix) {
  15533. if (shotPrefix.isNotEmpty())
  15534. savePng (lynx::shot::snapshot (c), shotPrefix + suffix);
  15535. };
  15536. if (auto panel = lynx::makeOtherAppsExportPanel (loader, name))
  15537. shot (*panel, "-panel.png");
  15538. ok = lynx::otherapps::write (loader.getSong(), name, options, juce::File (folderPath), context, result);
  15539. if (auto report = lynx::makeOtherAppsReportPanel (result.folder, result.written, result.failed))
  15540. shot (*report, "-report.png");
  15541. }
  15542. }
  15543. juce::String report;
  15544. report << (ok ? "ok " + result.folder.getFullPathName() : "error=" + error) << "\n";
  15545. for (const auto& w : result.written)
  15546. report << "written " << w << "\n";
  15547. for (const auto& f : result.failed)
  15548. report << "failed " << f << "\n";
  15549. juce::File (folderPath).getChildFile ("export-bundle.txt").replaceWithText (report);
  15550. setApplicationReturnValue (ok && result.failed.isEmpty() ? 0 : 1);
  15551. quit();
  15552. }
  15553. void runFlExport (const juce::String& inputPath, const juce::String& outputPath, bool substitute)
  15554. {
  15555. juce::String error;
  15556. bool ok = false;
  15557. lynx::flstudio::Written written;
  15558. {
  15559. lynx::AudioEngine loader (false);
  15560. const juce::File input (inputPath);
  15561. // a Live set opens through the same import as an .flp (as File › Open does, and --export-als accepts an .flp)
  15562. if (input.hasFileExtension ("flp;als"))
  15563. ok = loader.importFlpFile (input, error);
  15564. else if (auto song = lynx::ProjectFile::load (input, error))
  15565. {
  15566. loader.setSong (std::move (*song));
  15567. ok = true;
  15568. }
  15569. if (ok)
  15570. {
  15571. const juce::File output (outputPath);
  15572. const auto zip = output.hasFileExtension ("zip");
  15573. const auto mode = substitute ? lynx::flpexport::LynxOnly::substitute : lynx::flpexport::LynxOnly::renderAudio;
  15574. loader.capturePluginStates();
  15575. auto options = lynx::flstudio::optionsFor (&loader.getPluginHost(), mode, loader.getSong());
  15576. // --flp-ppq N: the file's PPQ (tests; default: 96 when the notes and clips fit it)
  15577. if (const auto args = juce::JUCEApplication::getCommandLineParameterArray(); args.contains ("--flp-ppq"))
  15578. options.ppq = juce::jlimit (0, 960, args[args.indexOf ("--flp-ppq") + 1].getIntValue());
  15579. const auto renderDir = zip ? juce::File::getSpecialLocation (juce::File::tempDirectory).getNonexistentChildFile ("LYNX FL export", {}, false)
  15580. : output.getSiblingFile (output.getFileNameWithoutExtension() + " audio");
  15581. ok = lynx::flstudio::exportProject (loader.getSong(), options, output, zip, renderDir, 44100.0,
  15582. [] (const lynx::Song& s, const lynx::ExportSettings& settings, const juce::File& wav,
  15583. const std::function<bool (double)>& progress, juce::String& err) {
  15584. lynx::ExportJob job (s, settings, wav);
  15585. return job.run (progress, err);
  15586. },
  15587. {}, written, error);
  15588. if (zip)
  15589. renderDir.deleteRecursively();
  15590. }
  15591. }
  15592. juce::String report;
  15593. report << (ok ? "ok" : "error=" + error) << "\n"
  15594. << "exact=" << (int) written.report.exact.size() << " rendered=" << (int) written.report.rendered.size()
  15595. << " substituted=" << (int) written.report.substituted.size() << " dropped=" << (int) written.report.dropped.size()
  15596. << " samples=" << written.samples << "\n\n"
  15597. << lynx::flstudio::reportText (written) << "\n";
  15598. juce::File (outputPath + ".txt").replaceWithText (report);
  15599. setApplicationReturnValue (ok ? 0 : 1);
  15600. quit();
  15601. }
  15602. // LYNX.exe --export project.(flp|als|lynx) output.(wav|flac|ogg|mp3) [--pattern] [--insert N] [--rate N]
  15603. // Same path as "Export" in the UI: the whole song (or the current pattern) with its tail.
  15604. void runExport (const juce::String& inputPath, const juce::String& outputPath, bool patternOnly, int insert)
  15605. {
  15606. juce::String error, report;
  15607. bool ok = false;
  15608. const auto started = juce::Time::getMillisecondCounterHiRes();
  15609. lynx::loadtrace::begin (inputPath.toStdString()); // phase times (round 112): report lines + load.log
  15610. {
  15611. lynx::AudioEngine loader (false);
  15612. const juce::File input (inputPath);
  15613. // --find-plugins: first the targeted scan opening the project in the app runs (its plugins not known yet)
  15614. if (input.hasFileExtension ("flp") && juce::JUCEApplication::getCommandLineParameters().contains ("--find-plugins"))
  15615. {
  15616. juce::MemoryBlock data;
  15617. if (input.loadFileAsData (data))
  15618. try
  15619. {
  15620. const auto uses = lynx::flpForeignPlugins (flp::parseProject ({ static_cast<const std::uint8_t*> (data.getData()), data.getSize() }));
  15621. auto& host = loader.getPluginHost();
  15622. const auto listed = std::chrono::steady_clock::now();
  15623. const auto files = host.filesToScanFor (uses);
  15624. lynx::loadtrace::add ("plugin_scan_list", lynx::loadtrace::msSince (listed));
  15625. report << "scanned=" << files.joinIntoString (";") << "\n";
  15626. const auto scanned = std::chrono::steady_clock::now();
  15627. host.scanFiles (files, {});
  15628. lynx::loadtrace::add ("plugin_scan", lynx::loadtrace::msSince (scanned), files.size());
  15629. }
  15630. catch (const flp::Error&)
  15631. {
  15632. }
  15633. }
  15634. if (input.hasFileExtension ("flp;als")) // a Live set opens through the same import (round 182b)
  15635. ok = loader.importFlpFile (input, error);
  15636. else if (auto song = lynx::ProjectFile::load (input, error))
  15637. {
  15638. loader.setSong (std::move (*song));
  15639. ok = true;
  15640. }
  15641. if (ok)
  15642. {
  15643. const juce::File output (outputPath);
  15644. lynx::ExportSettings settings;
  15645. settings.wholeSong = ! patternOnly;
  15646. settings.format = output.hasFileExtension ("flac") ? lynx::ExportSettings::Format::flac24
  15647. : output.hasFileExtension ("ogg") ? lynx::ExportSettings::Format::ogg
  15648. : lynx::ExportSettings::Format::wav24;
  15649. // --insert N: only that insert's output (what "Render to audio" records)
  15650. if (juce::JUCEApplication::getCommandLineParameters().contains ("--no-effects")
  15651. || juce::JUCEApplication::getCommandLineParameters().contains ("--sem-efeitos")) // performance diagnostics; --sem-efeitos: legacy alias
  15652. loader.editSong ([] (lynx::Song& s) {
  15653. for (auto& t : s.mixer)
  15654. t.effects.clear();
  15655. }, false);
  15656. if (juce::JUCEApplication::getCommandLineParameters().contains ("--no-automation")
  15657. || juce::JUCEApplication::getCommandLineParameters().contains ("--sem-automacao")) // --sem-automacao: legacy alias
  15658. loader.editSong ([] (lynx::Song& s) { s.automations.clear(); }, false);
  15659. const auto loaded = juce::Time::getMillisecondCounterHiRes();
  15660. // .mp3: the Export window's MP3 (320 kbps); everything else as before
  15661. auto options = settings.toOptions();
  15662. // --save-tempo: FL's "Tempo information" (acid chunk) on (round 167l: compare with FL's AcidBox render; --export)
  15663. if (juce::JUCEApplication::getCommandLineParameters().contains ("--save-tempo"))
  15664. options.saveTempo = true;
  15665. // --no-warmup: the export's plugin warm-up off (round 155: compare the start of the file)
  15666. if (juce::JUCEApplication::getCommandLineParameters().contains ("--no-warmup"))
  15667. options.pluginWarmUp = false;
  15668. // --rate N: render at another sample rate (round 157b: samples resampled as at a 48 kHz device)
  15669. if (const auto args = juce::JUCEApplication::getCommandLineParameterArray(); args.contains ("--rate"))
  15670. if (const auto rate = args[args.indexOf ("--rate") + 1].getDoubleValue(); rate >= 8000.0 && rate <= 384000.0)
  15671. options.sampleRate = rate;
  15672. if (output.hasFileExtension ("mp3"))
  15673. {
  15674. options.format = lynx::exportopts::Format::mp3;
  15675. options.mp3Kbps = 320;
  15676. }
  15677. lynx::ExportJob job (insert > 0 ? lynx::makeBounceSong (loader.getSong(), insert) : loader.getSong(), options, output);
  15678. job.setExtraData (true);
  15679. const auto prepared = juce::Time::getMillisecondCounterHiRes();
  15680. lynx::loadtrace::end();
  15681. int lastPercent = -1;
  15682. ok = job.run ([&lastPercent] (double p) {
  15683. lastPercent = (int) (p * 100.0);
  15684. return true;
  15685. }, error);
  15686. auto joined = [] (const std::map<std::string, int>& items) {
  15687. juce::StringArray names;
  15688. for (const auto& [name, count] : items)
  15689. names.add (juce::String::fromUTF8 (name.c_str()) + "x" + juce::String (count));
  15690. return names.joinIntoString (", ");
  15691. };
  15692. const auto& importReport = loader.getImportReport();
  15693. report << "converted=" << joined (importReport.converted) << "\n"
  15694. << "approximated=" << joined (importReport.approximated) << "\n"
  15695. << "unsupported=" << joined (importReport.unsupported) << "\n"
  15696. << "dropped_effects=" << joined (importReport.droppedEffects) << "\n"
  15697. << "partial_effects=" << joined (importReport.partialEffects) << "\n"
  15698. << "missing_samples=" << importReport.missingSamples << "\n";
  15699. // third-party plugins: how each was found, or what plays in its place (diagnostics for level differences)
  15700. for (const auto& line : loader.getMatchedPlugins())
  15701. report << "plugin_found=" << line << "\n";
  15702. for (const auto& m : loader.getMissingPluginDetails())
  15703. report << "plugin_missing=" << juce::String::fromUTF8 (m.name.c_str()) << " -> "
  15704. << juce::String::fromUTF8 (m.replacement.c_str()).replace ("{0}", juce::String::fromUTF8 (m.replacementArg.c_str())) << "\n";
  15705. {
  15706. const auto& song = loader.getSong();
  15707. for (std::size_t t = 0; t < song.mixer.size(); ++t)
  15708. {
  15709. const auto& track = song.mixer[t];
  15710. if (track.effects.empty() && track.sends.empty())
  15711. continue;
  15712. report << "insert " << (int) t << " vol=" << juce::String (track.volume / lynx::unityFader, 3)
  15713. << (track.muted ? " muted" : "") << (track.toMaster ? "" : " noMaster");
  15714. for (const auto& s : track.sends)
  15715. report << " send>" << s.target << "@" << juce::String (s.level, 3);
  15716. report << " |";
  15717. for (const auto& fx : track.effects)
  15718. report << " [" << (fx.kind == lynx::EffectKind::plugin ? juce::String::fromUTF8 (fx.plugin.name.c_str())
  15719. : juce::String::fromUTF8 (lynx::effectInfo (fx.kind).name))
  15720. << (fx.isSubstitute() ? " (substitute)" : "") << (fx.enabled ? "" : " off")
  15721. << (fx.mix < 0.999f ? " mix=" + juce::String (fx.mix, 2) : juce::String()) << "]";
  15722. report << "\n";
  15723. }
  15724. }
  15725. report << juce::String (lynx::loadtrace::reportLines());
  15726. lynx::PluginHost::settingsFolder().getChildFile ("load.log").replaceWithText (juce::String (lynx::loadtrace::table()));
  15727. report << "open_ms=" << juce::roundToInt (loaded - started) << "\n"
  15728. << "prepare_ms=" << juce::roundToInt (prepared - loaded) << "\n"
  15729. << "render_ms=" << juce::roundToInt (juce::Time::getMillisecondCounterHiRes() - prepared) << "\n"
  15730. << "graph_ms=" << juce::roundToInt (job.getEngine().getLastRenderStats().graphMs) << "\n"
  15731. << "write_ms=" << juce::roundToInt (job.getEngine().getLastRenderStats().writeMs) << "\n"
  15732. << "warmup_blocks=" << job.getEngine().getLastRenderStats().warmUp.blocks << "\n"
  15733. << "warmup_ms=" << juce::roundToInt (job.getEngine().getLastRenderStats().warmUp.wallSeconds * 1000.0) << "\n"
  15734. << "warmup_changes=" << job.getEngine().getLastRenderStats().warmUp.signatureChanges << "\n"
  15735. << "warmup_timed_out=" << (job.getEngine().getLastRenderStats().warmUp.timedOut ? 1 : 0) << "\n"
  15736. << "pdc_trim=" << job.getEngine().getLastRenderStats().trimmedSamples << "\n"
  15737. << "song_seconds=" << job.getMusicSeconds() << "\n"
  15738. << "peak=" << job.getPeak() << "\n"
  15739. << "final_progress=" << lastPercent << "\n"
  15740. << "bytes=" << output.getSize() << "\n";
  15741. ok = ok && job.getPeak() > 0.001f;
  15742. }
  15743. }
  15744. report << "result=" << (ok ? "OK" : "ERROR " + error) << "\n";
  15745. juce::File (outputPath + ".txt").replaceWithText (report);
  15746. setApplicationReturnValue (ok ? 0 : 1);
  15747. quit();
  15748. }
  15749. // LYNX.exe --snapshot prefix [project]: draws the window off-screen and writes
  15750. // prefix-rack.png, -pianoroll.png and -playlist.png (to check the UI without touching the screen).
  15751. // --editorcpu: one editor after another; each phase runs 2 s to settle and 8 s measured
  15752. struct EditorCpuRun final : juce::Timer
  15753. {
  15754. struct Case { lynx::EffectKind kind; const char* name; int type; bool demo; }; // type 0 native, 1 display-first, 2 Facet EQ
  15755. std::vector<Case> cases;
  15756. std::size_t at = 0;
  15757. int phase = 0;
  15758. double t0 = 0.0, c0 = 0.0;
  15759. juce::String report;
  15760. juce::File out;
  15761. std::unique_ptr<lynx::AudioEngine> engine;
  15762. std::unique_ptr<juce::DocumentWindow> window;
  15763. std::function<void()> done;
  15764. void start()
  15765. {
  15766. engine = std::make_unique<lynx::AudioEngine> (false);
  15767. report << "editor\tmode\tcpu % of one core\n";
  15768. open();
  15769. startTimer (250);
  15770. }
  15771. void open()
  15772. {
  15773. window.reset();
  15774. if (at >= cases.size()) { out.replaceWithText (report); stopTimer(); if (done) done(); return; }
  15775. const auto& c = cases[at];
  15776. lynx::Song song;
  15777. song.mixer.resize (2);
  15778. song.mixer[0].name = "Master";
  15779. song.mixer[1].name = "Insert 1";
  15780. song.mixer[1].effects.push_back (lynx::makeEffectSlot (c.kind));
  15781. engine->setSong (std::move (song));
  15782. engine->dispatchPendingMessages();
  15783. lynx::setNativeEditorDemo (c.demo);
  15784. auto editor = c.type == 1 ? lynx::makeProEditor (*engine, 1, 0, c.demo) : c.type == 2 ? lynx::makeFacetEqEditor (*engine, 1, 0, c.demo)
  15785. : lynx::makeNativeEffectEditor (*engine, 1, 0, 1.0f, 0);
  15786. window = std::make_unique<juce::DocumentWindow> (juce::String ("LYNX editor CPU - ") + c.name, lynx::theme::colour::bg1, 0);
  15787. window->setUsingNativeTitleBar (true);
  15788. window->setContentOwned (editor.release(), true);
  15789. const auto area = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea;
  15790. window->setTopLeftPosition (area.getRight() - window->getWidth() - 8, area.getBottom() - window->getHeight() - 8);
  15791. window->setVisible (true);
  15792. phase = 0;
  15793. t0 = juce::Time::getMillisecondCounterHiRes();
  15794. }
  15795. void timerCallback() override
  15796. {
  15797. const auto now = juce::Time::getMillisecondCounterHiRes();
  15798. if (phase == 0 && now - t0 > 2000.0) { phase = 1; t0 = now; c0 = lynx::processCpuSeconds(); return; }
  15799. if (phase == 1 && now - t0 > 8000.0)
  15800. {
  15801. const auto cpu = (lynx::processCpuSeconds() - c0) / ((now - t0) * 0.001) * 100.0;
  15802. const auto& c = cases[at];
  15803. report << c.name << "\t" << (c.demo ? "animating" : "idle") << "\t" << juce::String (cpu, 2) << "\n";
  15804. ++at;
  15805. open();
  15806. }
  15807. }
  15808. };
  15809. std::unique_ptr<EditorCpuRun> editorCpu;
  15810. void runEditorCpu (const juce::String& path)
  15811. {
  15812. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  15813. editorCpu = std::make_unique<EditorCpuRun>();
  15814. editorCpu->out = juce::File (path);
  15815. using K = lynx::EffectKind;
  15816. for (const auto demo : { false, true })
  15817. for (const auto& c : std::vector<EditorCpuRun::Case> { { K::facetEq, "Facet EQ", 2, demo }, { K::crestCompressor, "Crest Compressor", 1, demo },
  15818. { K::apexLimiter, "Apex Limiter", 1, demo }, { K::prismMultiband, "Prism Multiband", 1, demo },
  15819. { K::epochVerb, "Epoch Verb", 0, demo }, { K::glowLeveler, "Glow Leveler", 0, demo },
  15820. { K::fruityLimiter, "Fruity Limiter", 0, demo }, { K::lynxTune, "LYNX Tune", 0, demo } })
  15821. editorCpu->cases.push_back (c);
  15822. editorCpu->done = [this] { juce::MessageManager::callAsync ([this] { editorCpu.reset(); quit(); }); };
  15823. editorCpu->start();
  15824. }
  15825. struct ParityShow
  15826. {
  15827. std::unique_ptr<lynx::AudioEngine> engine;
  15828. std::unique_ptr<juce::Component> editor;
  15829. std::unique_ptr<juce::DocumentWindow> window;
  15830. ~ParityShow() { window.reset(); editor.reset(); engine.reset(); }
  15831. };
  15832. std::shared_ptr<ParityShow> parityShow;
  15833. bool parityShotFailed = false; // --parityshot: the effect name matched no built-in effect
  15834. void runParityShot (const juce::String& path, const juce::String& effectName, const juce::String& paramsFile)
  15835. {
  15836. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  15837. int kindIndex = -1;
  15838. for (int k = 0; k <= (int) lynx::lastEffectKind; ++k)
  15839. if (juce::String::fromUTF8 (lynx::effectInfo ((lynx::EffectKind) k).name).equalsIgnoreCase (effectName))
  15840. kindIndex = k;
  15841. if (kindIndex < 0)
  15842. {
  15843. // round tp172b7: say so and fail (a silent exit 0 hid a split effect name in a launch script)
  15844. std::fprintf (stderr, "unknown effect: %s\n", effectName.toRawUTF8());
  15845. std::fflush (stderr);
  15846. parityShotFailed = true;
  15847. return;
  15848. }
  15849. const auto kind = (lynx::EffectKind) kindIndex;
  15850. auto fx = lynx::makeEffectSlot (kind);
  15851. if (paramsFile.isNotEmpty())
  15852. for (const auto& line : juce::StringArray::fromLines (juce::File (paramsFile).loadFileAsString()))
  15853. {
  15854. const auto t = juce::StringArray::fromTokens (line, " \t", "");
  15855. const auto index = t.size() >= 2 ? t[0].getIntValue() : -1;
  15856. if (index >= 0 && index < lynx::maxEffectParams)
  15857. fx.params[(std::size_t) index] = t[1].getFloatValue();
  15858. }
  15859. auto offlineOwner = std::make_unique<lynx::AudioEngine> (false); // (kept alive by LYNX_PARITYSHOT_SHOW's window)
  15860. auto& offline = *offlineOwner;
  15861. auto song = lynx::Song::makeDefault();
  15862. song.mixer.resize (2);
  15863. song.mixer[0].name = "Master";
  15864. song.mixer[1].name = "Insert 1";
  15865. song.mixer[1].effects.assign (1, fx);
  15866. for (auto& c : song.channels)
  15867. c.mixerTrack = 1;
  15868. offline.setSong (std::move (song));
  15869. offline.dispatchPendingMessages();
  15870. const bool facet = kind == lynx::EffectKind::facetEq;
  15871. // round tp172b4: the originals are pictured idle (nothing playing), so the display-first editors are too: no demo
  15872. // history unless LYNX_PARITYSHOT_DEMO=1 asks for the running display
  15873. const bool demoDisplay = juce::SystemStats::getEnvironmentVariable ("LYNX_PARITYSHOT_DEMO", {}) == "1";
  15874. // (Ember in its Classic voicing: the Classic panel, as the mixer opens it)
  15875. const bool pro = lynx::ProEditorWindows::handles (kind)
  15876. && ! (kind == lynx::EffectKind::ember && fx.params[(std::size_t) lynx::mixsuite::ember::voicing] > 0.5f);
  15877. auto editor = facet ? lynx::makeFacetEqEditor (offline, 1, 0, false)
  15878. : pro ? lynx::makeProEditor (offline, 1, 0, demoDisplay) : lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
  15879. if (editor == nullptr)
  15880. return;
  15881. if (! pro) // the demo song through the effect, the editor ticked 30 times a second of audio as its timer would
  15882. {
  15883. lynx::AudioEngine::RenderOptions o;
  15884. o.seconds = 3.0;
  15885. o.sampleRate = 48000.0;
  15886. o.pluginWarmUp = false;
  15887. int sinceTick = 0;
  15888. o.capture = [&] (const float*, const float*, int n) {
  15889. sinceTick += n;
  15890. if (sinceTick < 1600) return;
  15891. sinceTick = 0;
  15892. if (facet) lynx::tickFacetEqEditor (*editor);
  15893. else lynx::tickNativeEffectEditor (*editor);
  15894. };
  15895. offline.renderOffline (o);
  15896. }
  15897. // round tp172b5: LYNX_PARITYSHOT_CLICKS drives the editor before the picture (the originals' pictures have their
  15898. // panels open), tokens in order: "x,y" a click, then the pointer leaves; "h:x,y" the pointer rests there (a hover);
  15899. // "d:x,y,x2,y2" a drag from there to there, the button still down in the picture
  15900. for (const auto& token : juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_PARITYSHOT_CLICKS", {}), " ", ""))
  15901. {
  15902. const auto hover = token.startsWith ("h:"), drag = token.startsWith ("d:");
  15903. const auto xy = juce::StringArray::fromTokens (hover || drag ? token.substring (2) : token, ",", "");
  15904. if (xy.size() < (drag ? 4 : 2))
  15905. continue;
  15906. const juce::Point<int> at (xy[0].getIntValue(), xy[1].getIntValue());
  15907. editor->setVisible (true); // (getComponentAt finds nothing in a hidden component; it never goes on screen)
  15908. auto* target = editor->getComponentAt (at);
  15909. if (target == nullptr)
  15910. continue;
  15911. const auto local = target->getLocalPoint (editor.get(), at).toFloat();
  15912. const auto now = juce::Time::getCurrentTime();
  15913. auto source = juce::Desktop::getInstance().getMainMouseSource();
  15914. const juce::ModifierKeys left (juce::ModifierKeys::leftButtonModifier);
  15915. const auto event = [&] (juce::Point<float> p, juce::ModifierKeys mods, bool dragged) {
  15916. return juce::MouseEvent (source, p, mods, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, target, target, now, local, now, 1, dragged);
  15917. };
  15918. target->mouseMove (event (local, {}, false));
  15919. if (hover)
  15920. continue;
  15921. target->mouseDown (event (local, left, false));
  15922. if (drag)
  15923. {
  15924. const auto end = target->getLocalPoint (editor.get(), juce::Point<int> (xy[2].getIntValue(), xy[3].getIntValue())).toFloat();
  15925. target->mouseDrag (event (end, left, true));
  15926. continue;
  15927. }
  15928. target->mouseUp (event (local, {}, false));
  15929. target->mouseExit (event ({ -1000.0f, -1000.0f }, {}, false));
  15930. }
  15931. // round tp172b6: LYNX_PARITYSHOT_SHOW=1 puts the same editor in a real window and keeps it open (for a guarded GUI check
  15932. // of its pop-up menus, which the offscreen picture cannot hold); closing the window quits
  15933. if (juce::SystemStats::getEnvironmentVariable ("LYNX_PARITYSHOT_SHOW", {}) == "1")
  15934. {
  15935. struct ShowWindow final : juce::DocumentWindow
  15936. {
  15937. ShowWindow() : juce::DocumentWindow ("LYNX parity check", juce::Colours::black, juce::DocumentWindow::closeButton) {}
  15938. void closeButtonPressed() override { juce::JUCEApplication::getInstance()->systemRequestedQuit(); }
  15939. };
  15940. parityShow = std::make_shared<ParityShow>();
  15941. parityShow->engine = std::move (offlineOwner);
  15942. parityShow->editor = std::move (editor);
  15943. auto window = std::make_unique<ShowWindow>();
  15944. window->setUsingNativeTitleBar (true);
  15945. window->setContentNonOwned (parityShow->editor.get(), true);
  15946. window->setTopLeftPosition (80, 80);
  15947. window->setVisible (true);
  15948. parityShow->window = std::move (window);
  15949. return;
  15950. }
  15951. // round 190ar: LYNX_PARITYSHOT_SCALE=2 draws the same editor at twice the pixel density (as on a 200 % display);
  15952. // round 190bi: the shared shot scale (--shot-scale, LYNX_SHOT_SCALE, LYNX_PARITYSHOT_SCALE as before)
  15953. const auto shotScale = lynx::shot::scale();
  15954. juce::Image image (juce::Image::ARGB, juce::roundToInt ((float) editor->getWidth() * shotScale), juce::roundToInt ((float) editor->getHeight() * shotScale), true);
  15955. {
  15956. juce::Graphics g (image);
  15957. g.fillAll (lynx::theme::panel);
  15958. g.addTransform (juce::AffineTransform::scale (shotScale));
  15959. editor->paintEntireComponent (g, false);
  15960. }
  15961. const auto file = lynx::shot::file (juce::File (path));
  15962. file.deleteFile();
  15963. juce::PNGImageFormat png;
  15964. if (auto stream = file.createOutputStream())
  15965. png.writeImageToStream (image, *stream);
  15966. }
  15967. // an Audio Effect Rack shaped like Live's reference (REA_rodada183c §8): two chains with chain-select zones and fades,
  15968. // four named macros (one on a chain's volume, one on two parameters), two variations, every view open
  15969. static lynx::EffectSlot shotRack()
  15970. {
  15971. auto slot = lynx::rack::makeRackSlot (lynx::RackDoc::Kind::audioEffect);
  15972. auto& doc = slot.patcher;
  15973. doc.rack[0].chains[0].name = "Vocoder";
  15974. lynx::PatchNode vocoder, eq, verb;
  15975. vocoder.effect = lynx::makeEffectSlot (lynx::EffectKind::vocodex);
  15976. eq.effect = lynx::makeEffectSlot (lynx::EffectKind::parametricEq);
  15977. verb.effect = lynx::makeEffectSlot (lynx::EffectKind::reeverb2);
  15978. const auto nVoc = lynx::rack::addDevice (doc, 0, vocoder);
  15979. const auto nEq = lynx::rack::addDevice (doc, 0, eq);
  15980. lynx::rack::addChain (doc, "dry bypass");
  15981. lynx::rack::addDevice (doc, 1, verb);
  15982. doc.rack[0].chains[0].select = { 0, 79, 0, 63 };
  15983. doc.rack[0].chains[1].select = { 32, 127, 48, 127 };
  15984. lynx::rack::setChainVolume (doc, 0, 0.33f);
  15985. lynx::rack::setChainVolume (doc, 1, 0.5f);
  15986. const char* names[] { "Sibilance", "Intensity", "Formant Shift", "Bright Level" };
  15987. for (int m = 0; m < 4; ++m)
  15988. doc.rack[0].macros[(std::size_t) m].name = names[m];
  15989. lynx::RackMapping vol;
  15990. vol.target = lynx::RackMapping::Target::chainVolume, vol.chain = 0, vol.min = 0.0f, vol.max = lynx::rack::unityVolume;
  15991. lynx::rack::map (doc, 0, vol);
  15992. lynx::RackMapping a, b, c, d;
  15993. a.node = nVoc, a.param = 0;
  15994. b.node = nVoc, b.param = 1, b.min = 0.2f, b.max = 0.8f;
  15995. c.node = nEq, c.param = 0, c.min = 0.3f, c.max = 0.9f;
  15996. d.node = nEq, d.param = 1;
  15997. lynx::rack::map (doc, 1, a);
  15998. lynx::rack::map (doc, 2, b);
  15999. lynx::rack::map (doc, 3, c);
  16000. lynx::rack::map (doc, 3, d);
  16001. lynx::rack::setMacro (doc, 0, 60.0f);
  16002. lynx::rack::setMacro (doc, 1, 40.0f);
  16003. lynx::rack::setMacro (doc, 2, 70.0f);
  16004. lynx::rack::setMacro (doc, 3, 86.0f);
  16005. lynx::rack::storeVariation (doc);
  16006. lynx::rack::renameVariation (doc, 0, "Verse");
  16007. lynx::rack::setMacro (doc, 3, 120.0f);
  16008. lynx::rack::storeVariation (doc);
  16009. lynx::rack::renameVariation (doc, 1, "Drop");
  16010. lynx::rack::launchVariation (doc, 0);
  16011. auto& r = doc.rack[0];
  16012. r.showMacros = r.showChains = r.showDevices = r.showVariations = true;
  16013. r.zoneEditor = 2;
  16014. r.selectedChain = 0;
  16015. lynx::rack::setSelector (doc, 56.0f);
  16016. lynx::rack::compile (doc);
  16017. return slot;
  16018. }
  16019. bool runRackShots (const juce::File& out, const juce::String& liveSet = {})
  16020. {
  16021. out.createDirectory();
  16022. lynx::AudioEngine offline (false);
  16023. auto save = [&] (juce::Component& c, const juce::String& name) {
  16024. auto image = lynx::shot::paint (c, lynx::theme::panel);
  16025. const auto f = lynx::shot::file (out.getChildFile (name));
  16026. f.deleteFile();
  16027. juce::PNGImageFormat png;
  16028. if (auto stream = f.createOutputStream())
  16029. return png.writeImageToStream (image, *stream);
  16030. return false;
  16031. };
  16032. auto song = lynx::Song::makeDefault();
  16033. song.mixer.resize (3);
  16034. song.mixer[1].name = "Vocal Main";
  16035. auto slot = shotRack();
  16036. song.mixer[1].effects = { slot };
  16037. // an Instrument Rack: three chains split over the keyboard
  16038. lynx::ChannelDef inst;
  16039. inst.name = "Keys Rack";
  16040. inst.instrument = lynx::InstrumentKind::patcher;
  16041. inst.patcher = lynx::rack::makeRack (lynx::RackDoc::Kind::instrument);
  16042. for (int k = 0; k < 3; ++k)
  16043. {
  16044. if (k > 0)
  16045. lynx::rack::addChain (inst.patcher);
  16046. lynx::PatchNode synth;
  16047. synth.generator = true;
  16048. synth.channel.instrument = lynx::InstrumentKind::synth;
  16049. synth.channel.name = "Synth";
  16050. lynx::rack::addDevice (inst.patcher, k, synth);
  16051. }
  16052. inst.patcher.rack[0].chains[0].key = { 0, 52, 0, 47 };
  16053. inst.patcher.rack[0].chains[1].key = { 48, 76, 53, 71 };
  16054. inst.patcher.rack[0].chains[2].key = { 72, 127, 77, 127 };
  16055. inst.patcher.rack[0].chains[0].name = "Low";
  16056. inst.patcher.rack[0].chains[1].name = "Mid";
  16057. inst.patcher.rack[0].chains[2].name = "High";
  16058. inst.patcher.rack[0].showChains = inst.patcher.rack[0].showDevices = true;
  16059. inst.patcher.rack[0].zoneEditor = 0;
  16060. lynx::rack::compile (inst.patcher);
  16061. song.channels.push_back (inst);
  16062. const auto channel = (int) song.channels.size() - 1;
  16063. offline.setSong (std::move (song));
  16064. offline.dispatchPendingMessages();
  16065. bool ok = true;
  16066. // [set.als]: a Live set's racks as LYNX imports them, the one with the most chains drawn with its title bar (the
  16067. // like-for-like pair with Live's own picture of that set)
  16068. if (liveSet.isNotEmpty())
  16069. {
  16070. juce::MemoryBlock bytes;
  16071. juce::File (liveSet).loadFileAsData (bytes);
  16072. const std::vector<std::uint8_t> data ((const std::uint8_t*) bytes.getData(), (const std::uint8_t*) bytes.getData() + bytes.getSize());
  16073. lynx::AlsImportOptions o;
  16074. o.common.projectFolder = juce::File (liveSet).getParentDirectory().getFullPathName().toStdString();
  16075. std::string error;
  16076. if (auto imported = lynx::importAls (data, o, &error))
  16077. {
  16078. int bestTrack = -1, bestSlot = -1;
  16079. std::size_t most = 0;
  16080. for (int t = 0; t < (int) imported->mixer.size(); ++t)
  16081. for (int s = 0; s < (int) imported->mixer[(std::size_t) t].effects.size(); ++s)
  16082. 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)
  16083. most = fx.patcher.rack[0].chains.size(), bestTrack = t, bestSlot = s;
  16084. if (bestTrack >= 0)
  16085. {
  16086. offline.setSong (std::move (*imported));
  16087. offline.dispatchPendingMessages();
  16088. auto view = lynx::RackWindows::makeSlotView (offline, bestTrack, bestSlot, true);
  16089. view->setSize (view->preferredWidth (228), 228);
  16090. ok = save (*view, "rack-live-import.png") && ok;
  16091. view->setMapMode (true);
  16092. view->setSize (view->preferredWidth (228), 228);
  16093. ok = save (*view, "rack-live-import-map.png") && ok;
  16094. return ok;
  16095. }
  16096. }
  16097. return false;
  16098. }
  16099. {
  16100. auto view = lynx::RackWindows::makeSlotView (offline, 1, 0, false);
  16101. view->setSize (view->preferredWidth (206), 206);
  16102. ok = save (*view, "rack-deviceview.png") && ok;
  16103. }
  16104. {
  16105. auto view = lynx::RackWindows::makeSlotView (offline, 1, 0, true);
  16106. view->setMapMode (true);
  16107. view->setSize (view->preferredWidth (228), 228);
  16108. ok = save (*view, "rack-mapmode.png") && ok;
  16109. }
  16110. {
  16111. auto view = lynx::RackWindows::makeChannelView (offline, channel, true);
  16112. view->setSize (view->preferredWidth (228), 228);
  16113. ok = save (*view, "rack-instrument.png") && ok;
  16114. }
  16115. return ok;
  16116. }
  16117. void runEq166fShots (const juce::String& folder)
  16118. {
  16119. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  16120. const juce::File out (folder);
  16121. out.createDirectory();
  16122. lynx::AudioEngine offline (false);
  16123. auto save = [&] (juce::Component& editor, const juce::String& name) {
  16124. auto image = lynx::shot::paint (editor, lynx::theme::panel);
  16125. const auto f = lynx::shot::file (out.getChildFile (name));
  16126. f.deleteFile();
  16127. juce::PNGImageFormat png;
  16128. if (auto stream = f.createOutputStream())
  16129. png.writeImageToStream (image, *stream);
  16130. };
  16131. // a song whose demo beat plays into insert 1 (the source) and, for Facet's target, its other half into insert 2
  16132. auto songWith = [] (const lynx::EffectSlot& fx, bool split) {
  16133. auto song = lynx::Song::makeDefault();
  16134. song.mixer.resize (3);
  16135. song.mixer[0].name = "Master";
  16136. song.mixer[1].name = "Vocal";
  16137. song.mixer[2].name = "Reference mix";
  16138. song.mixer[1].effects.assign (1, fx);
  16139. for (std::size_t c = 0; c < song.channels.size(); ++c)
  16140. song.channels[c].mixerTrack = split && c % 2 == 1 ? 2 : 1;
  16141. return song;
  16142. };
  16143. auto feed = [&] (juce::Component& editor, bool facet, int frames) {
  16144. // one continuous render of the song, the editor ticked 30 times a second of audio, as its timer would
  16145. lynx::AudioEngine::RenderOptions o;
  16146. o.seconds = frames / 30.0;
  16147. o.sampleRate = 48000.0;
  16148. o.pluginWarmUp = false;
  16149. int sinceTick = 0;
  16150. o.capture = [&] (const float*, const float*, int n) {
  16151. sinceTick += n;
  16152. if (sinceTick < 1600) return;
  16153. sinceTick = 0;
  16154. if (facet) lynx::tickFacetEqEditor (editor);
  16155. else lynx::tickNativeEffectEditor (editor);
  16156. };
  16157. offline.renderOffline (o);
  16158. if (facet) lynx::tickFacetEqEditor (editor);
  16159. else lynx::tickNativeEffectEditor (editor);
  16160. };
  16161. // Parametric EQ 2: spectrum + heatmap (Full), flat / band 4 +12 dB / band 4 -12 dB, then the Top position
  16162. auto& display = lynx::peqview::displaySettings();
  16163. const auto kept = display;
  16164. display.spectrum = display.heatmap = true;
  16165. display.position = 0;
  16166. 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" },
  16167. { 0.0, "peq2-heatmap-top.png" } })
  16168. {
  16169. auto eq = lynx::makeEffectSlot (lynx::EffectKind::parametricEq);
  16170. eq.params[(std::size_t) lynx::peq::param (3, 2)] = lynx::peq::gainValue (gain);
  16171. eq.params[(std::size_t) lynx::peq::param (3, 1)] = lynx::peq::hzValue (900.0);
  16172. display.position = juce::String (name).contains ("top") ? 1 : 0;
  16173. offline.setSong (songWith (eq, false));
  16174. offline.dispatchPendingMessages();
  16175. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.25f, 0);
  16176. feed (*editor, false, 120);
  16177. save (*editor, name);
  16178. }
  16179. display = kept;
  16180. // Facet EQ's comparative EQ: listening to the target (insert 2) with its spectrum over the source's
  16181. {
  16182. using namespace lynx::facet;
  16183. auto eq = lynx::makeEffectSlot (lynx::EffectKind::facetEq);
  16184. eq.params[(std::size_t) param (0, 0)] = shapeValue (Shape::bell);
  16185. eq.params[(std::size_t) param (0, 1)] = hzValue (250.0);
  16186. eq.params[(std::size_t) param (0, 2)] = gainValue (-4.0);
  16187. eq.params[(std::size_t) param (1, 0)] = shapeValue (Shape::highShelf);
  16188. eq.params[(std::size_t) param (1, 1)] = hzValue (6000.0);
  16189. eq.params[(std::size_t) param (1, 2)] = gainValue (3.0);
  16190. eq.params[(std::size_t) analyzerParam] = analyzerValue (Analyzer::both);
  16191. eq.sidechain = 2;
  16192. for (const auto& [l, name] : { std::pair { Listen::target, "facet-compare-target.png" }, { Listen::eq, "facet-compare-eq.png" } })
  16193. {
  16194. eq.params[(std::size_t) listenParam] = listenValue (l);
  16195. offline.setSong (songWith (eq, true));
  16196. offline.dispatchPendingMessages();
  16197. auto editor = lynx::makeFacetEqEditor (offline, 1, 0, false);
  16198. feed (*editor, true, 90);
  16199. save (*editor, name);
  16200. }
  16201. }
  16202. }
  16203. void runDesign168rShots (const juce::String& folder)
  16204. {
  16205. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  16206. const juce::File out (folder);
  16207. out.createDirectory();
  16208. lynx::AudioEngine offline (false);
  16209. using K = lynx::EffectKind;
  16210. for (const auto kind : { K::pitchCorrect, K::lovePhilter, K::peakController, K::spreader, K::fruityFastLP, K::flFrequencyShifter,
  16211. K::flLowLifter, K::distructor, K::flBassBoost, K::flDelay1, K::fl7BandEq, K::flCenter, K::flPhaseInverter,
  16212. K::eq, K::delay, K::reverb, K::limiter, K::filter, K::distortion, K::chorus, K::utility, K::lofi,
  16213. K::crossover, K::pitchShift, K::freqShift, K::rhythmGain, K::volumeGate })
  16214. {
  16215. const auto& bank = lynx::presets::factory (kind);
  16216. // Love Philter / Distructor play FL's state: their second picture is FL's default preset (when installed)
  16217. std::optional<lynx::EffectSlot> flPreset;
  16218. if (kind == K::lovePhilter || kind == K::distructor)
  16219. {
  16220. const auto roots = lynx::findFlStudioRoots();
  16221. const auto file = juce::File (juce::String::fromUTF8 (roots.data.c_str()))
  16222. .getChildFile ("Patches/Plugin presets/Effects")
  16223. .getChildFile (kind == K::lovePhilter ? "Fruity Love Philter/Default.fst" : "Distructor/Default.fst");
  16224. juce::MemoryBlock bytes;
  16225. if (file.loadFileAsData (bytes))
  16226. flPreset = lynx::effectFromFlPreset (std::vector<std::uint8_t> ((const std::uint8_t*) bytes.getData(),
  16227. (const std::uint8_t*) bytes.getData() + bytes.getSize()));
  16228. }
  16229. for (int pass = 0; pass < (bank.empty() && ! flPreset ? 1 : 2); ++pass)
  16230. {
  16231. auto fx = lynx::makeEffectSlot (kind);
  16232. if (pass == 1 && flPreset)
  16233. fx = *flPreset;
  16234. else if (pass == 1)
  16235. {
  16236. fx.params = lynx::presets::apply (kind, bank.front(), 120.0);
  16237. fx.presetName = bank.front().name;
  16238. }
  16239. lynx::Song song;
  16240. song.mixer.resize (2);
  16241. song.mixer[0].name = "Master";
  16242. song.mixer[1].name = "Insert 1";
  16243. song.mixer[1].effects.push_back (fx);
  16244. offline.setSong (std::move (song));
  16245. offline.dispatchPendingMessages();
  16246. const auto pages = juce::jmax (1, (int) lynx::plugui::layoutFor (kind).pages.size());
  16247. for (const auto scale : { 1.0f, 2.0f })
  16248. for (int page = 0; page < pages; ++page)
  16249. {
  16250. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, scale, page);
  16251. if (editor == nullptr)
  16252. continue;
  16253. juce::Image image (juce::Image::ARGB, juce::jmax (1, editor->getWidth()), juce::jmax (1, editor->getHeight()), true);
  16254. {
  16255. juce::Graphics g (image);
  16256. g.fillAll (lynx::theme::panel);
  16257. editor->paintEntireComponent (g, false);
  16258. }
  16259. // (FL's "Frequency Shifter" and LYNX's "Frequency shifter" differ only in case: FL editors get "FL ")
  16260. const auto file = out.getChildFile ((lynx::plugui::hasFlLayout (kind) ? "FL " : "")
  16261. + juce::String (lynx::effectInfo (kind).name).replaceCharacters ("/\\:", "---")
  16262. + (pass == 1 ? "-preset" : "") + (page > 0 ? "-p" + juce::String (page + 1) : juce::String())
  16263. + (scale > 1.5f ? "-200" : "-100") + ".png");
  16264. file.deleteFile();
  16265. juce::PNGImageFormat png;
  16266. if (auto stream = file.createOutputStream())
  16267. png.writeImageToStream (image, *stream);
  16268. }
  16269. }
  16270. }
  16271. }
  16272. bool runInstrumentShots (const juce::File& folder, const juce::String& which, const juce::String& source)
  16273. {
  16274. folder.createDirectory();
  16275. auto key = [] (juce::String n) { return n.toLowerCase().removeCharacters (" -!._"); };
  16276. juce::StringArray wanted;
  16277. wanted.addTokens (which, ",", "");
  16278. auto ok = true;
  16279. struct Shot
  16280. {
  16281. juce::String name;
  16282. std::optional<lynx::ChannelDef> channel;
  16283. };
  16284. std::vector<Shot> shots;
  16285. for (const auto& e : lynx::natives::instrumentEngines())
  16286. {
  16287. const auto name = key (e.name);
  16288. const auto banked = which == "banks" && lynx::banks::hasBank (e.kind);
  16289. if (! banked && ! wanted.contains (name))
  16290. continue;
  16291. auto channel = source == "fl" || source == "flm" ? lynx::natives::makeChannel (e.kind, lynx::flStudioAccess())
  16292. : lynx::banks::defaultChannel (e.kind, e.name);
  16293. // (round 190u) source "flm": the channel as the .flm import makes it (Transistor Bass: FL Studio Mobile's build)
  16294. if (source == "flm" && channel && e.kind == lynx::InstrumentKind::transistorbass)
  16295. {
  16296. 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
  16297. channel->modelParams = { 1.0f };
  16298. channel->samplePath.clear();
  16299. }
  16300. if (! channel)
  16301. {
  16302. std::fprintf (stderr, "%s: no %s channel\n", e.name, source.toRawUTF8());
  16303. ok = false;
  16304. continue;
  16305. }
  16306. shots.push_back ({ name, std::move (channel) });
  16307. }
  16308. // Autogun (round 169h): not in the Add menus (no preset files); FL's own render-test channel, either source
  16309. if (wanted.contains ("autogun"))
  16310. {
  16311. if (auto channel = lynx::natives::autogunShotChannel (lynx::flStudioAccess()))
  16312. shots.push_back ({ "autogun", std::move (channel) });
  16313. else
  16314. {
  16315. std::fprintf (stderr, "Autogun: no channel (FL Studio's Render tests\\Autogun.flp)\n");
  16316. ok = false;
  16317. }
  16318. }
  16319. for (auto& shot : shots)
  16320. {
  16321. const auto& name = shot.name;
  16322. auto& channel = shot.channel;
  16323. lynx::AudioEngine offline (false);
  16324. lynx::Song song;
  16325. song.mixer = lynx::Song::defaultMixer (2);
  16326. song.channels.push_back (*channel);
  16327. song.patterns.emplace_back();
  16328. {
  16329. juce::String error; // the project too, so an older build can picture the same channel (--snapshot)
  16330. lynx::ProjectFile::save (song, folder.getChildFile (name + "-" + source + ".lynx"), error);
  16331. }
  16332. offline.setSong (std::move (song));
  16333. offline.dispatchPendingMessages();
  16334. auto frame = lynx::makeChannelFrame (offline, 0, 0);
  16335. if (frame == nullptr || frame->getWidth() <= 0)
  16336. {
  16337. ok = false;
  16338. continue;
  16339. }
  16340. for (const auto scale : { 1.0f, 1.5f, 2.0f })
  16341. {
  16342. const auto file = folder.getChildFile (name + "-" + source + "-" + juce::String (juce::roundToInt (scale * 100)) + ".png");
  16343. savePng (frame->createComponentSnapshot (frame->getLocalBounds(), true, scale), file.getFullPathName());
  16344. std::printf ("%s %dx%d\n", file.getFullPathName().toRawUTF8(), frame->getWidth(), frame->getHeight());
  16345. }
  16346. // round 169h: the layout's other pages (Toxic's MIDI / Seq …), one shot each at 1.5×
  16347. for (int page = 1; page < lynx::showChannelLayoutPage (*frame, -1); ++page)
  16348. {
  16349. lynx::showChannelLayoutPage (*frame, page);
  16350. const auto file = folder.getChildFile (name + "-" + source + "-page" + juce::String (page) + "-150.png");
  16351. savePng (frame->createComponentSnapshot (frame->getLocalBounds(), true, 1.5f), file.getFullPathName());
  16352. std::printf ("%s\n", file.getFullPathName().toRawUTF8());
  16353. }
  16354. }
  16355. return ok;
  16356. }
  16357. // --- round 170j: the pilot editors with their own art -------------------------------------------------
  16358. struct ArtPilot
  16359. {
  16360. std::string file; // the art's name as a file name: "toxic-biohazard"
  16361. bool instrument;
  16362. lynx::InstrumentKind instrumentKind;
  16363. lynx::EffectKind effectKind;
  16364. lynx::skin::Style before; // the automatic style it had before the Themed style
  16365. };
  16366. static juce::StringArray& artOnly() // --artshot / --artgui: only these (file names), all when empty
  16367. {
  16368. static juce::StringArray only;
  16369. return only;
  16370. }
  16371. // every plugin with art of its own (round 170j/170k): generators first, then effects; built from the art
  16372. // registries, so a new theme is shot without touching this list
  16373. static const std::vector<ArtPilot>& artPilots()
  16374. {
  16375. using I = lynx::InstrumentKind;
  16376. using E = lynx::EffectKind;
  16377. static const std::vector<ArtPilot> list = [] {
  16378. std::vector<ArtPilot> all;
  16379. auto slug = [] (lynx::skin::Art a) {
  16380. return juce::String (lynx::skin::artName (a)).toLowerCase().replaceCharacters (" ", "-").removeCharacters ("!.()'").toStdString();
  16381. };
  16382. for (const auto& e : lynx::natives::instrumentEngines()) // (the engines' order first)
  16383. if (const auto a = lynx::skin::artForInstrument (e.kind); a != lynx::skin::Art::none)
  16384. all.push_back ({ slug (a), true, e.kind, E::reverb, lynx::skin::Style::neon });
  16385. for (int k = 0; k <= (int) I::wavetraveller; ++k) // then every other kind with art (DrumSynth, Autogun, Wasp...)
  16386. if (const auto a = lynx::skin::artForInstrument ((I) k); a != lynx::skin::Art::none)
  16387. all.push_back ({ slug (a), true, (I) k, E::reverb, lynx::skin::Style::neon });
  16388. for (int k = 0; k <= (int) lynx::lastEffectKind; ++k)
  16389. if (const auto a = lynx::skin::artForEffect ((E) k); a != lynx::skin::Art::none)
  16390. all.push_back ({ slug (a), false, I::synth, (E) k, lynx::skin::plainStyleFor (k) });
  16391. std::vector<ArtPilot> kept;
  16392. for (auto& p : all)
  16393. if (artOnly().isEmpty() || artOnly().contains (juce::String (p.file)))
  16394. if (std::none_of (kept.begin(), kept.end(), [&] (const ArtPilot& q) { return q.file == p.file; }))
  16395. kept.push_back (p);
  16396. return kept;
  16397. }();
  16398. return list;
  16399. }
  16400. // the song and the editor of a pilot (an instrument: the channel window on its Plugin tab)
  16401. static std::unique_ptr<juce::Component> makeArtPilot (lynx::AudioEngine& engine, const ArtPilot& p)
  16402. {
  16403. lynx::Song song;
  16404. song.mixer = lynx::Song::defaultMixer (2);
  16405. if (p.instrument)
  16406. {
  16407. for (const auto& e : lynx::natives::instrumentEngines())
  16408. if (e.kind == p.instrumentKind)
  16409. {
  16410. auto channel = lynx::natives::makeChannel (e.kind, lynx::flStudioAccess());
  16411. if (! channel) channel = lynx::banks::defaultChannel (e.kind, e.name);
  16412. if (! channel) return nullptr;
  16413. song.channels.push_back (*channel);
  16414. break;
  16415. }
  16416. if (song.channels.empty()) // a kind without an engine entry: its LYNX default, else an empty channel of that kind
  16417. {
  16418. const std::string name = lynx::skin::artName (lynx::skin::artForInstrument (p.instrumentKind));
  16419. auto channel = lynx::banks::defaultChannel (p.instrumentKind, name);
  16420. if (! channel)
  16421. {
  16422. channel = lynx::ChannelDef {};
  16423. channel->instrument = p.instrumentKind;
  16424. channel->name = name;
  16425. }
  16426. song.channels.push_back (*channel);
  16427. }
  16428. song.patterns.emplace_back();
  16429. }
  16430. else
  16431. {
  16432. song.mixer[1].effects.push_back (lynx::makeEffectSlot (p.effectKind));
  16433. }
  16434. engine.setSong (std::move (song));
  16435. engine.dispatchPendingMessages();
  16436. if (p.instrument) return lynx::makeChannelFrame (engine, 0, 0);
  16437. if (p.effectKind == lynx::EffectKind::facetEq) return lynx::makeFacetEqEditor (engine, 1, 0, true);
  16438. if (lynx::ProEditorWindows::handles (p.effectKind)) return lynx::makeProEditor (engine, 1, 0, true); // display-first editors, demo signal
  16439. return lynx::makeNativeEffectEditor (engine, 1, 0, 1.0f, 0);
  16440. }
  16441. // "before": the style each pilot had (forced for its run); "after": automatic (the pilots are Themed)
  16442. static void artPilotStyle (const ArtPilot& p, const juce::String& mode)
  16443. {
  16444. lynx::skin::setForcedStyle (mode == "before" ? (int) p.before : -1);
  16445. lynx::skin::setArtMotion (mode != "still");
  16446. }
  16447. bool runArtShots (const juce::File& folder, bool before)
  16448. {
  16449. folder.createDirectory();
  16450. auto ok = true;
  16451. juce::String titles ("editor\tsize\twidth\tname width at the style's size\tbox\tsize used\tlines\tresult\n");
  16452. for (const auto& p : artPilots())
  16453. {
  16454. artPilotStyle (p, before ? "before" : "after");
  16455. lynx::AudioEngine offline (false);
  16456. auto editor = makeArtPilot (offline, p);
  16457. if (editor == nullptr || editor->getWidth() <= 0)
  16458. {
  16459. std::fprintf (stderr, "%s: no editor\n", p.file.c_str());
  16460. ok = false;
  16461. continue;
  16462. }
  16463. if (p.effectKind == lynx::EffectKind::facetEq) lynx::tickFacetEqEditor (*editor);
  16464. // round 170k2: titles.tsv, how the header's name fitted (its width at the style's size, the box, the size used)
  16465. auto fit = [&] (const juce::String& at) {
  16466. const auto f = lynx::skin::lastTitleFit();
  16467. if (f.have <= 0.0f) return; // no plugin header drawn (a generator's channel window)
  16468. titles << juce::String (p.file) << "\t" << at << "\t" << editor->getWidth() << "\t" << juce::String (f.need, 1) << "\t" << juce::String (f.have, 1)
  16469. << "\t" << juce::String (f.size, 1) << "\t" << f.lines << "\t" << (f.clipped ? "ELLIPSIS" : "full") << "\n";
  16470. };
  16471. for (const auto scale : { 1.0f, 2.0f })
  16472. {
  16473. const auto file = folder.getChildFile (juce::String (p.file) + "-" + (before ? "before" : "after") + "-" + juce::String (juce::roundToInt (scale * 100)) + ".png");
  16474. lynx::skin::resetTitleFit();
  16475. savePng (editor->createComponentSnapshot (editor->getLocalBounds(), true, scale), file.getFullPathName());
  16476. std::printf ("%s %dx%d\n", file.getFullPathName().toRawUTF8(), editor->getWidth(), editor->getHeight());
  16477. if (scale == 1.0f) fit ("100");
  16478. }
  16479. // ... and at the smallest size its window allows (effect panels; the Pro editors scale as a whole)
  16480. if (const auto smallest = lynx::nativeEditorMinimumSize (*editor); smallest.x > 0)
  16481. {
  16482. editor->setSize (smallest.x, smallest.y);
  16483. const auto file = folder.getChildFile (juce::String (p.file) + "-" + (before ? "before" : "after") + "-min.png");
  16484. lynx::skin::resetTitleFit();
  16485. savePng (lynx::shot::snapshot (*editor), file.getFullPathName());
  16486. fit ("min");
  16487. }
  16488. }
  16489. folder.getChildFile (juce::String ("titles-") + (before ? "before" : "after") + ".tsv").replaceWithText (titles);
  16490. lynx::skin::setForcedStyle (-1);
  16491. return ok;
  16492. }
  16493. struct ArtGuiRun final : juce::Timer
  16494. {
  16495. juce::File folder;
  16496. juce::String mode, report;
  16497. std::size_t at = 0;
  16498. int phase = 0;
  16499. double t0 = 0.0, c0 = 0.0;
  16500. std::unique_ptr<lynx::AudioEngine> engine;
  16501. std::unique_ptr<juce::DocumentWindow> window;
  16502. std::function<void()> done;
  16503. void start()
  16504. {
  16505. engine = std::make_unique<lynx::AudioEngine> (false);
  16506. report << "editor\tmode\tcpu % of one core\tart layer animating\n";
  16507. open();
  16508. startTimer (100);
  16509. }
  16510. void open()
  16511. {
  16512. window.reset();
  16513. const auto& pilots = artPilots();
  16514. if (at >= pilots.size())
  16515. {
  16516. folder.getChildFile ("cpu-" + mode + ".txt").replaceWithText (report);
  16517. stopTimer();
  16518. lynx::skin::setForcedStyle (-1);
  16519. lynx::skin::setArtMotion (true);
  16520. if (done) done();
  16521. return;
  16522. }
  16523. const auto& p = pilots[at];
  16524. artPilotStyle (p, mode);
  16525. auto editor = makeArtPilot (*engine, p);
  16526. if (editor == nullptr) { ++at; open(); return; }
  16527. window = std::make_unique<juce::DocumentWindow> (juce::String ("LYNX art - ") + juce::String (p.file), lynx::theme::colour::bg1, 0);
  16528. window->setUsingNativeTitleBar (true);
  16529. window->setContentOwned (editor.release(), true);
  16530. const auto area = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea;
  16531. window->setTopLeftPosition (area.getX() + 24, area.getY() + 24);
  16532. window->setAlwaysOnTop (true);
  16533. window->setVisible (true);
  16534. phase = 0;
  16535. t0 = juce::Time::getMillisecondCounterHiRes();
  16536. }
  16537. bool animating() const
  16538. {
  16539. if (window == nullptr || window->getContentComponent() == nullptr) return false;
  16540. std::function<bool (juce::Component&)> find = [&] (juce::Component& c) {
  16541. if (auto* l = dynamic_cast<lynx::skin::ArtLayer*> (&c); l != nullptr && l->animating()) return true;
  16542. for (auto* child : c.getChildren())
  16543. if (find (*child)) return true;
  16544. return false;
  16545. };
  16546. return find (*window->getContentComponent());
  16547. }
  16548. void timerCallback() override
  16549. {
  16550. const auto now = juce::Time::getMillisecondCounterHiRes();
  16551. const auto& p = artPilots()[at];
  16552. const auto ready = folder.getChildFile (juce::String (p.file) + "-" + mode + ".ready");
  16553. const auto shotDone = folder.getChildFile (juce::String (p.file) + "-" + mode + ".done");
  16554. if (phase == 0 && now - t0 > 1500.0)
  16555. {
  16556. // the window's content on screen, in physical pixels, for the outside screenshot to crop
  16557. auto* c = window->getContentComponent();
  16558. const auto scale = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->scale;
  16559. const auto b = c->getScreenBounds();
  16560. shotDone.deleteFile();
  16561. ready.replaceWithText (juce::String (juce::roundToInt (b.getX() * scale)) + " " + juce::String (juce::roundToInt (b.getY() * scale)) + " "
  16562. + juce::String (juce::roundToInt (b.getWidth() * scale)) + " " + juce::String (juce::roundToInt (b.getHeight() * scale)));
  16563. phase = 1;
  16564. t0 = now;
  16565. return;
  16566. }
  16567. if (phase == 1 && (shotDone.existsAsFile() || now - t0 > 10000.0))
  16568. {
  16569. ready.deleteFile();
  16570. shotDone.deleteFile();
  16571. phase = 2;
  16572. t0 = now;
  16573. c0 = lynx::processCpuSeconds();
  16574. return;
  16575. }
  16576. if (phase == 2 && now - t0 > 6000.0)
  16577. {
  16578. const auto cpu = (lynx::processCpuSeconds() - c0) / ((now - t0) * 0.001) * 100.0;
  16579. report << juce::String (p.file) << "\t" << mode << "\t" << juce::String (cpu, 2) << "\t" << (animating() ? "yes" : "no") << "\n";
  16580. ++at;
  16581. open();
  16582. }
  16583. }
  16584. };
  16585. std::unique_ptr<ArtGuiRun> artGui;
  16586. void runArtGui (const juce::File& folder, const juce::String& mode)
  16587. {
  16588. folder.createDirectory();
  16589. artGui = std::make_unique<ArtGuiRun>();
  16590. artGui->folder = folder;
  16591. artGui->mode = mode;
  16592. artGui->done = [this] { juce::MessageManager::callAsync ([this] { artGui.reset(); quit(); }); };
  16593. artGui->start();
  16594. }
  16595. void runPluginEditorSnapshots (const juce::String& folder)
  16596. {
  16597. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  16598. {
  16599. const juce::File out (folder);
  16600. out.createDirectory();
  16601. lynx::AudioEngine offline (false);
  16602. const auto roots = lynx::findFlStudioRoots();
  16603. const auto presets = juce::File (juce::String::fromUTF8 (roots.data.c_str())).getChildFile ("Patches/Plugin presets/Effects");
  16604. auto kinds = lynx::plugui::flLayoutKinds();
  16605. kinds.push_back (lynx::EffectKind::maximus); // Soundgoodizer (below)
  16606. for (const auto own : lynx::plugui::ownLayoutKinds()) // LYNX's own panels (mixing suite, round 96)
  16607. kinds.push_back (own);
  16608. kinds.push_back (lynx::EffectKind::apexLimiter); // round 114: display-first editor
  16609. kinds.push_back (lynx::EffectKind::ridgeStrip); // round 145: the second pass shows the Vocal strip voicing
  16610. kinds.push_back (lynx::EffectKind::ridgeStrip); // round 165: the third pass shows the E console voicing
  16611. kinds.push_back (lynx::EffectKind::compressor); // round 152: the RComp role's panel (vintage voicing, RComp ranges)
  16612. const auto database = juce::File (juce::String::fromUTF8 (roots.data.c_str())).getChildFile ("Patches/Plugin database/Effects");
  16613. auto maximusPasses = 0; // Maximus has its own page (first pass); the second pass shows Soundgoodizer
  16614. auto ridgePasses = 0;
  16615. // round 173d3: the parity pictures of one editor — LYNX_PLUGUI_ONLY=<effect name>, LYNX_PLUGUI_PRESET=<.fst>,
  16616. // LYNX_PLUGUI_PAGES=<page,page,…> (the page numbers as the editor encodes them)
  16617. const auto only = juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGUI_ONLY", {});
  16618. const auto onlyPreset = juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGUI_PRESET", {});
  16619. const auto onlyPages = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGUI_PAGES", {}), ",", "");
  16620. for (const auto kind : kinds)
  16621. {
  16622. if (only.isNotEmpty() && only != lynx::effectInfo (kind).name)
  16623. continue;
  16624. auto fx = lynx::makeEffectSlot (kind);
  16625. juce::String name (lynx::effectInfo (kind).name);
  16626. for (const auto& plugin : lynx::flPluginsForEffect (kind))
  16627. {
  16628. const auto dir = presets.getChildFile (juce::String::fromUTF8 (plugin.c_str()));
  16629. auto file = dir.getChildFile ("Default.fst");
  16630. if (! file.existsAsFile()) // plugins without presets: their entry of FL's plugin database
  16631. for (const auto& f : database.findChildFiles (juce::File::findFiles, true, juce::String::fromUTF8 (plugin.c_str()) + ".fst"))
  16632. file = f;
  16633. if (only.isNotEmpty() && onlyPreset.isNotEmpty())
  16634. file = juce::File (onlyPreset);
  16635. if (! file.existsAsFile())
  16636. {
  16637. auto files = dir.findChildFiles (juce::File::findFiles, true, "*.fst");
  16638. std::sort (files.begin(), files.end(), [] (const juce::File& a, const juce::File& b) { return a.getFullPathName().compareNatural (b.getFullPathName()) < 0; });
  16639. file = files.isEmpty() ? juce::File() : files[0];
  16640. }
  16641. juce::MemoryBlock data;
  16642. if (file.existsAsFile() && file.loadFileAsData (data))
  16643. {
  16644. const auto* bytes = static_cast<const std::uint8_t*> (data.getData());
  16645. 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)
  16646. fx = *loaded;
  16647. }
  16648. name = juce::String::fromUTF8 (plugin.c_str());
  16649. break;
  16650. }
  16651. if (kind == lynx::EffectKind::maximus && ++maximusPasses == 2) // Soundgoodizer: preset A of the installation, Amount 60 %
  16652. {
  16653. juce::MemoryBlock data;
  16654. juce::File (juce::String::fromUTF8 (roots.factoryData.c_str())).getChildFile ("Plugins/Fruity/Effects/Soundgoodizer/Data/Presets/a.dat").loadFileAsData (data);
  16655. lynx::maximusfx::Blob blob;
  16656. blob.build = lynx::hlfx::MaximusBuild::soundgoodizer;
  16657. blob.mix = 600;
  16658. const auto* b = static_cast<const std::uint8_t*> (data.getData());
  16659. blob.state.assign (b, b + data.getSize());
  16660. fx = lynx::makeEffectSlot (kind);
  16661. fx.state = lynx::maximusfx::pack (blob);
  16662. name = "Soundgoodizer";
  16663. }
  16664. if (kind == lynx::EffectKind::ridgeStrip && ++ridgePasses == 2) // round 145: her Vocalstrip 2 setting
  16665. {
  16666. for (const auto& [param, value] : { std::pair<const char*, float> { "Vocal strip", 1.0f }, { "Compander", 1.0f },
  16667. { "Compander threshold", 0.3083f }, { "Compander ratio", 0.6929f }, { "Compander attack", 0.2543f },
  16668. { "Compander release", 0.5316f }, { "Make-up", 0.2917f }, { "Soft knee", 1.0f },
  16669. { "Expander threshold", 0.2198f }, { "Vocal input", 0.6792f }, { "Vocal output", 0.3938f },
  16670. { "Process order", 0.4783f }, { "De-esser", 1.0f } })
  16671. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, param)] = value;
  16672. name = "Ridge Strip (Vocal strip)";
  16673. }
  16674. else if (kind == lynx::EffectKind::ridgeStrip && ridgePasses == 3) // round 165: the E console, EQ to the side chain
  16675. {
  16676. for (const auto& [param, value] : { std::pair<const char*, float> { "Voicing", 1.0f }, { "HPF", 0.3f }, { "HF gain", 0.8f },
  16677. { "HF bell", 1.0f }, { "Ratio", 0.5f }, { "Comp. threshold", 0.4f }, { "EQ to SC", 1.0f },
  16678. { "Filter split", 1.0f }, { "Expander", 1.0f } })
  16679. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, param)] = value;
  16680. name = "Ridge Strip (E console)";
  16681. }
  16682. else if (kind == lynx::EffectKind::ridgeStrip) // a vocal setting, so the graphs show something
  16683. for (const auto& [param, value] : { std::pair<const char*, float> { "HPF", 0.3f }, { "LMF gain", 0.35f }, { "HF gain", 0.7f },
  16684. { "Ratio", 0.3f }, { "Comp. threshold", 0.55f } })
  16685. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, param)] = value;
  16686. if (kind == lynx::EffectKind::compressor) // round 152: the vintage voicing with the reference's ranges and meter
  16687. {
  16688. for (const auto& [param, value] : { std::pair<const char*, float> { "Voicing", 1.0f }, { "Ranges", 1.0f }, { "Limiter", 1.0f },
  16689. { "Threshold", 0.6f }, { "RC ratio", 0.4f } })
  16690. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, param)] = value;
  16691. name = "Compressor (RComp role)";
  16692. }
  16693. if (kind == lynx::EffectKind::apexLimiter) // round 114: gain into the ceiling, so the display shows reduction
  16694. fx.params[0] = 0.33f;
  16695. if (kind == lynx::EffectKind::ember)
  16696. {
  16697. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, "Drive")] = 0.5f;
  16698. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, "Bands")] = 1.0f; // round 108: the band rows
  16699. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, "B3 drive")] = 0.6f;
  16700. }
  16701. if (kind == lynx::EffectKind::crestCompressor) // round 108: a curve with a knee and a side-chain low cut
  16702. for (const auto& [param, value] : { std::pair<const char*, float> { "Threshold", 0.55f }, { "Knee", 0.15f },
  16703. { "SC1 shape", 0.5f }, { "SC1 freq.", 0.3f } })
  16704. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, param)] = value;
  16705. lynx::Song song;
  16706. song.mixer.resize (2);
  16707. song.mixer[0].name = "Master";
  16708. song.mixer[1].name = "Insert 1";
  16709. song.mixer[1].effects.push_back (fx);
  16710. offline.setSong (std::move (song));
  16711. offline.dispatchPendingMessages();
  16712. if (lynx::ProEditorWindows::handles (kind)) // round 114: the display-first editors, with a demo signal
  16713. {
  16714. auto editor = lynx::makeProEditor (offline, 1, 0, true);
  16715. auto image = lynx::shot::paint (*editor);
  16716. const auto file = lynx::shot::file (out.getChildFile (name + ".png"));
  16717. file.deleteFile();
  16718. juce::PNGImageFormat png;
  16719. if (auto stream = file.createOutputStream())
  16720. png.writeImageToStream (image, *stream);
  16721. continue;
  16722. }
  16723. const auto pages = name == "Soundgoodizer" ? 1 : juce::jmax (1, (int) lynx::plugui::layoutFor (kind).pages.size());
  16724. std::vector<int> pageList;
  16725. for (int page = 0; page < pages; ++page)
  16726. pageList.push_back (page);
  16727. if (only.isNotEmpty() && ! onlyPages.isEmpty())
  16728. {
  16729. pageList.clear();
  16730. for (const auto& p : onlyPages)
  16731. pageList.push_back (p.getIntValue());
  16732. }
  16733. for (const auto page : pageList)
  16734. {
  16735. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, page);
  16736. auto image = lynx::shot::paint (*editor, lynx::theme::panel);
  16737. const auto file = lynx::shot::file (out.getChildFile (name + (page > 0 ? "-p" + juce::String (page + 1) : juce::String()) + ".png"));
  16738. file.deleteFile();
  16739. juce::PNGImageFormat png;
  16740. if (auto stream = file.createOutputStream())
  16741. png.writeImageToStream (image, *stream);
  16742. }
  16743. }
  16744. // round 137: Echoform in its Rhythm mode (EchoBoy's role) with the Present era
  16745. {
  16746. namespace ef = lynx::echosuite::echoform;
  16747. auto fx = lynx::makeEffectSlot (lynx::EffectKind::echoform);
  16748. fx.params[ef::rhythm] = 1.0f;
  16749. fx.params[ef::rhythmRepeats] = 5.0f / 15.0f;
  16750. fx.params[ef::rhythmDecay] = 0.25f;
  16751. fx.params[ef::rhythmTap1 + 2] = 0.45f;
  16752. fx.params[ef::feedback] = 0.25f;
  16753. fx.params[ef::era] = 0.5f;
  16754. for (const auto& [param, value] : ef::rhythmPresetEdits (0)) // round 144: a pattern in the rhythm editor (Grid)
  16755. fx.params[(std::size_t) param] = value;
  16756. fx.params[ef::rhythmShape] = 0.5f; // swell
  16757. lynx::Song song;
  16758. song.mixer.resize (2);
  16759. song.mixer[0].name = "Master";
  16760. song.mixer[1].name = "Insert 1";
  16761. song.mixer[1].effects.push_back (fx);
  16762. offline.setSong (std::move (song));
  16763. offline.dispatchPendingMessages();
  16764. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
  16765. auto image = lynx::shot::paint (*editor, lynx::theme::panel);
  16766. const auto file = lynx::shot::file (out.getChildFile ("Echoform-rhythm.png"));
  16767. file.deleteFile();
  16768. juce::PNGImageFormat png;
  16769. if (auto stream = file.createOutputStream())
  16770. png.writeImageToStream (image, *stream);
  16771. }
  16772. // round 150: Echoform with a voicing (the Stereo / L/R offset controls on the Rhythm row)
  16773. {
  16774. namespace ef = lynx::echosuite::echoform;
  16775. auto fx = lynx::makeEffectSlot (lynx::EffectKind::echoform);
  16776. fx.params[ef::voicing] = ef::voicingValue (ef::voicingForEchoBoyStyle (19));
  16777. fx.params[ef::style] = ef::styleValue (ef::Style::dual);
  16778. lynx::Song song;
  16779. song.mixer.resize (2);
  16780. song.mixer[0].name = "Master";
  16781. song.mixer[1].name = "Insert 1";
  16782. song.mixer[1].effects.push_back (fx);
  16783. offline.setSong (std::move (song));
  16784. offline.dispatchPendingMessages();
  16785. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
  16786. auto image = lynx::shot::paint (*editor, lynx::theme::panel);
  16787. const auto file = lynx::shot::file (out.getChildFile ("Echoform-voicing.png"));
  16788. file.deleteFile();
  16789. juce::PNGImageFormat png;
  16790. if (auto stream = file.createOutputStream())
  16791. png.writeImageToStream (image, *stream);
  16792. }
  16793. // round 150: Auto-pan's Rhythm voicing with its Tweak row (PanMan's role)
  16794. {
  16795. auto fx = lynx::makeEffectSlot (lynx::EffectKind::autoPan);
  16796. fx.params[lynx::autopan::count] = 1.0f; // the Rhythm voicing
  16797. fx.params[lynx::autopan::count + 13] = 0.75f; // offset mod +90°
  16798. lynx::Song song;
  16799. song.mixer.resize (2);
  16800. song.mixer[0].name = "Master";
  16801. song.mixer[1].name = "Insert 1";
  16802. song.mixer[1].effects.push_back (fx);
  16803. offline.setSong (std::move (song));
  16804. offline.dispatchPendingMessages();
  16805. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
  16806. auto image = lynx::shot::paint (*editor, lynx::theme::panel);
  16807. const auto file = lynx::shot::file (out.getChildFile ("Auto-pan-tweak.png"));
  16808. file.deleteFile();
  16809. juce::PNGImageFormat png;
  16810. if (auto stream = file.createOutputStream())
  16811. png.writeImageToStream (image, *stream);
  16812. }
  16813. // round 165: Ember's Classic voicing (the Decapitator role) in its one-screen panel
  16814. {
  16815. namespace em = lynx::mixsuite::ember;
  16816. auto fx = lynx::makeEffectSlot (lynx::EffectKind::ember);
  16817. fx.params[em::voicing] = 1.0f;
  16818. fx.params[em::classicDrive] = 0.35f;
  16819. lynx::Song song;
  16820. song.mixer.resize (2);
  16821. song.mixer[0].name = "Master";
  16822. song.mixer[1].name = "Insert 1";
  16823. song.mixer[1].effects.push_back (fx);
  16824. offline.setSong (std::move (song));
  16825. offline.dispatchPendingMessages();
  16826. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
  16827. auto image = lynx::shot::paint (*editor, lynx::theme::panel);
  16828. const auto file = lynx::shot::file (out.getChildFile ("Ember Saturator-classic.png"));
  16829. file.deleteFile();
  16830. juce::PNGImageFormat png;
  16831. if (auto stream = file.createOutputStream())
  16832. png.writeImageToStream (image, *stream);
  16833. }
  16834. // round 152: Foil Plate's one-knob Plate view (the Little Plate role)
  16835. {
  16836. auto fx = lynx::makeEffectSlot (lynx::EffectKind::foilPlate);
  16837. fx.params[14] = 1.0f; // the measured plate voicing
  16838. fx.params[15] = 1.0f; // View = Plate
  16839. lynx::Song song;
  16840. song.mixer.resize (2);
  16841. song.mixer[0].name = "Master";
  16842. song.mixer[1].name = "Insert 1";
  16843. song.mixer[1].effects.push_back (fx);
  16844. offline.setSong (std::move (song));
  16845. offline.dispatchPendingMessages();
  16846. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
  16847. auto image = lynx::shot::paint (*editor, lynx::theme::panel);
  16848. const auto file = lynx::shot::file (out.getChildFile ("Foil Plate-plate.png"));
  16849. file.deleteFile();
  16850. juce::PNGImageFormat png;
  16851. if (auto stream = file.createOutputStream())
  16852. png.writeImageToStream (image, *stream);
  16853. }
  16854. // LYNX's own editors with live displays (round 103): Facet EQ (a mixing curve, one dynamic band, demo analyser)
  16855. // and LYNX Tune (demo pitch phrase)
  16856. {
  16857. lynx::setNativeEditorDemo (true);
  16858. using namespace lynx::facet;
  16859. auto eq = lynx::makeEffectSlot (lynx::EffectKind::facetEq);
  16860. const struct { Shape s; double f, g, q; int slope; double range; } bandsDemo[] = {
  16861. { Shape::lowCut, 32, 0, 1, 24, 0 }, { Shape::bell, 110, 3, 1.2, 12, 0 }, { Shape::bell, 380, -3.5, 1.6, 12, 0 },
  16862. { Shape::bell, 3200, 0, 2.5, 12, -6 }, { Shape::highShelf, 9000, 2.5, 0.8, 12, 0 }
  16863. };
  16864. for (int b = 0; b < 5; ++b)
  16865. {
  16866. eq.params[(std::size_t) param (b, 0)] = shapeValue (bandsDemo[b].s);
  16867. eq.params[(std::size_t) param (b, 1)] = hzValue (bandsDemo[b].f);
  16868. eq.params[(std::size_t) param (b, 2)] = gainValue (bandsDemo[b].g);
  16869. eq.params[(std::size_t) param (b, 3)] = qValue (bandsDemo[b].q);
  16870. eq.params[(std::size_t) param (b, 4)] = slopeValue (bandsDemo[b].slope);
  16871. eq.params[(std::size_t) (rangeParam0 + b)] = rangeValue (bandsDemo[b].range);
  16872. }
  16873. eq.params[(std::size_t) phaseParam] = phaseValue (Phase::natural);
  16874. const auto own = [&] (const lynx::EffectSlot& fx, const juce::String& file, bool facetEditor, int page = 0) {
  16875. lynx::Song song;
  16876. song.mixer.resize (2);
  16877. song.mixer[0].name = "Master";
  16878. song.mixer[1].name = "Vocal";
  16879. song.mixer[1].effects.push_back (fx);
  16880. offline.setSong (std::move (song));
  16881. offline.dispatchPendingMessages();
  16882. auto editor = facetEditor ? lynx::makeFacetEqEditor (offline, 1, 0, true) : lynx::makeNativeEffectEditor (offline, 1, 0, 1.25f, page);
  16883. auto image = lynx::shot::paint (*editor, lynx::theme::panel);
  16884. const auto f = lynx::shot::file (out.getChildFile (file));
  16885. f.deleteFile();
  16886. juce::PNGImageFormat png;
  16887. if (auto stream = f.createOutputStream())
  16888. png.writeImageToStream (image, *stream);
  16889. };
  16890. own (eq, "Facet EQ.png", true);
  16891. own (lynx::makeEffectSlot (lynx::EffectKind::lynxTune), "LYNX Tune.png", false);
  16892. {
  16893. // round 128: the ADVANCED page, with E bypassed and A removed on the keyboard and a created vibrato
  16894. auto tune = lynx::makeEffectSlot (lynx::EffectKind::lynxTune);
  16895. tune.params[(std::size_t) (lynx::lynxtune::bypassC + 4)] = 1.0f;
  16896. tune.params[(std::size_t) (lynx::lynxtune::noteC + 9)] = 0.0f;
  16897. tune.params[lynx::lynxtune::vibratoShape] = 1.0f / 3.0f;
  16898. // round 166c: the created vibrato's amplitude / formant / variation, a short throat, In scale +2
  16899. tune.params[lynx::lynxtune::vibratoAmplitude] = 1.0f / 3.0f;
  16900. tune.params[lynx::lynxtune::vibratoFormant] = 0.7f;
  16901. tune.params[lynx::lynxtune::vibratoVariation] = 0.2f;
  16902. tune.params[lynx::lynxtune::throatLength] = lynx::lynxtune::throatValue (80.0);
  16903. tune.params[lynx::lynxtune::transposeInScale] = 1.0f;
  16904. tune.params[lynx::lynxtune::scaleTranspose] = lynx::lynxtune::scaleTransposeValue (2);
  16905. own (tune, "LYNX Tune-p2.png", false, 1);
  16906. }
  16907. own (lynx::makeEffectSlot (lynx::EffectKind::lynxTune), "LYNX Tune-p3.png", false, 2); // round 135w: Real-time
  16908. lynx::setNativeEditorDemo (false);
  16909. }
  16910. // generators in FL's arrangement: the channel's plugin page with the FL preset's settings
  16911. const auto generators = juce::File (juce::String::fromUTF8 (roots.data.c_str())).getChildFile ("Patches/Plugin presets/Generators");
  16912. 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" } })
  16913. {
  16914. juce::MemoryBlock data;
  16915. if (juce::String (folder) == "Harmor") // the first preset whose state the engine reads
  16916. {
  16917. auto files = generators.getChildFile (folder).findChildFiles (juce::File::findFiles, true, "*.fst");
  16918. files.sort();
  16919. for (const auto& f : files)
  16920. {
  16921. juce::MemoryBlock block;
  16922. if (! f.loadFileAsData (block))
  16923. continue;
  16924. const auto* b = static_cast<const std::uint8_t*> (block.getData());
  16925. try
  16926. {
  16927. const auto p = flp::parseProject (std::vector<std::uint8_t> (b, b + block.getSize()), true);
  16928. if (! p.channels.empty() && lynx::harmorStateUsable (p.channels.front().pluginState))
  16929. {
  16930. preset = nullptr;
  16931. data = block;
  16932. break;
  16933. }
  16934. }
  16935. catch (const std::exception&)
  16936. {
  16937. }
  16938. }
  16939. }
  16940. auto file = preset == nullptr ? juce::File() : juce::String (preset).isEmpty() ? database.getSiblingFile ("Generators").getChildFile ("Misc").getChildFile (juce::String (folder) + ".fst")
  16941. : generators.getChildFile (folder).getChildFile (preset);
  16942. if (! file.existsAsFile())
  16943. {
  16944. auto files = generators.getChildFile (folder).findChildFiles (juce::File::findFiles, true, "*.fst");
  16945. files.sort();
  16946. file = files.isEmpty() ? juce::File() : files[0];
  16947. }
  16948. if (data.isEmpty() && ! file.loadFileAsData (data))
  16949. continue;
  16950. try
  16951. {
  16952. const auto* bytes = static_cast<const std::uint8_t*> (data.getData());
  16953. auto project = flp::parseProject (std::vector<std::uint8_t> (bytes, bytes + data.getSize()), true);
  16954. if (project.channels.empty())
  16955. continue;
  16956. project.channels.front().type = flp::ChannelType::native;
  16957. lynx::FlpImportOptions options;
  16958. options.roots = roots;
  16959. options.fileExists = [] (const std::string& path) { return lynx::platform::localFile (path).existsAsFile(); };
  16960. options.readFile = [] (const std::string& path) {
  16961. juce::MemoryBlock block;
  16962. lynx::platform::localFile (path).loadFileAsData (block);
  16963. const auto* b = static_cast<const std::uint8_t*> (block.getData());
  16964. return std::vector<std::uint8_t> (b, b + block.getSize());
  16965. };
  16966. options.saveEmbedded = [out] (const std::vector<std::uint8_t>& wav, const std::string& name) {
  16967. const auto f = out.getChildFile ("samples").getNonexistentChildFile (juce::String::fromUTF8 (name.c_str()), ".wav");
  16968. f.getParentDirectory().createDirectory();
  16969. f.replaceWithData (wav.data(), wav.size());
  16970. return f.getFullPathName().toStdString();
  16971. };
  16972. auto song = lynx::importFlp (project, options);
  16973. // the page only needs the plugin's saved state (FL Keys' sample zones need the installed wavetables)
  16974. if (! song.channels.empty() && project.channels.front().pluginName == "BooBass" && song.channels.front().instrument != lynx::InstrumentKind::boobass)
  16975. {
  16976. song.channels.front().instrument = lynx::InstrumentKind::boobass; // (its sound needs the engine DLL; the page does not)
  16977. song.channels.front().modelParams.assign (3, 32768.0f);
  16978. }
  16979. if (! song.channels.empty() && project.channels.front().pluginName == "FL Keys")
  16980. {
  16981. song.channels.front().instrument = lynx::InstrumentKind::flkeys;
  16982. song.channels.front().pluginState = project.channels.front().pluginState;
  16983. }
  16984. offline.setSong (std::move (song));
  16985. offline.dispatchPendingMessages();
  16986. if (offline.getSong().channels.empty())
  16987. continue;
  16988. auto panel = lynx::makeChannelSettingsPanel (offline, 0);
  16989. auto image = lynx::shot::paint (*panel, lynx::theme::panel);
  16990. const auto out2 = lynx::shot::file (out.getChildFile (juce::String (folder) + ".png"));
  16991. out2.deleteFile();
  16992. juce::PNGImageFormat png;
  16993. if (auto stream = out2.createOutputStream())
  16994. png.writeImageToStream (image, *stream);
  16995. }
  16996. catch (const std::exception&)
  16997. {
  16998. }
  16999. }
  17000. }
  17001. quit();
  17002. }
  17003. void runVideoShot (const juce::String& prefix, const juce::String& videoPath)
  17004. {
  17005. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  17006. // the message loop runs while the frames decode (modal loops are off): a timer takes one snapshot per step
  17007. struct VideoShot final : juce::Timer
  17008. {
  17009. lynx::AudioEngine offline { false };
  17010. std::unique_ptr<juce::Component> editor;
  17011. juce::String prefix, report;
  17012. int step = 0;
  17013. std::function<void()> done;
  17014. void moveTo (double seconds)
  17015. {
  17016. offline.getTransport().positionTicks.store (seconds * offline.getSong().bpm / 60.0 * lynx::ppq);
  17017. }
  17018. void timerCallback() override
  17019. {
  17020. static constexpr double times[] = { 0.0, 1.5, 3.25 };
  17021. constexpr int typeInStep = (int) std::size (times) + 1;
  17022. if (step > 0 && step < typeInStep && editor != nullptr)
  17023. savePng (lynx::shot::snapshot (*editor), prefix + "-" + juce::String (step - 1) + ".png");
  17024. if (editor != nullptr && step == (int) std::size (times))
  17025. {
  17026. // round 174d: FL's in-place type-in of the current time (a right click on it)
  17027. lynx::videoview::openTypeIn (*editor, 2);
  17028. ++step;
  17029. return;
  17030. }
  17031. if (editor != nullptr && step == typeInStep)
  17032. savePng (lynx::shot::snapshot (*editor), prefix + "-typein.png");
  17033. if (editor == nullptr || step >= typeInStep)
  17034. {
  17035. stopTimer();
  17036. juce::File (prefix + "-report.txt").replaceWithText (report);
  17037. if (done)
  17038. done();
  17039. return;
  17040. }
  17041. moveTo (times[step++]);
  17042. }
  17043. };
  17044. static std::unique_ptr<VideoShot> shot;
  17045. shot = std::make_unique<VideoShot>();
  17046. shot->prefix = prefix;
  17047. auto& offline = shot->offline;
  17048. lynx::videoview::install (offline);
  17049. lynx::Song song;
  17050. song.mixer = lynx::Song::defaultMixer (2);
  17051. lynx::ChannelDef c;
  17052. c.name = "Fruity Video Player";
  17053. c.instrument = lynx::InstrumentKind::videoplayer;
  17054. lynx::video::Settings vs;
  17055. vs.path = juce::File (videoPath).getFullPathName().toStdString();
  17056. vs.delay = lynx::video::unitsPerSecond / 2; // the video starts at 0.5 s
  17057. c.pluginState = lynx::video::write (vs);
  17058. song.channels.push_back (c);
  17059. song.patterns.emplace_back();
  17060. {
  17061. // round 174d (A3): the same Video Player in a song whose tempo drops from 120 to 60 BPM at bar 5, for FL
  17062. // (LYNX.exe --export-flp <prefix>-tempo.lynx <prefix>-tempo.flp), to compare FL's video clock with LYNX's
  17063. auto fl = song;
  17064. fl.bpm = 120.0;
  17065. fl.mode = lynx::PlayMode::song;
  17066. auto settings = vs;
  17067. settings.delay = 0;
  17068. settings.timeDisplay = lynx::video::Settings {}.timeDisplay;
  17069. fl.channels[0].pluginState = lynx::video::write (settings);
  17070. fl.patterns[0].name = "Pattern 1";
  17071. lynx::Automation tempo;
  17072. tempo.name = "Tempo";
  17073. tempo.target = { lynx::AutomationTargetKind::tempo, 0, 0, 0 };
  17074. const auto bar = (std::int64_t) lynx::ppq * 4;
  17075. tempo.points = { { 0, lynx::valueFromTempo (120.0), 0.0f }, { bar * 4 - 1, lynx::valueFromTempo (120.0), 0.0f },
  17076. { bar * 4, lynx::valueFromTempo (60.0), 0.0f }, { bar * 8, lynx::valueFromTempo (60.0), 0.0f } };
  17077. fl.automations.push_back (tempo);
  17078. lynx::Clip at;
  17079. at.kind = lynx::ClipKind::automation;
  17080. at.automation = 0;
  17081. at.track = 1;
  17082. at.start = 0;
  17083. at.length = bar * 8;
  17084. fl.playlist.push_back (at);
  17085. lynx::Clip pc;
  17086. pc.pattern = 0;
  17087. pc.track = 0;
  17088. pc.start = 0;
  17089. pc.length = bar * 8;
  17090. fl.playlist.push_back (pc);
  17091. juce::String error;
  17092. lynx::ProjectFile::save (fl, juce::File (prefix + "-tempo.lynx"), error);
  17093. }
  17094. offline.setSong (std::move (song));
  17095. offline.dispatchPendingMessages();
  17096. auto& report = shot->report;
  17097. report << "ffmpeg: " << lynx::findFfmpeg().getFullPathName() << "\n";
  17098. report << lynx::videoview::report (vs.path).fromFirstOccurrenceOf ("Input #0", true, false).upToFirstOccurrenceOf ("At least", false, false) << "\n";
  17099. shot->editor = lynx::makeChannelSettingsPanel (offline, 0);
  17100. if (shot->editor != nullptr)
  17101. shot->editor->setVisible (true);
  17102. shot->done = [this] { juce::MessageManager::callAsync ([this] { shot.reset(); quit(); }); };
  17103. shot->startTimer (1500);
  17104. }
  17105. void runVideoTrackShot (const juce::String& prefix, const juce::String& videoPath, const juce::String& secondPath)
  17106. {
  17107. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  17108. struct TrackShot final : juce::Timer
  17109. {
  17110. lynx::AudioEngine offline { false };
  17111. std::unique_ptr<lynx::PlaylistComponent> playlist;
  17112. std::unique_ptr<lynx::media::FrameDecoder> decoder;
  17113. juce::String prefix, report, path;
  17114. double fps = 25.0;
  17115. int step = 0, waits = 0, adrStep = 0;
  17116. std::unique_ptr<juce::Component> adrPanel;
  17117. std::function<void()> done;
  17118. // song times (s): before, inside the first clip (on and between frame edges), across the second clip
  17119. std::vector<double> times { 0.0, 1.0, 2.0 + 1.0 / 25.0, 2.5, 4.0, 7.3 };
  17120. void timerCallback() override
  17121. {
  17122. if (step > 0 && adrStep == 0)
  17123. {
  17124. // the frame the decoder shows for the wanted file time (the clip starts at song 1.0 s, offset 0)
  17125. const auto want = times[(std::size_t) step - 1] - 1.0;
  17126. double ft = -1.0;
  17127. const auto img = decoder->frame (ft);
  17128. const auto expected = std::floor (want * fps + 1e-6) / fps;
  17129. if (want >= 0.0 && ft < expected - 1e-3 && ++waits < 20)
  17130. return; // (still decoding)
  17131. waits = 0;
  17132. report << "song " << juce::String (times[(std::size_t) step - 1], 3) << " s: wanted file time " << juce::String (want, 4)
  17133. << ", frame shown at " << juce::String (ft, 4) << " (expected " << juce::String (expected, 4) << ")"
  17134. << (want < 0.0 ? " [before the clip]" : std::abs (ft - expected) < 1e-3 ? " OK" : " MISMATCH") << "\n";
  17135. savePng (lynx::shot::snapshot (*playlist), prefix + "-playlist-" + juce::String (step - 1) + ".png");
  17136. if (img.isValid())
  17137. savePng (img, prefix + "-frame-" + juce::String (step - 1) + ".png");
  17138. for (int w = 0; w < juce::Desktop::getInstance().getNumComponents(); ++w)
  17139. if (auto* c = juce::Desktop::getInstance().getComponent (w); c != nullptr && c->getName().startsWith ("Picture"))
  17140. savePng (lynx::shot::snapshot (*c), prefix + "-window-" + juce::String (step - 1) + ".png");
  17141. }
  17142. if (step >= (int) times.size() && adrStep == 0)
  17143. {
  17144. // the ADR window: two cues, takes on the first; the play position inside the streamer before the in
  17145. // point (4.0 s), so the video window shows the streamer and the line
  17146. adrStep = 1;
  17147. offline.editSong ([] (lynx::Song& s) {
  17148. lynx::AdrCue a, b;
  17149. a.id = "SC1-01";
  17150. a.in = 4.0;
  17151. a.out = 6.4;
  17152. a.character = "Dr. Silva";
  17153. a.line = "We have to leave before the storm reaches the coast.";
  17154. a.notes = "softer, out of breath";
  17155. a.status = lynx::AdrCue::Status::recorded;
  17156. for (int n = 1; n <= 3; ++n)
  17157. {
  17158. lynx::AdrTake t;
  17159. t.number = n;
  17160. t.name = lynx::adr::takeName (a, n);
  17161. t.rating = n == 2 ? 4 : n;
  17162. t.circled = n == 2;
  17163. a.takes.push_back (t);
  17164. }
  17165. a.selected = 2;
  17166. lynx::adr::setCompRange (a, 4.0, 5.1, 2);
  17167. lynx::adr::setCompRange (a, 5.1, 6.4, 3);
  17168. b.id = "SC1-02";
  17169. b.in = 8.0;
  17170. b.out = 9.5;
  17171. b.character = "Marta";
  17172. b.line = "Then we go now.";
  17173. s.adr.cues = { a, b };
  17174. s.adr.current = 0;
  17175. });
  17176. adrPanel = lynx::adrwindow::makePanel (offline);
  17177. adrPanel->setSize (1200, 640);
  17178. adrPanel->setVisible (true);
  17179. offline.getTransport().positionTicks.store (3.0 * offline.getSong().bpm / 60.0 * lynx::ppq);
  17180. decoder->request (2.0, false);
  17181. return;
  17182. }
  17183. if (adrStep == 1)
  17184. {
  17185. adrStep = 2;
  17186. savePng (lynx::shot::snapshot (*adrPanel), prefix + "-adr.png");
  17187. for (int w = 0; w < juce::Desktop::getInstance().getNumComponents(); ++w)
  17188. if (auto* c = juce::Desktop::getInstance().getComponent (w); c != nullptr && c->getName().startsWith ("Picture"))
  17189. savePng (lynx::shot::snapshot (*c), prefix + "-adr-window.png");
  17190. offline.getTransport().positionTicks.store (4.5 * offline.getSong().bpm / 60.0 * lynx::ppq);
  17191. decoder->request (3.5, false);
  17192. return;
  17193. }
  17194. if (adrStep == 2)
  17195. {
  17196. for (int w = 0; w < juce::Desktop::getInstance().getNumComponents(); ++w)
  17197. if (auto* c = juce::Desktop::getInstance().getComponent (w); c != nullptr && c->getName().startsWith ("Picture"))
  17198. savePng (lynx::shot::snapshot (*c), prefix + "-adr-window-line.png");
  17199. adrPanel.reset();
  17200. // export with video: a 3 s mix under the picture, re-encoded (the clip starts at 1 s) and copied (from 1 s)
  17201. {
  17202. const juce::File wav (prefix + "-mix.wav");
  17203. wav.deleteFile();
  17204. juce::WavAudioFormat format;
  17205. if (std::unique_ptr<juce::OutputStream> os (wav.createOutputStream().release()); os != nullptr)
  17206. if (std::unique_ptr<juce::AudioFormatWriter> w (format.createWriterFor (os.get(), 48000.0, 2, 16, {}, 0)); w != nullptr)
  17207. {
  17208. os.release();
  17209. juce::AudioBuffer<float> b (2, 48000 * 3);
  17210. for (int k = 0; k < b.getNumSamples(); ++k)
  17211. 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));
  17212. w->writeFromAudioSampleBuffer (b, 0, b.getNumSamples());
  17213. }
  17214. for (const auto origin : { 0.0, 1.0 })
  17215. {
  17216. const juce::File out (prefix + "-mux-" + juce::String ((int) origin) + ".mp4");
  17217. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  17218. const auto error = lynx::videotracks::muxWithVideo (offline.getSong(), origin, wav, out);
  17219. report << "export with video from " << origin << " s: " << (error.isEmpty() ? "OK " + juce::String (out.getSize()) + " bytes" : "FAILED " + error)
  17220. << " (" << juce::String ((juce::Time::getMillisecondCounterHiRes() - t0) / 1000.0, 2) << " s)\n";
  17221. }
  17222. }
  17223. stopTimer();
  17224. report << "frames decoded " << decoder->frameCount() << ", dropped " << decoder->droppedCount() << "\n";
  17225. juce::File (prefix + "-report.txt").replaceWithText (report);
  17226. if (done)
  17227. done();
  17228. return;
  17229. }
  17230. const auto t = times[(std::size_t) step++];
  17231. offline.getTransport().positionTicks.store (t * offline.getSong().bpm / 60.0 * lynx::ppq);
  17232. decoder->request (std::max (0.0, t - 1.0), false);
  17233. }
  17234. };
  17235. static std::unique_ptr<TrackShot> shot;
  17236. shot = std::make_unique<TrackShot>();
  17237. shot->prefix = prefix;
  17238. auto& offline = shot->offline;
  17239. lynx::Song song;
  17240. song.mixer = lynx::Song::defaultMixer (2);
  17241. song.patterns.emplace_back();
  17242. song.mode = lynx::PlayMode::song;
  17243. song.bpm = 120.0;
  17244. offline.setSong (std::move (song));
  17245. offline.dispatchPendingMessages();
  17246. const juce::File video (videoPath);
  17247. const auto pr = lynx::media::probe (video.getFullPathName());
  17248. auto& report = shot->report;
  17249. report << "decoder: " << (pr.backend.isEmpty() ? juce::String ("none") : pr.backend) << " (system: " << lynx::media::nativeBackendName()
  17250. << ", ffmpeg: " << lynx::findFfmpeg().getFullPathName() << ")\n";
  17251. report << "video: " << pr.info.width << "x" << pr.info.height << " " << juce::String (pr.info.fps, 3) << " fps " << juce::String (pr.info.duration, 3)
  17252. << " s, sound " << (pr.info.hasAudio ? "yes" : "no") << "\n";
  17253. shot->fps = pr.info.fps > 1.0 ? pr.info.fps : 25.0;
  17254. shot->times[2] = 2.0 + 1.0 / shot->fps; // (exactly on a frame edge)
  17255. lynx::videotracks::importVideo (offline, video, 1.0, -1);
  17256. if (secondPath.isNotEmpty())
  17257. lynx::videotracks::importVideo (offline, juce::File (secondPath), 3.0, 1);
  17258. offline.editSong ([] (lynx::Song& s) {
  17259. s.video.startTimecode = 3600.0;
  17260. s.video.burnIn = true;
  17261. if (s.videoTracks.size() < 2)
  17262. s.videoTracks.push_back ({});
  17263. s.videoTracks[0].name = "Picture";
  17264. s.videoTracks[1].name = "Reference";
  17265. });
  17266. report << "project rate: " << lynx::vtime::rateName (offline.getSong().video.rate) << ", clip 1: "
  17267. << juce::String (offline.getSong().videoTracks[0].clips.empty() ? -1.0 : offline.getSong().videoTracks[0].clips[0].length, 3) << " s\n";
  17268. // the project round trip
  17269. {
  17270. const juce::File file (prefix + "-project.lynx");
  17271. juce::String error;
  17272. lynx::ProjectFile::save (offline.getSong(), file, error);
  17273. const auto back = lynx::ProjectFile::load (file, error);
  17274. report << "project file round trip: " << (back && back->videoTracks == offline.getSong().videoTracks && back->video == offline.getSong().video ? "OK" : "MISMATCH " + error) << "\n";
  17275. }
  17276. shot->playlist = std::make_unique<lynx::PlaylistComponent> (offline);
  17277. shot->playlist->setSize (1400, 640);
  17278. shot->playlist->setVisible (true);
  17279. shot->decoder = std::make_unique<lynx::media::FrameDecoder>();
  17280. shot->decoder->setSource (video.getFullPathName(), pr.info);
  17281. shot->decoder->setSize (pr.info.width, pr.info.height);
  17282. shot->decoder->startThread (juce::Thread::Priority::low);
  17283. lynx::videotracks::showWindow (offline, 0);
  17284. shot->done = [this] { juce::MessageManager::callAsync ([this] { shot.reset(); quit(); }); };
  17285. shot->startTimer (700);
  17286. }
  17287. void runDanceShot (const juce::String& prefix)
  17288. {
  17289. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  17290. // the moves: one row each, eight moments of a cycle (both facings for Spinning; Pose ends the sheet)
  17291. {
  17292. constexpr int cell = 120, cols = 8;
  17293. auto sheet = lynx::shot::canvas (130 + cols * cell, lynx::dance::moveCount * cell + 10);
  17294. {
  17295. // (the picture is complete when its Graphics is gone: round 190ba, the file was blank on Windows)
  17296. juce::Graphics g (sheet);
  17297. lynx::shot::logical (g);
  17298. g.fillAll (lynx::theme::colour::bg0);
  17299. for (int m = 0; m < lynx::dance::moveCount; ++m)
  17300. {
  17301. g.setColour (lynx::theme::colour::textSecondary);
  17302. g.setFont (14.0f);
  17303. g.drawText (lynx::dance::moveName (m), 8, m * cell + 5, 118, cell, juce::Justification::centredLeft);
  17304. for (int k = 0; k < cols; ++k)
  17305. {
  17306. const auto pose = lynx::dance::pose (m, k / (double) cols + (m == lynx::dance::freestyle ? k * 2 : 0), 1);
  17307. lynx::dancer::draw (g, { 130.0f + (k + 0.5f) * cell, (float) (m + 1) * cell - 6.0f }, 92.0f, pose, false, juce::Colour (0xffff3048));
  17308. }
  17309. }
  17310. }
  17311. savePng (sheet, prefix + "-moves.png");
  17312. }
  17313. lynx::AudioEngine offline (false);
  17314. lynx::Song song;
  17315. song.mixer = lynx::Song::defaultMixer (2);
  17316. for (int d = 0; d < 2; ++d)
  17317. {
  17318. lynx::ChannelDef c;
  17319. c.name = d == 0 ? "Fruity Dance" : "Fruity Dance #2";
  17320. c.instrument = lynx::InstrumentKind::fruitydance;
  17321. lynx::dance::Settings s;
  17322. s.move = d == 0 ? lynx::dance::stepping : lynx::dance::waving;
  17323. s.x = d == 0 ? 520 : 760;
  17324. s.y = 560;
  17325. s.colour = d == 0 ? 0xffff3048 : 0xff30a8ff;
  17326. s.mirrored = d == 1;
  17327. c.pluginState = lynx::dance::toState (s);
  17328. song.channels.push_back (c);
  17329. }
  17330. // Issue #121 (round 190ba): a sprite sheet in FL's Fruity Dance format (8 frames across, a row per move, a names
  17331. // file beside it), made here from LYNX's own poses, loaded back as a user's sheet would be
  17332. juce::String sheetReport;
  17333. {
  17334. constexpr int fw = 120, fh = 150;
  17335. const std::vector<std::pair<const char*, int>> rows { { "Idle", lynx::dance::waiting }, { "Step", lynx::dance::stepping },
  17336. { "Jump", lynx::dance::jumping }, { "Wave", lynx::dance::waving },
  17337. { "Windmill", lynx::dance::windmill }, { "Held", lynx::dance::held } };
  17338. juce::Image sheet (juce::Image::ARGB, fw * lynx::dance::sheetColumns, fh * (int) rows.size(), true);
  17339. {
  17340. juce::Graphics g (sheet);
  17341. for (int r = 0; r < (int) rows.size(); ++r)
  17342. for (int k = 0; k < lynx::dance::sheetColumns; ++k)
  17343. {
  17344. juce::Graphics::ScopedSaveState save (g);
  17345. g.reduceClipRegion (k * fw, r * fh, fw, fh);
  17346. lynx::dancer::draw (g, { (k + 0.5f) * fw, (float) (r + 1) * fh - 8.0f }, 96.0f,
  17347. lynx::dance::pose (rows[(std::size_t) r].second, k / (double) lynx::dance::sheetColumns, 1), false, juce::Colour (0xff35c46a));
  17348. }
  17349. }
  17350. const juce::File picture (prefix + "-sheet.png");
  17351. savePng (sheet, picture.getFullPathName());
  17352. juce::String names;
  17353. for (const auto& [name, move] : rows)
  17354. names << (names.isEmpty() ? "" : "\r\n") << name;
  17355. picture.withFileExtension ("txt").replaceWithText (names, false, false, nullptr);
  17356. // a picture that is not a whole number of frames: FL's "Bitmap size is incorrect."
  17357. const juce::File wrong (prefix + "-sheet-wrong.png");
  17358. savePng (sheet.getClippedImage ({ 0, 0, sheet.getWidth() - 3, sheet.getHeight() }), wrong.getFullPathName());
  17359. wrong.withFileExtension ("txt").replaceWithText (names, false, false, nullptr);
  17360. auto error = lynx::dancer::SheetError::none;
  17361. const auto loaded = lynx::dancer::sheetFor (picture.getFullPathName().toStdString(), &error);
  17362. auto wrongError = lynx::dancer::SheetError::none;
  17363. const auto refused = lynx::dancer::sheetFor (wrong.getFullPathName().toStdString(), &wrongError);
  17364. auto missingError = lynx::dancer::SheetError::none;
  17365. const auto missing = lynx::dancer::sheetFor (juce::File (prefix + "-sheet-none.png").getFullPathName().toStdString(), &missingError);
  17366. sheetReport << "sheet_loaded=" << (loaded != nullptr ? 1 : 0) << "\n"
  17367. << "sheet_wrong_size_refused=" << (refused == nullptr && wrongError == lynx::dancer::SheetError::size ? 1 : 0) << "\n"
  17368. << "sheet_missing_refused=" << (missing == nullptr && missingError == lynx::dancer::SheetError::missing ? 1 : 0) << "\n";
  17369. bool ok = loaded != nullptr && refused == nullptr && missing == nullptr;
  17370. if (loaded != nullptr)
  17371. {
  17372. sheetReport << "sheet_rows=" << loaded->layout.rows << "\nsheet_frame=" << loaded->layout.frameWidth << "x" << loaded->layout.frameHeight
  17373. << "\nsheet_moves=" << loaded->moves() << "\nsheet_names=";
  17374. for (const auto& n : loaded->names)
  17375. sheetReport << juce::String::fromUTF8 (n.c_str()) << ";";
  17376. sheetReport << "\n";
  17377. ok = ok && loaded->layout.rows == (int) rows.size() && loaded->layout.frameWidth == fw && loaded->layout.frameHeight == fh;
  17378. // the animation as the stage draws it: a row of moments of the move "Wave" (blending on), then mirrored,
  17379. // then the row shown while the dancer is held
  17380. auto strip = lynx::shot::canvas (fw * 12, fh * 3 + 20);
  17381. int solid = 0;
  17382. {
  17383. juce::Graphics g (strip);
  17384. lynx::shot::logical (g);
  17385. g.fillAll (lynx::theme::colour::bg0);
  17386. for (int line = 0; line < 3; ++line)
  17387. {
  17388. lynx::dance::SheetAnimator animator (3);
  17389. for (int k = 0; k < 12; ++k)
  17390. {
  17391. const auto frame = animator.advance (k / 12.0 + 0.001, loaded->layout.rows, 4, line == 1, true, 0.5f, line == 2);
  17392. const juce::Point<float> feet ((k + 0.5f) * fw, (float) (line + 1) * fh + 5.0f);
  17393. lynx::dancer::drawSheet (g, *loaded, feet, 1.0f, frame);
  17394. solid += lynx::dancer::sheetSolidAt (*loaded, feet, 1.0f, frame, feet.translated (0.0f, -70.0f)) ? 1 : 0;
  17395. ok = ok && ! lynx::dancer::sheetSolidAt (*loaded, feet, 1.0f, frame, feet.translated (-(float) fw * 0.5f + 1.0f, -(float) fh + 1.0f));
  17396. }
  17397. }
  17398. }
  17399. // mirrored = the same frame flipped left-right, on whatever renderer this build draws with
  17400. {
  17401. lynx::dance::SheetFrame plain;
  17402. plain.row = 3;
  17403. plain.column = 2;
  17404. auto turned = plain;
  17405. turned.mirrored = true;
  17406. juce::Image a (juce::Image::ARGB, fw, fh, true), b (juce::Image::ARGB, fw, fh, true);
  17407. {
  17408. juce::Graphics ga (a);
  17409. lynx::dancer::drawSheet (ga, *loaded, { fw * 0.5f, (float) fh }, 1.0f, plain);
  17410. }
  17411. {
  17412. juce::Graphics gb (b);
  17413. lynx::dancer::drawSheet (gb, *loaded, { fw * 0.5f, (float) fh }, 1.0f, turned);
  17414. }
  17415. int same = 0, flippedSame = 0, solidPixels = 0;
  17416. for (int y = 0; y < fh; ++y)
  17417. for (int x = 0; x < fw; ++x)
  17418. {
  17419. const auto pa = a.getPixelAt (x, y);
  17420. if (pa.getAlpha() < 200)
  17421. continue;
  17422. ++solidPixels;
  17423. auto alike = [pa] (juce::Colour c) {
  17424. return std::abs ((int) c.getRed() - (int) pa.getRed()) + std::abs ((int) c.getGreen() - (int) pa.getGreen())
  17425. + std::abs ((int) c.getBlue() - (int) pa.getBlue()) + std::abs ((int) c.getAlpha() - (int) pa.getAlpha()) < 12;
  17426. };
  17427. same += alike (b.getPixelAt (x, y)) ? 1 : 0;
  17428. flippedSame += alike (b.getPixelAt (fw - 1 - x, y)) ? 1 : 0;
  17429. }
  17430. const auto flips = solidPixels > 500 && flippedSame >= solidPixels * 98 / 100 && same < solidPixels * 95 / 100;
  17431. sheetReport << "sheet_mirror_flips=" << (flips ? 1 : 0) << " (" << flippedSame << " of " << solidPixels << " solid pixels match flipped, " << same
  17432. << " unflipped)\n";
  17433. ok = ok && flips;
  17434. }
  17435. sheetReport << "sheet_body_solid=" << solid << "/36\n";
  17436. ok = ok && solid >= 18;
  17437. savePng (strip, prefix + "-sheet-frames.png");
  17438. }
  17439. sheetReport << "sheet_result=" << (ok ? "OK" : "ERROR") << "\n";
  17440. lynx::ChannelDef c;
  17441. c.name = "Fruity Dance #3";
  17442. c.instrument = lynx::InstrumentKind::fruitydance;
  17443. lynx::dance::Settings s;
  17444. s.move = 2; // (the sheet's second row: "Step")
  17445. s.x = 1000;
  17446. s.y = 560;
  17447. s.sheet = picture.getFullPathName().toStdString();
  17448. c.pluginState = lynx::dance::toState (s);
  17449. song.channels.push_back (c);
  17450. }
  17451. song.patterns.emplace_back();
  17452. {
  17453. const juce::File demo (prefix + "-demo.lynx");
  17454. juce::String error;
  17455. lynx::ProjectFile::save (song, demo, error);
  17456. }
  17457. offline.setSong (std::move (song));
  17458. offline.dispatchPendingMessages();
  17459. if (auto editor = lynx::makeChannelSettingsPanel (offline, 0))
  17460. savePng (lynx::shot::snapshot (*editor), prefix + "-editor.png");
  17461. if (auto frame = lynx::makeChannelFrame (offline, 1, 0))
  17462. savePng (lynx::shot::snapshot (*frame), prefix + "-frame.png");
  17463. if (auto editor = lynx::makeChannelSettingsPanel (offline, 2))
  17464. savePng (lynx::shot::snapshot (*editor), prefix + "-sheet-editor.png");
  17465. {
  17466. // the stage with the three dancers (the third from the sheet)
  17467. lynx::DanceStage stage (offline);
  17468. stage.setSize (1280, 640);
  17469. stage.update();
  17470. sheetReport << "stage_dancers=" << stage.dancerCount() << "\n";
  17471. auto picture = lynx::shot::canvas (1280, 640);
  17472. {
  17473. juce::Graphics g (picture);
  17474. lynx::shot::logical (g);
  17475. g.fillAll (lynx::theme::colour::bg0);
  17476. stage.paintEntireComponent (g, true);
  17477. }
  17478. savePng (picture, prefix + "-sheet-stage.png");
  17479. }
  17480. juce::File (prefix + "-sheetreport.txt").replaceWithText (sheetReport);
  17481. }
  17482. void runControllerShot (const juce::String& prefix)
  17483. {
  17484. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  17485. lynx::AudioEngine offline (false);
  17486. lynx::Song song;
  17487. song.mixer = lynx::Song::defaultMixer (2);
  17488. song.mixer[1].name = "Insert 1";
  17489. auto fx = lynx::makeEffectSlot (lynx::EffectKind::formulaController);
  17490. lynx::formula::State formula;
  17491. formula.formula = "a*Sin(SongTime*Pi*b*4)+c";
  17492. fx.state = lynx::formula::writeState (formula);
  17493. fx.params[0] = 0.5f;
  17494. fx.params[1] = 0.25f;
  17495. fx.params[2] = 0.5f;
  17496. song.mixer[1].effects.push_back (fx);
  17497. // round 164: X-Y (slot 2), X-Y-Z (slot 3) and a Control Surface (slot 4)
  17498. {
  17499. auto xyFx = lynx::makeEffectSlot (lynx::EffectKind::xyController);
  17500. xyFx.params[(std::size_t) lynx::xy::level (0)] = 0.3f;
  17501. xyFx.params[(std::size_t) lynx::xy::level (1)] = 0.7f;
  17502. xyFx.params[(std::size_t) lynx::xy::tension (0)] = 0.8f;
  17503. song.mixer[1].effects.push_back (xyFx);
  17504. auto xyzFx = lynx::makeEffectSlot (lynx::EffectKind::xyzController);
  17505. xyzFx.params[(std::size_t) lynx::xy::level (2)] = 0.8f;
  17506. song.mixer[1].effects.push_back (xyzFx);
  17507. // round 165: an X-Y-Z whose X curve is FL's "Stairs" (tension +40 %) and Y a bent single curve
  17508. xyzFx.params[(std::size_t) lynx::xy::curveMode (0)] = lynx::xy::curveModeValue (lynx::flcurve::stairs);
  17509. xyzFx.params[(std::size_t) lynx::xy::tension (0)] = 0.7f;
  17510. xyzFx.params[(std::size_t) lynx::xy::level (0)] = 0.62f;
  17511. xyzFx.params[(std::size_t) lynx::xy::tension (1)] = 0.825f;
  17512. song.mixer[1].effects.push_back (xyzFx);
  17513. auto panel = lynx::makeEffectSlot (lynx::EffectKind::controlSurface);
  17514. lynx::SurfaceControl c;
  17515. for (const auto& [kind, name, v, x, y] : std::vector<std::tuple<lynx::SurfaceControl::Kind, const char*, float, float, float>> {
  17516. { lynx::SurfaceControl::Kind::knob, "Cutoff", 0.65f, 20.0f, 20.0f },
  17517. { lynx::SurfaceControl::Kind::knob, "Reso", 0.3f, 90.0f, 20.0f },
  17518. { lynx::SurfaceControl::Kind::slider, "Mix", 0.8f, 170.0f, 20.0f },
  17519. { lynx::SurfaceControl::Kind::xy, "Space", 0.4f, 230.0f, 20.0f },
  17520. { lynx::SurfaceControl::Kind::button, "Drop", 0.0f, 20.0f, 110.0f },
  17521. { lynx::SurfaceControl::Kind::checkBox, "Bypass", 1.0f, 20.0f, 160.0f } })
  17522. {
  17523. c.kind = kind;
  17524. c.name = name;
  17525. c.value = v;
  17526. c.valueY = 0.6f;
  17527. c.x = x;
  17528. c.y = y;
  17529. lynx::surface::add (panel, c);
  17530. }
  17531. song.mixer[1].effects.push_back (panel);
  17532. }
  17533. lynx::ChannelDef env;
  17534. env.name = "Envelope Controller";
  17535. env.instrument = lynx::InstrumentKind::controller;
  17536. auto ecData = lynx::defaultEnvelopeController();
  17537. ecData[0].lfoOn = true;
  17538. ecData[0].lfoTempo = true;
  17539. ecData[0].lfoSpeed = 40898;
  17540. ecData[0].maps[lynx::mapKeyboard].count = 2;
  17541. ecData[0].maps[lynx::mapKeyboard].time = { 0.2f, 0.8f };
  17542. ecData[0].maps[lynx::mapKeyboard].level = { 0.0f, 1.0f };
  17543. ecData[0].maps[lynx::mapModX] = ecData[0].maps[lynx::mapKeyboard];
  17544. env.controllerState = lynx::writeEnvelopeController (ecData);
  17545. song.channels.push_back (env);
  17546. lynx::ChannelDef out;
  17547. out.name = "MIDI Out";
  17548. out.instrument = lynx::InstrumentKind::midiOut;
  17549. lynx::midictl::MidiOutSettings settings;
  17550. settings.port = 1;
  17551. lynx::midictl::writeMidiOut (out.pluginState, settings);
  17552. song.channels.push_back (out);
  17553. // a Layer (round 164) over three synths split across the keyboard, crossfading
  17554. for (const auto* name : { "Bass", "Pad", "Lead" })
  17555. {
  17556. lynx::ChannelDef c;
  17557. c.name = name;
  17558. c.instrument = lynx::InstrumentKind::synth;
  17559. song.channels.push_back (c);
  17560. }
  17561. {
  17562. lynx::ChannelDef layer;
  17563. layer.name = "Layer";
  17564. layer.instrument = lynx::InstrumentKind::layer;
  17565. song.channels.push_back (layer);
  17566. const auto self = (int) song.channels.size() - 1;
  17567. lynx::layer::setChildren (song, self, { 2, 3, 4 });
  17568. song.channels[2].keyLow = 0, song.channels[2].keyHigh = 47;
  17569. song.channels[3].keyLow = 36, song.channels[3].keyHigh = 83;
  17570. song.channels[4].keyLow = 72, song.channels[4].keyHigh = 127;
  17571. song.channels[(std::size_t) self].layer.crossfade = true;
  17572. song.channels[(std::size_t) self].layer.fade = 0.35f;
  17573. }
  17574. {
  17575. lynx::ChannelDef dash; // channel 6
  17576. dash.name = "Dashboard";
  17577. dash.instrument = lynx::InstrumentKind::dashboard;
  17578. dash.patcher.surface = lynx::surface::starterControls();
  17579. song.channels.push_back (dash);
  17580. }
  17581. {
  17582. lynx::ChannelDef volt; // channel 7: FL's render-test settings (main L pitch, R gate × 0.5) with Out 2 on insert 3
  17583. volt.name = "Voltage Controller";
  17584. volt.instrument = lynx::InstrumentKind::voltage;
  17585. lynx::voltage::Settings v;
  17586. v.enabled = true;
  17587. v.params[9] = 49152;
  17588. v.unipolar[2] = true;
  17589. v.tracks = { 3, 0, 0 };
  17590. v.source[6] = lynx::voltage::Source::clock;
  17591. volt.pluginState = lynx::voltage::write (v);
  17592. song.channels.push_back (volt);
  17593. }
  17594. song.patterns.emplace_back();
  17595. offline.setSong (std::move (song));
  17596. offline.dispatchPendingMessages();
  17597. auto shoot = [&] (std::unique_ptr<juce::Component> c, const juce::String& name) {
  17598. if (c == nullptr)
  17599. return;
  17600. savePng (lynx::shot::snapshot (*c), prefix + name);
  17601. };
  17602. shoot (lynx::makeChannelSettingsPanel (offline, 0), "-envelope-controller.png");
  17603. shoot (lynx::makeChannelSettingsPanel (offline, 1), "-midi-out.png");
  17604. shoot (lynx::makeChannelSettingsPanel (offline, 5), "-layer.png");
  17605. shoot (lynx::makeChannelFrame (offline, 3, -1), "-layer-child-misc.png"); // (the key-region ruler over the root keyboard)
  17606. {
  17607. const auto slotOf = [] (int k) -> lynx::SlotLocator {
  17608. return [k] (lynx::Song& s) { return &s.mixer[1].effects[(std::size_t) k]; };
  17609. };
  17610. const lynx::AutomationTarget target { lynx::AutomationTargetKind::effectParam, 1, 1, 0 };
  17611. shoot (lynx::makeXyControllerEditor (offline, slotOf (1), nullptr, target), "-xy-controller.png");
  17612. shoot (lynx::makeXyControllerEditor (offline, slotOf (2), nullptr, target), "-xyz-controller.png");
  17613. shoot (lynx::makeXyControllerEditor (offline, slotOf (3), nullptr, target), "-xyz-controller-stairs.png");
  17614. shoot (lynx::makeControlSurfaceEditor (offline, slotOf (4), target), "-control-surface.png");
  17615. shoot (lynx::makeChannelSettingsPanel (offline, 6), "-dashboard.png");
  17616. shoot (lynx::makeChannelSettingsPanel (offline, 7), "-voltage-controller.png");
  17617. }
  17618. // FL's Dashboard presets of this PC's FL Studio, imported (round 164f): one PNG each
  17619. if (const auto fl = lynx::findFlStudio(); fl.installDir.isDirectory())
  17620. for (const auto& file : fl.installDir.getChildFile ("Data/Patches/Plugin presets/Generators/Dashboard").findChildFiles (juce::File::findFiles, false, "*.fst"))
  17621. {
  17622. juce::MemoryBlock bytes;
  17623. if (! file.loadFileAsData (bytes))
  17624. continue;
  17625. const auto preset = flp::parseProject ({ (const std::uint8_t*) bytes.getData(), bytes.getSize() }, true);
  17626. const auto dash = preset.channels.empty() ? std::nullopt : lynx::surface::parseFlDashboard (preset.channels[0].pluginState);
  17627. if (! dash || dash->controls.empty())
  17628. continue;
  17629. offline.editSong ([&] (lynx::Song& s) {
  17630. s.channels[6].name = file.getFileNameWithoutExtension().toStdString();
  17631. s.channels[6].patcher.surface = dash->controls;
  17632. s.channels[6].pluginState = preset.channels[0].pluginState; // (its MIDI port, channel, program)
  17633. });
  17634. offline.dispatchPendingMessages();
  17635. const auto name = file.getFileNameWithoutExtension().replaceCharacter (' ', '-');
  17636. shoot (lynx::makeChannelSettingsPanel (offline, 6), "-dashboard-fl-" + name + ".png");
  17637. // edit mode (round 165): each control's output number and the MIDI it sends ("1 CC74")
  17638. if (auto panel = lynx::makeChannelSettingsPanel (offline, 6))
  17639. {
  17640. std::function<void (juce::Component&)> pressEdit = [&] (juce::Component& c) {
  17641. for (auto* child : c.getChildren())
  17642. {
  17643. if (auto* b = dynamic_cast<juce::TextButton*> (child); b != nullptr && b->getButtonText() == lynx::tr ("Edit"))
  17644. b->setToggleState (true, juce::sendNotificationSync);
  17645. pressEdit (*child);
  17646. }
  17647. };
  17648. pressEdit (*panel);
  17649. shoot (std::move (panel), "-dashboard-fl-" + name + "-edit.png");
  17650. }
  17651. }
  17652. // the Envelope Controller's pages (issue #7): one PNG per part of the dropdown
  17653. if (auto ec = lynx::makeEnvelopeControllerEditor (offline, 0))
  17654. for (int part = 0; part < 7; ++part)
  17655. {
  17656. for (auto* child : ec->getChildren())
  17657. if (auto* box = dynamic_cast<juce::ComboBox*> (child))
  17658. box->setSelectedItemIndex (part, juce::sendNotificationSync);
  17659. savePng (lynx::shot::snapshot (*ec), prefix + "-ec-part" + juce::String (part) + ".png");
  17660. }
  17661. lynx::FormulaControllerWindows::open (offline, 1, 0);
  17662. for (int k = 0; k < juce::TopLevelWindow::getNumTopLevelWindows(); ++k)
  17663. if (auto* w = dynamic_cast<juce::DocumentWindow*> (juce::TopLevelWindow::getTopLevelWindow (k)))
  17664. if (w->getName().startsWith ("Formula") && w->getContentComponent() != nullptr)
  17665. savePng (lynx::shot::snapshot (*w->getContentComponent()), prefix + "-formula-controller.png");
  17666. lynx::FormulaControllerWindows::closeAll();
  17667. }
  17668. bool runEdisonSlotTest (const juce::String& folderPath, const juce::String& flp)
  17669. {
  17670. namespace ae = lynx::audioedit;
  17671. namespace ef = lynx::edisonfx;
  17672. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  17673. const juce::File folder (folderPath);
  17674. folder.createDirectory();
  17675. juce::String report;
  17676. bool all = true;
  17677. auto check = [&] (const juce::String& name, bool ok, const juce::String& note = {}) {
  17678. report << name << "=" << (ok ? "ok" : "FAIL") << (note.isNotEmpty() ? " (" + note + ")" : juce::String()) << "\n";
  17679. all = all && ok;
  17680. };
  17681. auto shot = [&folder] (juce::Component& c, const juce::String& name) {
  17682. savePng (lynx::shot::paint (c, lynx::theme::panel), folder.getChildFile (name).getFullPathName());
  17683. };
  17684. auto findSlot = [] (const lynx::Song& song, int& track, int& slot) {
  17685. for (track = 0; track < (int) song.mixer.size(); ++track)
  17686. for (slot = 0; slot < (int) song.mixer[(std::size_t) track].effects.size(); ++slot)
  17687. if (song.mixer[(std::size_t) track].effects[(std::size_t) slot].kind == lynx::EffectKind::edison)
  17688. return true;
  17689. return false;
  17690. };
  17691. {
  17692. lynx::AudioEngine engine (false);
  17693. engine.setRecordingTarget (folder.getChildFile ("Audio").getChildFile ("Recorded"), "Test");
  17694. // a project without the plugin is written as before: nothing of it in the file, and it reads back the same
  17695. const auto before = lynx::ProjectFile::toJson (engine.getSong(), false);
  17696. juce::String error;
  17697. const auto same = lynx::ProjectFile::fromJson (before, error);
  17698. check ("old_project_text_has_no_trace", ! before.containsIgnoreCase ("edison"));
  17699. check ("old_project_round_trip_stable", same.has_value() && lynx::ProjectFile::toJson (*same, false) == before);
  17700. const auto at = lynx::addEdisonSlot (engine, 1);
  17701. engine.dispatchPendingMessages();
  17702. check ("slot_added_to_first_empty_slot", at == 0 && engine.getSong().mixer[1].effects.size() == 1
  17703. && engine.getSong().mixer[1].effects[0].kind == lynx::EffectKind::edison);
  17704. if (at < 0)
  17705. {
  17706. folder.getChildFile ("report.txt").replaceWithText (report);
  17707. return false;
  17708. }
  17709. const auto second = lynx::addEdisonSlot (engine, 1); // several instances on a track
  17710. engine.dispatchPendingMessages();
  17711. check ("second_instance_on_the_same_track", second == 1);
  17712. engine.editSong ([at] (lynx::Song& s) {
  17713. s.mixer[1].effects[(std::size_t) at].params[ef::recordMode] = ef::modeValue (ef::Mode::now);
  17714. });
  17715. engine.dispatchPendingMessages();
  17716. const auto slotOf = [&engine, at] { return engine.getSong().mixer[1].effects[(std::size_t) at]; };
  17717. const auto fx = engine.getEffect (1, at);
  17718. const auto p = std::dynamic_pointer_cast<ef::Processor> (fx);
  17719. const auto session = ef::findSession (slotOf().instance.id);
  17720. check ("engine_built_the_effect_with_its_session", p != nullptr && session != nullptr);
  17721. const auto other = ef::findSession (engine.getSong().mixer[1].effects[1].instance.id);
  17722. check ("instances_have_their_own_audio", other != nullptr && other != session);
  17723. if (p == nullptr || session == nullptr)
  17724. {
  17725. folder.getChildFile ("report.txt").replaceWithText (report);
  17726. return false;
  17727. }
  17728. // idle: the audio passes through bit for bit
  17729. const auto rate = p->sampleRate();
  17730. std::vector<float> l (512), r (512);
  17731. auto fill = [&] (int block) {
  17732. for (int k = 0; k < 512; ++k)
  17733. {
  17734. const auto t = (double) (block * 512 + k) / rate;
  17735. l[(std::size_t) k] = 0.6f * (float) std::sin (2.0 * 3.141592653589793 * 220.0 * t);
  17736. r[(std::size_t) k] = 0.4f * (float) std::sin (2.0 * 3.141592653589793 * 330.0 * t);
  17737. }
  17738. };
  17739. fill (0);
  17740. auto inL = l, inR = r;
  17741. p->process (l.data(), r.data(), 512, slotOf().params, 120.0);
  17742. check ("idle_pass_through_bit_exact", l == inL && r == inR);
  17743. // a take through the slot (Now), then the flush that makes it a file of the project
  17744. std::vector<float> wantL, wantR;
  17745. check ("record_starts", session->start (p, true));
  17746. for (int block = 0; block < 60; ++block)
  17747. {
  17748. fill (block);
  17749. wantL.insert (wantL.end(), l.begin(), l.end());
  17750. wantR.insert (wantR.end(), r.begin(), r.end());
  17751. p->process (l.data(), r.data(), 512, slotOf().params, 120.0);
  17752. }
  17753. session->stop();
  17754. check ("take_is_the_input", session->document().audio.numChannels() == 2 && session->document().audio.channels[0] == wantL
  17755. && session->document().audio.channels[1] == wantR);
  17756. ae::Document withMarkers = session->document();
  17757. ae::addMarker (withMarkers, 4000, "Verse");
  17758. ae::addMarker (withMarkers, 12000);
  17759. ae::setLoop (withMarkers, { 2000, 20000 });
  17760. session->setDocument (withMarkers);
  17761. engine.flushEdisonAudio();
  17762. engine.dispatchPendingMessages();
  17763. const juce::File file (juce::String::fromUTF8 (slotOf().samplePath.c_str()));
  17764. check ("audio_written_to_the_project_folder", file.existsAsFile() && file.isAChildOf (folder.getChildFile ("Audio").getChildFile ("Recorded")),
  17765. file.getFullPathName());
  17766. check ("file_listed_with_the_session_recordings", std::find (engine.getSessionRecordings().begin(), engine.getSessionRecordings().end(), file)
  17767. != engine.getSessionRecordings().end());
  17768. check ("effect_kept_running_through_the_flush", engine.getEffect (1, at) == fx);
  17769. check ("nothing_unsaved_after_the_flush", ! session->dirty());
  17770. engine.flushEdisonAudio(); // (a second flush writes nothing new)
  17771. check ("second_flush_keeps_the_file", juce::File (juce::String::fromUTF8 (slotOf().samplePath.c_str())) == file);
  17772. // the project file: saved, loaded, the same slot with the same audio
  17773. engine.editSong ([at] (lynx::Song& s) {
  17774. auto& params = s.mixer[1].effects[(std::size_t) at].params;
  17775. params[ef::recordMode] = ef::modeValue (ef::Mode::onPlay);
  17776. params[ef::append] = 0.0f;
  17777. params[ef::muteInput] = 1.0f;
  17778. params[ef::slave] = 1.0f;
  17779. params[ef::maxTime] = 5.0f / 6.0f;
  17780. });
  17781. engine.capturePluginStates();
  17782. const auto project = folder.getChildFile ("edison-slot.lynx");
  17783. check ("project_saved", lynx::ProjectFile::save (engine.getSong(), project, error), error);
  17784. auto loaded = lynx::ProjectFile::load (project, error);
  17785. check ("project_loaded", loaded.has_value(), error);
  17786. if (loaded)
  17787. {
  17788. const auto& a = slotOf();
  17789. const auto& b = loaded->mixer[1].effects[(std::size_t) at];
  17790. check ("slot_kind_kept", b.kind == lynx::EffectKind::edison && loaded->mixer[1].effects.size() == 2);
  17791. check ("slot_settings_kept", ef::modeOf (b.params) == ef::Mode::onPlay && b.params[ef::append] < 0.5f && b.params[ef::muteInput] >= 0.5f
  17792. && b.params[ef::slave] >= 0.5f && ef::maxTimeIndexOf (b.params) == 5
  17793. && std::abs (b.params[ef::noiseThreshold] - a.params[ef::noiseThreshold]) < 1.0e-6f);
  17794. check ("slot_audio_path_kept", b.samplePath == a.samplePath);
  17795. check ("project_text_round_trip_stable", lynx::ProjectFile::toJson (*loaded, false) == lynx::ProjectFile::toJson (engine.getSong(), false));
  17796. lynx::AudioEngine second (false);
  17797. second.setSong (std::move (*loaded));
  17798. second.dispatchPendingMessages();
  17799. const auto reopened = ef::findSession (second.getSong().mixer[1].effects[(std::size_t) at].instance.id);
  17800. check ("reopened_project_has_the_audio", reopened != nullptr && reopened != session
  17801. && reopened->document().audio.channels == withMarkers.audio.channels
  17802. && reopened->document().audio.sampleRate == withMarkers.audio.sampleRate);
  17803. check ("reopened_project_has_markers_and_loop", reopened != nullptr && reopened->document().markers.size() == 2
  17804. && reopened->document().markers[0].name == "Verse"
  17805. && reopened->document().loopStart == 2000 && reopened->document().loopEnd == 20000);
  17806. check ("reopened_empty_instance_is_empty", ef::findSession (second.getSong().mixer[1].effects[1].instance.id) != nullptr
  17807. && ef::findSession (second.getSong().mixer[1].effects[1].instance.id)->document().audio.empty());
  17808. if (auto editor = lynx::makeEdisonSlotEditor (second, 1, at))
  17809. {
  17810. editor->setSize (1120, 600);
  17811. second.dispatchPendingMessages();
  17812. shot (*editor, "slot-editor-reopened.png");
  17813. }
  17814. }
  17815. // the plugin's window: the audio editor on the slot (empty instance, then the one with the take)
  17816. if (auto editor = lynx::makeEdisonSlotEditor (engine, 1, 1))
  17817. {
  17818. editor->setSize (1120, 600);
  17819. engine.dispatchPendingMessages();
  17820. shot (*editor, "slot-editor-empty.png");
  17821. }
  17822. auto editor = lynx::makeEdisonSlotEditor (engine, 1, at);
  17823. check ("slot_window_is_the_audio_editor", editor != nullptr);
  17824. if (editor != nullptr)
  17825. {
  17826. editor->setSize (1120, 600);
  17827. engine.dispatchPendingMessages();
  17828. shot (*editor, "slot-editor.png");
  17829. juce::File (folder.getChildFile ("slot-menu.txt")).replaceWithText (lynx::audioEditorMenuForSnapshot (*editor).joinIntoString ("\n") + "\n");
  17830. }
  17831. check ("no_editor_for_other_slots", lynx::makeEdisonSlotEditor (engine, 0, 0) == nullptr);
  17832. editor.reset();
  17833. // deleting the slot leaves the song without it (the file stays for the unused-recordings prompt)
  17834. engine.editSong ([at] (lynx::Song& s) { s.mixer[1].effects.erase (s.mixer[1].effects.begin() + at); });
  17835. engine.dispatchPendingMessages();
  17836. check ("deleted_slot_is_gone", engine.getSong().mixer[1].effects.size() == 1 && file.existsAsFile());
  17837. }
  17838. if (flp.isNotEmpty())
  17839. {
  17840. lynx::AudioEngine engine (false);
  17841. juce::String error;
  17842. const auto imported = engine.importFlpFile (juce::File (flp), error);
  17843. engine.dispatchPendingMessages();
  17844. check ("flp_imported", imported, error);
  17845. int count = 0, withAudio = 0;
  17846. const auto& song = engine.getSong();
  17847. for (int t = 0; t < (int) song.mixer.size(); ++t)
  17848. for (int s = 0; s < (int) song.mixer[(std::size_t) t].effects.size(); ++s)
  17849. {
  17850. const auto& fx = song.mixer[(std::size_t) t].effects[(std::size_t) s];
  17851. if (fx.kind != lynx::EffectKind::edison)
  17852. continue;
  17853. ++count;
  17854. const auto session = ef::findSession (fx.instance.id);
  17855. const auto frames = session != nullptr ? session->document().audio.frames() : -1;
  17856. withAudio += frames > 0 ? 1 : 0;
  17857. report << "flp_slot track " << t << " slot " << s << ": mode " << ef::modeName (ef::modeOf (fx.params))
  17858. << ", append " << (fx.params[ef::append] >= 0.5f ? "on" : "off") << ", mute input " << (fx.params[ef::muteInput] >= 0.5f ? "on" : "off")
  17859. << ", slave " << (fx.params[ef::slave] >= 0.5f ? "on" : "off") << ", loop " << (fx.params[ef::loopPlay] >= 0.5f ? "on" : "off")
  17860. << ", max time index " << ef::maxTimeIndexOf (fx.params) << ", threshold " << juce::String (fx.params[ef::noiseThreshold], 4)
  17861. << ", state " << (int) fx.state.size() << " bytes, audio " << (juce::int64) frames << " frames"
  17862. << (session != nullptr && frames > 0 ? " at " + juce::String (session->document().audio.sampleRate, 0) + " Hz, "
  17863. + juce::String (session->document().audio.numChannels()) + " ch, "
  17864. + juce::String ((int) session->document().markers.size()) + " markers"
  17865. : juce::String())
  17866. << "\n";
  17867. if (count == 1 || (frames > 0 && withAudio == 1))
  17868. if (auto editor = lynx::makeEdisonSlotEditor (engine, t, s))
  17869. {
  17870. editor->setSize (1120, 600);
  17871. engine.dispatchPendingMessages();
  17872. shot (*editor, frames > 0 ? "slot-editor-flp-audio.png" : "slot-editor-flp.png");
  17873. }
  17874. }
  17875. check ("flp_edison_slots_kept_as_the_plugin", count > 0, juce::String (count) + " slots, " + juce::String (withAudio) + " with audio");
  17876. // saved as .lynx and read again: still the plugin, FL's state (the audio) with it
  17877. int t = 0, s = 0;
  17878. if (findSlot (song, t, s))
  17879. {
  17880. const auto project = folder.getChildFile ("edison-flp.lynx");
  17881. const auto saved = lynx::ProjectFile::save (song, project, error);
  17882. std::optional<lynx::Song> loaded;
  17883. if (saved)
  17884. loaded = lynx::ProjectFile::load (project, error);
  17885. check ("flp_slot_survives_the_project_file", loaded.has_value() && t < (int) loaded->mixer.size()
  17886. && s < (int) loaded->mixer[(std::size_t) t].effects.size()
  17887. && loaded->mixer[(std::size_t) t].effects[(std::size_t) s].kind == lynx::EffectKind::edison
  17888. && loaded->mixer[(std::size_t) t].effects[(std::size_t) s].state == song.mixer[(std::size_t) t].effects[(std::size_t) s].state
  17889. && loaded->mixer[(std::size_t) t].effects[(std::size_t) s].params == song.mixer[(std::size_t) t].effects[(std::size_t) s].params,
  17890. error);
  17891. }
  17892. }
  17893. // round 190ct (live FL check 190cq): the open-and-record preset, the fresh defaults and the question before
  17894. // "Remove all Edison instances", in the app
  17895. {
  17896. lynx::AudioEngine engine (false);
  17897. lynx::MainComponent ui (engine, false);
  17898. ui.setSize (1600, 900);
  17899. engine.dispatchPendingMessages();
  17900. const auto toolsMenu = [&ui] {
  17901. const auto names = ui.getMenuNamesForSnapshot();
  17902. for (int m = 0; m < names.size(); ++m)
  17903. if (names[m] == lynx::tr ("Tools"))
  17904. return ui.getMenuForSnapshot (m);
  17905. return juce::PopupMenu();
  17906. };
  17907. const auto removeItem = [&toolsMenu] (bool& found, bool& enabled) {
  17908. found = enabled = false;
  17909. const auto menu = toolsMenu(); // (the iterator keeps a reference)
  17910. for (juce::PopupMenu::MenuItemIterator it (menu, true); it.next();)
  17911. if (it.getItem().text == lynx::tr ("Remove all Edison instances"))
  17912. {
  17913. found = true;
  17914. enabled = it.getItem().isEnabled;
  17915. if (enabled && it.getItem().action)
  17916. it.getItem().action(); // asks: nothing may go before the answer
  17917. return;
  17918. }
  17919. };
  17920. const auto count = [&engine] {
  17921. int n = 0;
  17922. for (const auto& track : engine.getSong().mixer)
  17923. for (const auto& fx : track.effects)
  17924. n += fx.kind == lynx::EffectKind::edison ? 1 : 0;
  17925. return n;
  17926. };
  17927. bool found = false, enabled = false;
  17928. removeItem (found, enabled);
  17929. check ("remove_all_edison_enabled_with_none", found && enabled && count() == 0);
  17930. const auto plain = lynx::addEdisonSlot (engine, 1);
  17931. const auto armed = lynx::addEdisonSlot (engine, 2, true);
  17932. engine.dispatchPendingMessages();
  17933. if (plain >= 0 && armed >= 0)
  17934. {
  17935. const auto& a = engine.getSong().mixer[1].effects[(std::size_t) plain].params;
  17936. const auto& b = engine.getSong().mixer[2].effects[(std::size_t) armed].params;
  17937. check ("open_audio_editor_fresh_defaults", ef::modeOf (a) == ef::Mode::onInput && ef::maxTimeIndexOf (a) == 5 && a[ef::append] >= 0.5f
  17938. && a[ef::slave] < 0.5f);
  17939. check ("open_audio_editor_and_record_preset", ef::modeOf (b) == ef::Mode::onPlay && ef::maxTimeIndexOf (b) == 3 && b[ef::append] < 0.5f
  17940. && b[ef::slave] >= 0.5f);
  17941. }
  17942. else
  17943. check ("open_audio_editor_slots_added", false);
  17944. removeItem (found, enabled);
  17945. engine.dispatchPendingMessages();
  17946. check ("remove_all_edison_asks_first", found && enabled && count() == 2);
  17947. const auto question = lynx::removeAllEdisonInstancesQuestion();
  17948. check ("remove_all_edison_question_is_fls", question.getTitle() == lynx::tr ("Remove Edison instances")
  17949. && question.getMessage() == lynx::tr ("Are you sure you want to remove all Edison instances from the project ?")
  17950. && question.getNumButtons() == 2 && question.getButtonText (0) == lynx::tr ("Yes")
  17951. && question.getButtonText (1) == lynx::tr ("No"));
  17952. // LYNX keeps an undo for the removal (rollup 190cv), so the question may not promise "(No undo)" in any
  17953. // language, and the Yes action must come back with one undo
  17954. {
  17955. bool noUndoLine = false;
  17956. for (const auto& line : juce::StringArray::fromLines (question.getMessage()))
  17957. noUndoLine = noUndoLine || line.trim().startsWithChar ('(');
  17958. check ("remove_all_edison_question_has_no_no_undo_line", ! noUndoLine && ! question.getMessage().contains ("No undo"));
  17959. const int before = count();
  17960. lynx::removeAllEdisonInstances (engine);
  17961. engine.dispatchPendingMessages();
  17962. const int removed = count();
  17963. engine.undo();
  17964. engine.dispatchPendingMessages();
  17965. check ("remove_all_edison_yes_removes_and_undo_restores", before == 2 && removed == 0 && count() == 2);
  17966. }
  17967. {
  17968. juce::AlertWindow box (question.getTitle(), question.getMessage(), question.getIconType());
  17969. box.addButton (question.getButtonText (0), 1);
  17970. box.addButton (question.getButtonText (1), 0);
  17971. box.setSize (box.getWidth(), box.getHeight());
  17972. savePng (lynx::shot::paint (box, lynx::theme::panel), folder.getChildFile ("remove-all-edison-question.png").getFullPathName());
  17973. }
  17974. {
  17975. lynx::EffectSlot slot = lynx::makeEffectSlot (lynx::EffectKind::edison);
  17976. lynx::edisonfx::setOpenAndRecord (slot.params);
  17977. engine.editSong ([&slot] (lynx::Song& s) { s.mixer[3].effects.push_back (slot); });
  17978. engine.dispatchPendingMessages();
  17979. if (const auto editor = lynx::makeEdisonSlotEditor (engine, 3, 0))
  17980. {
  17981. editor->setSize (1120, 600);
  17982. engine.dispatchPendingMessages();
  17983. shot (*editor, "slot-editor-open-and-record.png");
  17984. }
  17985. if (const auto editor = lynx::makeEdisonSlotEditor (engine, 1, plain))
  17986. {
  17987. editor->setSize (1120, 600);
  17988. engine.dispatchPendingMessages();
  17989. shot (*editor, "slot-editor-fresh-defaults.png");
  17990. }
  17991. }
  17992. }
  17993. report << (all ? "ALL OK\n" : "FAILURES\n");
  17994. folder.getChildFile ("report.txt").replaceWithText (report);
  17995. return all;
  17996. }
  17997. void runEdisonShot (const juce::String& prefix, const juce::String& file)
  17998. {
  17999. namespace ae = lynx::audioedit;
  18000. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  18001. lynx::AudioEngine offline (false);
  18002. ae::Document d;
  18003. if (file.isNotEmpty())
  18004. {
  18005. juce::MemoryBlock bytes;
  18006. if (! juce::File (file).loadFileAsData (bytes) || ! ae::decodeWav (static_cast<const std::uint8_t*> (bytes.getData()), bytes.getSize(), d))
  18007. {
  18008. std::fprintf (stderr, "edisonshot: cannot read %s\n", file.toRawUTF8());
  18009. return;
  18010. }
  18011. }
  18012. else
  18013. {
  18014. // a drum loop with a hum and hiss under it (something for the denoiser and the EQ to show)
  18015. d.title = "Drum loop";
  18016. d.audio.sampleRate = 44100.0;
  18017. const auto frames = (std::size_t) (44100 * 2);
  18018. d.audio.channels.assign (2, std::vector<float> (frames, 0.0f));
  18019. std::uint32_t seed = 7;
  18020. for (std::size_t i = 0; i < frames; ++i)
  18021. {
  18022. seed = seed * 1664525u + 1013904223u;
  18023. const auto hiss = ((float) (seed >> 8) / 16777216.0f - 0.5f) * 0.02f;
  18024. const auto hum = 0.01f * (float) std::sin (2.0 * 3.141592653589793 * 50.0 * (double) i / 44100.0);
  18025. d.audio.channels[0][i] = hiss + hum;
  18026. d.audio.channels[1][i] = hiss * 0.9f + hum;
  18027. }
  18028. for (int hit = 0; hit < 8; ++hit)
  18029. {
  18030. const auto at = (std::size_t) hit * frames / 8;
  18031. const auto kick = hit % 2 == 0;
  18032. double phase = 0.0;
  18033. for (std::size_t i = 0; i < 12000 && at + i < frames; ++i)
  18034. {
  18035. seed = seed * 1664525u + 1013904223u;
  18036. const auto noise = (float) (seed >> 8) / 16777216.0f - 0.5f;
  18037. const auto t = (double) i / 44100.0;
  18038. phase += 2.0 * 3.141592653589793 * (kick ? 45.0 + 160.0 * std::exp (-t * 30.0) : 190.0) / 44100.0;
  18039. const auto body = (float) std::sin (phase) * (float) std::exp (-t * (kick ? 9.0 : 22.0));
  18040. const auto v = kick ? 0.85f * body : 0.35f * body + 0.6f * noise * (float) std::exp (-t * 18.0);
  18041. d.audio.channels[0][at + i] += v;
  18042. d.audio.channels[1][at + i] += kick ? v : v * 0.8f;
  18043. }
  18044. }
  18045. for (int hit = 1; hit < 8; ++hit)
  18046. ae::addMarker (d, (std::int64_t) (hit * frames / 8));
  18047. ae::setLoop (d, { 0, (std::int64_t) frames });
  18048. }
  18049. // a volume envelope (a fade-in and a dip) to show the envelope mode and the envelope tools
  18050. 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 } };
  18051. auto editor = lynx::makeAudioEditorForSnapshot (offline, d, false);
  18052. auto shot = [&prefix] (juce::Component& c, const juce::String& name) {
  18053. auto image = lynx::shot::paint (c, lynx::theme::panel);
  18054. savePng (image, prefix + name);
  18055. };
  18056. editor->setSize (1120, 600);
  18057. lynx::setAudioEditorEnvelopeModeForSnapshot (*editor, 1);
  18058. shot (*editor, "-editor-volume-envelope.png");
  18059. lynx::setAudioEditorEnvelopeModeForSnapshot (*editor, 0);
  18060. juce::File (prefix + "-menu.txt").replaceWithText (lynx::audioEditorMenuForSnapshot (*editor).joinIntoString ("\n") + "\n");
  18061. // round 190ee: the first marker's menu (Trigger note) and FL's four snap modes on a probe frame
  18062. if (! d.markers.empty())
  18063. juce::File (prefix + "-marker-menu.txt").replaceWithText (lynx::audioEditorMarkerMenuForSnapshot (*editor, 0).joinIntoString ("\n") + "\n");
  18064. {
  18065. juce::StringArray snaps;
  18066. const auto probe = (std::int64_t) (d.audio.frames() * 3 / 8) + 777;
  18067. for (int mode = 0; mode < 4; ++mode)
  18068. snaps.add (lynx::setAudioEditorSnapForSnapshot (*editor, mode, probe));
  18069. juce::File (prefix + "-snap.txt").replaceWithText (snaps.joinIntoString ("\n") + "\n");
  18070. shot (*editor, "-editor-snap-on.png");
  18071. }
  18072. for (int t = 0; lynx::audioToolNameForSnapshot (t) != nullptr; ++t)
  18073. {
  18074. const auto envelopeTool = t >= 10 && t <= 14; // Scale levels .. Create sequence work on the volume envelope
  18075. if (auto panel = lynx::makeAudioToolPanelForSnapshot (*editor, t, envelopeTool ? 1 : 0))
  18076. {
  18077. offline.dispatchPendingMessages();
  18078. const auto name = juce::String (lynx::audioToolNameForSnapshot (t)).toLowerCase().retainCharacters ("abcdefghijklmnopqrstuvwxyz ").trim().replaceCharacter (' ', '-');
  18079. shot (*panel, "-tool-" + juce::String (t).paddedLeft ('0', 2) + "-" + name + ".png");
  18080. if (envelopeTool)
  18081. shot (*editor, "-tool-" + juce::String (t).paddedLeft ('0', 2) + "-" + name + "-editor.png");
  18082. panel.reset(); // (puts the envelope back)
  18083. }
  18084. }
  18085. }
  18086. static juce::TextButton* findButton (juce::Component& root, const juce::String& text)
  18087. {
  18088. if (auto* b = dynamic_cast<juce::TextButton*> (&root); b != nullptr && b->getButtonText() == text)
  18089. return b;
  18090. for (auto* child : root.getChildren())
  18091. if (auto* b = findButton (*child, text))
  18092. return b;
  18093. return nullptr;
  18094. }
  18095. // a VFX Script editor's Script / Log / API reference tabs, then the Script tab of a script with an error
  18096. void shootScriptTabs (juce::Component& panel, lynx::AudioEngine& engine, int index, const juce::String& name)
  18097. {
  18098. const std::pair<const char*, const char*> tabs[] = { { "Script", "script" }, { "Log", "log" }, { "API reference", "api" } };
  18099. for (const auto& [tab, file] : tabs)
  18100. if (auto* b = findButton (panel, lynx::tr (tab)); b != nullptr && b->onClick)
  18101. {
  18102. b->onClick();
  18103. savePng (lynx::shot::snapshot (panel), name + "-tab-" + file + ".png");
  18104. }
  18105. engine.editSong ([&] (lynx::Song& s) {
  18106. auto st = *lynx::vfx::readState (s.channels[(std::size_t) index].pluginState);
  18107. auto settings = lynx::vfx::parseScript (st.fl).value_or (lynx::vfx::defaultScript());
  18108. settings.setSource ("import flvfx as vfx\n\ndef onTriggerVoice(incomingVoice):\n v = vfx.Voice(incomingVoice)\n"
  18109. " v.note += 7\n v.trigger(\n\ndef onReleaseVoice(incomingVoice):\n pass\n");
  18110. st.fl = lynx::vfx::writeScript (settings);
  18111. s.channels[(std::size_t) index].pluginState = lynx::vfx::writeState (st);
  18112. });
  18113. engine.dispatchPendingMessages();
  18114. if (auto broken = lynx::makeChannelSettingsPanel (engine, index))
  18115. {
  18116. engine.dispatchPendingMessages();
  18117. if (auto* b = findButton (*broken, lynx::tr ("Script")); b != nullptr && b->onClick)
  18118. b->onClick();
  18119. savePng (lynx::shot::snapshot (*broken), name + "-error.png");
  18120. }
  18121. }
  18122. void runVfxShot (const juce::String& prefix)
  18123. {
  18124. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  18125. lynx::AudioEngine offline (false);
  18126. lynx::MainComponent ui (offline, false);
  18127. ui.setSize (1280, 720);
  18128. auto song = lynx::Song::makeDefault();
  18129. song.channels.clear();
  18130. for (const auto kind : lynx::vfx::allKinds)
  18131. {
  18132. lynx::ChannelDef c;
  18133. lynx::vfx::makeChannel (c, kind);
  18134. if (kind == lynx::vfx::Kind::keyMapper) // a chord on every key: something to see in the grid
  18135. for (const auto& p : lynx::vfx::builtInPresets (kind))
  18136. if (p.name == "Major triad")
  18137. {
  18138. auto st = *lynx::vfx::readState (c.pluginState);
  18139. st.fl = p.fl;
  18140. c.pluginState = lynx::vfx::writeState (st);
  18141. }
  18142. song.channels.push_back (c);
  18143. }
  18144. // a Patcher: its notes through a Color Mapper to three synths
  18145. lynx::ChannelDef patcher;
  18146. patcher.name = "Patcher";
  18147. patcher.instrument = lynx::InstrumentKind::patcher;
  18148. lynx::PatchNode mapper;
  18149. mapper.generator = true;
  18150. lynx::vfx::makeChannel (mapper.channel, lynx::vfx::Kind::colorMapper);
  18151. mapper.x = 260.0f;
  18152. patcher.patcher.nodes.push_back (mapper);
  18153. lynx::PatchWire notes;
  18154. notes.kind = lynx::PatchWire::Kind::midi, notes.to = 0;
  18155. patcher.patcher.wires.push_back (notes);
  18156. for (int k = 0; k < 3; ++k)
  18157. {
  18158. lynx::PatchNode synth;
  18159. synth.generator = true;
  18160. synth.channel.instrument = lynx::InstrumentKind::synth;
  18161. synth.channel.name = "Synth " + std::to_string (k + 1);
  18162. synth.x = 520.0f, synth.y = (float) k * 90.0f;
  18163. patcher.patcher.nodes.push_back (synth);
  18164. lynx::PatchWire in, out;
  18165. in.kind = lynx::PatchWire::Kind::midi, in.from = 0, in.fromPort = k, in.to = 1 + k;
  18166. out.from = 1 + k, out.to = lynx::patchToHost;
  18167. patcher.patcher.wires.push_back (in);
  18168. patcher.patcher.wires.push_back (out);
  18169. }
  18170. patcher.patcher.outputX = 760.0f;
  18171. song.channels.push_back (patcher);
  18172. offline.setSong (std::move (song));
  18173. offline.dispatchPendingMessages();
  18174. for (int c = 0; c < lynx::vfx::kindCount; ++c)
  18175. if (auto panel = lynx::makeChannelSettingsPanel (offline, c))
  18176. {
  18177. offline.dispatchPendingMessages();
  18178. savePng (lynx::shot::snapshot (*panel),
  18179. prefix + "-" + juce::String (lynx::vfx::flName (*lynx::vfx::kindOf (offline.getSong().channels[(std::size_t) c]))).replaceCharacter (' ', '-').toLowerCase() + ".png");
  18180. }
  18181. // with FL Studio installed: the Sequencer with FL's factory bank (to compare with FL's own editor) and
  18182. // a Script with FL's "Snap To Scale"
  18183. if (const auto roots = lynx::findFlStudioRoots(); ! roots.data.empty())
  18184. {
  18185. const auto data = juce::File (juce::String::fromUTF8 (roots.data.c_str()));
  18186. const std::pair<lynx::vfx::Kind, juce::String> extra[] = {
  18187. { lynx::vfx::Kind::sequencer, "Patches/Plugin database/Effects/Patcher/VFX Sequencer.fst" },
  18188. { lynx::vfx::Kind::script, "Patches/Plugin presets/Effects/VFX Script/Snap To Scale.fst" },
  18189. };
  18190. for (const auto& [kind, path] : extra)
  18191. {
  18192. juce::MemoryBlock bytes;
  18193. if (! data.getChildFile (path).loadFileAsData (bytes))
  18194. continue;
  18195. const auto* b = static_cast<const std::uint8_t*> (bytes.getData());
  18196. const auto fl = lynx::vfx::stateFromFlPreset (std::vector<std::uint8_t> (b, b + bytes.getSize()), kind);
  18197. int index = -1;
  18198. for (int c = 0; c < lynx::vfx::kindCount; ++c)
  18199. if (lynx::vfx::kindOf (offline.getSong().channels[(std::size_t) c]) == kind)
  18200. index = c;
  18201. if (! fl || index < 0)
  18202. continue;
  18203. offline.editSong ([&] (lynx::Song& s) {
  18204. auto st = *lynx::vfx::readState (s.channels[(std::size_t) index].pluginState);
  18205. st.fl = *fl;
  18206. s.channels[(std::size_t) index].pluginState = lynx::vfx::writeState (st);
  18207. });
  18208. offline.dispatchPendingMessages();
  18209. if (auto panel = lynx::makeChannelSettingsPanel (offline, index))
  18210. {
  18211. offline.dispatchPendingMessages();
  18212. const auto name = prefix + "-" + juce::String (lynx::vfx::flName (kind)).replaceCharacter (' ', '-').toLowerCase();
  18213. savePng (lynx::shot::snapshot (*panel), name + "-fl.png");
  18214. if (kind == lynx::vfx::Kind::script) // the editor's other tabs (round 165d)
  18215. shootScriptTabs (*panel, offline, index, name);
  18216. }
  18217. }
  18218. }
  18219. lynx::PatcherWindows::openChannel (offline, lynx::vfx::kindCount);
  18220. for (int k = 0; k < juce::TopLevelWindow::getNumTopLevelWindows(); ++k)
  18221. if (auto* w = dynamic_cast<juce::DocumentWindow*> (juce::TopLevelWindow::getTopLevelWindow (k)))
  18222. if (w->getName().startsWith (lynx::tr ("Patcher")) && w->getContentComponent() != nullptr)
  18223. {
  18224. auto* content = w->getContentComponent();
  18225. savePng (lynx::shot::snapshot (*content), prefix + "-patcher.png");
  18226. delete w;
  18227. break;
  18228. }
  18229. lynx::PatcherWindows::shootMenus (offline, true, lynx::vfx::kindCount, 0, [&] (const juce::Image& image, const juce::String& name) {
  18230. savePng (image, prefix + "-patcher-menu-" + name + ".png");
  18231. });
  18232. // a plugin renamed in the Plugin database ("1_EQ", FL): the Quick-add palette and the mixer slot show the new name
  18233. if (juce::SystemStats::getEnvironmentVariable ("LYNX_TEST_MODE", {}).isNotEmpty())
  18234. {
  18235. const auto key = std::string ("lynx:fx:") + lynx::effectInfo (lynx::EffectKind::parametricEq).name;
  18236. offline.getPluginHost().setPluginName (key, "1_EQ");
  18237. offline.editSong ([] (lynx::Song& s) {
  18238. if (s.mixer.size() > 1)
  18239. {
  18240. lynx::EffectSlot slot;
  18241. slot.kind = lynx::EffectKind::parametricEq;
  18242. s.mixer[1].effects.push_back (slot);
  18243. }
  18244. });
  18245. offline.dispatchPendingMessages();
  18246. {
  18247. lynx::QuickAddTargets targets;
  18248. targets.addInstrument = [] (lynx::ChannelDef) {};
  18249. targets.addEffect = [] (lynx::EffectSlot) {};
  18250. auto palette = lynx::makeQuickAddPalette (offline, std::move (targets));
  18251. savePng (lynx::shot::snapshot (*palette), prefix + "-quickadd-renamed.png");
  18252. }
  18253. ui.selectTabForSnapshot (3);
  18254. ui.getMixerForSnapshot().selectTrack (1);
  18255. offline.dispatchPendingMessages();
  18256. savePng (lynx::shot::snapshot (ui), prefix + "-mixer-renamed.png");
  18257. offline.getPluginHost().setPluginName (key, "");
  18258. }
  18259. }
  18260. void runAudioXShot (const juce::String& prefix)
  18261. {
  18262. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  18263. lynx::AudioEngine offline (false);
  18264. {
  18265. lynx::MainComponent ui (offline, false);
  18266. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  18267. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  18268. offline.dispatchPendingMessages();
  18269. // 1. sends: insert 1 feeds insert 3 pre-fader and insert 4 post-fader (FL's way)
  18270. offline.editSong ([] (lynx::Song& s) {
  18271. if (s.mixer.size() < 5)
  18272. return;
  18273. s.mixer[1].name = "Vocal";
  18274. s.mixer[3].name = "Reverb";
  18275. s.mixer[4].name = "Delay";
  18276. s.setRoute (1, 3, true);
  18277. s.setRoute (1, 4, true);
  18278. s.setRouteLevel (1, 3, 0.6f);
  18279. s.setRouteLevel (1, 4, 0.4f);
  18280. s.setSendPre (1, 3, true);
  18281. });
  18282. offline.dispatchPendingMessages();
  18283. ui.selectTabForSnapshot (3);
  18284. ui.getMixerForSnapshot().selectTrack (1);
  18285. offline.dispatchPendingMessages();
  18286. saveSnapshot (ui, prefix + "-send-pre.png");
  18287. auto& strips = ui.getMixerForSnapshot().getStripsForSnapshot();
  18288. saveMenus (juce::StringArray { "Send to Reverb (pre-fader)", "Send to Delay (post-fader)" },
  18289. std::vector<juce::PopupMenu> { strips.buildSendMenu (3), strips.buildSendMenu (4) }, prefix + "-send-menu.png");
  18290. // 2. low latency while recording: the monitored track's look-ahead limiter is bypassed, the EQ stays
  18291. offline.editSong ([] (lynx::Song& s) {
  18292. s.mixer[1].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::parametricEq));
  18293. s.mixer[1].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::limiter));
  18294. s.mixer[1].inputChannel = 0;
  18295. s.mixer[1].monitor = lynx::InputMonitor::on;
  18296. });
  18297. offline.dispatchPendingMessages();
  18298. saveSnapshot (ui, prefix + "-lowlat-off.png");
  18299. auto options = offline.getRecordOptions();
  18300. options.lowLatencyRecording = true;
  18301. offline.setRecordOptions (options);
  18302. offline.dispatchPendingMessages();
  18303. ui.getMixerForSnapshot().selectTrack (1);
  18304. offline.dispatchPendingMessages();
  18305. saveSnapshot (ui, prefix + "-lowlat-on.png");
  18306. saveMenus (juce::StringArray { "Record" }, std::vector<juce::PopupMenu> { ui.getFullRecordMenuForSnapshot() }, prefix + "-lowlat-menu.png");
  18307. juce::String report;
  18308. report << "latency_with_option=" << offline.getLatencySamples() << " bypassed_slots=" << offline.lowLatencyBypassedCount() << "\n";
  18309. options.lowLatencyRecording = false;
  18310. offline.setRecordOptions (options);
  18311. offline.dispatchPendingMessages();
  18312. report << "latency_without_option=" << offline.getLatencySamples() << "\n";
  18313. // 3. the Browser's "Preview in time": a 120 BPM loop previewed in a 140 BPM project
  18314. const auto dir = juce::File (prefix).getParentDirectory().getChildFile ("audiox-preview");
  18315. dir.createDirectory();
  18316. const auto wav = dir.getChildFile ("Drum loop 120 bpm.wav");
  18317. {
  18318. const int frames = 44100 * 4;
  18319. juce::AudioBuffer<float> audio (1, frames);
  18320. for (int i = 0; i < frames; ++i)
  18321. {
  18322. const auto t = (double) (i % 22050) / 44100.0;
  18323. 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)));
  18324. }
  18325. wav.deleteFile();
  18326. juce::WavAudioFormat format;
  18327. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  18328. if (auto* w = format.createWriterFor (out.get(), 44100.0, 1, 16, {}, 0))
  18329. {
  18330. out.release();
  18331. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  18332. writer->writeFromAudioSampleBuffer (audio, 0, frames);
  18333. }
  18334. }
  18335. offline.getTransport().bpm.store (140.0);
  18336. offline.setPreviewInTime (true);
  18337. ui.showDesktopForSnapshot (false);
  18338. offline.previewFile (wav);
  18339. offline.finishPreviewJobs();
  18340. ui.getBrowserForSnapshot().showPreviewForSnapshot (wav);
  18341. offline.dispatchPendingMessages();
  18342. saveSnapshot (ui, prefix + "-preview-in-time.png");
  18343. saveMenus (juce::StringArray { "Browser options" }, std::vector<juce::PopupMenu> { ui.getBrowserForSnapshot().buildViewMenu() }, prefix + "-preview-menu.png");
  18344. const auto& timing = offline.getPreviewTiming();
  18345. report << "preview file_bpm=" << timing.fileBpm << " project_bpm=" << timing.projectBpm << " ratio=" << timing.ratio
  18346. << " prepare_ms=" << juce::String (offline.getLastPreviewPrepareMs(), 1) << "\n";
  18347. offline.previewFile ({});
  18348. offline.setPreviewInTime (false);
  18349. juce::File (prefix + "-report.txt").replaceWithText (report);
  18350. }
  18351. }
  18352. void runComp177Shot (const juce::String& prefix, const juce::String& projectPath)
  18353. {
  18354. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  18355. lynx::AudioEngine offline (false);
  18356. {
  18357. lynx::MainComponent ui (offline, false);
  18358. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  18359. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  18360. ui.openFile (juce::File (projectPath));
  18361. offline.dispatchPendingMessages();
  18362. ui.selectTabForSnapshot (2);
  18363. offline.dispatchPendingMessages();
  18364. auto& playlist = ui.getPlaylistForSnapshot();
  18365. std::int64_t last = 0;
  18366. for (const auto& c : offline.getSong().playlist)
  18367. last = std::max (last, c.end());
  18368. const auto bars = juce::jmax (1, (int) (last / (4 * lynx::ppq)) + 1);
  18369. playlist.setViewForSnapshot (juce::jmax (60.0, (ui.getWidth() - 300.0) / bars), 0, 0);
  18370. // (the first paint asks for the clips' waveforms, a worker thread loads them)
  18371. saveSnapshot (ui, prefix + "-opened.png");
  18372. juce::Thread::sleep (3000);
  18373. offline.dispatchPendingMessages();
  18374. saveSnapshot (ui, prefix + "-opened.png");
  18375. // a muted clip selected
  18376. for (int c = 0; c < (int) offline.getSong().playlist.size(); ++c)
  18377. if (offline.getSong().playlist[(std::size_t) c].muted)
  18378. {
  18379. playlist.selectClipsForSnapshot ({ c });
  18380. offline.dispatchPendingMessages();
  18381. saveSnapshot (ui, prefix + "-selected.png");
  18382. playlist.selectClipsForSnapshot ({});
  18383. break;
  18384. }
  18385. juce::String report;
  18386. const auto listTracks = [&offline, &report] (const juce::String& title) {
  18387. const auto& s = offline.getSong();
  18388. report << title << "\n";
  18389. for (int t = 0; t < (int) s.playlistTracks.size(); ++t)
  18390. {
  18391. int clips = 0, muted = 0;
  18392. for (const auto& c : s.playlist)
  18393. if (c.track == t)
  18394. ++clips, muted += c.muted ? 1 : 0;
  18395. const auto& pt = s.playlistTracks[(std::size_t) t];
  18396. if (clips > 0 || pt.grouped || ! pt.name.empty())
  18397. report << "track " << (t + 1) << " '" << juce::String::fromUTF8 (pt.name.c_str()) << "' grouped=" << (pt.grouped ? 1 : 0) << " collapsed=" << (pt.collapsed ? 1 : 0)
  18398. << " comp=" << (pt.compTrack ? 1 : 0) << " clips=" << clips << " muted=" << muted << "\n";
  18399. }
  18400. };
  18401. listTracks ("opened");
  18402. // the first group's header (a member's menu holds "Comp these takes" too)
  18403. int firstGroup = -1;
  18404. for (int t = 0; t < (int) offline.getSong().playlistTracks.size() && firstGroup < 0; ++t)
  18405. if (lynx::comp::canComp (offline.getSong(), t))
  18406. firstGroup = t;
  18407. report << "first group with takes: track " << (firstGroup + 1) << "\n";
  18408. if (firstGroup >= 0)
  18409. {
  18410. saveMenus (juce::StringArray { "Playlist track" }, std::vector<juce::PopupMenu> { playlist.getTrackMenuForSnapshot (firstGroup) }, prefix + "-trackmenu.png");
  18411. int comp = -1;
  18412. offline.editSong ([firstGroup, &comp] (lynx::Song& s) { comp = lynx::comp::compTakes (s, firstGroup); });
  18413. offline.dispatchPendingMessages();
  18414. saveSnapshot (ui, prefix + "-comped.png");
  18415. listTracks ("after Comp these takes");
  18416. const auto g = lynx::comp::groupOf (offline.getSong(), comp);
  18417. std::int64_t from = -1, to = 0;
  18418. for (const auto& c : offline.getSong().playlist)
  18419. if (c.track == g.first)
  18420. from = from < 0 ? c.start : std::min (from, c.start), to = std::max (to, c.end());
  18421. if (g.valid() && to > from)
  18422. {
  18423. offline.editSong ([&g, from, to] (lynx::Song& s) { lynx::comp::swipe (s, g.first, from + (to - from) / 4, from + (to - from) / 2); });
  18424. offline.dispatchPendingMessages();
  18425. saveSnapshot (ui, prefix + "-swiped.png");
  18426. listTracks ("after a swipe of the middle of the first lane");
  18427. // a lane auditioned; the crossfade close up; the comp flattened
  18428. offline.editSong ([&g] (lynx::Song& s) { lynx::comp::setAudition (s, g.first); }, false);
  18429. offline.dispatchPendingMessages();
  18430. saveSnapshot (ui, prefix + "-audition.png");
  18431. offline.editSong ([] (lynx::Song& s) { lynx::comp::setAudition (s, -1); }, false);
  18432. const auto switchAt = from + (to - from) / 4;
  18433. playlist.setViewForSnapshot (4.0 * 4.0 * lynx::ppq, 0, 0);
  18434. playlist.setScrollTickForSnapshot ((double) (switchAt - 100));
  18435. juce::Thread::sleep (1500);
  18436. offline.dispatchPendingMessages();
  18437. saveSnapshot (ui, prefix + "-crossfade.png");
  18438. playlist.setViewForSnapshot (juce::jmax (60.0, (ui.getWidth() - 300.0) / bars), 0, 0);
  18439. offline.editSong ([comp] (lynx::Song& s) { lynx::comp::flatten (s, comp); });
  18440. offline.dispatchPendingMessages();
  18441. saveSnapshot (ui, prefix + "-flattened.png");
  18442. listTracks ("after Flatten comp");
  18443. }
  18444. }
  18445. saveMenus (juce::StringArray { "Record" }, std::vector<juce::PopupMenu> { ui.getRecordMenuForSnapshot() }, prefix + "-recordmenu.png");
  18446. juce::File (prefix + "-tracks.txt").replaceWithText (report);
  18447. }
  18448. }
  18449. // Round 190bx: the Settings pages alone (the full --snapshot takes minutes). prefix-settings-<page>.png at the
  18450. // window's size, -small.png at 390 x 390 (rows must scroll, never be cut off or squeezed) and -whole.png tall
  18451. // enough to show every row of the page.
  18452. void runSettingsShot (const juce::String& prefix)
  18453. {
  18454. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  18455. {
  18456. lynx::AudioEngine offline (false);
  18457. offline.editSong ([] (lynx::Song& s) {
  18458. s.info = { "Night Drive", "LYNX SHARE demo", "Synthwave", "https://lynx-share.com",
  18459. "Made with LYNX SHARE.\nDrums and bass from the Channel Rack, pads from the Browser.", false };
  18460. }, false);
  18461. auto shoot = [&] (lynx::SettingsPage page, const juce::String& name, int width, int height) {
  18462. auto panel = lynx::makeSettingsPanel (offline, page);
  18463. if (width > 0)
  18464. panel->setSize (width, height);
  18465. juce::Component frame;
  18466. frame.setSize (panel->getWidth(), panel->getHeight());
  18467. frame.addAndMakeVisible (*panel);
  18468. panel->setTopLeftPosition (0, 0);
  18469. juce::Image image (juce::Image::ARGB, frame.getWidth(), frame.getHeight(), true);
  18470. {
  18471. juce::Graphics g (image);
  18472. g.fillAll (lynx::theme::panel);
  18473. frame.paintEntireComponent (g, false);
  18474. }
  18475. savePng (image, prefix + "-settings-" + name + ".png");
  18476. };
  18477. const std::pair<lynx::SettingsPage, const char*> pages[] = { { lynx::SettingsPage::audio, "audio" }, { lynx::SettingsPage::midi, "midi" },
  18478. { lynx::SettingsPage::general, "general" }, { lynx::SettingsPage::theme, "theme" },
  18479. { lynx::SettingsPage::files, "files" }, { lynx::SettingsPage::extras, "extras" },
  18480. { lynx::SettingsPage::project, "project" }, { lynx::SettingsPage::info, "info" } };
  18481. for (const auto& [page, name] : pages)
  18482. {
  18483. shoot (page, name, 0, 0);
  18484. shoot (page, juce::String (name) + "-small", 390, 390);
  18485. }
  18486. shoot (lynx::SettingsPage::audio, "audio-whole", 680, 1500);
  18487. shoot (lynx::SettingsPage::general, "general-whole", 680, 2400); // (round 190gh: + the Updates section's previous-version row)
  18488. }
  18489. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  18490. }
  18491. // round 190bw: FL's 13 curve modes of an automation clip's points (see --curveshot)
  18492. bool runTrackModeShot (const juce::String& prefix)
  18493. {
  18494. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  18495. lynx::AudioEngine offline (false);
  18496. bool all = true;
  18497. juce::String report;
  18498. {
  18499. lynx::MainComponent ui (offline, false);
  18500. ui.setSize (1600, 900);
  18501. offline.dispatchPendingMessages();
  18502. auto& playlist = ui.getPlaylistForSnapshot();
  18503. // the track's menu, Track mode and Audio track side by side; the Audio track entries as FL writes them
  18504. // ("-" in front = greyed, "v" = ticked)
  18505. const auto shoot = [&] (int track, const juce::String& name, const juce::StringArray& fl) {
  18506. const auto menu = playlist.getTrackMenuForSnapshot (track);
  18507. juce::StringArray names { "Track " + juce::String (track + 1) };
  18508. std::vector<juce::PopupMenu> menus { menu };
  18509. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  18510. if (it.getItem().subMenu != nullptr && it.getItem().text == lynx::theme::mnemonic (lynx::tr ("Track mode"), 'T'))
  18511. {
  18512. names.add (lynx::tr ("Track mode"));
  18513. menus.push_back (*it.getItem().subMenu);
  18514. }
  18515. if (menus.size() == 2)
  18516. for (juce::PopupMenu::MenuItemIterator it (menus[1]); it.next();)
  18517. if (it.getItem().subMenu != nullptr && it.getItem().text == lynx::theme::mnemonic (lynx::tr ("Audio track"), 'A'))
  18518. {
  18519. names.add (lynx::tr ("Audio track"));
  18520. menus.push_back (*it.getItem().subMenu);
  18521. }
  18522. juce::StringArray lynxList;
  18523. if (menus.size() == 3)
  18524. for (juce::PopupMenu::MenuItemIterator it (menus[2]); it.next();)
  18525. lynxList.add (it.getItem().isSeparator ? juce::String ("|")
  18526. : (it.getItem().isTicked ? "v " : "") + juce::String (it.getItem().isEnabled ? "" : "- ") + it.getItem().text);
  18527. saveMenus (names, menus, prefix + "-" + name + ".png");
  18528. const auto same = menus.size() == 3 && lynxList == fl;
  18529. all = all && same;
  18530. report << name << ": " << (same ? "SAME AS FL" : "DIFFERENT") << "\n LYNX: " << lynxList.joinIntoString (" / ")
  18531. << "\n FL: " << fl.joinIntoString (" / ") << "\n";
  18532. };
  18533. const auto flList = [] (int inserts, std::map<int, juce::String> named, std::set<int> greyed) {
  18534. juce::StringArray l { "New mixer track(s)", "|" };
  18535. for (int i = 1; i <= inserts; ++i)
  18536. l.add ((greyed.count (i) ? "- " : "") + juce::String (i) + ". " + (named.count (i) ? named[i] : "Insert " + juce::String (i)));
  18537. return l;
  18538. };
  18539. // q1-01: a fresh project, Track 1 unassigned
  18540. shoot (0, "fresh", flList (16, {}, {}));
  18541. // q1-02: Track 1 linked to insert 6, insert 7 renamed "Vox chain"; Track 2's menu
  18542. offline.editSong ([] (lynx::Song& s) {
  18543. lynx::trackmodes::assignAudioTracks (s, { 0 }, 6);
  18544. s.mixer[7].name = "Vox chain";
  18545. });
  18546. offline.dispatchPendingMessages();
  18547. shoot (1, "linked-renamed", flList (16, { { 7, "Vox chain" } }, { 6 }));
  18548. // q1-07: the rest of FL's session (live 190cu Q2): Track 3 → 7; Track 4 → New mixer track (17), insert 9
  18549. // renamed "Vox chain", Track 4 → 9; Track 5 "Lead" → 11, insert 12 "Vox chain", Track 5 → 12; Track 6 "Lead"
  18550. // (unassigned), insert 13 "Vox chain", Track 6 → 13. Track 7's menu
  18551. offline.editSong ([] (lynx::Song& s) {
  18552. namespace tm = lynx::trackmodes;
  18553. if (s.playlistTracks.size() < 8)
  18554. s.playlistTracks.resize (8);
  18555. tm::assignAudioTracks (s, { 2 }, 7);
  18556. tm::assignAudioTracks (s, { 3 }, tm::newMixerTrack);
  18557. s.mixer[9].name = "Vox chain";
  18558. tm::assignAudioTracks (s, { 3 }, 9);
  18559. s.playlistTracks[4].name = "Lead";
  18560. tm::assignAudioTracks (s, { 4 }, 11);
  18561. s.mixer[12].name = "Vox chain";
  18562. tm::assignAudioTracks (s, { 4 }, 12);
  18563. s.playlistTracks[5].name = "Lead";
  18564. s.mixer[13].name = "Vox chain";
  18565. tm::assignAudioTracks (s, { 5 }, 13);
  18566. });
  18567. offline.dispatchPendingMessages();
  18568. shoot (6, "full-state", flList (17, { { 7, "Vox chain" }, { 9, "Insert 17" }, { 12, "Lead" }, { 13, "Vox chain" } }, { 6, 7, 9, 12, 13 }));
  18569. }
  18570. report << (all ? "ALL SAME AS FL\n" : "FAILURES\n");
  18571. juce::File (prefix + "-report.txt").replaceWithText (report);
  18572. return all;
  18573. }
  18574. void runCurveShot (const juce::String& prefix)
  18575. {
  18576. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  18577. lynx::AudioEngine offline (false);
  18578. {
  18579. lynx::MainComponent ui (offline, false);
  18580. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  18581. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  18582. offline.dispatchPendingMessages();
  18583. // FL's menu order, one bar per mode, the levels going up and down; a tension where the mode needs one to show
  18584. static const int order[] = { lynx::flcurve::smooth, lynx::flcurve::hold, lynx::flcurve::singleCurve, lynx::flcurve::singleCurve2,
  18585. lynx::flcurve::singleCurve3, lynx::flcurve::doubleCurve, lynx::flcurve::doubleCurve2, lynx::flcurve::doubleCurve3,
  18586. lynx::flcurve::halfSine, lynx::flcurve::stairs, lynx::flcurve::smoothStairs, lynx::flcurve::pulse, lynx::flcurve::wave };
  18587. const auto bar = (std::int64_t) lynx::ppq * 4;
  18588. offline.editSong ([bar] (lynx::Song& song) {
  18589. song.mode = lynx::PlayMode::song;
  18590. lynx::Automation a;
  18591. a.name = "Curve modes";
  18592. a.target = { lynx::AutomationTargetKind::mixerVolume, 1 };
  18593. a.points.push_back ({ 0, 0.15f, 0.0f });
  18594. int k = 0;
  18595. for (const auto mode : order)
  18596. {
  18597. const auto stepped = mode == lynx::flcurve::stairs || mode == lynx::flcurve::smoothStairs || mode == lynx::flcurve::pulse || mode == lynx::flcurve::wave;
  18598. a.points.back().mode = (std::uint8_t) mode;
  18599. a.points.back().tension = mode == lynx::flcurve::smooth || mode == lynx::flcurve::hold ? 0.0f : stepped ? -0.72f : (k % 2 == 0 ? 0.55f : -0.55f);
  18600. ++k;
  18601. a.points.push_back ({ bar * k, k % 2 == 1 ? 0.85f : 0.15f, 0.0f });
  18602. }
  18603. song.automations.insert (song.automations.begin(), a);
  18604. for (auto& c : song.playlist)
  18605. if (c.kind == lynx::ClipKind::automation)
  18606. ++c.automation;
  18607. lynx::Clip clip;
  18608. clip.kind = lynx::ClipKind::automation;
  18609. clip.automation = 0;
  18610. clip.track = 3;
  18611. clip.length = bar * 13;
  18612. song.playlist.push_back (clip);
  18613. if (song.playlistTracks.size() < 4)
  18614. song.playlistTracks.resize (4);
  18615. song.playlistTracks[3].height = 150;
  18616. }, false);
  18617. offline.dispatchPendingMessages();
  18618. ui.selectTabForSnapshot (2);
  18619. offline.dispatchPendingMessages();
  18620. auto& playlist = ui.getPlaylistForSnapshot();
  18621. saveSnapshot (ui, prefix + "-playlist.png");
  18622. const auto clipIndex = (int) offline.getSong().playlist.size() - 1;
  18623. // the point menu of the point that ends the "Stairs" segment (point 10), and of the first point
  18624. saveMenus (juce::StringArray { "Automation point (ends a Stairs segment)", "First point" },
  18625. std::vector<juce::PopupMenu> { playlist.getAutomationPointMenuForSnapshot (clipIndex, 10), playlist.getAutomationPointMenuForSnapshot (clipIndex, 0) },
  18626. prefix + "-point-menu.png");
  18627. auto editor = lynx::makeAutomationEditor (offline, 0);
  18628. editor->setSize (1500, 420);
  18629. savePng (editor->createComponentSnapshot (editor->getLocalBounds()), prefix + "-editor.png");
  18630. editor.reset();
  18631. // the project itself, for --export-flp and a look at the same clip in FL
  18632. {
  18633. juce::String saveError;
  18634. lynx::ProjectFile::save (offline.getSong(), juce::File (prefix + "-modes.lynx"), saveError);
  18635. }
  18636. // part 2: the Piano roll tools that gained FL's options (they preview on the pattern and put the notes back)
  18637. ui.selectTabForSnapshot (1);
  18638. offline.dispatchPendingMessages();
  18639. auto& roll = ui.getPianoRollForSnapshot();
  18640. const std::pair<lynx::NoteTool, const char*> tools[] = { { lynx::NoteTool::flip, "-tool-flip.png" },
  18641. { lynx::NoteTool::limit, "-tool-limit.png" },
  18642. { lynx::NoteTool::scaleLevels, "-tool-scalelevels.png" },
  18643. { lynx::NoteTool::randomise, "-tool-randomise.png" },
  18644. { lynx::NoteTool::lfo, "-tool-lfo.png" } };
  18645. // round 190ct: checks of the FL-live fixes, one line each in <prefix>-checks.txt (OK / FAIL)
  18646. juce::StringArray checks;
  18647. const auto check = [&checks] (bool ok, const juce::String& what) { checks.add ((ok ? "OK " : "FAIL ") + what); };
  18648. {
  18649. juce::String header;
  18650. const auto pointMenu = playlist.getAutomationPointMenuForSnapshot (clipIndex, 10); // (the iterator keeps a reference)
  18651. for (juce::PopupMenu::MenuItemIterator it (pointMenu); it.next();)
  18652. {
  18653. header = it.getItem().text;
  18654. break;
  18655. }
  18656. check (header == "Point 11/14", "point menu header \"" + header + "\" (FL: \"Point n/N\")");
  18657. }
  18658. for (const auto& [tool, name] : tools)
  18659. {
  18660. auto panel = lynx::makeNoteToolPanel (offline, tool, roll.noteIndicesForSnapshot(), roll.gridForSnapshot());
  18661. offline.dispatchPendingMessages();
  18662. savePng (panel->createComponentSnapshot (panel->getLocalBounds()), prefix + name);
  18663. if (tool == lynx::NoteTool::flip)
  18664. {
  18665. std::vector<juce::ToggleButton*> toggles;
  18666. for (auto* child : panel->getChildren())
  18667. if (auto* t = dynamic_cast<juce::ToggleButton*> (child))
  18668. toggles.push_back (t);
  18669. check (toggles.size() == 3 && toggles[0]->getToggleState() && toggles[1]->getToggleState() && ! toggles[2]->getToggleState(),
  18670. "flip opens with Flip horizontally on, Preserve start times on, Flip vertically off");
  18671. if (toggles.size() == 3)
  18672. {
  18673. toggles[2]->setToggleState (true, juce::sendNotificationSync);
  18674. check (! toggles[0]->getToggleState() && toggles[2]->getToggleState(), "flip: vertically turns horizontally off (radios)");
  18675. toggles[0]->setToggleState (true, juce::sendNotificationSync);
  18676. check (toggles[0]->getToggleState() && ! toggles[2]->getToggleState(), "flip: horizontally turns vertically off (radios)");
  18677. }
  18678. }
  18679. if (tool == lynx::NoteTool::limit)
  18680. {
  18681. auto* list = lynx::noteToolLongestChoiceForSnapshot (*panel);
  18682. juce::ComboBox* key = nullptr;
  18683. for (auto* child : panel->getChildren())
  18684. if (auto* box = dynamic_cast<juce::ComboBox*> (child); box != nullptr && box->getNumItems() == 12)
  18685. key = box;
  18686. check (list != nullptr && list->getNumItems() == 89, "limit list has (none) + 66 chords + 22 scales: "
  18687. + juce::String (list != nullptr ? list->getNumItems() : 0));
  18688. check (list != nullptr && key != nullptr && list->getY() == key->getY() && list->getX() > key->getRight(),
  18689. "limit: Key and the chord / scale list share one row");
  18690. if (list != nullptr)
  18691. saveMenus (juce::StringArray { "Limit: Key / scale list" }, std::vector<juce::PopupMenu> { *list->getRootMenu() },
  18692. prefix + "-tool-limit-list.png");
  18693. }
  18694. if (tool == lynx::NoteTool::lfo)
  18695. saveMenus (juce::StringArray { "LFO tool: right-click on a Period slider" },
  18696. std::vector<juce::PopupMenu> { lynx::noteToolPresetMenuForSnapshot (*panel) }, prefix + "-tool-lfo-steps.png");
  18697. }
  18698. juce::File (prefix + "-checks.txt").replaceWithText (checks.joinIntoString ("\n") + "\n");
  18699. }
  18700. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  18701. }
  18702. bool runEvPaneShot (const juce::String& prefix, const juce::String& projectPath)
  18703. {
  18704. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  18705. lynx::AudioEngine offline (false);
  18706. juce::StringArray report;
  18707. bool ok = true;
  18708. {
  18709. lynx::MainComponent ui (offline, false);
  18710. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  18711. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  18712. if (projectPath.isNotEmpty())
  18713. ui.openFile (juce::File (projectPath));
  18714. offline.dispatchPendingMessages();
  18715. ui.selectTabForSnapshot (1); // the Piano Roll
  18716. offline.dispatchPendingMessages();
  18717. auto& roll = ui.getPianoRollForSnapshot();
  18718. roll.scrollToNotes();
  18719. const auto area = ui.getLocalArea (&roll, roll.getLocalBounds());
  18720. const auto file = lynx::platform::settingsFile ("piano-roll-event-pane.txt");
  18721. auto source = juce::Desktop::getInstance().getMainMouseSource();
  18722. const auto now = juce::Time::getCurrentTime();
  18723. auto event = [&] (juce::Point<int> p, juce::Point<int> down, juce::ModifierKeys mods, int clicks, bool dragged) {
  18724. return juce::MouseEvent (source, p.toFloat(), mods, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, &roll, &roll, now, down.toFloat(), now, clicks, dragged);
  18725. };
  18726. auto barCentre = [&roll] { return roll.eventPaneBarArea().getCentre(); };
  18727. const juce::ModifierKeys left (juce::ModifierKeys::leftButtonModifier), right (juce::ModifierKeys::rightButtonModifier),
  18728. middle (juce::ModifierKeys::middleButtonModifier);
  18729. auto click = [&] (juce::ModifierKeys button, int clicks) {
  18730. const auto at = barCentre();
  18731. roll.mouseDown (event (at, at, button, clicks, false));
  18732. roll.mouseUp (event (at, at, {}, clicks, false));
  18733. offline.dispatchPendingMessages();
  18734. };
  18735. auto dragTo = [&] (int y) {
  18736. const auto at = barCentre();
  18737. roll.mouseDown (event (at, at, left, 1, false));
  18738. for (int step = 1; step <= 8; ++step) // (a few moves, as a hand does)
  18739. roll.mouseDrag (event ({ at.x, at.y + (y - at.y) * step / 8 }, at, left, 1, true));
  18740. roll.mouseUp (event ({ at.x, y }, at, {}, 1, true));
  18741. offline.dispatchPendingMessages();
  18742. };
  18743. auto state = [&] (const juce::String& name) {
  18744. const auto grid = roll.getHeight() - lynx::PianoRollComponent::headerHeight - roll.velocityHeight - lynx::evpane::barThickness;
  18745. const auto& st = lynx::PianoRollComponent::eventPaneState();
  18746. report.add (name + ": roll " + juce::String (roll.getHeight()) + " px, grid " + juce::String (juce::jmax (0, grid)) + " px, bar top "
  18747. + juce::String (roll.eventPaneBarTopForTests()) + ", event editor " + juce::String (roll.velocityHeight) + " px, aspect "
  18748. + juce::String (st.aspect, 4) + ", spare " + juce::String (st.spare, 4) + ", file \"" + file.loadFileAsString().trim().replace ("\n", " ") + "\"");
  18749. saveArea (ui, area, prefix + "-" + name + ".png");
  18750. };
  18751. auto expect = [&] (bool condition, const juce::String& what) {
  18752. report.add ((condition ? "PASS " : "FAIL ") + what);
  18753. ok = ok && condition;
  18754. };
  18755. state ("1-default");
  18756. const auto defaultLane = roll.velocityHeight;
  18757. expect (std::abs (lynx::PianoRollComponent::eventPaneState().aspect - 0.8f) < 1e-6f, "default place is FL's 0.8");
  18758. ui.setHintForSnapshot (roll.hintAt (barCentre()));
  18759. saveSnapshot (ui, prefix + "-2-hover-hint.png");
  18760. ui.setHintForSnapshot ({});
  18761. const auto travelTop = lynx::PianoRollComponent::headerHeight, travelBottom = roll.getHeight() - lynx::evpane::barThickness;
  18762. dragTo (travelTop + (travelBottom - travelTop) * 45 / 100);
  18763. state ("3-dragged-larger");
  18764. const auto largeLane = roll.velocityHeight;
  18765. expect (largeLane > defaultLane * 2, "drag up makes the event editor taller");
  18766. expect (lynx::evpane::fromText (file.loadFileAsString().toStdString()) == lynx::PianoRollComponent::eventPaneState(),
  18767. "the place is written to the settings file on release");
  18768. click (right, 1);
  18769. state ("4-right-click-alternate");
  18770. expect (roll.velocityHeight == 0, "right-click: the alternate size (FL's spare 1.0) folds the event editor away");
  18771. click (right, 1);
  18772. state ("5-right-click-back");
  18773. expect (roll.velocityHeight == largeLane, "right-click again: back to the dragged size");
  18774. roll.runAction ("pianoRoll.eventPaneAlternate");
  18775. offline.dispatchPendingMessages();
  18776. expect (roll.velocityHeight == 0, "Shift+Enter (pianoRoll.eventPaneAlternate) swaps too");
  18777. roll.runAction ("pianoRoll.eventPaneAlternate");
  18778. offline.dispatchPendingMessages();
  18779. dragTo (travelTop + 10);
  18780. state ("6-grid-folded");
  18781. expect (roll.eventPaneBarTopForTests() == travelTop, "a drag within 23 px of the top folds the note grid away");
  18782. click (middle, 1);
  18783. state ("7-middle-click-default");
  18784. expect (roll.velocityHeight == defaultLane, "middle-click: back to the default place");
  18785. // a taller window keeps the proportion (the place is a fraction of the travel)
  18786. dragTo (travelTop + (travelBottom - travelTop) * 60 / 100);
  18787. const auto before = lynx::PianoRollComponent::eventPaneState().aspect;
  18788. roll.setSize (roll.getWidth(), roll.getHeight() + 200);
  18789. offline.dispatchPendingMessages();
  18790. const auto newTravel = roll.getHeight() - lynx::evpane::barThickness - travelTop;
  18791. expect (std::abs (roll.eventPaneBarTopForTests() - (travelTop + juce::roundToInt (before * (float) newTravel))) <= 1,
  18792. "a taller window keeps the proportion");
  18793. roll.setSize (roll.getWidth(), roll.getHeight() - 200);
  18794. offline.dispatchPendingMessages();
  18795. click (middle, 1); // leave FL's default behind
  18796. }
  18797. report.add (ok ? "RESULT OK" : "RESULT FAIL");
  18798. juce::File (prefix + "-report.txt").replaceWithText (report.joinIntoString ("\n") + "\n");
  18799. return ok;
  18800. }
  18801. void runFeat166Shot (const juce::String& prefix, const juce::String& projectPath)
  18802. {
  18803. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  18804. lynx::AudioEngine offline (false);
  18805. {
  18806. lynx::MainComponent ui (offline, false);
  18807. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  18808. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  18809. if (projectPath.isNotEmpty())
  18810. ui.openFile (juce::File (projectPath));
  18811. offline.dispatchPendingMessages();
  18812. ui.selectTabForSnapshot (1); // the Piano Roll, on the channel with the most notes
  18813. offline.dispatchPendingMessages();
  18814. // the scale the pattern's notes fit best (major / minor, any root)
  18815. const auto& song = offline.getSong();
  18816. const auto& notes = song.patterns[(std::size_t) song.currentPattern].notes;
  18817. int bestRoot = 0, bestScale = 1, bestHits = -1;
  18818. for (int sc = 1; sc < (int) lynx::notetools::scales().size(); ++sc)
  18819. {
  18820. const juce::String name (lynx::notetools::scales()[(std::size_t) sc].name);
  18821. if (name != "Major" && name != "Minor")
  18822. continue;
  18823. for (int root = 0; root < 12; ++root)
  18824. {
  18825. int hits = 0;
  18826. for (const auto& n : notes)
  18827. hits += lynx::notetools::inScale (n.key, root, sc) ? 1 : 0;
  18828. if (hits > bestHits)
  18829. bestHits = hits, bestRoot = root, bestScale = sc;
  18830. }
  18831. }
  18832. auto& roll = ui.getPianoRollForSnapshot();
  18833. roll.setScaleForSnapshot (bestRoot, bestScale);
  18834. roll.scrollToNotes();
  18835. offline.dispatchPendingMessages();
  18836. saveSnapshot (ui, prefix + "-pr-scale.png");
  18837. roll.setFoldToScale (true);
  18838. offline.dispatchPendingMessages();
  18839. saveSnapshot (ui, prefix + "-pr-folded.png");
  18840. roll.setFoldToScale (false);
  18841. // ghost channels: only the first other channel with notes stays a ghost
  18842. const auto selected = offline.getSelectedChannel();
  18843. int keep = -1;
  18844. for (const auto& n : notes)
  18845. if (n.channel != selected && keep < 0)
  18846. keep = n.channel;
  18847. offline.editSong ([keep] (lynx::Song& s) {
  18848. for (int c = 0; c < (int) s.channels.size(); ++c)
  18849. s.channels[(std::size_t) c].ghostHidden = c != keep;
  18850. }, false);
  18851. offline.dispatchPendingMessages();
  18852. saveSnapshot (ui, prefix + "-pr-ghost-one.png");
  18853. saveMenus (juce::StringArray { "Ghost channels" }, { roll.ghostChannelsMenu() }, prefix + "-ghostmenu.png");
  18854. offline.editSong ([] (lynx::Song& s) {
  18855. for (auto& c : s.channels)
  18856. c.ghostHidden = false;
  18857. }, false);
  18858. // the Mixer at 500 inserts
  18859. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  18860. offline.editSong ([] (lynx::Song& s) { lynx::mixerops::insertTracks (s, (int) s.mixer.size(), lynx::mixerops::roomForInserts (s)); }, false);
  18861. const auto t1 = juce::Time::getMillisecondCounterHiRes();
  18862. offline.dispatchPendingMessages();
  18863. ui.selectTabForSnapshot (3);
  18864. offline.dispatchPendingMessages();
  18865. auto& mixer = ui.getMixerForSnapshot();
  18866. const auto t2 = juce::Time::getMillisecondCounterHiRes();
  18867. saveSnapshot (ui, prefix + "-mixer500-start.png");
  18868. const auto t3 = juce::Time::getMillisecondCounterHiRes();
  18869. mixer.selectTrack ((int) offline.getSong().mixer.size() - 1);
  18870. offline.dispatchPendingMessages();
  18871. saveSnapshot (ui, prefix + "-mixer500-end.png");
  18872. juce::File (prefix + "-mixer500.txt")
  18873. .replaceWithText ("inserts=" + juce::String ((int) offline.getSong().mixer.size() - 1) + "\nfill_ms=" + juce::String (t1 - t0, 2)
  18874. + "\nsnapshot_ms=" + juce::String (t3 - t2, 2) + "\n");
  18875. }
  18876. }
  18877. // Round 190ay, Freeze, end to end with the real engine, files and export (LYNX.exe --freezetest prefix [project]).
  18878. // The project (.lynx / .flp / .als; without one, a small demo song) is rendered live, every channel that can be
  18879. // frozen is frozen, and the same render is made again: the two mixes must null. Written to prefix-report.txt: the
  18880. // null residual, the process memory and the render time before / frozen / unfrozen, what a save holds, whether
  18881. // Unfreeze gives the channels back as they were, the out-of-date and missing-audio states. Shots: the Channel Rack
  18882. // (live, frozen, out of date), the channel menus, the Piano roll of a frozen channel. The frozen audio goes to
  18883. // prefix-data (never next to the project). True = every check passed.
  18884. bool runFreezeTest (const juce::String& prefix, const juce::String& projectPath, const juce::String& mode = {})
  18885. {
  18886. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  18887. lynx::AudioEngine offline (false);
  18888. lynx::MainComponent ui (offline, false);
  18889. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  18890. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  18891. const auto write = [&prefix, &ui] (const char* name) {
  18892. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  18893. file.deleteFile();
  18894. juce::FileOutputStream out (file);
  18895. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (ui), out);
  18896. };
  18897. juce::String report;
  18898. int failures = 0;
  18899. const auto check = [&] (bool ok, const juce::String& what) {
  18900. report << (ok ? "ok " : "FAIL ") << what << "\n";
  18901. failures += ok ? 0 : 1;
  18902. };
  18903. const auto flush = [&] { juce::File (prefix + "-report.txt").replaceWithText (report + "failures=" + juce::String (failures) + "\n"); };
  18904. if (projectPath.isNotEmpty())
  18905. {
  18906. ui.openFile (juce::File (projectPath));
  18907. offline.dispatchPendingMessages();
  18908. }
  18909. else
  18910. offline.editSong ([] (lynx::Song& s) {
  18911. s.channels.clear();
  18912. s.patterns.clear();
  18913. s.playlist.clear();
  18914. s.bpm = 120.0;
  18915. const char* names[] = { "Lead", "Bass", "Pad", "Kick" };
  18916. for (int c = 0; c < 4; ++c)
  18917. {
  18918. lynx::ChannelDef d;
  18919. d.name = names[c];
  18920. d.instrument = c == 3 ? lynx::InstrumentKind::kick : lynx::InstrumentKind::synth;
  18921. d.synth.release = 0.3f + 0.3f * (float) c;
  18922. d.synth.cutoff = 1500.0f + 900.0f * (float) c;
  18923. d.mixerTrack = c + 1;
  18924. s.channels.push_back (d);
  18925. }
  18926. for (int p = 0; p < 2; ++p)
  18927. {
  18928. auto& pattern = s.patterns.emplace_back();
  18929. pattern.name = p == 0 ? "Verse" : "Break";
  18930. pattern.lengthTicks = 4 * lynx::ppq * 4;
  18931. for (int c = 0; c < 4; ++c)
  18932. for (int step = 0; step < (p == 0 ? 8 : 2); ++step)
  18933. {
  18934. lynx::Note n;
  18935. n.channel = c;
  18936. n.start = (std::int64_t) step * lynx::ppq * (p == 0 ? 2 : 1) + (c == 2 ? lynx::ppq / 2 : 0);
  18937. n.length = c == 3 ? lynx::ppq / 4 : lynx::ppq;
  18938. n.key = c == 3 ? 36 : 48 + c * 7 + (step * 5) % 12;
  18939. pattern.notes.push_back (n);
  18940. }
  18941. pattern.sortNotes();
  18942. }
  18943. const int order[] = { 0, 0, 1, 0 };
  18944. for (int i = 0; i < 4; ++i)
  18945. {
  18946. lynx::Clip clip;
  18947. clip.pattern = order[i];
  18948. clip.start = (std::int64_t) i * 16 * lynx::ppq;
  18949. clip.length = 16 * lynx::ppq;
  18950. s.playlist.push_back (clip);
  18951. }
  18952. s.mode = lynx::PlayMode::song;
  18953. });
  18954. offline.dispatchPendingMessages();
  18955. // the case Freeze exists for, a heavy hosted plugin: LYNX_FREEZETEST_PLUGIN = a plugin file whose first
  18956. // instrument plays the demo song's Lead (tools/testplugin/lynx_test_heavy_vst3.cpp: memory, CPU, latency, a
  18957. // state, and with LYNX_TEST_HEAVY_LOG the instances alive)
  18958. int hostedChannel = -1;
  18959. const auto hostedLog = juce::SystemStats::getEnvironmentVariable ("LYNX_TEST_HEAVY_LOG", {});
  18960. const auto hostedAlive = [&hostedLog] {
  18961. int alive = 0;
  18962. juce::StringArray lines;
  18963. juce::File (hostedLog).readLines (lines);
  18964. for (const auto& l : lines)
  18965. alive += l.startsWith ("create") ? 1 : l.startsWith ("destroy") ? -1 : 0;
  18966. return alive;
  18967. };
  18968. if (const auto pluginPath = juce::SystemStats::getEnvironmentVariable ("LYNX_FREEZETEST_PLUGIN", {}); pluginPath.isNotEmpty() && projectPath.isEmpty())
  18969. {
  18970. auto& host = offline.getPluginHost();
  18971. const auto added = host.addPluginFile (juce::File (pluginPath));
  18972. report << "hosted plugin file: " << pluginPath << " (" << added << " plugins)\n";
  18973. for (const auto& type : host.getKnownPlugins().getTypes())
  18974. if (type.isInstrument && juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginPath).getFileName())
  18975. {
  18976. offline.editSong ([&type] (lynx::Song& s) {
  18977. auto& c = s.channels[0];
  18978. c.instrument = lynx::InstrumentKind::plugin;
  18979. c.plugin.id = type.createIdentifierString().toStdString();
  18980. c.plugin.name = type.name.toStdString();
  18981. });
  18982. hostedChannel = 0;
  18983. break;
  18984. }
  18985. offline.dispatchPendingMessages();
  18986. auto* instance = dynamic_cast<lynx::PluginInstrument*> (offline.getChannelInstrument (0).get());
  18987. check (hostedChannel == 0 && instance != nullptr, "the hosted plugin is loaded on channel 1");
  18988. report << "hosted plugin: " << juce::String::fromUTF8 (offline.getSong().channels[0].plugin.name.c_str())
  18989. << ", engine latency " << offline.getLatencySamples() << " frames, instances alive " << hostedAlive() << "\n";
  18990. }
  18991. const auto hostedLine = [&] (const char* stage) {
  18992. if (hostedChannel < 0)
  18993. return;
  18994. offline.freeRetiredRacks();
  18995. report << "hosted, " << stage << ": instance on the channel "
  18996. << (dynamic_cast<lynx::PluginInstrument*> (offline.getChannelInstrument (hostedChannel).get()) != nullptr ? "yes" : "no")
  18997. << ", plugin instances alive in the process " << (hostedLog.isNotEmpty() ? juce::String (hostedAlive()) : juce::String ("(no log)")) << "\n";
  18998. };
  18999. const juce::File data (prefix + "-data");
  19000. data.deleteRecursively();
  19001. offline.setRecordingTarget (data.getChildFile ("Audio").getChildFile ("Recorded"), "freezetest");
  19002. report << "project=" << (projectPath.isNotEmpty() ? projectPath : juce::String ("(demo song)")) << "\n"
  19003. << "frozen_audio_folder=" << offline.getFreezeFolder().getFullPathName() << "\n";
  19004. const auto megabytes = [] (std::int64_t bytes) { return juce::String ((double) bytes / 1048576.0, 1); };
  19005. struct Mix
  19006. {
  19007. juce::AudioBuffer<float> audio;
  19008. double renderSeconds = 0.0, audioSeconds = 0.0;
  19009. std::int64_t workingSet = 0, privateBytes = 0;
  19010. };
  19011. // the song as it stands, rendered by an export (its own engine: frozen channels play their audio there too)
  19012. const auto renderMix = [&] (const char* name, const lynx::Song* other = nullptr, std::vector<int>* renderedLive = nullptr, int range = 0) {
  19013. Mix m;
  19014. offline.dispatchPendingMessages();
  19015. offline.freeRetiredRacks(); // (what the message loop does in the app: this mode runs without one)
  19016. m.workingSet = lynx::toolbar::PerformanceMeter::processMemoryBytes();
  19017. m.privateBytes = lynx::toolbar::PerformanceMeter::processPrivateBytes();
  19018. const juce::File file (prefix + "-" + name + ".wav");
  19019. lynx::ExportSettings settings;
  19020. settings.format = lynx::ExportSettings::Format::wav32Float;
  19021. settings.sampleRate = offline.getTransport().sampleRate.load();
  19022. settings.tailSeconds = 2.0;
  19023. juce::String error;
  19024. {
  19025. auto options = settings.toOptions();
  19026. options.hqAllPlugins = false; // the quality heard while playing: what a frozen channel's audio is made at
  19027. options.disableMaxPolyphony = false; // (and each channel's Max polyphony, as while playing)
  19028. if (range == 1)
  19029. options.range = lynx::exportopts::Range::selection;
  19030. if (range == 2)
  19031. {
  19032. options.range = lynx::exportopts::Range::pattern;
  19033. options.loops = 2;
  19034. }
  19035. lynx::ExportJob job (other != nullptr ? *other : offline.getSong(), options, file);
  19036. if (renderedLive != nullptr)
  19037. *renderedLive = job.channelsRenderedLive();
  19038. const auto started = juce::Time::getMillisecondCounterHiRes();
  19039. const auto ok = job.run ([] (double) { return true; }, error);
  19040. m.renderSeconds = (juce::Time::getMillisecondCounterHiRes() - started) / 1000.0;
  19041. check (ok, juce::String ("render ") + name + (ok ? juce::String() : ": " + error));
  19042. }
  19043. juce::WavAudioFormat wav;
  19044. if (std::unique_ptr<juce::AudioFormatReader> reader { wav.createReaderFor (file.createInputStream().release(), true) })
  19045. {
  19046. m.audio.setSize (2, (int) reader->lengthInSamples);
  19047. reader->read (&m.audio, 0, (int) reader->lengthInSamples, 0, true, true);
  19048. m.audioSeconds = (double) reader->lengthInSamples / reader->sampleRate;
  19049. }
  19050. file.deleteFile();
  19051. return m;
  19052. };
  19053. // the worst sample difference, in dB below the first mix's peak
  19054. const auto residual = [] (const Mix& a, const Mix& b, float& peak) {
  19055. float worst = 0.0f;
  19056. peak = 0.0f;
  19057. const auto n = juce::jmin (a.audio.getNumSamples(), b.audio.getNumSamples());
  19058. for (int ch = 0; ch < 2; ++ch)
  19059. for (int i = 0; i < n; ++i)
  19060. {
  19061. worst = juce::jmax (worst, std::abs (a.audio.getSample (ch, i) - b.audio.getSample (ch, i)));
  19062. peak = juce::jmax (peak, std::abs (a.audio.getSample (ch, i)));
  19063. }
  19064. return worst <= 0.0f ? -200.0 : 20.0 * std::log10 ((double) worst / (double) juce::jmax (peak, 1.0e-12f));
  19065. };
  19066. const auto line = [&] (const char* name, const Mix& m) {
  19067. report << name << ": working set " << megabytes (m.workingSet) << " MB, private " << megabytes (m.privateBytes) << " MB, render "
  19068. << juce::String (m.renderSeconds, 2) << " s for " << juce::String (m.audioSeconds, 2) << " s of audio ("
  19069. << juce::String (m.audioSeconds > 0.0 ? 100.0 * m.renderSeconds / m.audioSeconds : 0.0, 1) << " % of real time)\n";
  19070. };
  19071. if (mode == "measure")
  19072. {
  19073. // a process that only loaded this project and renders it: its memory with the project loaded, and after
  19074. int frozenCount = 0, hosted = 0;
  19075. for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
  19076. {
  19077. frozenCount += offline.getSong().channels[(std::size_t) c].freeze.on();
  19078. hosted += dynamic_cast<lynx::PluginInstrument*> (offline.getChannelInstrument (c).get()) != nullptr;
  19079. }
  19080. report << "channels " << (int) offline.getSong().channels.size() << ", frozen " << frozenCount << ", hosted plugin instances " << hosted << "\n";
  19081. const auto m = renderMix ("measure");
  19082. line ("loaded ", m);
  19083. report << "after the render: working set " << megabytes (lynx::toolbar::PerformanceMeter::processMemoryBytes()) << " MB, private "
  19084. << megabytes (lynx::toolbar::PerformanceMeter::processPrivateBytes()) << " MB\n";
  19085. flush();
  19086. return failures == 0;
  19087. }
  19088. // --- live ---
  19089. offline.capturePluginStates();
  19090. offline.editSong ([] (lynx::Song&) {}, false); // (whatever any edit settles — ids of new objects... — settled first)
  19091. const auto before = offline.getSong();
  19092. // (the project's working-time counter runs on while the test does: not part of what is compared)
  19093. const auto savedJson = [] (lynx::Song song) {
  19094. song.info.workSeconds = 0.0;
  19095. return lynx::ProjectFile::toJson (song, false);
  19096. };
  19097. const auto jsonBefore = savedJson (before);
  19098. std::vector<int> targets;
  19099. for (int c = 0; c < (int) before.channels.size(); ++c)
  19100. {
  19101. const auto* why = lynx::freeze::whyNot (before, c);
  19102. const auto plays = std::any_of (before.patterns.begin(), before.patterns.end(), [c] (const lynx::Pattern& p) {
  19103. return std::any_of (p.notes.begin(), p.notes.end(), [c] (const lynx::Note& n) { return n.channel == c; });
  19104. });
  19105. report << "channel " << (c + 1) << " '" << juce::String::fromUTF8 (before.channels[(std::size_t) c].name.c_str()) << "': "
  19106. << (why != nullptr ? juce::String ("not frozen (") + why + ")" : plays ? juce::String ("freeze") : juce::String ("no notes, left alone")) << "\n";
  19107. if (why == nullptr && plays)
  19108. {
  19109. targets.push_back (c);
  19110. // what could make a stem differ from the live channel, for the record
  19111. const auto& def = before.channels[(std::size_t) c];
  19112. int volPan = 0, params = 0, live = 0, lanes = 0, routes = 0;
  19113. for (const auto& a : before.automations)
  19114. if (a.target.index == c)
  19115. {
  19116. volPan += a.target.kind == lynx::AutomationTargetKind::channelVolume || a.target.kind == lynx::AutomationTargetKind::channelPan;
  19117. params += a.target.kind == lynx::AutomationTargetKind::channelParam;
  19118. live += a.isLive() && (a.target.kind == lynx::AutomationTargetKind::channelVolume || a.target.kind == lynx::AutomationTargetKind::channelPan
  19119. || a.target.kind == lynx::AutomationTargetKind::channelParam);
  19120. }
  19121. for (const auto& p : before.patterns)
  19122. for (const auto& lane : p.events)
  19123. lanes += lane.target.index == c && (lane.target.kind == lynx::AutomationTargetKind::channelVolume
  19124. || lane.target.kind == lynx::AutomationTargetKind::channelPan
  19125. || lane.target.kind == lynx::AutomationTargetKind::channelParam);
  19126. for (const auto& m : before.modulators)
  19127. for (const auto& r : m.routes)
  19128. routes += r.target.index == c && (r.target.kind == lynx::AutomationTargetKind::channelVolume
  19129. || r.target.kind == lynx::AutomationTargetKind::channelPan
  19130. || r.target.kind == lynx::AutomationTargetKind::channelParam);
  19131. report << " instrument kind " << (int) def.instrument << ", insert " << def.mixerTrack << ", automation: volume/pan " << volPan
  19132. << ", parameters " << params << ", live links " << live << ", event lanes " << lanes << ", modulator routes " << routes << "\n";
  19133. }
  19134. }
  19135. check (! targets.empty(), "the project has channels to freeze (" + juce::String ((int) targets.size()) + ")");
  19136. if (targets.empty())
  19137. {
  19138. flush();
  19139. return false;
  19140. }
  19141. const auto first = targets.front();
  19142. offline.setSelectedChannel (first);
  19143. ui.selectTabForSnapshot (0);
  19144. write ("rack-live");
  19145. saveMenus (juce::StringArray { "Channel (live)" }, std::vector<juce::PopupMenu> { ui.getRackForSnapshot().getChannelMenuForSnapshot (first) }, prefix + "-menu-live.png");
  19146. const auto live = renderMix ("live");
  19147. line ("live ", live);
  19148. hostedLine ("live");
  19149. const auto hostedState = hostedChannel >= 0 ? before.channels[(std::size_t) hostedChannel].plugin.state : std::string();
  19150. if (hostedChannel >= 0)
  19151. check (! hostedState.empty(), "the hosted plugin's state is in the project (" + juce::String ((int) hostedState.size()) + " characters)");
  19152. flush();
  19153. // --- frozen ---
  19154. const auto freezeStarted = juce::Time::getMillisecondCounterHiRes();
  19155. for (const auto c : targets)
  19156. {
  19157. const auto error = lynx::freezeChannelNow (offline, c);
  19158. check (error.isEmpty(), "freeze channel " + juce::String (c + 1) + (error.isEmpty() ? juce::String() : ": " + error));
  19159. }
  19160. const auto freezeSeconds = (juce::Time::getMillisecondCounterHiRes() - freezeStarted) / 1000.0;
  19161. offline.dispatchPendingMessages();
  19162. std::int64_t stemBytes = 0;
  19163. int stemFiles = 0;
  19164. bool pluginsGone = true, allFrozen = true;
  19165. for (const auto c : targets)
  19166. {
  19167. const auto& ch = offline.getSong().channels[(std::size_t) c];
  19168. allFrozen = allFrozen && ch.freeze.on() && ! offline.frozenAudioMissing (c) && ! offline.freezeOutOfDate (c);
  19169. for (const auto& stem : ch.freeze.stems)
  19170. {
  19171. stemBytes += juce::File (juce::String::fromUTF8 (stem.path.c_str())).getSize();
  19172. ++stemFiles;
  19173. }
  19174. pluginsGone = pluginsGone && dynamic_cast<lynx::PluginInstrument*> (offline.getChannelInstrument (c).get()) == nullptr;
  19175. auto thawed = ch;
  19176. thawed.freeze = {};
  19177. check (thawed == before.channels[(std::size_t) c], "channel " + juce::String (c + 1) + " keeps its instrument and settings as they were while frozen");
  19178. }
  19179. check (allFrozen, "every target is frozen, its audio on disk and up to date");
  19180. check (pluginsGone, "no hosted plugin instance is left on a frozen channel");
  19181. report << "freeze: " << juce::String (freezeSeconds, 2) << " s for " << (int) targets.size() << " channels, " << stemFiles << " files, "
  19182. << megabytes (stemBytes) << " MB on disk\n";
  19183. if (mode == "keep")
  19184. {
  19185. juce::String error;
  19186. check (lynx::ProjectFile::save (offline.getSong(), juce::File (prefix + "-frozen.lynx"), error), "the frozen project is saved" + (error.isEmpty() ? juce::String() : ": " + error));
  19187. flush();
  19188. return failures == 0;
  19189. }
  19190. const auto frozen = renderMix ("frozen");
  19191. line ("frozen ", frozen);
  19192. hostedLine ("frozen");
  19193. if (hostedChannel >= 0 && hostedLog.isNotEmpty())
  19194. check (hostedAlive() == 0, "while frozen no instance of the hosted plugin is alive in the process");
  19195. float peak = 0.0f;
  19196. const auto nullFrozen = residual (live, frozen, peak);
  19197. report << "null frozen vs live: " << juce::String (nullFrozen, 1) << " dB (peak " << juce::String (peak, 4) << ", "
  19198. << live.audio.getNumSamples() << " / " << frozen.audio.getNumSamples() << " samples)\n";
  19199. check (peak > 0.001f && nullFrozen < -90.0 && live.audio.getNumSamples() == frozen.audio.getNumSamples(), "the frozen mix nulls against the live mix (below -90 dB)");
  19200. ui.selectTabForSnapshot (0);
  19201. ui.setHintForSnapshot (ui.getRackForSnapshot().getChannelHintForSnapshot (first));
  19202. write ("rack-frozen");
  19203. saveMenus (juce::StringArray { "Channel (frozen)" }, std::vector<juce::PopupMenu> { ui.getRackForSnapshot().getChannelMenuForSnapshot (first) }, prefix + "-menu-frozen.png");
  19204. report << "hint frozen: " << ui.getRackForSnapshot().getChannelHintForSnapshot (first).text << "\n";
  19205. offline.setSelectedChannel (first);
  19206. ui.selectTabForSnapshot (1);
  19207. offline.setSelectedChannel (first);
  19208. offline.dispatchPendingMessages();
  19209. ui.setHintForSnapshot ({ lynx::tr ("{0} is frozen: Unfreeze to edit ([RMB] on the channel, Unfreeze)",
  19210. { juce::String::fromUTF8 (offline.getSong().channels[(std::size_t) first].name.c_str()) }), {} });
  19211. write ("pianoroll-frozen");
  19212. // --- exports that do not play the song's timeline once: a selection, one pattern twice ---
  19213. // (the frozen audio is the whole song from its start: those renders play the instruments, never a wrong part of it)
  19214. if (projectPath.isEmpty())
  19215. {
  19216. auto part = offline.getSong();
  19217. part.loopStart = 16 * lynx::ppq;
  19218. part.loopEnd = 40 * lynx::ppq;
  19219. const auto partLive = lynx::freeze::thawed (part);
  19220. for (int range = 1; range <= 2; ++range)
  19221. {
  19222. std::vector<int> renderedLive;
  19223. const auto a = renderMix (range == 1 ? "selection-live" : "pattern-live", &partLive, nullptr, range);
  19224. const auto b = renderMix (range == 1 ? "selection-frozen" : "pattern-frozen", &part, &renderedLive, range);
  19225. float partPeak = 0.0f;
  19226. const auto null = residual (a, b, partPeak);
  19227. report << (range == 1 ? "export of a selection (bars 5-10)" : "export of the current pattern, twice") << ", frozen vs live: " << juce::String (null, 1)
  19228. << " dB (peak " << juce::String (partPeak, 4) << ", " << juce::String (b.audioSeconds, 2) << " s), channels rendered live: " << (int) renderedLive.size() << "\n";
  19229. check (partPeak > 0.001f && null < -90.0 && a.audio.getNumSamples() == b.audio.getNumSamples(),
  19230. 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");
  19231. }
  19232. }
  19233. // --- what a save holds ---
  19234. {
  19235. const auto json = lynx::ProjectFile::toJson (offline.getSong(), false);
  19236. juce::String error;
  19237. const auto loaded = lynx::ProjectFile::fromJson (json, error);
  19238. check (json.contains ("\"freeze\""), "the saved project holds the frozen state");
  19239. check (loaded.has_value() && loaded->channels.size() == offline.getSong().channels.size()
  19240. && loaded->channels[(std::size_t) first].freeze == offline.getSong().channels[(std::size_t) first].freeze,
  19241. "a frozen project loads frozen, with the same audio files");
  19242. check (savedJson (lynx::freeze::thawed (offline.getSong())) == jsonBefore,
  19243. "without the frozen state the saved project is byte for byte what it was before the freeze");
  19244. check (! jsonBefore.contains ("\"freeze\""), "a project with nothing frozen has no freeze field");
  19245. }
  19246. // --- out of date: the tempo, a note of the frozen channel; not another channel's notes ---
  19247. {
  19248. offline.editSong ([] (lynx::Song& s) { s.bpm += 4.0; });
  19249. check (offline.freezeOutOfDate (first), "a tempo change marks the freeze out of date");
  19250. ui.selectTabForSnapshot (0);
  19251. ui.setHintForSnapshot (ui.getRackForSnapshot().getChannelHintForSnapshot (first));
  19252. write ("rack-out-of-date");
  19253. report << "hint out of date: " << ui.getRackForSnapshot().getChannelHintForSnapshot (first).text << "\n";
  19254. offline.editSong ([] (lynx::Song& s) { s.bpm -= 4.0; });
  19255. check (! offline.freezeOutOfDate (first), "the tempo back: up to date again");
  19256. int pattern = -1;
  19257. for (int p = 0; p < (int) before.patterns.size() && pattern < 0; ++p)
  19258. for (const auto& n : before.patterns[(std::size_t) p].notes)
  19259. if (n.channel == first)
  19260. {
  19261. pattern = p;
  19262. break;
  19263. }
  19264. if (pattern >= 0)
  19265. {
  19266. offline.editSong ([pattern, first] (lynx::Song& s) {
  19267. lynx::Note n;
  19268. n.channel = first;
  19269. n.start = 0;
  19270. n.key = 71;
  19271. s.patterns[(std::size_t) pattern].notes.push_back (n);
  19272. s.patterns[(std::size_t) pattern].sortNotes();
  19273. });
  19274. check (offline.freezeOutOfDate (first), "a note edit on the frozen channel marks it out of date");
  19275. bool othersFresh = true;
  19276. for (const auto c : targets)
  19277. othersFresh = othersFresh && (c == first || ! offline.freezeOutOfDate (c));
  19278. check (othersFresh, "the other frozen channels stay up to date");
  19279. // an export of the project in that state: the out-of-date channel renders live (never the old audio),
  19280. // the others keep their frozen audio — the same mix as the edited project with nothing frozen
  19281. {
  19282. std::vector<int> renderedLive;
  19283. const auto stale = renderMix ("stale", nullptr, &renderedLive);
  19284. const auto edited = lynx::freeze::thawed (offline.getSong());
  19285. const auto reference = renderMix ("stale-reference", &edited);
  19286. float stalePeak = 0.0f;
  19287. const auto nullStale = residual (reference, stale, stalePeak);
  19288. const auto nullOld = residual (frozen, stale, stalePeak);
  19289. report << "export with channel " << (first + 1) << " out of date: " << juce::String (nullStale, 1) << " dB vs the edited project live, "
  19290. << juce::String (nullOld, 1) << " dB vs the old frozen mix; channels rendered live: " << (int) renderedLive.size() << "\n";
  19291. check (renderedLive == std::vector<int> { first }, "an export renders the out-of-date frozen channel live, and only that one");
  19292. check (nullStale < -90.0 && nullOld > -60.0, "an export of an out-of-date freeze holds the edited notes, not the old audio");
  19293. }
  19294. offline.editSong ([&before] (lynx::Song& s) { s.patterns = before.patterns; });
  19295. check (! offline.freezeOutOfDate (first), "the notes back: up to date again");
  19296. }
  19297. }
  19298. // --- the audio gone: the instrument plays, never silence ---
  19299. {
  19300. const auto stems = offline.getSong().channels[(std::size_t) first].freeze.stems;
  19301. std::vector<std::pair<juce::File, juce::File>> moved;
  19302. for (const auto& stem : stems)
  19303. {
  19304. const juce::File file (juce::String::fromUTF8 (stem.path.c_str()));
  19305. const auto away = file.getSiblingFile (file.getFileName() + ".away");
  19306. if (file.moveFileTo (away))
  19307. moved.emplace_back (file, away);
  19308. }
  19309. offline.editSong ([] (lynx::Song&) {}, false);
  19310. check (offline.frozenAudioMissing (first), "frozen audio that is not on disk is noticed");
  19311. report << "hint audio missing: " << ui.getRackForSnapshot().getChannelHintForSnapshot (first).text << "\n";
  19312. const auto fallback = renderMix ("missing");
  19313. const auto nullMissing = residual (live, fallback, peak);
  19314. report << "null with the first channel's audio missing vs live: " << juce::String (nullMissing, 1) << " dB\n";
  19315. check (nullMissing < -90.0, "with its audio missing the channel plays its instrument");
  19316. for (const auto& [file, away] : moved)
  19317. away.moveFileTo (file);
  19318. offline.editSong ([] (lynx::Song&) {}, false);
  19319. check (! offline.frozenAudioMissing (first), "the audio back: frozen again");
  19320. // the frozen mix did not null and the first channel is not (alone) why: which one is, each thawed in turn
  19321. if (nullFrozen >= -90.0 && nullMissing >= -90.0)
  19322. for (const auto c : targets)
  19323. {
  19324. if (c == first)
  19325. continue;
  19326. std::vector<std::pair<juce::File, juce::File>> aside;
  19327. for (const auto& stem : offline.getSong().channels[(std::size_t) c].freeze.stems)
  19328. {
  19329. const juce::File file (juce::String::fromUTF8 (stem.path.c_str()));
  19330. const auto away = file.getSiblingFile (file.getFileName() + ".away");
  19331. if (file.moveFileTo (away))
  19332. aside.emplace_back (file, away);
  19333. }
  19334. offline.editSong ([] (lynx::Song&) {}, false);
  19335. const auto one = renderMix ("thawed");
  19336. report << "null with channel " << (c + 1) << " thawed vs live: " << juce::String (residual (live, one, peak), 1) << " dB\n";
  19337. for (const auto& [file, away] : aside)
  19338. away.moveFileTo (file);
  19339. offline.editSong ([] (lynx::Song&) {}, false);
  19340. }
  19341. }
  19342. // --- unfrozen ---
  19343. std::vector<juce::File> stemPaths;
  19344. for (const auto c : targets)
  19345. for (const auto& stem : offline.getSong().channels[(std::size_t) c].freeze.stems)
  19346. stemPaths.emplace_back (juce::String::fromUTF8 (stem.path.c_str()));
  19347. for (const auto c : targets)
  19348. lynx::unfreezeChannel (offline, c);
  19349. offline.dispatchPendingMessages();
  19350. check (offline.getSong().channels == before.channels, "Unfreeze gives every channel back exactly as it was (instrument, plugin state, settings)");
  19351. {
  19352. const auto jsonAfter = savedJson (offline.getSong());
  19353. check (jsonAfter == jsonBefore, "the unfrozen project saves byte for byte as before the freeze");
  19354. if (jsonAfter != jsonBefore)
  19355. {
  19356. juce::File (prefix + "-before.json").replaceWithText (jsonBefore);
  19357. juce::File (prefix + "-after.json").replaceWithText (jsonAfter);
  19358. }
  19359. }
  19360. int left = 0;
  19361. for (const auto& f : stemPaths)
  19362. left += f.existsAsFile() ? 1 : 0;
  19363. check (left == 0, "Unfreeze deletes the frozen audio (" + juce::String (left) + " of " + juce::String ((int) stemPaths.size()) + " files left)");
  19364. if (hostedChannel >= 0)
  19365. {
  19366. // the new instance (it starts with another tuning than the first one had) took the saved state
  19367. offline.capturePluginStates();
  19368. check (dynamic_cast<lynx::PluginInstrument*> (offline.getChannelInstrument (hostedChannel).get()) != nullptr, "Unfreeze loads the hosted plugin again");
  19369. check (offline.getSong().channels[(std::size_t) hostedChannel].plugin.state == hostedState,
  19370. "the hosted plugin's state, read back from the new instance, is the state it had before the freeze");
  19371. }
  19372. const auto unfrozen = renderMix ("unfrozen");
  19373. line ("unfrozen ", unfrozen);
  19374. hostedLine ("unfrozen");
  19375. const auto nullUnfrozen = residual (live, unfrozen, peak);
  19376. report << "null unfrozen vs live: " << juce::String (nullUnfrozen, 1) << " dB\n";
  19377. check (nullUnfrozen < -90.0, "the unfrozen mix nulls against the live mix");
  19378. ui.selectTabForSnapshot (0);
  19379. flush();
  19380. data.deleteRecursively();
  19381. return failures == 0;
  19382. }
  19383. // Round 190ff, the Clip-launch workflow's track commands end to end with the real engine, files and export
  19384. // (LYNX --trackfreezetest prefix). A demo song of three tracks (Lead through a delay and a reverb whose mix is
  19385. // automated, Bass through a delay, Drums on a bare insert; each insert's fader, pan and EQ set) is rendered live; then
  19386. // Freeze Track on every track (the instrument with its volume and pan through its insert's effects), the same render
  19387. // again (must null), the effects and instruments unloaded, the render time (the CPU while frozen), what a save holds;
  19388. // Flatten (Bounce Track in Place on a frozen track) with its undo; Bounce Track in Place of a live track; Bounce to New
  19389. // Track of a track's clips against that track's device output; Consolidate of pattern clips; Unfreeze. Written to
  19390. // prefix-report.txt; shots of the grid, the column menus, the Detail View's frozen devices and the Playlist's clip
  19391. // menu. True = every check passed.
  19392. bool runTrackFreezeTest (const juce::String& prefix)
  19393. {
  19394. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  19395. lynx::AudioEngine offline (false);
  19396. lynx::MainComponent ui (offline, false);
  19397. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  19398. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  19399. const auto write = [&prefix, &ui] (const char* name) {
  19400. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  19401. file.deleteFile();
  19402. juce::FileOutputStream out (file);
  19403. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (ui), out);
  19404. };
  19405. juce::String report;
  19406. int failures = 0;
  19407. const auto check = [&] (bool ok, const juce::String& what) {
  19408. report << (ok ? "ok " : "FAIL ") << what << "\n";
  19409. failures += ok ? 0 : 1;
  19410. };
  19411. const auto flush = [&] { juce::File (prefix + "-report.txt").replaceWithText (report + "failures=" + juce::String (failures) + "\n"); };
  19412. const juce::File data (prefix + "-data");
  19413. data.deleteRecursively();
  19414. offline.setRecordingTarget (data.getChildFile ("Audio").getChildFile ("Recorded"), "trackfreezetest");
  19415. ui.setVisible (true);
  19416. lynx::DetailView::shownSetting = lynx::DetailView::devicesPage = true;
  19417. ui.setClipLaunchWorkflow (true);
  19418. offline.editSong ([] (lynx::Song& s) {
  19419. s.channels.clear();
  19420. s.patterns.clear();
  19421. s.playlist.clear();
  19422. s.automations.clear();
  19423. s.bpm = 120.0;
  19424. s.mode = lynx::PlayMode::song;
  19425. const char* names[] = { "Lead", "Bass", "Drums" };
  19426. for (int c = 0; c < 3; ++c)
  19427. {
  19428. lynx::ChannelDef d;
  19429. d.name = names[c];
  19430. d.instrument = c == 2 ? lynx::InstrumentKind::kick : lynx::InstrumentKind::synth;
  19431. d.synth.release = c == 0 ? 0.6f : 0.2f;
  19432. d.synth.cutoff = c == 0 ? 2400.0f : 900.0f;
  19433. d.volume = c == 0 ? 0.65f : 0.78f;
  19434. d.pan = c == 0 ? 0.25f : 0.0f;
  19435. d.mixerTrack = c + 1;
  19436. s.channels.push_back (d);
  19437. }
  19438. if (s.mixer.size() < 5)
  19439. s.mixer.resize (5);
  19440. s.mixer[1].effects = { lynx::makeEffectSlot (lynx::EffectKind::delay), lynx::makeEffectSlot (lynx::EffectKind::reverb) };
  19441. s.mixer[2].effects = { lynx::makeEffectSlot (lynx::EffectKind::delay) };
  19442. s.mixer[3].effects.clear();
  19443. for (int t = 1; t <= 3; ++t)
  19444. {
  19445. s.mixer[(std::size_t) t].name = names[t - 1];
  19446. s.mixer[(std::size_t) t].volume = 0.7f;
  19447. s.mixer[(std::size_t) t].pan = t == 1 ? -0.3f : 0.1f;
  19448. s.mixer[(std::size_t) t].eq.gainDb[1] = 3.0f;
  19449. }
  19450. for (int p = 0; p < 3; ++p)
  19451. {
  19452. auto& pattern = s.patterns.emplace_back();
  19453. pattern.name = names[p];
  19454. pattern.lengthTicks = 4 * lynx::ppq * 2;
  19455. for (int step = 0; step < 8; ++step)
  19456. {
  19457. lynx::Note n;
  19458. n.channel = p;
  19459. n.start = (std::int64_t) step * lynx::ppq;
  19460. n.length = p == 2 ? lynx::ppq / 4 : lynx::ppq / 2;
  19461. n.key = p == 2 ? 36 : (p == 0 ? 60 : 36) + (step * 5) % 12;
  19462. pattern.notes.push_back (n);
  19463. }
  19464. }
  19465. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 4));
  19466. for (int t = 0; t < 3; ++t)
  19467. {
  19468. s.playlistTracks[(std::size_t) t].name = names[t];
  19469. for (int k = 0; k < 3; ++k)
  19470. {
  19471. if (t == 0 && k == 1)
  19472. continue; // (a gap in the Lead: its tail rings into it)
  19473. lynx::Clip clip;
  19474. clip.pattern = t;
  19475. clip.track = t;
  19476. clip.start = (std::int64_t) k * 8 * lynx::ppq;
  19477. clip.length = 8 * lynx::ppq;
  19478. s.playlist.push_back (clip);
  19479. }
  19480. }
  19481. // the Lead's reverb mix rises over the song (automation the freeze takes into its audio)
  19482. lynx::Automation a;
  19483. a.name = "Lead reverb mix";
  19484. a.target = { lynx::AutomationTargetKind::effectMix, 1, 1, 0 };
  19485. a.points = { { 0, 0.2f }, { 24 * lynx::ppq, 0.9f } };
  19486. s.automations.push_back (a);
  19487. lynx::Clip lane;
  19488. lane.kind = lynx::ClipKind::automation;
  19489. lane.automation = 0;
  19490. lane.track = 3;
  19491. lane.length = 24 * lynx::ppq;
  19492. s.playlist.push_back (lane);
  19493. std::stable_sort (s.playlist.begin(), s.playlist.end(), [] (const lynx::Clip& x, const lynx::Clip& y) { return x.start < y.start; });
  19494. });
  19495. offline.dispatchPendingMessages();
  19496. const auto megabytes = [] (std::int64_t bytes) { return juce::String ((double) bytes / 1048576.0, 1); };
  19497. struct Mix
  19498. {
  19499. juce::AudioBuffer<float> audio;
  19500. double renderSeconds = 0.0, audioSeconds = 0.0;
  19501. };
  19502. const auto renderMix = [&] (const char* name, const lynx::Song* other = nullptr) {
  19503. Mix m;
  19504. offline.dispatchPendingMessages();
  19505. offline.freeRetiredRacks();
  19506. const juce::File file (prefix + "-" + name + ".wav");
  19507. lynx::ExportSettings settings;
  19508. settings.format = lynx::ExportSettings::Format::wav32Float;
  19509. settings.sampleRate = offline.getTransport().sampleRate.load();
  19510. settings.tailSeconds = 2.0;
  19511. juce::String error;
  19512. auto options = settings.toOptions();
  19513. options.hqAllPlugins = false;
  19514. options.disableMaxPolyphony = false;
  19515. {
  19516. lynx::ExportJob job (other != nullptr ? *other : offline.getSong(), options, file);
  19517. const auto started = juce::Time::getMillisecondCounterHiRes();
  19518. const auto ok = job.run ([] (double) { return true; }, error);
  19519. m.renderSeconds = (juce::Time::getMillisecondCounterHiRes() - started) / 1000.0;
  19520. check (ok, juce::String ("render ") + name + (ok ? juce::String() : ": " + error));
  19521. }
  19522. juce::WavAudioFormat wav;
  19523. if (std::unique_ptr<juce::AudioFormatReader> reader { wav.createReaderFor (file.createInputStream().release(), true) })
  19524. {
  19525. m.audio.setSize (2, (int) reader->lengthInSamples);
  19526. reader->read (&m.audio, 0, (int) reader->lengthInSamples, 0, true, true);
  19527. m.audioSeconds = (double) reader->lengthInSamples / reader->sampleRate;
  19528. }
  19529. if (juce::SystemStats::getEnvironmentVariable ("LYNX_TRACKFREEZE_KEEP", {}).isEmpty()) // (kept: to look at a residual)
  19530. file.deleteFile();
  19531. return m;
  19532. };
  19533. const auto residual = [] (const Mix& a, const Mix& b, float& peak) {
  19534. float worst = 0.0f;
  19535. peak = 0.0f;
  19536. const auto n = juce::jmin (a.audio.getNumSamples(), b.audio.getNumSamples());
  19537. for (int ch = 0; ch < 2; ++ch)
  19538. for (int i = 0; i < n; ++i)
  19539. {
  19540. worst = juce::jmax (worst, std::abs (a.audio.getSample (ch, i) - b.audio.getSample (ch, i)));
  19541. peak = juce::jmax (peak, std::abs (a.audio.getSample (ch, i)));
  19542. }
  19543. return worst <= 0.0f ? -200.0 : 20.0 * std::log10 ((double) worst / (double) juce::jmax (peak, 1.0e-12f));
  19544. };
  19545. const auto nullLine = [&] (const char* what, const Mix& a, const Mix& b, double limit) {
  19546. float peak = 0.0f;
  19547. const auto r = residual (a, b, peak);
  19548. report << what << ": " << juce::String (r, 1) << " dB (peak " << juce::String (peak, 4) << ", " << a.audio.getNumSamples() << " / "
  19549. << b.audio.getNumSamples() << " samples)\n";
  19550. check (peak > 0.001f && r < limit && a.audio.getNumSamples() == b.audio.getNumSamples(), juce::String (what) + " below " + juce::String (limit, 0) + " dB");
  19551. return r;
  19552. };
  19553. const auto savedJson = [] (lynx::Song song) {
  19554. song.info.workSeconds = 0.0;
  19555. return lynx::ProjectFile::toJson (song, false);
  19556. };
  19557. // --- live ---
  19558. offline.capturePluginStates();
  19559. offline.editSong ([] (lynx::Song&) {}, false);
  19560. const auto before = offline.getSong();
  19561. const auto jsonBefore = savedJson (before);
  19562. auto* grid = ui.getClipGridForSnapshot();
  19563. check (grid != nullptr, "the Clip-launch workflow's grid is there");
  19564. if (grid == nullptr)
  19565. {
  19566. flush();
  19567. return false;
  19568. }
  19569. ui.setClipGridView (lynx::PlaylistArea::GridView::beside);
  19570. write ("live");
  19571. saveMenus (juce::StringArray { "Track title (live)" }, std::vector<juce::PopupMenu> { lynx::clipGridHeaderMenu (*grid, 0) }, prefix + "-menu-track-live.png");
  19572. int leadClip = -1;
  19573. for (int i = 0; i < (int) before.playlist.size() && leadClip < 0; ++i)
  19574. if (before.playlist[(std::size_t) i].track == 0 && before.playlist[(std::size_t) i].kind == lynx::ClipKind::pattern)
  19575. leadClip = i;
  19576. ui.getPlaylistForSnapshot().selectForSnapshot ({ leadClip });
  19577. saveMenus (juce::StringArray { "Playlist clip (Clip-launch workflow)" }, std::vector<juce::PopupMenu> { ui.getPlaylistForSnapshot().getClipMenuForSnapshot (leadClip) },
  19578. prefix + "-menu-clip.png");
  19579. const auto live = renderMix ("live");
  19580. report << "live: render " << juce::String (live.renderSeconds, 2) << " s for " << juce::String (live.audioSeconds, 2) << " s of audio\n";
  19581. // --- Freeze Track on every track ---
  19582. std::vector<int> channels;
  19583. for (int t = 0; t < 3; ++t)
  19584. {
  19585. const auto c = lynx::detailchain::forTrack (before, t).channel;
  19586. check (c == t, "track " + juce::String (t + 1) + " shows channel " + juce::String (t + 1));
  19587. const auto* why = lynx::freeze::whyNotTrack (before, c);
  19588. check (why == nullptr, "track " + juce::String (t + 1) + " can be frozen" + (why != nullptr ? juce::String (": ") + why : juce::String()));
  19589. const auto error = lynx::freezeTrackNow (offline, c);
  19590. check (error.isEmpty(), "Freeze Track " + juce::String (t + 1) + (error.isEmpty() ? juce::String() : ": " + error));
  19591. channels.push_back (c);
  19592. }
  19593. offline.dispatchPendingMessages();
  19594. offline.freeRetiredRacks();
  19595. int loadedEffects = 0;
  19596. for (int t = 1; t <= 3; ++t)
  19597. for (int slot = 0; slot < (int) offline.getSong().mixer[(std::size_t) t].effects.size(); ++slot)
  19598. loadedEffects += offline.getEffect (t, slot) != nullptr ? 1 : 0;
  19599. check (loadedEffects == 0, "no effect of a frozen track is loaded (" + juce::String (loadedEffects) + " left)");
  19600. bool fresh = true;
  19601. for (const auto c : channels)
  19602. {
  19603. const auto& f = offline.getSong().channels[(std::size_t) c].freeze;
  19604. fresh = fresh && f.on() && f.insert == c + 1 && lynx::freeze::trackFreezeHolds (offline.getSong(), c) && ! offline.freezeOutOfDate (c)
  19605. && ! offline.frozenAudioMissing (c);
  19606. }
  19607. check (fresh, "every track is frozen with its insert, its audio on disk and up to date");
  19608. check (offline.getSong().mixer == before.mixer, "the project keeps every effect as it was (Unfreeze brings them back)");
  19609. const auto frozenSong = offline.getSong();
  19610. const auto frozen = renderMix ("frozen");
  19611. report << "frozen: render " << juce::String (frozen.renderSeconds, 2) << " s (" << juce::String (100.0 * frozen.renderSeconds / juce::jmax (0.001, live.renderSeconds), 0)
  19612. << " % of the live render's time)\n";
  19613. nullLine ("frozen vs live", live, frozen, -90.0);
  19614. write ("frozen");
  19615. saveMenus (juce::StringArray { "Track title (frozen)" }, std::vector<juce::PopupMenu> { lynx::clipGridHeaderMenu (*grid, 0) }, prefix + "-menu-track-frozen.png");
  19616. if (auto* detail = ui.getDetailViewForSnapshot())
  19617. {
  19618. detail->showSelection (0, 0);
  19619. detail->setPage (lynx::DetailView::Page::devices);
  19620. write ("detail-frozen");
  19621. }
  19622. // the insert's fader is live: moved, the frozen and the live song change alike
  19623. {
  19624. auto liveLouder = before, frozenLouder = frozenSong;
  19625. liveLouder.mixer[1].volume = frozenLouder.mixer[1].volume = 0.8f;
  19626. nullLine ("frozen vs live, the Lead's fader moved afterwards", renderMix ("live-louder", &liveLouder), renderMix ("frozen-louder", &frozenLouder), -90.0);
  19627. }
  19628. // --- what a save holds ---
  19629. {
  19630. const auto json = lynx::ProjectFile::toJson (offline.getSong(), false);
  19631. juce::String error;
  19632. const auto loaded = lynx::ProjectFile::fromJson (json, error);
  19633. check (json.contains ("\"trackFreeze\"") && ! json.contains ("\"freeze\""), "a track freeze is saved under its own key (older versions play it live)");
  19634. check (loaded.has_value() && loaded->channels.size() == frozenSong.channels.size() && loaded->channels[0].freeze == frozenSong.channels[0].freeze,
  19635. "a track-frozen project loads frozen, with its insert and audio files");
  19636. check (savedJson (lynx::freeze::thawed (offline.getSong())) == jsonBefore, "without the frozen state the project saves as before the freeze");
  19637. }
  19638. // --- an edit of a frozen device's insert routing: the freeze stops holding, the track plays live ---
  19639. {
  19640. offline.editSong ([] (lynx::Song& s) { s.channels[1].mixerTrack = 1; }); // (the Bass into the Lead's insert)
  19641. check (! lynx::freeze::trackFreezeHolds (offline.getSong(), 0) && offline.freezeOutOfDate (0), "another channel routed into a frozen insert: out of date, plays live");
  19642. offline.undo();
  19643. offline.dispatchPendingMessages();
  19644. check (lynx::freeze::trackFreezeHolds (offline.getSong(), 0) && ! offline.freezeOutOfDate (0), "undo: frozen again");
  19645. }
  19646. // --- Flatten: Bounce Track in Place on the frozen Lead, and its undo ---
  19647. {
  19648. const auto error = lynx::flattenChannelNow (offline, 0);
  19649. check (error.isEmpty(), "Bounce Track in Place of the frozen Lead (Flatten)" + (error.isEmpty() ? juce::String() : ": " + error));
  19650. const auto& song = offline.getSong();
  19651. check (song.channels[0].instrument == lynx::InstrumentKind::audioClip && song.mixer[1].effects.empty() && song.mixer[1].volume == before.mixer[1].volume
  19652. && song.channels[0].name == "Lead (Bounce)",
  19653. "the Lead is audio now (\"Lead (Bounce)\"), its insert's effects removed, its fader kept");
  19654. int audioClips = 0;
  19655. for (const auto& c : song.playlist)
  19656. audioClips += c.kind == lynx::ClipKind::audio && c.channel == 0;
  19657. report << "flattened Lead: " << audioClips << " audio clips\n";
  19658. write ("flattened");
  19659. // over the song (the flattened clips end where the arrangement ends, as a frozen track plays; an export's
  19660. // ring-out after the song's end is not in them)
  19661. const auto span = (int) std::llround (before.secondsForTicks (24 * lynx::ppq) * offline.getTransport().sampleRate.load());
  19662. auto flatMix = renderMix ("flattened");
  19663. auto reference = live;
  19664. reference.audio.setSize (2, juce::jmin (span, reference.audio.getNumSamples()), true);
  19665. flatMix.audio.setSize (2, reference.audio.getNumSamples(), true);
  19666. nullLine ("flattened (Lead) + frozen (others) vs live, over the song", reference, flatMix, -90.0);
  19667. offline.undo();
  19668. offline.dispatchPendingMessages();
  19669. check (savedJson (offline.getSong()) == savedJson (frozenSong), "undo of the Flatten: the frozen project exactly as before");
  19670. }
  19671. // --- Unfreeze every track ---
  19672. for (const auto c : channels)
  19673. lynx::unfreezeChannel (offline, c);
  19674. offline.dispatchPendingMessages();
  19675. check (savedJson (offline.getSong()) == jsonBefore, "Unfreeze: the project saves byte for byte as before the freeze");
  19676. nullLine ("unfrozen vs live", live, renderMix ("unfrozen"), -90.0);
  19677. // --- Bounce Track in Place of a live track (render and flatten in one step, one undo) ---
  19678. {
  19679. const auto error = lynx::freezeTrackNow (offline, 1, true);
  19680. check (error.isEmpty(), "Bounce Track in Place of the live Bass" + (error.isEmpty() ? juce::String() : ": " + error));
  19681. check (offline.getSong().channels[1].instrument == lynx::InstrumentKind::audioClip && ! offline.getSong().channels[1].freeze.on(),
  19682. "the Bass is audio, not frozen");
  19683. auto bouncedMix = renderMix ("bounced");
  19684. auto reference = live;
  19685. const auto span = (int) std::llround (before.secondsForTicks (24 * lynx::ppq) * offline.getTransport().sampleRate.load());
  19686. reference.audio.setSize (2, juce::jmin (span, reference.audio.getNumSamples()), true);
  19687. bouncedMix.audio.setSize (2, reference.audio.getNumSamples(), true);
  19688. nullLine ("Bass bounced in place vs live, over the song", reference, bouncedMix, -90.0);
  19689. offline.undo();
  19690. offline.dispatchPendingMessages();
  19691. check (savedJson (offline.getSong()) == jsonBefore, "undo of Bounce Track in Place: the project as before");
  19692. }
  19693. // --- Bounce to New Track: the Lead's clips onto a new track (the clips muted, the new track with the Lead's mixer) ---
  19694. {
  19695. std::vector<int> leadClips;
  19696. for (int i = 0; i < (int) offline.getSong().playlist.size(); ++i)
  19697. if (offline.getSong().playlist[(std::size_t) i].track == 0 && offline.getSong().playlist[(std::size_t) i].kind == lynx::ClipKind::pattern)
  19698. leadClips.push_back (i);
  19699. const auto channelsBefore = offline.getSong().channels.size();
  19700. const auto error = lynx::bounceToNewTrack (offline, leadClips, true);
  19701. check (error.isEmpty(), "Bounce to New Track of the Lead's clips" + (error.isEmpty() ? juce::String() : ": " + error));
  19702. const auto& song = offline.getSong();
  19703. check (song.channels.size() == channelsBefore + 1 && song.channels.back().instrument == lynx::InstrumentKind::audioClip
  19704. && song.channels.back().mixerTrack > 3 && song.mixer[(std::size_t) song.channels.back().mixerTrack].volume == before.mixer[1].volume,
  19705. "a new audio channel holds the bounce, on an insert with the Lead's mixer");
  19706. // the song's span (the bounce stops at the last clip's end, the live render rings on after it)
  19707. auto bounced = renderMix ("bounced-new-track");
  19708. auto reference = live;
  19709. const auto span = (int) std::llround (before.secondsForTicks (24 * lynx::ppq) * offline.getTransport().sampleRate.load());
  19710. reference.audio.setSize (2, juce::jmin (span, reference.audio.getNumSamples()), true);
  19711. bounced.audio.setSize (2, reference.audio.getNumSamples(), true);
  19712. nullLine ("Bounce to New Track (Lead's clips muted) vs live, over the song", reference, bounced, -90.0);
  19713. write ("bounced-new-track");
  19714. offline.undo();
  19715. offline.dispatchPendingMessages();
  19716. check (savedJson (offline.getSong()) == jsonBefore, "undo of Bounce to New Track: the project as before");
  19717. }
  19718. // --- Consolidate: the Bass's three pattern clips become one ---
  19719. {
  19720. std::vector<int> bassClips;
  19721. for (int i = 0; i < (int) offline.getSong().playlist.size(); ++i)
  19722. if (offline.getSong().playlist[(std::size_t) i].track == 1 && offline.getSong().playlist[(std::size_t) i].kind == lynx::ClipKind::pattern)
  19723. bassClips.push_back (i);
  19724. const auto error = lynx::consolidateClips (offline, bassClips, true);
  19725. check (error.isEmpty(), "Consolidate of the Bass's clips" + (error.isEmpty() ? juce::String() : ": " + error));
  19726. int left = 0;
  19727. for (const auto& c : offline.getSong().playlist)
  19728. left += c.track == 1 && c.kind == lynx::ClipKind::pattern;
  19729. check (left == 1, "one clip on the Bass track (" + juce::String (left) + ")");
  19730. nullLine ("consolidated vs live", live, renderMix ("consolidated"), -90.0);
  19731. offline.undo();
  19732. offline.dispatchPendingMessages();
  19733. check (savedJson (offline.getSong()) == jsonBefore, "undo of Consolidate: the project as before");
  19734. }
  19735. report << "frozen audio folder: " << offline.getFreezeFolder().getFullPathName() << "\n";
  19736. flush();
  19737. data.deleteRecursively();
  19738. (void) megabytes;
  19739. return failures == 0;
  19740. }
  19741. // --paintbench (round 190ge): the paint cost of every main view, off screen. Each view is shown maximised in a
  19742. // LYNX_SNAPSHOT_SIZE window (default 1920x1080) and drawn whole into a picture `frames` times (after a repaint of
  19743. // all of it, so no cached picture is reused: the cost of a frame after an edit), then `frames` times without the
  19744. // repaint (what a view's own caches leave of a frame). The report gives the median and the 90th percentile of
  19745. // the message thread's CPU per frame.
  19746. void runPaintBench (const juce::File& project, const juce::File& report)
  19747. {
  19748. // LYNX_PROFILE_MAIN=<file> (round 190gr): the message thread sampled while it paints (Windows; one view at a time
  19749. // with LYNX_PAINTBENCH_VIEWS)
  19750. const auto profile = juce::SystemStats::getEnvironmentVariable ("LYNX_PROFILE_MAIN", {});
  19751. if (profile.isNotEmpty())
  19752. lynx::crashguard::startMainProfiler (profile.toStdString(), 1000, 2);
  19753. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  19754. lynx::AudioEngine offline (false);
  19755. lynx::MainComponent ui (offline, false);
  19756. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1920x1080"), "x", "");
  19757. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  19758. juce::String text;
  19759. text << "project: " << project.getFullPathName() << "\nLYNX " << getApplicationVersion() << ", " << juce::SystemStats::getCpuModel()
  19760. << ", window " << ui.getWidth() << "x" << ui.getHeight() << "\n";
  19761. if (project.existsAsFile())
  19762. {
  19763. ui.openFile (project);
  19764. offline.dispatchPendingMessages();
  19765. }
  19766. const auto& song = offline.getSong();
  19767. text << "channels " << (int) song.channels.size() << ", patterns " << (int) song.patterns.size() << ", playlist clips " << (int) song.playlist.size()
  19768. << ", inserts " << (int) song.mixer.size() << "\n";
  19769. // the playhead a third into the song (song mode) so the views draw it as when playing
  19770. offline.getTransport().songMode = true;
  19771. offline.getTransport().positionTicks.store ((double) song.songLength() / 3.0);
  19772. const auto frames = juce::jlimit (3, 500, juce::SystemStats::getEnvironmentVariable ("LYNX_PAINTBENCH_FRAMES", "40").getIntValue());
  19773. juce::Image image (juce::Image::ARGB, ui.getWidth(), ui.getHeight(), true);
  19774. {
  19775. // (round 190gr) which renderer draws the frames: the software one (Linux), Direct2D (Windows), Core Graphics
  19776. juce::Graphics g (image);
  19777. auto& context = g.getInternalContext();
  19778. text << "renderer: " << (dynamic_cast<juce::LowLevelGraphicsSoftwareRenderer*> (&context) != nullptr ? "software" : typeid (context).name())
  19779. << ", paint caches " << (lynx::ui::paintCache() ? "on" : "off (LYNX_PAINT_CACHE=0)") << ", paint savings "
  19780. << (lynx::ui::paintSavings() ? "on" : "off (LYNX_PAINT_SAVINGS=0)") << "\n";
  19781. }
  19782. // LYNX_PAINTBENCH_VIEWS="mixer,channel rack" (round 190gr): only those views
  19783. const auto onlyViews = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_PAINTBENCH_VIEWS", {}), ",", "");
  19784. const auto wanted = [&onlyViews] (const juce::String& name) { return onlyViews.isEmpty() || onlyViews.contains (name); };
  19785. // the picture's pixels as one number: the same before and after a change = the same drawing
  19786. auto pixelHash = [&image] {
  19787. const juce::Image::BitmapData data (image, juce::Image::BitmapData::readOnly);
  19788. std::uint64_t h = 1469598103934665603ull;
  19789. for (int y = 0; y < data.height; ++y)
  19790. for (int x = 0; x < data.width; ++x)
  19791. h = (h ^ data.getPixelColour (x, y).getARGB()) * 1099511628211ull;
  19792. return juce::String::toHexString ((juce::int64) h);
  19793. };
  19794. // mode 0: whole frames after a repaint of everything; 1: whole frames, the views' own caches kept; 2: a 14-pixel
  19795. // column of the whole height at 40 places (what a moving playhead repaints each frame)
  19796. auto measure = [&] (const juce::String& name, int mode) {
  19797. offline.dispatchPendingMessages();
  19798. std::vector<double> ms, wall;
  19799. juce::String hash;
  19800. for (int f = -3; f < frames; ++f) // (3 frames to warm the caches up)
  19801. {
  19802. if (mode == 0)
  19803. ui.repaint();
  19804. const auto column = juce::Rectangle<int> ((juce::jmax (0, f) * 97) % juce::jmax (1, ui.getWidth() - 14), 0, 14, ui.getHeight());
  19805. const auto t0 = lynx::threadCpuSeconds();
  19806. const auto w0 = juce::Time::getMillisecondCounterHiRes();
  19807. {
  19808. juce::Graphics g (image);
  19809. if (mode == 2)
  19810. g.reduceClipRegion (column);
  19811. ui.paintEntireComponent (g, true);
  19812. }
  19813. if (f >= 0)
  19814. {
  19815. ms.push_back (1000.0 * (lynx::threadCpuSeconds() - t0));
  19816. wall.push_back (juce::Time::getMillisecondCounterHiRes() - w0); // (round 190gr: Direct2D's work ends with the frame)
  19817. }
  19818. if (f == 0 && mode == 0)
  19819. {
  19820. hash = pixelHash();
  19821. // LYNX_PAINTBENCH_PNG=<prefix> (round 190gr): the whole frame as <prefix>-<view>.png, to compare pixels
  19822. if (const auto png = juce::SystemStats::getEnvironmentVariable ("LYNX_PAINTBENCH_PNG", {}); png.isNotEmpty())
  19823. {
  19824. const juce::File file (png + "-" + name.replaceCharacter (' ', '-') + ".png");
  19825. file.deleteFile();
  19826. juce::FileOutputStream out (file);
  19827. juce::PNGImageFormat().writeImageToStream (image, out);
  19828. }
  19829. }
  19830. }
  19831. std::sort (ms.begin(), ms.end());
  19832. std::sort (wall.begin(), wall.end());
  19833. text << name << (mode == 0 ? ", whole frame" : mode == 1 ? ", cached frame" : ", playhead column") << ": median "
  19834. << juce::String (ms[ms.size() / 2], 3) << " ms, p90 " << juce::String (ms[(ms.size() * 9) / 10], 3) << " ms, wall median "
  19835. << juce::String (wall[wall.size() / 2], 3) << " ms"
  19836. << (hash.isNotEmpty() ? ", pixels " + hash : juce::String()) << "\n";
  19837. report.replaceWithText (text);
  19838. };
  19839. auto measureAll = [&] (const juce::String& name) {
  19840. if (! wanted (name))
  19841. return;
  19842. measure (name, 0);
  19843. measure (name, 1);
  19844. measure (name, 2);
  19845. // the columns' pixels too (painted over the whole frame: culling must not change a pixel)
  19846. ui.repaint();
  19847. {
  19848. juce::Graphics g (image);
  19849. ui.paintEntireComponent (g, true);
  19850. for (int x = 3; x < ui.getWidth() - 14; x += 211)
  19851. {
  19852. juce::Graphics::ScopedSaveState state (g);
  19853. g.reduceClipRegion (x, 0, 14, ui.getHeight());
  19854. ui.paintEntireComponent (g, true);
  19855. }
  19856. }
  19857. text << name << ", columns over the whole frame: pixels " << pixelHash() << "\n";
  19858. };
  19859. const char* views[] { "channel rack", "piano roll", "playlist", "mixer" };
  19860. for (int v = 0; v < 4; ++v)
  19861. {
  19862. ui.selectTabForSnapshot (v);
  19863. measureAll (views[v]);
  19864. }
  19865. ui.showDesktopForSnapshot (false);
  19866. measureAll ("desktop");
  19867. ui.selectTabForSnapshot (2);
  19868. ui.setClipLaunchWorkflow (true);
  19869. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  19870. measureAll ("clip grid");
  19871. ui.setClipLaunchWorkflow (false);
  19872. text << "result=OK\n";
  19873. report.replaceWithText (text);
  19874. if (profile.isNotEmpty())
  19875. lynx::crashguard::stopMainProfiler();
  19876. }
  19877. void runGridShot (const juce::String& prefix, const juce::String& projectPath = {})
  19878. {
  19879. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  19880. lynx::AudioEngine offline (false);
  19881. lynx::MainComponent ui (offline, false);
  19882. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  19883. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  19884. const auto write = [&prefix, &ui] (const char* name) {
  19885. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  19886. file.deleteFile();
  19887. juce::FileOutputStream out (file);
  19888. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (ui), out);
  19889. };
  19890. ui.selectTabForSnapshot (2); // the Playlist panel, maximized
  19891. if (projectPath.isNotEmpty())
  19892. {
  19893. ui.openFile (juce::File (projectPath));
  19894. offline.dispatchPendingMessages();
  19895. ui.setClipLaunchWorkflow (true);
  19896. offline.dispatchPendingMessages();
  19897. write ("file-both");
  19898. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  19899. write ("file-grid");
  19900. const auto& song = offline.getSong();
  19901. juce::String info;
  19902. info << "grid " << (song.clipGrid ? "yes" : "no") << ", clips " << (song.clipGrid ? (int) song.clipGrid->clips.size() : 0)
  19903. << ", scenes " << (song.clipGrid ? (int) song.clipGrid->scenes.size() : 0) << ", playlist clips " << (int) song.playlist.size() << "\n";
  19904. juce::File (prefix + "-file.txt").replaceWithText (info);
  19905. ui.setClipLaunchWorkflow (false);
  19906. return;
  19907. }
  19908. write ("pattern"); // Pattern workflow: nothing of the grid exists yet
  19909. const auto madeBefore = lynx::launcher::Runtime::instances.load();
  19910. offline.editSong ([] (lynx::Song& s) {
  19911. while (s.patterns.size() < 6)
  19912. s.patterns.emplace_back();
  19913. for (int p = 0; p < 6; ++p)
  19914. {
  19915. auto& pattern = s.patterns[(std::size_t) p];
  19916. const char* names[] { "Drums A", "Drums B", "Bass", "Chords", "Lead", "Pad" };
  19917. pattern.name = names[p];
  19918. pattern.lengthTicks = 4 * lynx::ppq;
  19919. }
  19920. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 6));
  19921. const char* tracks[] { "Drums", "Bass", "Chords", "Lead", "Vocals", "FX" };
  19922. for (int t = 0; t < 6; ++t)
  19923. s.playlistTracks[(std::size_t) t].name = tracks[t];
  19924. 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 } };
  19925. for (const auto& c : placed)
  19926. {
  19927. lynx::Clip clip;
  19928. clip.pattern = c[2];
  19929. clip.length = 4 * lynx::ppq;
  19930. lynx::launcher::setClip (s, c[0], c[1], clip);
  19931. }
  19932. auto& grid = lynx::launcher::ensureGrid (s);
  19933. const char* scenes[] { "Intro", "Verse", "Drop", "Break" };
  19934. grid.scenes.resize (6);
  19935. for (int r = 0; r < 4; ++r)
  19936. grid.scenes[(std::size_t) r].name = scenes[r];
  19937. }, false);
  19938. offline.dispatchPendingMessages();
  19939. write ("pattern-edited"); // the same song as -pattern-after: the workflow must leave no trace
  19940. ui.setClipLaunchWorkflow (true);
  19941. offline.dispatchPendingMessages();
  19942. if (auto* runtime = offline.launcherStateForSnapshot())
  19943. {
  19944. runtime->tracks[0].playing.store (2);
  19945. runtime->tracks[0].progress.store (0.4f);
  19946. runtime->tracks[0].taken.store (true);
  19947. runtime->tracks[1].playing.store (2);
  19948. runtime->tracks[1].progress.store (0.4f);
  19949. runtime->tracks[1].taken.store (true);
  19950. runtime->tracks[2].pending.store (2);
  19951. runtime->tracks[3].taken.store (true);
  19952. }
  19953. write ("both");
  19954. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  19955. write ("grid");
  19956. // round 190bv: recording into slots and the Groove Pool. Two tracks armed (round record buttons in their empty
  19957. // slots, their arm buttons lit), one of them recording and one waiting for its start; then a clip through a
  19958. // groove with the pool shown, and the slot menus
  19959. if (auto* gridView = ui.getClipGridForSnapshot())
  19960. {
  19961. offline.setGridTrackArmed (4, true);
  19962. offline.setGridTrackArmed (5, true, false);
  19963. offline.dispatchPendingMessages();
  19964. write ("rec-armed");
  19965. if (auto* runtime = offline.launcherStateForSnapshot())
  19966. {
  19967. runtime->tracks[4].recording.store (1);
  19968. runtime->tracks[4].recordFrom.store (0.0); // (round 190cy: one beat recorded, the counter reads 0.1.0)
  19969. runtime->clockNow.store ((double) lynx::ppq);
  19970. runtime->tracks[5].recordPending.store (1);
  19971. }
  19972. write ("rec-recording");
  19973. if (auto* runtime = offline.launcherStateForSnapshot())
  19974. {
  19975. runtime->tracks[4].recording.store (-1);
  19976. runtime->tracks[5].recordPending.store (-1);
  19977. }
  19978. offline.editSong ([] (lynx::Song& s) {
  19979. const auto& bank = lynx::groove::factoryBank();
  19980. std::uint32_t first = 0;
  19981. for (const auto index : { std::size_t (9), std::size_t (20), std::size_t (27) })
  19982. if (index < bank.size())
  19983. {
  19984. const auto id = lynx::groove::add (s.grooves, bank[index].groove);
  19985. first = first == 0 ? id : first;
  19986. }
  19987. lynx::groove::setClipGroove (s, 0, 0, first);
  19988. }, false);
  19989. offline.dispatchPendingMessages();
  19990. lynx::setClipGridGroovePoolShown (*gridView, true);
  19991. write ("groove-pool");
  19992. saveMenus ({ "Clip slot", "Groove", "Empty slot" },
  19993. { lynx::clipGridSlotMenu (*gridView, 0, 0), [&] {
  19994. juce::PopupMenu found;
  19995. const auto menu = lynx::clipGridSlotMenu (*gridView, 0, 0);
  19996. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  19997. if (it.getItem().subMenu != nullptr && it.getItem().text == lynx::tr ("Groove"))
  19998. found = *it.getItem().subMenu;
  19999. return found;
  20000. }(), lynx::clipGridSlotMenu (*gridView, 4, 1) },
  20001. prefix + "-rec-menus.png");
  20002. lynx::setClipGridGroovePoolShown (*gridView, false);
  20003. // round 190cy: a second record button pressed while recording: the first take ("Vocals 1") plays on, the
  20004. // clicked slot records "Vocals 2" with its counter at 2.0.2 (as Live 12.4.16, live check 190cw shot 03b)
  20005. {
  20006. const auto name = offline.slotRecordingName (4);
  20007. offline.editSong ([&name] (lynx::Song& s) { lynx::session::placeRecordedPattern (s, 4, 0, {}, 8 * lynx::ppq, name); }, false);
  20008. offline.dispatchPendingMessages();
  20009. if (auto* runtime = offline.launcherStateForSnapshot())
  20010. {
  20011. runtime->tracks[4].playing.store (0);
  20012. runtime->tracks[4].progress.store (0.3f);
  20013. runtime->tracks[4].recording.store (1);
  20014. runtime->tracks[4].recordFrom.store (0.0);
  20015. runtime->clockNow.store (8.0 * lynx::ppq + 2.0 * lynx::ppq / 4.0);
  20016. }
  20017. write ("rec-second");
  20018. if (auto* runtime = offline.launcherStateForSnapshot())
  20019. {
  20020. runtime->tracks[4].playing.store (-1);
  20021. runtime->tracks[4].recording.store (-1);
  20022. }
  20023. offline.editSong ([] (lynx::Song& s) {
  20024. if (lynx::session::cut (s, 4, 0) && ! s.patterns.empty())
  20025. s.patterns.pop_back();
  20026. }, false);
  20027. offline.dispatchPendingMessages();
  20028. }
  20029. offline.setGridTrackArmed (4, false);
  20030. offline.setGridTrackArmed (5, false);
  20031. offline.dispatchPendingMessages();
  20032. }
  20033. ui.setClipGridView (lynx::PlaylistArea::GridView::song);
  20034. write ("song");
  20035. ui.setClipLaunchWorkflow (false);
  20036. write ("pattern-after");
  20037. juce::File (prefix + "-counts.txt").replaceWithText ("runtimes before " + juce::String (madeBefore) + ", after " + juce::String (lynx::launcher::Runtime::instances.load()) + "\n");
  20038. }
  20039. // Round 190bu: the Simple workflow's track dock (ui/SimpleDock.h), off-screen
  20040. void runSimpleFxShot (const juce::String& prefix)
  20041. {
  20042. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  20043. lynx::AudioEngine offline (false);
  20044. lynx::MainComponent ui (offline, false);
  20045. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  20046. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  20047. const auto writeImage = [&prefix] (const juce::Image& image, const juce::String& name) {
  20048. const auto file = juce::File (prefix + "-" + name + ".png");
  20049. file.deleteFile();
  20050. juce::FileOutputStream out (file);
  20051. juce::PNGImageFormat().writeImageToStream (image, out);
  20052. };
  20053. juce::String report;
  20054. const auto line = [&report] (const juce::String& text) { report << text << "\n"; };
  20055. const auto check = [&report] (const juce::String& what, bool ok) { report << (ok ? "OK " : "ERROR ") << what << "\n"; };
  20056. const auto madeBefore = lynx::SimpleWorkflow::instances.load();
  20057. ui.selectTabForSnapshot (2);
  20058. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  20059. offline.dispatchPendingMessages();
  20060. auto* simple = ui.getSimpleWorkflowForSnapshot();
  20061. if (simple == nullptr)
  20062. {
  20063. juce::File (prefix + "-report.txt").replaceWithText ("ERROR no Simple workflow\n");
  20064. return;
  20065. }
  20066. simple->hideChooser();
  20067. // three tracks: a voice, keys with a few chords, a drum kit
  20068. int keysInsert = -1;
  20069. offline.editSong ([&keysInsert] (lynx::Song& s) {
  20070. namespace st = lynx::simpletracks;
  20071. st::Request q;
  20072. q.kind = st::Kind::voice;
  20073. q.name = "Lead vocal";
  20074. st::addTrack (s, q);
  20075. q = {};
  20076. q.kind = st::Kind::instrument;
  20077. q.name = "Keys";
  20078. lynx::ChannelDef keys;
  20079. keys.instrument = lynx::InstrumentKind::synth;
  20080. q.channel = keys;
  20081. lynx::Pattern chords;
  20082. for (int i = 0; i < 4; ++i)
  20083. for (int k : { 60, 64, 67 })
  20084. chords.notes.push_back (lynx::Note { (std::int64_t) i * 4 * lynx::ppq, 4 * lynx::ppq - lynx::ppq / 4, 0, k });
  20085. q.pattern = chords;
  20086. keysInsert = st::addTrack (s, q).insert;
  20087. q = {};
  20088. q.kind = st::Kind::drums;
  20089. for (auto kind : { lynx::InstrumentKind::kick, lynx::InstrumentKind::snare, lynx::InstrumentKind::hat })
  20090. {
  20091. lynx::ChannelDef c;
  20092. c.instrument = kind;
  20093. c.name = kind == lynx::InstrumentKind::kick ? "Kick" : kind == lynx::InstrumentKind::snare ? "Snare" : "Hat";
  20094. q.kit.push_back (c);
  20095. }
  20096. lynx::Pattern beat;
  20097. for (int step = 0; step < 16; step += 2)
  20098. beat.notes.push_back (lynx::Note { (std::int64_t) step * lynx::ticksPerStep, lynx::ticksPerStep, 2, 60 });
  20099. q.pattern = beat;
  20100. st::addTrack (s, q);
  20101. });
  20102. offline.dispatchPendingMessages();
  20103. simple->hideChooser();
  20104. auto& playlist = ui.getPlaylistForSnapshot();
  20105. // the tracks' places in the Playlist
  20106. int voiceTrack = -1, keysTrack = -1, drumsTrack = -1;
  20107. {
  20108. const auto& song = offline.getSong();
  20109. for (int t = 0; t < (int) song.playlistTracks.size(); ++t)
  20110. if (const auto kind = lynx::simpletracks::kindOf (song, t))
  20111. {
  20112. if (*kind == lynx::simpletracks::Kind::audio && voiceTrack < 0)
  20113. voiceTrack = t;
  20114. else if (*kind == lynx::simpletracks::Kind::instrument && keysTrack < 0)
  20115. keysTrack = t;
  20116. else if (*kind == lynx::simpletracks::Kind::drums && drumsTrack < 0)
  20117. drumsTrack = t;
  20118. }
  20119. }
  20120. check ("three Simple tracks (voice, keys, drums)", voiceTrack >= 0 && keysTrack >= 0 && drumsTrack >= 0);
  20121. playlist.selectTrack (keysTrack);
  20122. offline.dispatchPendingMessages();
  20123. auto* dock = simple->dockForSnapshot();
  20124. if (dock == nullptr)
  20125. {
  20126. juce::File (prefix + "-report.txt").replaceWithText (report + "ERROR no dock\n");
  20127. return;
  20128. }
  20129. // the whole window and the dock alone, at 1x and 2x
  20130. const auto shots = [&] (const juce::String& name) {
  20131. offline.dispatchPendingMessages();
  20132. for (float scale : { 1.0f, 2.0f })
  20133. {
  20134. const auto suffix = scale > 1.0f ? juce::String ("@2x") : juce::String();
  20135. writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, scale), name + suffix);
  20136. writeImage (dock->createComponentSnapshot (dock->getLocalBounds(), true, scale), "dock-" + name + suffix);
  20137. }
  20138. };
  20139. const auto menuShot = [&] (const juce::PopupMenu& menu, const juce::String& title, const juce::String& subTitle, const juce::String& name) {
  20140. juce::StringArray names { title };
  20141. std::vector<juce::PopupMenu> menus { menu };
  20142. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  20143. if (it.getItem().subMenu != nullptr && it.getItem().text == subTitle)
  20144. {
  20145. names.add (subTitle);
  20146. menus.push_back (*it.getItem().subMenu);
  20147. }
  20148. saveMenus (names, menus, prefix + "-" + name + ".png");
  20149. };
  20150. // --- the Instrument tab ---------------------------------------------------------------------------------------
  20151. check ("the dock shows the selected track", dock->shownTrack() == keysTrack && dock->isVisible() && dock->getParentComponent() != nullptr);
  20152. check ("an instrument track opens on its sound", dock->hasInstrumentTabForCheck() && dock->getTab() == lynx::SimpleDock::Tab::instrument);
  20153. const auto channel = dock->channelForCheck();
  20154. line ("sound at first: " + dock->soundNameForCheck() + ", rows in its category: " + juce::String (dock->soundRowsForCheck()));
  20155. shots ("instrument");
  20156. // a click on a row of another category: the track plays that sound, its own settings stay
  20157. const auto before = offline.getSong().channels[(std::size_t) channel];
  20158. dock->showCategoryForSnapshot ((int) lynx::soundlib::Category::pad);
  20159. offline.dispatchPendingMessages();
  20160. const auto padRows = dock->soundRowsForCheck();
  20161. dock->clickSoundForCheck (juce::jmin (2, padRows - 1));
  20162. offline.dispatchPendingMessages();
  20163. {
  20164. const auto& now = offline.getSong().channels[(std::size_t) channel];
  20165. const auto found = lynx::soundlib::find (lynx::soundlib::builtIn(), now);
  20166. check ("a click on a sound puts it on the track's channel (" + dock->soundNameForCheck() + ")",
  20167. padRows > 0 && found >= 0 && lynx::soundlib::builtIn()[(std::size_t) found].category == lynx::soundlib::Category::pad
  20168. && ! lynx::soundlib::sameSound (before, now));
  20169. check ("the channel keeps its name, level and insert", now.name == before.name && now.volume == before.volume && now.mixerTrack == before.mixerTrack);
  20170. double seconds = 0.0;
  20171. const auto heard = offline.auditionSound (now, { 60, 64, 67 }, &seconds);
  20172. check ("the sound's audition renders (" + juce::String (seconds, 2) + " s)", heard && seconds > 1.0);
  20173. }
  20174. shots ("instrument-pad");
  20175. const auto picked = dock->soundNameForCheck();
  20176. dock->stepSoundForCheck (1);
  20177. offline.dispatchPendingMessages();
  20178. const auto stepped = dock->soundNameForCheck();
  20179. dock->stepSoundForCheck (-1);
  20180. offline.dispatchPendingMessages();
  20181. check ("the arrows step through the category (" + picked + " -> " + stepped + " -> back)", stepped != picked && dock->soundNameForCheck() == picked);
  20182. check ("one undo step per sound", offline.canUndo());
  20183. // the user's SoundFont files (an index made here: no file is read)
  20184. {
  20185. std::vector<lynx::sf::IndexedFont> fonts (2);
  20186. fonts[0].path = "/home/me/SoundFonts/Concert Band.sf2";
  20187. fonts[0].name = "Concert Band";
  20188. int program = 0;
  20189. for (const char* name : { "Grand Piano", "Bright Piano", "Electric Piano", "Harpsichord", "Clavinet", "Celesta", "Music Box", "Vibraphone" })
  20190. fonts[0].presets.push_back ({ name, 0, program++ });
  20191. 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 } })
  20192. fonts[0].presets.push_back ({ name, 0, p });
  20193. fonts[0].presets.push_back ({ "Standard Kit", 128, 0 });
  20194. fonts[1].path = "/home/me/SoundFonts/Old Upright.sf2";
  20195. fonts[1].name = "Old Upright";
  20196. fonts[1].presets.push_back ({ "Old Upright", 0, 0 });
  20197. fonts[1].presets.push_back ({ "Old Upright Soft", 0, 1 });
  20198. dock->setFontsForSnapshot (fonts);
  20199. dock->showCategoryForSnapshot ((int) lynx::soundlib::Category::keys);
  20200. offline.dispatchPendingMessages();
  20201. check ("My SoundFonts lists the presets of the user's files by category (Keys: " + juce::String (dock->soundRowsForCheck()) + " of 17)", dock->soundRowsForCheck() == 7);
  20202. dock->clickSoundForCheck (0);
  20203. offline.dispatchPendingMessages();
  20204. const auto& now = offline.getSong().channels[(std::size_t) channel];
  20205. check ("a SoundFont preset becomes the track's sound (" + dock->soundNameForCheck() + ")",
  20206. now.instrument == lynx::InstrumentKind::soundfont && juce::String (now.samplePath).endsWith (".sf2"));
  20207. shots ("instrument-soundfonts");
  20208. }
  20209. // --- the Effects tab ------------------------------------------------------------------------------------------
  20210. playlist.selectTrack (voiceTrack);
  20211. offline.dispatchPendingMessages();
  20212. const auto insert = dock->insertForCheck();
  20213. check ("an audio track has no Instrument tab and opens on its effects",
  20214. dock->shownTrack() == voiceTrack && ! dock->hasInstrumentTabForCheck() && dock->getTab() == lynx::SimpleDock::Tab::effects && insert > 0);
  20215. check ("no effects yet: no cards", dock->cardCountForCheck() == 0);
  20216. shots ("effects-empty");
  20217. menuShot (dock->addMenuForSnapshot(), lynx::tr ("Add an effect"), {}, "menu-add");
  20218. // + adds one-knob effects at the end of the chain
  20219. dock->addOneKnobForCheck (lynx::goals::brighter);
  20220. dock->addOneKnobForCheck (lynx::goals::room);
  20221. dock->addOneKnobForCheck (lynx::goals::level);
  20222. offline.dispatchPendingMessages();
  20223. const auto slotsText = [&offline] (int t) {
  20224. juce::String text;
  20225. const auto rows = lynx::mixerops::effectRows (offline.getSong().mixer[(std::size_t) t].effects); // (the Mixer's slot of each)
  20226. std::size_t at = 0;
  20227. for (const auto& fx : offline.getSong().mixer[(std::size_t) t].effects)
  20228. text << "[slot " << rows[at++] + 1 << " " << lynx::effectInfo (fx.kind).name
  20229. << (lynx::goals::active (fx) ? " = " + juce::String (lynx::goals::name (fx.goal)) + " " + juce::String (juce::roundToInt (fx.goalAmount * 100.0f)) + "%" : juce::String())
  20230. << (fx.enabled ? "" : " off") << "] ";
  20231. return text.trimEnd();
  20232. };
  20233. line ("after + x3: " + slotsText (insert));
  20234. check ("three cards, three one-knob effects", dock->cardCountForCheck() == 3 && dock->oneKnobCardsForCheck() == 3);
  20235. // the knob writes the effect's own parameters
  20236. const auto roomBefore = offline.getSong().mixer[(std::size_t) insert].effects[1];
  20237. dock->turnKnobForCheck (1, 0.8f);
  20238. offline.dispatchPendingMessages();
  20239. {
  20240. const auto& room = offline.getSong().mixer[(std::size_t) insert].effects[1];
  20241. 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));
  20242. }
  20243. // ‹ › reorder, × removes
  20244. dock->moveCardForCheck (2, -1);
  20245. offline.dispatchPendingMessages();
  20246. line ("Level moved left: " + slotsText (insert));
  20247. {
  20248. const auto& fx = offline.getSong().mixer[(std::size_t) insert].effects;
  20249. check ("the card moved one place earlier", fx.size() == 3 && fx[1].goal == lynx::goals::level && fx[2].goal == lynx::goals::room);
  20250. }
  20251. dock->removeCardForCheck (0);
  20252. offline.dispatchPendingMessages();
  20253. line ("Brighter removed: " + slotsText (insert));
  20254. check ("the card is gone", dock->cardCountForCheck() == 2 && offline.getSong().mixer[(std::size_t) insert].effects.size() == 2);
  20255. // a hand edit in the full editor: the slot is an ordinary effect again (its card shows Mix)
  20256. offline.editSong ([insert] (lynx::Song& s) {
  20257. auto& slot = s.mixer[(std::size_t) insert].effects[0];
  20258. const auto moved = (std::size_t) lynx::goals::mapping (slot.goal, slot.goalAmount).back().param;
  20259. slot.params[moved] = slot.params[moved] > 0.5f ? 0.2f : 0.9f;
  20260. });
  20261. offline.dispatchPendingMessages();
  20262. check ("a parameter moved by hand makes the card an ordinary effect", dock->cardCountForCheck() == 2 && dock->oneKnobCardsForCheck() == 1);
  20263. dock->turnKnobForCheck (0, 0.5f); // (its knob is the slot's Mix now)
  20264. offline.dispatchPendingMessages();
  20265. 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);
  20266. // a preset replaces the chain; Blend is the chain's dry/wet
  20267. if (const auto* preset = lynx::chains::find ("Clear Voice"))
  20268. offline.editSongStructural ([insert, preset] (lynx::Song& s) { lynx::chains::apply (s, insert, *preset); });
  20269. offline.dispatchPendingMessages();
  20270. line ("preset Clear Voice: " + slotsText (insert));
  20271. 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)
  20272. && dock->cardCountForCheck() == (int) offline.getSong().mixer[(std::size_t) insert].effects.size());
  20273. shots ("effects-preset");
  20274. menuShot (dock->presetMenuForSnapshot(), lynx::tr ("Preset"), lynx::tr ("Voice"), "menu-preset");
  20275. dock->setBlendForCheck (0.7f);
  20276. dock->addOneKnobForCheck (lynx::goals::echo);
  20277. offline.dispatchPendingMessages();
  20278. check ("Blend 70 % is the insert's chain blend; the preset shows as edited",
  20279. std::abs (offline.getSong().mixer[(std::size_t) insert].chainBlend - 0.7f) < 1.0e-6f && ! lynx::chains::unchanged (offline.getSong(), insert));
  20280. shots ("effects-edited");
  20281. // a user preset: saved to a file, loaded on another track (its slots and Blend; that track's level stays)
  20282. const auto mine = offline.getSong().mixer[(std::size_t) insert];
  20283. const auto saved = lynx::SimpleDock::saveUserPreset (offline, insert, "My voice");
  20284. const auto file = lynx::SimpleDock::userPresetFolder().getChildFile ("My voice.lynxtrack");
  20285. check ("the preset is saved as " + file.getFileName(), saved && file.existsAsFile() && offline.getSong().mixer[(std::size_t) insert].chainPreset == "My voice");
  20286. offline.editSong ([keysInsert] (lynx::Song& s) { s.mixer[(std::size_t) keysInsert].volume = 0.42f; });
  20287. const auto loaded = keysInsert > 0 && lynx::SimpleDock::loadUserPreset (offline, keysInsert, file);
  20288. offline.dispatchPendingMessages();
  20289. {
  20290. const auto& other = offline.getSong().mixer[(std::size_t) keysInsert];
  20291. auto same = loaded && other.effects.size() == mine.effects.size() && std::abs (other.chainBlend - mine.chainBlend) < 1.0e-6f && other.chainPreset == "My voice";
  20292. for (std::size_t i = 0; same && i < mine.effects.size(); ++i)
  20293. same = other.effects[i].kind == mine.effects[i].kind && other.effects[i].goal == mine.effects[i].goal
  20294. && 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]);
  20295. check ("loaded on the Keys track: the same slots and Blend", same);
  20296. check ("the Keys track keeps its level", std::abs (other.volume - 0.42f) < 1.0e-6f);
  20297. line ("Keys after load: " + slotsText (keysInsert));
  20298. }
  20299. menuShot (dock->presetMenuForSnapshot(), lynx::tr ("Preset"), lynx::tr ("My presets"), "menu-preset-mine");
  20300. file.deleteFile();
  20301. // the drums: effects only (a kit has no single sound to pick)
  20302. playlist.selectTrack (drumsTrack);
  20303. offline.dispatchPendingMessages();
  20304. check ("the Drums track shows its insert's effects, no Instrument tab", dock->shownTrack() == drumsTrack && ! dock->hasInstrumentTabForCheck() && dock->insertForCheck() > 0);
  20305. if (const auto* preset = lynx::chains::find ("Smash Room"))
  20306. offline.editSongStructural ([t = dock->insertForCheck(), preset] (lynx::Song& s) { lynx::chains::apply (s, t, *preset); });
  20307. shots ("effects-drums");
  20308. // the project file keeps all of it
  20309. {
  20310. juce::String error;
  20311. const auto json = lynx::ProjectFile::toJson (offline.getSong());
  20312. const auto back = lynx::ProjectFile::fromJson (json, error);
  20313. auto same = back && back->mixer.size() == offline.getSong().mixer.size();
  20314. for (std::size_t t = 0; same && t < back->mixer.size(); ++t)
  20315. {
  20316. const auto& a = offline.getSong().mixer[t];
  20317. const auto& b = back->mixer[t];
  20318. same = a.effects.size() == b.effects.size() && std::abs (a.chainBlend - b.chainBlend) < 1.0e-6f && a.chainPreset == b.chainPreset;
  20319. for (std::size_t i = 0; same && i < a.effects.size(); ++i)
  20320. 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
  20321. && std::abs (a.effects[i].goalAmount - b.effects[i].goalAmount) < 1.0e-6f;
  20322. }
  20323. check ("saved and loaded as a project: the same chains, knobs, Blend and preset names", same);
  20324. }
  20325. // --- the same plugins in the same slots in FL's layout --------------------------------------------------------
  20326. const auto simpleSong = offline.getSong();
  20327. const auto inSimple = slotsText (insert);
  20328. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
  20329. offline.dispatchPendingMessages();
  20330. check ("Pattern workflow: the dock is gone", dock->getParentComponent() == nullptr);
  20331. ui.selectTabForSnapshot (3);
  20332. ui.getMixerForSnapshot().selectTrack (insert);
  20333. offline.dispatchPendingMessages();
  20334. for (float scale : { 1.0f, 2.0f })
  20335. writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, scale), juce::String ("pattern-mixer") + (scale > 1.0f ? "@2x" : ""));
  20336. line ("Simple layout: " + inSimple);
  20337. line ("Pattern layout: " + slotsText (insert));
  20338. check ("the same effects in the same Mixer slots in the Pattern workflow", offline.getSong().mixer == simpleSong.mixer && offline.getSong().channels == simpleSong.channels);
  20339. // an effect added in the Mixer's way shows as a card when the Simple workflow comes back
  20340. offline.editSongStructural ([insert] (lynx::Song& s) { lynx::mixerops::insertEffectAtRow (s, insert, lynx::makeEffectSlot (lynx::EffectKind::chorus), 7); });
  20341. ui.selectTabForSnapshot (2);
  20342. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  20343. offline.dispatchPendingMessages();
  20344. simple->hideChooser();
  20345. playlist.selectTrack (voiceTrack);
  20346. offline.dispatchPendingMessages();
  20347. check ("back in Simple: the dock shows the insert as it is now, the Mixer's new effect too",
  20348. dock->getParentComponent() != nullptr && dock->cardCountForCheck() == (int) offline.getSong().mixer[(std::size_t) insert].effects.size()
  20349. && lynx::mixerops::effectRows (offline.getSong().mixer[(std::size_t) insert].effects).back() == 7);
  20350. line ("Simple again: " + slotsText (insert));
  20351. shots ("effects-back");
  20352. // hidden with its key, shown again by "+FX"
  20353. simple->toggleDock();
  20354. offline.dispatchPendingMessages();
  20355. check ("Ctrl+Alt+L hides the dock", ! simple->isDockShowing() && ! lynx::SimpleDock::shownSetting);
  20356. writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, 1.0f), "dock-hidden");
  20357. simple->showEffectsOfInsert (keysInsert);
  20358. offline.dispatchPendingMessages();
  20359. check ("+FX on a track header shows the dock on that track's effects",
  20360. simple->isDockShowing() && dock->shownTrack() == keysTrack && dock->getTab() == lynx::SimpleDock::Tab::effects && dock->insertForCheck() == keysInsert);
  20361. simple->cycleDockTab();
  20362. check ("Shift+Tab goes to the Instrument tab", dock->getTab() == lynx::SimpleDock::Tab::instrument);
  20363. line ("Simple workflow objects: " + juce::String (madeBefore) + " before, " + juce::String (lynx::SimpleWorkflow::instances.load()) + " after");
  20364. line (report.contains ("ERROR ") ? "RESULT ERROR" : "RESULT OK");
  20365. juce::File (prefix + "-report.txt").replaceWithText (report);
  20366. }
  20367. // --simpleclosetest (round 190fc, 0.1.27 RC blocker B1): every close in the Simple layout crashed (the Simple workflow
  20368. // was destroyed after the Workspace and its destructor called into it). Off-screen, no window: the main window in the
  20369. // Simple layout with everything of it open — Welcome, the first-song tour's card, Start from, a demo song, each dock
  20370. // tab (the Editor tab docks the Piano roll), Finish, Lyrics, the chooser — then destroyed as the app's shutdown does.
  20371. // A second main window goes Simple -> Pattern -> Simple and closes too. Checks: no Simple workflow outlives its main
  20372. // window's destructor body, none is left at all. (Under ASan on Linux the old order is a heap-use-after-free.)
  20373. bool runDonateShot (const juce::String& prefix)
  20374. {
  20375. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  20376. juce::String report;
  20377. bool ok = true;
  20378. const auto line = [&report, &prefix] (const juce::String& text) {
  20379. report << text << "\n";
  20380. juce::File (prefix + "-report.txt").replaceWithText (report); // (written as it goes)
  20381. };
  20382. const auto check = [&line, &ok] (const juce::String& what, bool good) {
  20383. line ((good ? "ok " : "FAIL ") + what);
  20384. ok = ok && good;
  20385. };
  20386. const auto writeImage = [&prefix] (const juce::Image& image, const juce::String& name) {
  20387. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  20388. file.deleteFile();
  20389. juce::FileOutputStream out (file);
  20390. juce::PNGImageFormat().writeImageToStream (image, out);
  20391. };
  20392. // a window as the --snapshot route saves one (off the desktop, on the theme's panel colour), at 1x and 2x
  20393. const auto saveAlert = [&] (juce::AlertWindow& w, const juce::String& name) {
  20394. if (w.isOnDesktop())
  20395. w.removeFromDesktop();
  20396. w.setOpaque (true);
  20397. juce::Component frame;
  20398. frame.setSize (w.getWidth(), w.getHeight());
  20399. frame.setOpaque (true);
  20400. frame.addAndMakeVisible (w);
  20401. w.setTopLeftPosition (0, 0);
  20402. writeImage (lynx::shot::paint (frame, lynx::theme::panel), name);
  20403. writeImage (frame.createComponentSnapshot (frame.getLocalBounds(), true, 2.0f), name + "@2x");
  20404. frame.removeChildComponent (&w);
  20405. };
  20406. const auto buttonTexts = [] (juce::AlertWindow& w) {
  20407. juce::StringArray texts;
  20408. for (int b = 0; b < w.getNumButtons(); ++b)
  20409. if (auto* button = w.getButton (b))
  20410. texts.add (button->getButtonText());
  20411. return texts;
  20412. };
  20413. check ("the donation page is one constant, on Ko-fi", juce::String (lynx::links::donate).startsWith ("https://ko-fi"));
  20414. line ("donate URL: " + juce::String (lynx::links::donate));
  20415. const auto stateFile = lynx::PluginHost::settingsFolder().getChildFile ("support-note.txt");
  20416. const auto hadState = stateFile.existsAsFile();
  20417. const auto oldState = stateFile.loadFileAsString();
  20418. line ("state file: " + stateFile.getFullPathName() + (hadState ? " (exists; put back at the end)" : ""));
  20419. {
  20420. lynx::AudioEngine offline (false);
  20421. lynx::MainComponent ui (offline, false);
  20422. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  20423. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  20424. ui.setVisible (true);
  20425. const auto settle = [&] {
  20426. for (int k = 0; k < 3; ++k)
  20427. offline.dispatchPendingMessages();
  20428. };
  20429. // --- Help › Support LYNX SHARE..., right above About, in the three layouts ----------------------------------
  20430. for (auto [style, name] : { std::pair { lynx::layoutstyle::Style::pattern, "pattern" }, { lynx::layoutstyle::Style::clipLaunch, "cliplaunch" },
  20431. { lynx::layoutstyle::Style::simple, "simple" } })
  20432. {
  20433. ui.setLayoutStyle (style);
  20434. settle();
  20435. const auto help = ui.getMenuForSnapshot (ui.getMenuNamesForSnapshot().indexOf (lynx::tr ("Help")));
  20436. juce::StringArray items;
  20437. for (juce::PopupMenu::MenuItemIterator it (help); it.next();)
  20438. if (! it.getItem().isSeparator)
  20439. items.add (it.getItem().text);
  20440. const auto support = items.indexOf (lynx::tr ("Support LYNX SHARE..."));
  20441. const auto about = items.indexOf (lynx::tr ("About LYNX SHARE"));
  20442. check (juce::String ("Help has Support LYNX SHARE... right above About LYNX SHARE (") + name + " layout)",
  20443. support >= 0 && about == support + 1);
  20444. saveMenus ({ lynx::tr ("Help") }, { help }, prefix + "-menu-help-" + name + ".png");
  20445. }
  20446. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
  20447. settle();
  20448. // --- the Support window -------------------------------------------------------------------------------------
  20449. {
  20450. auto w = lynx::support::makeSupportWindow();
  20451. const auto texts = buttonTexts (*w);
  20452. check ("Support window: Donate on Ko-fi, Close", texts == juce::StringArray { lynx::tr ("Donate on Ko-fi"), lynx::tr ("Close") });
  20453. check ("Support window: Donate on Ko-fi points at the constant",
  20454. w->getButton (0) != nullptr && w->getButton (0)->getTooltip() == juce::String (lynx::links::donate));
  20455. check ("Support window title", w->getName() == lynx::tr ("Support LYNX SHARE"));
  20456. saveAlert (*w, "support");
  20457. }
  20458. // --- the About window ---------------------------------------------------------------------------------------
  20459. {
  20460. auto w = lynx::MainComponent::makeAboutWindow();
  20461. const auto texts = buttonTexts (*w);
  20462. check ("About window: Support LYNX SHARE (result 2) and OK", texts == juce::StringArray { lynx::tr ("Support LYNX SHARE"), lynx::tr ("OK") });
  20463. saveAlert (*w, "about");
  20464. }
  20465. // --- Settings › General › Show the support note -------------------------------------------------------------
  20466. {
  20467. auto page = lynx::makeGeneralPage (offline, {}, false);
  20468. bool found = false;
  20469. std::function<void (juce::Component&)> walk = [&] (juce::Component& c) {
  20470. if (auto* t = dynamic_cast<juce::ToggleButton*> (&c); t != nullptr && t->getButtonText() == lynx::tr ("Show the support note"))
  20471. found = t->getToggleState();
  20472. for (auto* child : c.getChildren())
  20473. walk (*child);
  20474. };
  20475. walk (*page);
  20476. check ("Settings > General: \"Show the support note\", ticked by default", found);
  20477. }
  20478. // --- the start-up note's rules, end to end on the saved state ----------------------------------------------
  20479. lynx::supportnote::Moment moment; // (the main window here is off-screen: the moment is set by hand)
  20480. lynx::support::StartupNote note (ui, [&moment] { return moment; }, [] { return 0; });
  20481. const auto state = [] { return lynx::support::loadState(); };
  20482. const auto setState = [] (int launches, int next, bool show) { lynx::support::saveState ({ launches, next, show }); };
  20483. stateFile.deleteFile();
  20484. for (int k = 0; k < 15; ++k)
  20485. note.begin (true);
  20486. note.pollForSnapshot();
  20487. check ("test mode / CI runs: 15 starts, nothing counted, no file, no card", ! stateFile.existsAsFile() && ! note.isCardShowing());
  20488. check ("a first start's defaults: next at start 10, shown", state() == lynx::supportnote::State { 0, 10, true });
  20489. for (int k = 1; k <= 9; ++k)
  20490. {
  20491. note.begin (false);
  20492. note.pollForSnapshot();
  20493. }
  20494. check ("starts 1 to 9: counted, no card", state().launches == 9 && ! note.isCardShowing());
  20495. moment.playing = true;
  20496. note.begin (false); // the 10th start
  20497. note.pollForSnapshot();
  20498. check ("10th start while playing: the card waits", state().launches == 10 && ! note.isCardShowing());
  20499. moment = {};
  20500. moment.dialogOpen = true;
  20501. note.pollForSnapshot();
  20502. check ("... and while a dialog is open", ! note.isCardShowing());
  20503. moment = {};
  20504. note.pollForSnapshot();
  20505. check ("10th start, a quiet moment: the card shows", note.isCardShowing());
  20506. check ("shown: left without an answer it comes back 30 starts later", state().nextAt == 40);
  20507. if (auto* card = note.cardForSnapshot())
  20508. {
  20509. const auto b = card->getBounds();
  20510. check ("the card sits in the bottom-right corner", b.getRight() <= ui.getWidth() - 8 && b.getRight() >= ui.getWidth() - 40
  20511. && b.getBottom() <= ui.getHeight() - 4 && b.getBottom() >= ui.getHeight() - 40);
  20512. writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, 1.0f), "note-in-window");
  20513. writeImage (card->createComponentSnapshot (card->getLocalBounds(), true, 2.0f), "note@2x");
  20514. // the corner of the window around the card, at 2x
  20515. writeImage (ui.createComponentSnapshot (b.expanded (220, 120).getIntersection (ui.getLocalBounds()), true, 2.0f), "note-corner@2x");
  20516. }
  20517. moment.playing = true;
  20518. note.pollForSnapshot();
  20519. check ("playback starts: the card steps aside", ! note.isCardShowing());
  20520. moment = {};
  20521. // Not now: again after 30 more starts
  20522. setState (10, 10, true);
  20523. note.begin (false); // start 11
  20524. note.pollForSnapshot();
  20525. if (auto* card = note.cardForSnapshot(); card != nullptr && card->buttonForSnapshot (lynx::supportnote::Choice::notNow) != nullptr)
  20526. card->buttonForSnapshot (lynx::supportnote::Choice::notNow)->onClick();
  20527. note.closeCard(); // (the click closes it on the next message turn)
  20528. check ("Not now: next at start 41", state() == lynx::supportnote::State { 11, 41, true });
  20529. for (int k = 12; k <= 40; ++k)
  20530. {
  20531. note.begin (false);
  20532. note.pollForSnapshot();
  20533. if (note.isCardShowing())
  20534. break;
  20535. }
  20536. check ("Not now: starts 12 to 40 without the card", ! note.isCardShowing() && state().launches == 40);
  20537. note.begin (false);
  20538. note.pollForSnapshot();
  20539. check ("Not now: the card again at start 41", note.isCardShowing());
  20540. // Don't show again: never, and Settings shows the box unticked
  20541. if (auto* card = note.cardForSnapshot())
  20542. card->buttonForSnapshot (lynx::supportnote::Choice::never)->onClick();
  20543. note.closeCard();
  20544. check ("Don't show again: off", ! state().show && ! lynx::support::noteEnabled());
  20545. for (int k = 0; k < 200; ++k)
  20546. {
  20547. note.begin (false);
  20548. note.pollForSnapshot();
  20549. }
  20550. check ("Don't show again: 200 more starts, never", ! note.isCardShowing());
  20551. // Support: opens the Support window (on the next message turn) and the note doesn't come back
  20552. setState (20, 10, true);
  20553. note.begin (false);
  20554. note.pollForSnapshot();
  20555. if (auto* card = note.cardForSnapshot())
  20556. card->buttonForSnapshot (lynx::supportnote::Choice::support)->onClick();
  20557. note.closeCard();
  20558. check ("Support: the note has done its job", ! state().show);
  20559. // Settings off: never; on again: counts from now
  20560. setState (5, 10, true);
  20561. lynx::support::setNoteEnabled (false);
  20562. for (int k = 0; k < 100; ++k)
  20563. {
  20564. note.begin (false);
  20565. note.pollForSnapshot();
  20566. }
  20567. check ("Settings off: 100 starts, never", ! note.isCardShowing() && state().launches == 105);
  20568. lynx::support::setNoteEnabled (true);
  20569. check ("Settings on again: next 30 starts later", state() == lynx::supportnote::State { 105, 135, true });
  20570. note.closeCard();
  20571. }
  20572. stateFile.deleteFile();
  20573. if (hadState)
  20574. stateFile.replaceWithText (oldState);
  20575. line (ok ? "result=OK" : "result=FAILED");
  20576. return ok;
  20577. }
  20578. bool runSimpleCloseTest (const juce::String& reportPath)
  20579. {
  20580. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  20581. juce::String report;
  20582. bool ok = true;
  20583. const auto line = [&report, &reportPath] (const juce::String& text) {
  20584. report << text << "\n";
  20585. juce::File (reportPath).replaceWithText (report); // (written as it goes: a crash still leaves the last step)
  20586. };
  20587. const auto check = [&line, &ok] (const juce::String& what, bool good) {
  20588. line ((good ? "ok " : "FAIL ") + what);
  20589. ok = ok && good;
  20590. };
  20591. const auto aliveBefore = lynx::SimpleWorkflow::alive.load();
  20592. {
  20593. lynx::AudioEngine offline (false);
  20594. {
  20595. lynx::MainComponent ui (offline, false);
  20596. ui.setSize (1600, 900);
  20597. ui.setVisible (true); // (no window: the docked editor and the tour only need their parents visible)
  20598. const auto settle = [&] {
  20599. for (int k = 0; k < 3; ++k)
  20600. offline.dispatchPendingMessages();
  20601. };
  20602. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  20603. settle();
  20604. auto* simple = ui.getSimpleWorkflowForSnapshot();
  20605. check ("the Simple workflow is up", simple != nullptr);
  20606. if (simple != nullptr)
  20607. {
  20608. const auto empty = lynx::builtInTemplateIndex ("Empty");
  20609. offline.setSong (empty >= 0 ? lynx::makeNewProject (empty) : lynx::makeNewProject());
  20610. settle();
  20611. simple->showWelcome();
  20612. settle();
  20613. auto* tour = simple->tourForSnapshot();
  20614. check ("Welcome screen shown", tour != nullptr && tour->isWelcomeShowing());
  20615. simple->startOrContinueTour();
  20616. settle();
  20617. simple->doTourStep (lynx::tour::beat);
  20618. settle();
  20619. check ("the tour runs with its card up", simple->tourRunning() && tour != nullptr && tour->cardForSnapshot() != nullptr);
  20620. // a demo song from Start from (the panel stays up over the Playlist)
  20621. if (auto* start = simple->startFromForSnapshot(); start != nullptr && lynx::demos::count > 1)
  20622. {
  20623. offline.setSong (lynx::demos::make (1));
  20624. settle();
  20625. check ("a demo song opened, Start from up", simple->isStartFromShowing() && ! offline.getSong().playlist.empty());
  20626. }
  20627. // the dock on a track, every tab (the Editor tab docks the Piano roll)
  20628. if (auto* dock = simple->dockForSnapshot())
  20629. {
  20630. simple->trackSelected ([] (const lynx::Song& song) { // the first Instrument track (the dock's Keyboard and Editor tabs are for it)
  20631. for (int t = 0; t < (int) song.playlistTracks.size(); ++t)
  20632. if (lynx::simpletracks::kindOf (song, t) == lynx::simpletracks::Kind::instrument)
  20633. return t;
  20634. return 0;
  20635. } (offline.getSong()));
  20636. for (auto tab : { lynx::SimpleDock::Tab::instrument, lynx::SimpleDock::Tab::keyboard, lynx::SimpleDock::Tab::editor,
  20637. lynx::SimpleDock::Tab::effects, lynx::SimpleDock::Tab::editor })
  20638. {
  20639. dock->setTab (tab);
  20640. settle();
  20641. }
  20642. check ("the dock shows", simple->isDockShowing());
  20643. line ("dock tab at the close: " + juce::String ((int) dock->getTab()) + " (2 = Editor, the docked Piano roll)");
  20644. }
  20645. ui.toggleLyrics(); // (Lyrics, then Finish: they share the dock on the right)
  20646. settle();
  20647. simple->showFinish();
  20648. settle();
  20649. check ("Finish open", simple->isFinishShowing());
  20650. simple->showChooser();
  20651. settle();
  20652. line ("Simple workflow objects alive before the close: " + juce::String (lynx::SimpleWorkflow::alive.load() - aliveBefore));
  20653. }
  20654. } // (the main window goes as at shutdown)
  20655. check ("no Simple workflow outlived its main window's destructor body (it reaches the Workspace)",
  20656. lynx::MainComponent::simpleWorkflowAliveAfterTeardown == aliveBefore);
  20657. check ("none left after the close", lynx::SimpleWorkflow::alive.load() == aliveBefore);
  20658. // Simple, then Pattern, then Simple again, and closed
  20659. {
  20660. lynx::MainComponent ui (offline, false);
  20661. ui.setSize (1600, 900);
  20662. ui.setVisible (true);
  20663. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  20664. offline.dispatchPendingMessages();
  20665. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
  20666. offline.dispatchPendingMessages();
  20667. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  20668. offline.dispatchPendingMessages();
  20669. if (auto* simple = ui.getSimpleWorkflowForSnapshot())
  20670. simple->showWelcome();
  20671. offline.dispatchPendingMessages();
  20672. }
  20673. check ("Simple -> Pattern -> Simple, closed: none outlived the destructor body", lynx::MainComponent::simpleWorkflowAliveAfterTeardown == aliveBefore
  20674. && lynx::SimpleWorkflow::alive.load() == aliveBefore);
  20675. }
  20676. line (ok ? "result=OK" : "result=FAILED");
  20677. return ok;
  20678. }
  20679. void runTour190dvShot (const juce::String& prefix)
  20680. {
  20681. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  20682. lynx::AudioEngine offline (false);
  20683. lynx::MainComponent ui (offline, false);
  20684. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  20685. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  20686. ui.setVisible (true); // (no window: the docked editor and the ring's targets only need their parents visible)
  20687. const auto writeImage = [&prefix] (const juce::Image& image, const juce::String& name) {
  20688. const auto file = juce::File (prefix + "-" + name + ".png");
  20689. file.deleteFile();
  20690. juce::FileOutputStream out (file);
  20691. juce::PNGImageFormat().writeImageToStream (image, out);
  20692. };
  20693. juce::String report;
  20694. // (written as it goes: a run that stops halfway still leaves its checks)
  20695. const auto line = [&report, &prefix] (const juce::String& text) {
  20696. report << text << "\n";
  20697. juce::File (prefix + "-report.txt").replaceWithText (report);
  20698. };
  20699. const auto check = [&line] (const juce::String& what, bool ok) { line ((ok ? "OK " : "ERROR ") + what); };
  20700. ui.selectTabForSnapshot (2);
  20701. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  20702. offline.dispatchPendingMessages();
  20703. auto* simple = ui.getSimpleWorkflowForSnapshot();
  20704. auto* tour = simple != nullptr ? simple->tourForSnapshot() : nullptr;
  20705. if (tour == nullptr)
  20706. {
  20707. juce::File (prefix + "-report.txt").replaceWithText ("ERROR no Simple workflow / tour\n");
  20708. return;
  20709. }
  20710. check ("no Welcome screen by itself in a --snapshot route (not a real first start)", ! tour->isWelcomeShowing());
  20711. const auto settle = [&] {
  20712. for (int k = 0; k < 3; ++k)
  20713. offline.dispatchPendingMessages();
  20714. };
  20715. const auto window = [&] (const juce::String& name, bool twoX = false) {
  20716. settle();
  20717. tour->ringForSnapshot(); // (the ring follows the layout: resolved now, as its timer would)
  20718. writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, 1.0f), name);
  20719. if (twoX)
  20720. if (auto* card = tour->cardForSnapshot(); card != nullptr && card->getParentComponent() != nullptr)
  20721. writeImage (card->createComponentSnapshot (card->getLocalBounds(), true, 2.0f), name + "-card@2x");
  20722. };
  20723. const auto stepIs = [&] (int step, const juce::String& target) {
  20724. settle();
  20725. const auto ring = tour->ringForSnapshot();
  20726. const auto id = tour->targetIdForSnapshot();
  20727. line ("step " + juce::String (tour->step() + 1) + " (" + lynx::tour::stepId (tour->step()) + "): ring on " + (id.isEmpty() ? juce::String ("-") : id) + " "
  20728. + ring.toString());
  20729. check (juce::String ("the card shows step ") + lynx::tour::stepId (step), tour->isRunning() && tour->step() == step);
  20730. if (target.isNotEmpty())
  20731. check ("the ring is on " + target, id == target && ! ring.isEmpty());
  20732. };
  20733. // --- the Welcome screen (on a new, empty project: the built-in "Empty" template, as File › New can give) -------------
  20734. const auto emptyProject = [] {
  20735. const auto index = lynx::builtInTemplateIndex ("Empty");
  20736. return index >= 0 ? lynx::makeNewProject (index) : lynx::makeNewProject();
  20737. };
  20738. offline.setSong (emptyProject());
  20739. settle();
  20740. check ("the new project is empty for the Simple workflow (it opens on the chooser)", lynx::simpletracks::isEmptySong (offline.getSong()));
  20741. simple->showWelcome();
  20742. settle();
  20743. check ("Help › Welcome screen shows it", tour->isWelcomeShowing());
  20744. window ("welcome");
  20745. if (auto* w = tour->welcomeForSnapshot())
  20746. writeImage (w->createComponentSnapshot (w->getLocalBounds(), true, 2.0f), "welcome@2x");
  20747. tour->clickForSnapshot ("welcome.tour");
  20748. settle();
  20749. check ("Make my first song: the Welcome screen closes, the tour starts, the chooser comes up for the beat",
  20750. ! tour->isWelcomeShowing() && tour->isRunning() && simple->isChooserShowing());
  20751. // --- step 1: the beat ---------------------------------------------------------------------------------------------
  20752. stepIs (lynx::tour::beat, "simple.tile.drums");
  20753. window ("step1-beat", true);
  20754. simple->showStarterPageForSnapshot();
  20755. stepIs (lynx::tour::beat, "simple.starters");
  20756. window ("step1-beat-starters");
  20757. tour->clickForSnapshot ("do");
  20758. settle();
  20759. check ("Do it for me added a starter beat", lynx::tour::hasBeat (offline.getSong()));
  20760. // --- step 2: the key ----------------------------------------------------------------------------------------------
  20761. stepIs (lynx::tour::key, "toolbar.key");
  20762. window ("step2-key", true);
  20763. tour->clickForSnapshot ("do");
  20764. settle();
  20765. check ("Do it for me set A minor", lynx::projectkey::get (offline.getSong()).has_value());
  20766. // --- step 3: an instrument (Add track opens the chooser: the ring moves to its tile) ------------------------------
  20767. stepIs (lynx::tour::instrument, "simple.addTrack");
  20768. window ("step3-instrument", true);
  20769. simple->showChooser();
  20770. stepIs (lynx::tour::instrument, "simple.tile.instrument");
  20771. window ("step3-instrument-chooser");
  20772. tour->clickForSnapshot ("do");
  20773. settle();
  20774. check ("Do it for me added an Instrument track (the chooser closed)", lynx::tour::firstInstrumentTrack (offline.getSong()) >= 0 && ! simple->isChooserShowing());
  20775. // --- step 4: chords -----------------------------------------------------------------------------------------------
  20776. stepIs (lynx::tour::chords, "keyboard.chordPad");
  20777. window ("step4-chords", true);
  20778. tour->clickForSnapshot ("do");
  20779. settle();
  20780. check ("Do it for me wrote four chords (12 notes) on the instrument's pattern", [&] {
  20781. const auto& song = offline.getSong();
  20782. const auto p = lynx::simpletracks::patternOf (song, lynx::tour::firstInstrumentTrack (song));
  20783. return p >= 0 && song.patterns[(std::size_t) p].notes.size() == 12;
  20784. }());
  20785. // --- step 5: a voice or a loop (no "Do it for me": a loop is dropped as a user would) ------------------------------
  20786. stepIs (lynx::tour::loop, "simple.addTrack");
  20787. window ("step5-loop", true);
  20788. {
  20789. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-190dv-loops");
  20790. dir.deleteRecursively();
  20791. dir.createDirectory();
  20792. const auto wav = dir.getChildFile ("Warm Keys 120 Am.wav");
  20793. const int frames = 192000;
  20794. juce::AudioBuffer<float> audio (1, frames);
  20795. for (int i = 0; i < frames; ++i)
  20796. {
  20797. const auto t = (double) i / 48000.0;
  20798. double v = 0.0;
  20799. for (const auto key : { 57, 60, 64 })
  20800. v += std::sin (2.0 * juce::MathConstants<double>::pi * 440.0 * std::pow (2.0, (key - 69) / 12.0) * t);
  20801. audio.setSample (0, i, (float) (0.1 * v * (1.0 - std::exp (-std::fmod (t, 0.5) * 60.0))));
  20802. }
  20803. {
  20804. juce::WavAudioFormat format;
  20805. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  20806. if (auto* w = format.createWriterFor (out.get(), 48000.0, 1, 16, {}, 0))
  20807. {
  20808. out.release();
  20809. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  20810. writer->writeFromAudioSampleBuffer (audio, 0, frames);
  20811. }
  20812. }
  20813. simple->dropFiles ({ wav.getFullPathName() }, 0);
  20814. settle();
  20815. check ("a dropped loop (A minor in its name) follows the key", [&] {
  20816. for (const auto& c : offline.getSong().playlist)
  20817. if (c.kind == lynx::ClipKind::audio)
  20818. return c.followKey;
  20819. return false;
  20820. }());
  20821. }
  20822. // --- step 6: a one-knob effect --------------------------------------------------------------------------------------
  20823. stepIs (lynx::tour::effect, "simple.dock.addEffect");
  20824. window ("step6-effect", true);
  20825. tour->clickForSnapshot ("do");
  20826. settle();
  20827. check ("Do it for me put Room on the instrument track", lynx::tour::hasOneKnob (offline.getSong()));
  20828. // --- step 7: Finish -----------------------------------------------------------------------------------------------
  20829. stepIs (lynx::tour::finish, "simple.finish");
  20830. window ("step7-finish", true);
  20831. tour->clickForSnapshot ("do");
  20832. settle();
  20833. check ("Do it for me opened Finish and chose Balanced", simple->isFinishShowing() && lynx::looks::present (offline.getSong()));
  20834. // --- the end card, Back / Next, close -------------------------------------------------------------------------------
  20835. settle();
  20836. check ("the end card", tour->isRunning() && tour->step() == lynx::tour::stepCount);
  20837. window ("end", true);
  20838. tour->clickForSnapshot ("back");
  20839. settle();
  20840. check ("Back: the Finish step again, shown done (the tour waits for Next)", tour->step() == lynx::tour::finish
  20841. && tour->machineForCheck().shownDone (offline.getSong()));
  20842. window ("back-done", true);
  20843. tour->clickForSnapshot ("next");
  20844. settle();
  20845. check ("Next: the end card again", tour->step() == lynx::tour::stepCount);
  20846. check ("all seven steps done by the song", tour->machineForCheck().state().completed == 0x7fu);
  20847. tour->clickForSnapshot ("close");
  20848. settle();
  20849. check ("closing the end card ends the tour (not continued from Help)", ! tour->isRunning() && ! tour->canContinue()
  20850. && tour->machineForCheck().state().done);
  20851. line ("-- paused tour");
  20852. // --- a paused tour, the Help menu and the chooser's button ---------------------------------------------------------
  20853. offline.setSong (emptyProject());
  20854. settle();
  20855. tour->machineForCheck() = lynx::tour::Machine {};
  20856. simple->startOrContinueTour();
  20857. settle();
  20858. line ("-- do beat");
  20859. simple->doTourStep (lynx::tour::beat);
  20860. settle();
  20861. check ("a new tour on an empty project: the beat done moves it to the key", tour->step() == lynx::tour::key);
  20862. tour->clickForSnapshot ("close");
  20863. settle();
  20864. check ("closing the card pauses the tour (Help continues it)", ! tour->isRunning() && tour->canContinue());
  20865. line ("-- help menu");
  20866. {
  20867. const auto help = ui.getMenuForSnapshot (ui.getMenuNamesForSnapshot().indexOf (lynx::tr ("Help")));
  20868. bool continueItem = false, welcomeItem = false;
  20869. for (juce::PopupMenu::MenuItemIterator it (help); it.next();)
  20870. {
  20871. continueItem = continueItem || it.getItem().text.startsWith (lynx::tr ("Continue the first-song tour (step {0} of {1})", { "2", "7" }));
  20872. welcomeItem = welcomeItem || it.getItem().text == lynx::tr ("Welcome screen...");
  20873. }
  20874. check ("Help: Continue the first-song tour (step 2 of 7) and Welcome screen...", continueItem && welcomeItem);
  20875. saveMenus ({ lynx::tr ("Help") }, { help }, prefix + "-menu-help.png");
  20876. }
  20877. simple->startOrContinueTour();
  20878. settle();
  20879. check ("Help › Continue: back on the key step", tour->isRunning() && tour->step() == lynx::tour::key);
  20880. tour->clickForSnapshot ("skip");
  20881. settle();
  20882. check ("Skip tour ends it", ! tour->isRunning() && ! tour->canContinue());
  20883. offline.setSong (emptyProject());
  20884. settle();
  20885. simple->showChooser();
  20886. window ("chooser");
  20887. line ("-- start from");
  20888. // --- Start from: the three demo songs; a demo opened in Simple -------------------------------------------------------
  20889. if (auto* start = simple->startFromForSnapshot())
  20890. {
  20891. settle();
  20892. writeImage (start->createComponentSnapshot (start->getLocalBounds(), true, 1.0f), "startfrom");
  20893. const auto list = lynx::startfrom::entries();
  20894. int demos = 0;
  20895. for (const auto& e : list)
  20896. demos += e.kind == lynx::startfrom::Entry::Kind::demo && e.playable ? 1 : 0;
  20897. check ("Start from lists three playable demo songs first", demos == 3 && list.size() >= 3 && list[1].demo == 1 && list[2].demo == 2);
  20898. for (int d = 1; d < 3 && d < (int) list.size(); ++d)
  20899. 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");
  20900. simple->hideStartFrom();
  20901. }
  20902. line ("-- demos");
  20903. for (int d = 1; d < lynx::demos::count; ++d)
  20904. {
  20905. offline.setSong (lynx::demos::make (d));
  20906. settle();
  20907. simple->hideChooser();
  20908. window (juce::String ("demo-") + (d == 1 ? "hiphop" : "pop"));
  20909. // the committed file is the generated song
  20910. const auto file = juce::File::getCurrentWorkingDirectory().getChildFile ("resources/demos").getChildFile (lynx::demos::fileName (d));
  20911. juce::String error;
  20912. const auto loaded = lynx::ProjectFile::load (file, error);
  20913. check ("resources/demos/" + juce::String (lynx::demos::fileName (d)) + " loads and is the generated song",
  20914. loaded.has_value() && lynx::ProjectFile::toJson (*loaded, false) == lynx::ProjectFile::toJson (lynx::demos::make (d), false));
  20915. }
  20916. line (report.contains ("ERROR ") ? "RESULT ERROR" : "RESULT OK");
  20917. juce::File (prefix + "-report.txt").replaceWithText (report);
  20918. }
  20919. // --patterns190ea (round 190ea): FL keeps at least one pattern; the engine now does too (AudioEngine::publishSong,
  20920. // Song::keepOnePattern). Before, a Song without a pattern crashed the docked Piano roll's listener.
  20921. bool runPatterns190ea (const juce::String& reportPath)
  20922. {
  20923. namespace st = lynx::simpletracks;
  20924. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  20925. lynx::AudioEngine offline (false);
  20926. lynx::MainComponent ui (offline, false);
  20927. ui.setSize (1600, 900);
  20928. ui.setVisible (true); // (no window: the docked editor only needs its parents visible)
  20929. juce::String report;
  20930. bool ok = true;
  20931. const auto check = [&report, &ok] (const juce::String& what, bool good) {
  20932. report << (good ? "OK " : "ERROR ") << what << "\n";
  20933. ok = ok && good;
  20934. };
  20935. const auto save = [&report, &reportPath] { juce::File (reportPath).replaceWithText (report); };
  20936. const auto settle = [&] { offline.dispatchPendingMessages(); ui.getPianoRollForSnapshot().repaint(); };
  20937. const auto onePattern = [&offline] {
  20938. const auto& s = offline.getSong();
  20939. return s.patterns.size() >= 1 && s.currentPattern >= 0 && s.currentPattern < (int) s.patterns.size();
  20940. };
  20941. // the hand-built songs the engine can be given: none of them has a pattern
  20942. const auto bare = [] {
  20943. lynx::Song s;
  20944. s.mixer = lynx::Song::defaultMixer();
  20945. return s;
  20946. };
  20947. // every way to reach "no pattern" in the current layout
  20948. const auto paths = [&] (const juce::String& where) {
  20949. offline.setSong (bare());
  20950. settle();
  20951. check (where + ": a song without a pattern opens with one empty \"Pattern 1\"",
  20952. onePattern() && offline.getSong().patterns.size() == 1 && offline.getSong().patterns[0].name == "Pattern 1"
  20953. && offline.getSong().patterns[0].notes.empty());
  20954. offline.editSong ([] (lynx::Song& s) { s.patterns.clear(); });
  20955. settle();
  20956. check (where + ": an edit that clears every pattern leaves one", onePattern());
  20957. offline.editSong ([] (lynx::Song& s) {
  20958. s.patterns.resize (2);
  20959. s.patterns[1].notes.push_back ({});
  20960. s.currentPattern = 1;
  20961. });
  20962. settle();
  20963. offline.editSong ([] (lynx::Song& s) { s.removePattern (s.currentPattern); });
  20964. offline.editSong ([] (lynx::Song& s) { s.removePattern (s.currentPattern); });
  20965. settle();
  20966. check (where + ": deleting the last pattern leaves an empty \"Pattern 1\" (FL's invariant)",
  20967. onePattern() && offline.getSong().patterns.size() == 1 && offline.getSong().patterns[0].notes.empty());
  20968. for (int k = 0; k < 6; ++k)
  20969. {
  20970. offline.undo();
  20971. settle();
  20972. }
  20973. check (where + ": undo back over those steps keeps a pattern", onePattern());
  20974. for (int k = 0; k < 6; ++k)
  20975. {
  20976. offline.redo();
  20977. settle();
  20978. }
  20979. check (where + ": redo keeps a pattern", onePattern());
  20980. offline.applyRemote (bare());
  20981. settle();
  20982. check (where + ": a live session's remote song without a pattern gets one", onePattern());
  20983. offline.editSong ([] (lynx::Song& s) { s.currentPattern = 99; });
  20984. settle();
  20985. check (where + ": a current pattern out of range is put back in range", onePattern() && offline.getSong().currentPattern == 0);
  20986. };
  20987. // the Simple layout with the Piano roll docked in the Editor tab (round 190dv's crash)
  20988. ui.selectTabForSnapshot (2);
  20989. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  20990. settle();
  20991. auto* simple = ui.getSimpleWorkflowForSnapshot();
  20992. check ("the Simple workflow is up", simple != nullptr);
  20993. if (simple == nullptr)
  20994. {
  20995. save();
  20996. return false;
  20997. }
  20998. simple->hideChooser();
  20999. st::Request q;
  21000. q.kind = st::Kind::instrument;
  21001. q.name = "Keys";
  21002. lynx::ChannelDef synth;
  21003. synth.instrument = lynx::InstrumentKind::synth;
  21004. q.channel = synth;
  21005. q.emptyBars = 4;
  21006. st::Result r;
  21007. offline.editSong ([&] (lynx::Song& s) { r = st::addTrack (s, q); });
  21008. settle();
  21009. ui.getPlaylistForSnapshot().selectTrack (r.track);
  21010. simple->trackSelected (r.track);
  21011. settle();
  21012. auto* dock = simple->dockForSnapshot();
  21013. check ("the instrument track's dock has the Editor tab", dock != nullptr && dock->hasPlayTabsForCheck());
  21014. if (dock != nullptr)
  21015. dock->setTab (lynx::SimpleDock::Tab::editor);
  21016. settle();
  21017. check ("the Piano roll is docked in the Editor tab", dock != nullptr && dock->isEditorDocked() && dock->isParentOf (&ui.getPianoRollForSnapshot()));
  21018. paths ("Simple, Editor tab");
  21019. // the Pattern layout with the Piano roll panel, then the Clip-launch layout
  21020. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
  21021. settle();
  21022. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::pianoRoll });
  21023. settle();
  21024. paths ("Pattern layout, Piano roll");
  21025. ui.setLayoutStyle (lynx::layoutstyle::Style::clipLaunch);
  21026. settle();
  21027. paths ("Clip-launch layout");
  21028. report << (ok ? "RESULT OK\n" : "RESULT FAILED\n");
  21029. save();
  21030. return ok;
  21031. }
  21032. // round 190fo: the Simple layout's Sampler track (16 pads) and a folder of stems and MIDI files, off-screen at 1x and
  21033. // 2x, with a text report of the checks (.lynx round trip, kits, typing keys, the folder import)
  21034. void runReabl190foShot (const juce::String& prefix)
  21035. {
  21036. namespace st = lynx::simpletracks;
  21037. namespace sp = lynx::simplepads;
  21038. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  21039. lynx::AudioEngine offline (false);
  21040. lynx::MainComponent ui (offline, false);
  21041. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  21042. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  21043. ui.setVisible (true);
  21044. const auto writeImage = [&prefix] (const juce::Image& image, const juce::String& name) {
  21045. const auto file = juce::File (prefix + "-" + name + ".png");
  21046. file.deleteFile();
  21047. juce::FileOutputStream out (file);
  21048. juce::PNGImageFormat().writeImageToStream (image, out);
  21049. };
  21050. juce::String report;
  21051. const auto line = [&report] (const juce::String& text) { report << text << "\n"; };
  21052. const auto check = [&report] (const juce::String& what, bool ok) { report << (ok ? "OK " : "ERROR ") << what << "\n"; };
  21053. ui.selectTabForSnapshot (2);
  21054. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  21055. offline.dispatchPendingMessages();
  21056. auto* simple = ui.getSimpleWorkflowForSnapshot();
  21057. if (simple == nullptr)
  21058. {
  21059. juce::File (prefix + "-report.txt").replaceWithText ("ERROR no Simple workflow\n");
  21060. return;
  21061. }
  21062. const auto whole = [&] (const juce::String& name) {
  21063. offline.dispatchPendingMessages();
  21064. for (float scale : { 1.0f, 2.0f })
  21065. writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, scale), name + (scale > 1.0f ? "@2x" : ""));
  21066. };
  21067. // the chooser: the Sampler tile (16 pads, "On keys..." for one sample over the keys) and Import's "Folder..."
  21068. simple->showChooser();
  21069. whole ("chooser");
  21070. simple->hideChooser();
  21071. // --- test sounds -------------------------------------------------------------------------------------------------
  21072. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-190fo");
  21073. dir.deleteRecursively();
  21074. dir.createDirectory();
  21075. const auto writeWav = [] (const juce::File& wav, int frames, const std::function<float (int)>& f) {
  21076. juce::AudioBuffer<float> audio (1, frames);
  21077. for (int i = 0; i < frames; ++i)
  21078. audio.setSample (0, i, f (i));
  21079. wav.getParentDirectory().createDirectory();
  21080. juce::WavAudioFormat format;
  21081. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  21082. if (auto* w = format.createWriterFor (out.get(), 48000.0, 1, 16, {}, 0))
  21083. {
  21084. out.release();
  21085. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  21086. writer->writeFromAudioSampleBuffer (audio, 0, frames);
  21087. }
  21088. return wav;
  21089. };
  21090. juce::Random rnd (190);
  21091. const auto pi = juce::MathConstants<double>::pi;
  21092. const auto kick = writeWav (dir.getChildFile ("pads/Kick.wav"), 24000, [pi] (int i) {
  21093. const auto t = i / 48000.0;
  21094. return (float) (0.9 * std::sin (2.0 * pi * (50.0 * t + 60.0 * (1.0 - std::exp (-t * 30.0)) / 30.0)) * std::exp (-t * 7.0));
  21095. });
  21096. const auto snare = writeWav (dir.getChildFile ("pads/Snare.wav"), 14400, [&rnd] (int i) { return (float) ((rnd.nextFloat() * 2.0f - 1.0f) * 0.6f * std::exp (-i / 4000.0f)); });
  21097. const auto hat = writeWav (dir.getChildFile ("pads/Hat.wav"), 4800, [&rnd] (int i) { return (float) ((rnd.nextFloat() * 2.0f - 1.0f) * 0.4f * std::exp (-i / 900.0f)); });
  21098. const auto chord = writeWav (dir.getChildFile ("pads/Chord stab.wav"), 48000, [pi] (int i) {
  21099. const auto t = i / 48000.0;
  21100. double v = 0.0;
  21101. for (int k : { 57, 60, 64 })
  21102. v += std::sin (2.0 * pi * 440.0 * std::pow (2.0, (k - 69) / 12.0) * t);
  21103. return (float) (0.2 * v * std::exp (-t * 2.5));
  21104. });
  21105. const auto vox = writeWav (dir.getChildFile ("pads/Vox hey.wav"), 30000, [pi] (int i) {
  21106. const auto t = i / 48000.0;
  21107. return (float) (0.5 * std::sin (2.0 * pi * 220.0 * t + 2.0 * std::sin (2.0 * pi * 660.0 * t)) * std::sin (pi * t / 0.625));
  21108. });
  21109. // --- the Sampler track ---------------------------------------------------------------------------------------------
  21110. check ("the Sampler tile's track was added", simple->addPads());
  21111. offline.dispatchPendingMessages();
  21112. const auto& song0 = offline.getSong();
  21113. int track = -1;
  21114. for (int t = 0; t < (int) song0.playlistTracks.size() && track < 0; ++t)
  21115. if (st::kindOf (song0, t) == st::Kind::pads)
  21116. track = t;
  21117. check ("a Sampler track with 16 pads", track >= 0 && [&] {
  21118. const auto c = sp::padChannels (song0, track);
  21119. return std::all_of (c.begin(), c.end(), [] (int i) { return i >= 0; });
  21120. }());
  21121. auto* dock = simple->dockForSnapshot();
  21122. if (dock == nullptr || track < 0)
  21123. {
  21124. juce::File (prefix + "-report.txt").replaceWithText (report + "ERROR no dock / track\n");
  21125. return;
  21126. }
  21127. simple->trackSelected (track);
  21128. offline.dispatchPendingMessages();
  21129. check ("the dock opens on the Pads tab", dock->hasPadsTabForCheck() && dock->getTab() == lynx::SimpleDock::Tab::pads);
  21130. const auto shots = [&] (const juce::String& name) {
  21131. offline.dispatchPendingMessages();
  21132. for (float scale : { 1.0f, 2.0f })
  21133. {
  21134. const auto suffix = scale > 1.0f ? juce::String ("@2x") : juce::String();
  21135. writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, scale), name + suffix);
  21136. writeImage (dock->createComponentSnapshot (dock->getLocalBounds(), true, scale), "dock-" + name + suffix);
  21137. }
  21138. };
  21139. shots ("pads-empty");
  21140. const juce::File files[] { kick, snare, hat, hat, chord, vox };
  21141. for (int p = 0; p < 6; ++p)
  21142. dock->padsLoadForCheck (p, files[p]);
  21143. offline.dispatchPendingMessages();
  21144. check ("six pads hold a sound", [&] {
  21145. int n = 0;
  21146. for (int p = 0; p < sp::padCount; ++p)
  21147. n += sp::hasSample (offline.getSong(), track, p) ? 1 : 0;
  21148. return n == 6;
  21149. }());
  21150. // pad 3 = the open hat: one-shot, group 1 with pad 2 (closed hat), a colour; pad 4 = the chord, looped and darker
  21151. dock->padsSelectForCheck (2);
  21152. dock->padsModeForCheck (1);
  21153. dock->padsSelectForCheck (3);
  21154. dock->padsModeForCheck (1);
  21155. offline.editSong ([track] (lynx::Song& s) {
  21156. for (int p : { 2, 3 })
  21157. if (const auto c = sp::padChannel (s, track, p); c >= 0)
  21158. {
  21159. s.channels[(std::size_t) c].simplePad.group = 1;
  21160. s.channels[(std::size_t) c].simplePad.colour = 2;
  21161. sp::apply (s.channels[(std::size_t) c], 4800);
  21162. }
  21163. });
  21164. dock->padsSelectForCheck (4);
  21165. dock->padsModeForCheck (2);
  21166. dock->padsKnobForCheck (2, 0.3f); // tone: a low-pass
  21167. dock->padsKnobForCheck (1, 0.35f); // release
  21168. dock->padsRegionForCheck (0.05f, 0.7f);
  21169. dock->padsNormalizeForCheck();
  21170. dock->padsUpdateForCheck();
  21171. {
  21172. const auto& s = offline.getSong();
  21173. const auto& c = s.channels[(std::size_t) sp::padChannel (s, track, 4)];
  21174. line ("pad 5: mode " + juce::String ((int) c.simplePad.mode) + " tone " + juce::String (c.simplePad.tone, 2) + " cutoff " + juce::String (c.sampler.cutoff, 0)
  21175. + " release " + juce::String (c.sampler.release, 3) + " region " + juce::String (c.sampler.regionStart, 2) + "-" + juce::String (c.sampler.regionEnd, 2)
  21176. + " gain " + juce::String (c.sampler.gainDb, 2) + " dB zones " + juce::String ((int) c.zones.size()));
  21177. check ("pad 5 loops its region, darker, normalized", c.simplePad.mode == 2 && c.zones.size() == 1 && c.zones[0].loopMode == 2 && c.simplePad.tone < -0.3f
  21178. && c.sampler.filterType == 0 && c.sampler.cutoff < 5000.0f && c.sampler.gainDb > 0.5f);
  21179. const auto& h = s.channels[(std::size_t) sp::padChannel (s, track, 3)];
  21180. check ("the hats share a choke group of this insert", h.cutGroup > 1000 && h.cutGroup == s.channels[(std::size_t) sp::padChannel (s, track, 2)].cutGroup);
  21181. }
  21182. shots ("pads");
  21183. dock->padsHitForCheck (0);
  21184. dock->lightPad (2);
  21185. shots ("pads-hit");
  21186. // the typing keys: V plays pad 1, M pad 4, 7 pad 16; Z is not a pad key
  21187. check ("typing keys reach the pads", simple->padChannelForKey ('V') == sp::padChannel (offline.getSong(), track, 0)
  21188. && simple->padChannelForKey ('m') == sp::padChannel (offline.getSong(), track, 3)
  21189. && simple->padChannelForKey ('7') == sp::padChannel (offline.getSong(), track, 15)
  21190. && simple->padChannelForKey ('Z') == -1);
  21191. // drag pad 6 (vox) onto the empty pad 9: it moves; Alt-drag pad 1 onto pad 10: a copy
  21192. dock->padsDragForCheck (5, 8, false);
  21193. dock->padsDragForCheck (0, 9, true);
  21194. check ("a pad moved and a pad copied", ! sp::hasSample (offline.getSong(), track, 5) && sp::hasSample (offline.getSong(), track, 8)
  21195. && sp::hasSample (offline.getSong(), track, 9) && sp::hasSample (offline.getSong(), track, 0));
  21196. dock->padsSelectForCheck (4);
  21197. shots ("pads-moved");
  21198. saveMenus ({ "Pad menu", "Colour", "Copy a value to every pad" }, [&] {
  21199. const auto top = dock->padMenuForSnapshot (4);
  21200. std::vector<juce::PopupMenu> menus { top };
  21201. for (juce::PopupMenu::MenuItemIterator it (top); it.next();)
  21202. if (it.getItem().subMenu != nullptr)
  21203. menus.push_back (*it.getItem().subMenu);
  21204. return menus;
  21205. }(), prefix + "-menu-pad.png");
  21206. // kits: saved, the pads cleared, opened again
  21207. const auto kitFile = lynx::platform::documentsFolder().getChildFile ("LYNX/Sampler kits/Test kit 190fo.lynxkit");
  21208. kitFile.deleteFile();
  21209. check ("the pads saved as a kit", dock->saveKitForCheck ("Test kit 190fo") && kitFile.existsAsFile());
  21210. saveMenus ({ "Kit", "My kits" }, [&] {
  21211. const auto top = dock->kitMenuForSnapshot();
  21212. std::vector<juce::PopupMenu> menus { top };
  21213. for (juce::PopupMenu::MenuItemIterator it (top); it.next();)
  21214. if (it.getItem().subMenu != nullptr && it.getItem().text == lynx::tr ("My kits"))
  21215. menus.push_back (*it.getItem().subMenu);
  21216. return menus;
  21217. }(), prefix + "-menu-kit.png");
  21218. const auto before = offline.getSong().channels;
  21219. offline.editSong ([track] (lynx::Song& s) {
  21220. for (int p = 0; p < sp::padCount; ++p)
  21221. sp::clearPad (s, track, p);
  21222. });
  21223. check ("the kit opens the same pads again", dock->openKitForCheck (kitFile) && [&] {
  21224. const auto& now = offline.getSong().channels;
  21225. for (int p = 0; p < sp::padCount; ++p)
  21226. {
  21227. const auto c = sp::padChannel (offline.getSong(), track, p);
  21228. if (c < 0 || now[(std::size_t) c].samplePath != before[(std::size_t) c].samplePath || now[(std::size_t) c].simplePad != before[(std::size_t) c].simplePad
  21229. || now[(std::size_t) c].sampler.release != before[(std::size_t) c].sampler.release || now[(std::size_t) c].zones != before[(std::size_t) c].zones)
  21230. return false;
  21231. }
  21232. return true;
  21233. }());
  21234. {
  21235. const auto renamed = kitFile.getSiblingFile ("Renamed kit 190fo.lynxkit");
  21236. renamed.deleteFile();
  21237. check ("a kit renamed (and a one-letter name refused)", ! lynx::SimpleDock::renameKitForCheck (kitFile, "x")
  21238. && lynx::SimpleDock::renameKitForCheck (kitFile, "Renamed kit 190fo") && renamed.existsAsFile()
  21239. && ! kitFile.exists());
  21240. renamed.deleteFile();
  21241. }
  21242. kitFile.deleteFile();
  21243. // a beat on the pads (the track's pattern) and the .lynx round trip
  21244. offline.editSong ([track] (lynx::Song& s) {
  21245. const auto pattern = [&] {
  21246. for (const auto& c : s.playlist)
  21247. if (c.track == track && c.kind == lynx::ClipKind::pattern)
  21248. return c.pattern;
  21249. return -1;
  21250. }();
  21251. if (pattern < 0)
  21252. return;
  21253. for (int step = 0; step < 16; ++step)
  21254. {
  21255. const int pad = step % 4 == 0 ? 0 : step % 8 == 4 ? 1 : 2;
  21256. lynx::Note n;
  21257. n.channel = sp::padChannel (s, track, pad);
  21258. n.key = sp::padKey;
  21259. n.start = (std::int64_t) step * lynx::ticksPerStep;
  21260. n.length = lynx::ticksPerStep;
  21261. s.patterns[(std::size_t) pattern].notes.push_back (n);
  21262. }
  21263. });
  21264. {
  21265. const auto json = lynx::ProjectFile::toJson (offline.getSong());
  21266. juce::String error;
  21267. const auto back = lynx::ProjectFile::fromJson (json, error);
  21268. bool same = back.has_value() && back->channels.size() == offline.getSong().channels.size() && st::kindOf (*back, track) == st::Kind::pads;
  21269. for (std::size_t c = 0; same && c < back->channels.size(); ++c)
  21270. {
  21271. const auto& a = back->channels[c];
  21272. const auto& b = offline.getSong().channels[c];
  21273. same = a.simplePad == b.simplePad && a.zones == b.zones && a.cutGroup == b.cutGroup && a.cutBy == b.cutBy && a.samplePath == b.samplePath
  21274. && a.sampler.regionStart == b.sampler.regionStart && a.sampler.release == b.sampler.release && a.sampler.cutoff == b.sampler.cutoff;
  21275. }
  21276. check ("pads, their modes, groups and loops survive .lynx", same);
  21277. lynx::Song plain = lynx::Song::makeDefault();
  21278. check ("a project without pads writes no pad field", ! lynx::ProjectFile::toJson (plain).contains ("simplePad"));
  21279. }
  21280. ui.getPlaylistForSnapshot().selectTrack (track);
  21281. // --- a folder of stems and MIDI files (the other app's "download stems" naming) --------------------------------------
  21282. const auto stems = dir.getChildFile ("My song stems");
  21283. writeWav (stems.getChildFile ("01_Drums.wav"), 96000, [&rnd] (int i) { return (i % 24000) < 2000 ? (rnd.nextFloat() - 0.5f) * 0.8f : 0.0f; });
  21284. writeWav (stems.getChildFile ("02_Bass.wav"), 96000, [pi] (int i) { return (float) (0.3 * std::sin (2.0 * pi * 55.0 * i / 48000.0)); });
  21285. writeWav (stems.getChildFile ("10_Lead Vox.wav"), 96000, [pi] (int i) { return (float) (0.2 * std::sin (2.0 * pi * 330.0 * i / 48000.0)); });
  21286. {
  21287. juce::MidiMessageSequence seq;
  21288. for (int k = 0; k < 8; ++k)
  21289. {
  21290. seq.addEvent (juce::MidiMessage::noteOn (1, 36 + (k % 4) * 3, (juce::uint8) 100), k * 480.0);
  21291. seq.addEvent (juce::MidiMessage::noteOff (1, 36 + (k % 4) * 3), k * 480.0 + 400.0);
  21292. }
  21293. seq.updateMatchedPairs();
  21294. juce::MidiFile midi;
  21295. midi.setTicksPerQuarterNote (960);
  21296. midi.addTrack (seq);
  21297. for (const auto& name : { "02_Bass.mid", "03_Keys.mid" })
  21298. {
  21299. juce::FileOutputStream out (stems.getChildFile (name));
  21300. midi.writeTo (out);
  21301. }
  21302. }
  21303. const auto tracksBefore = [&] {
  21304. int n = 0;
  21305. for (int t = 0; t < (int) offline.getSong().playlistTracks.size(); ++t)
  21306. n += st::kindOf (offline.getSong(), t).has_value() ? 1 : 0;
  21307. return n;
  21308. }();
  21309. simple->addFilesForCheck ({ stems });
  21310. offline.dispatchPendingMessages();
  21311. {
  21312. const auto& s = offline.getSong();
  21313. juce::StringArray names;
  21314. int muted = 0, count = 0;
  21315. for (int t = 0; t < (int) s.playlistTracks.size(); ++t)
  21316. if (st::kindOf (s, t).has_value())
  21317. {
  21318. ++count;
  21319. if (count > tracksBefore)
  21320. {
  21321. names.add (juce::String::fromUTF8 (s.playlistTracks[(std::size_t) t].name.c_str()) + (s.playlistTracks[(std::size_t) t].muted ? " (muted)" : ""));
  21322. muted += s.playlistTracks[(std::size_t) t].muted ? 1 : 0;
  21323. }
  21324. }
  21325. line ("folder tracks: " + names.joinIntoString (", "));
  21326. check ("the folder gave 5 tracks in number order, named without numbers, the Bass notes muted (its stem plays)",
  21327. names == juce::StringArray { "Drums", "Bass", "Lead Vox", "Bass 2 (muted)", "Keys" } && muted == 1);
  21328. bool atZero = true;
  21329. for (const auto& c : s.playlist)
  21330. if (c.track >= 0 && st::kindOf (s, c.track) == st::Kind::audio)
  21331. atZero = atZero && c.start == 0;
  21332. check ("every stem starts at the song's start", atZero);
  21333. }
  21334. simple->hideChooser();
  21335. whole ("folder-import");
  21336. dir.deleteRecursively();
  21337. line (report.contains ("ERROR ") ? "RESULT ERROR" : "RESULT OK");
  21338. juce::File (prefix + "-report.txt").replaceWithText (report);
  21339. }
  21340. void runSimple190dsShot (const juce::String& prefix)
  21341. {
  21342. namespace st = lynx::simpletracks;
  21343. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  21344. lynx::AudioEngine offline (false);
  21345. lynx::MainComponent ui (offline, false);
  21346. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  21347. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  21348. ui.setVisible (true); // (no window: the docked editor only needs its parents visible)
  21349. const auto writeImage = [&prefix] (const juce::Image& image, const juce::String& name) {
  21350. const auto file = juce::File (prefix + "-" + name + ".png");
  21351. file.deleteFile();
  21352. juce::FileOutputStream out (file);
  21353. juce::PNGImageFormat().writeImageToStream (image, out);
  21354. };
  21355. juce::String report;
  21356. const auto line = [&report] (const juce::String& text) { report << text << "\n"; };
  21357. const auto check = [&report] (const juce::String& what, bool ok) { report << (ok ? "OK " : "ERROR ") << what << "\n"; };
  21358. ui.selectTabForSnapshot (2);
  21359. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  21360. offline.dispatchPendingMessages();
  21361. auto* simple = ui.getSimpleWorkflowForSnapshot();
  21362. if (simple == nullptr)
  21363. {
  21364. juce::File (prefix + "-report.txt").replaceWithText ("ERROR no Simple workflow\n");
  21365. return;
  21366. }
  21367. simple->hideChooser();
  21368. auto& playlist = ui.getPlaylistForSnapshot();
  21369. // --- three loops: two with their key in the name, one only in its sound ---------------------------------------
  21370. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-190ds-loops");
  21371. dir.deleteRecursively();
  21372. dir.createDirectory();
  21373. // a chord loop (two bars at 120 BPM, 48 kHz): each chord's notes with six harmonics, a soft attack per beat
  21374. const auto writeLoop = [&dir] (const juce::String& name, std::vector<std::vector<int>> chords) {
  21375. const int frames = 192000;
  21376. juce::AudioBuffer<float> audio (1, frames);
  21377. audio.clear();
  21378. for (int i = 0; i < frames; ++i)
  21379. {
  21380. const auto& chord = chords[(std::size_t) (i / (frames / (int) chords.size()))];
  21381. const auto t = (double) i / 48000.0;
  21382. const auto beat = std::fmod (t, 0.5);
  21383. double v = 0.0;
  21384. for (const auto key : chord)
  21385. {
  21386. const auto f = 440.0 * std::pow (2.0, (key - 69) / 12.0);
  21387. for (int h = 1; h <= 6; ++h)
  21388. v += std::sin (2.0 * juce::MathConstants<double>::pi * f * h * t) / (h * h);
  21389. }
  21390. audio.setSample (0, i, (float) (0.08 * v * (1.0 - std::exp (-beat * 60.0)) * (0.6 + 0.4 * std::exp (-beat * 3.0))));
  21391. }
  21392. const auto wav = dir.getChildFile (name);
  21393. juce::WavAudioFormat format;
  21394. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  21395. if (auto* w = format.createWriterFor (out.get(), 48000.0, 1, 16, {}, 0))
  21396. {
  21397. out.release();
  21398. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  21399. writer->writeFromAudioSampleBuffer (audio, 0, frames);
  21400. }
  21401. return wav.getFullPathName();
  21402. };
  21403. const auto gMinor = writeLoop ("Night Pad 120 Gm.wav", { { 55, 58, 62 }, { 51, 55, 58 }, { 53, 57, 60 }, { 55, 58, 62 } });
  21404. const auto dMinor = writeLoop ("Pluck_120_D_minor.wav", { { 50, 53, 57 }, { 46, 50, 53 }, { 48, 52, 55 }, { 50, 53, 57 } });
  21405. 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 } });
  21406. lynx::SimpleWorkflow::answerForSnapshot = 1; // "Set the project key to G minor?" — yes
  21407. simple->dropFiles ({ gMinor, dMinor, eMinor }, 0);
  21408. lynx::SimpleWorkflow::answerForSnapshot = -1;
  21409. offline.dispatchPendingMessages();
  21410. simple->hideChooser();
  21411. line ("question: " + simple->lastKeyQuestionForCheck());
  21412. check ("the first keyed loop offered its key (G minor)", simple->lastKeyQuestionForCheck().contains ("G minor"));
  21413. {
  21414. const auto& song = offline.getSong();
  21415. const auto key = lynx::projectkey::get (song);
  21416. check ("the project key is G minor", key && key->root == 7 && lynx::projectkey::isMinor (*key));
  21417. std::vector<int> clips;
  21418. for (int i = 0; i < (int) song.playlist.size(); ++i)
  21419. if (song.playlist[(std::size_t) i].kind == lynx::ClipKind::audio)
  21420. clips.push_back (i);
  21421. check ("three loop clips", clips.size() == 3);
  21422. const int expect[] { 0, 5, 3 }; // G minor, D minor (F -> Bb: +5), E minor detected (G -> Bb: +3)
  21423. const int roots[] { 7, 2, 4 };
  21424. const int sources[] { 1, 1, 2 };
  21425. for (std::size_t k = 0; k < clips.size() && k < 3; ++k)
  21426. {
  21427. const auto& c = song.playlist[(std::size_t) clips[k]];
  21428. const auto& sampler = song.channels[(std::size_t) c.channel].sampler;
  21429. line ("loop " + juce::String ((int) k + 1) + ": key " + juce::String (sampler.loopKeyRoot) + (sampler.loopKeyMinor ? "m" : "") + " source "
  21430. + juce::String ((int) sampler.loopKeySource) + " follow " + juce::String (c.followKey ? 1 : 0) + " shift " + juce::String ((int) c.keyShift)
  21431. + " pitch " + juce::String (c.pitch));
  21432. check ("loop " + juce::String ((int) k + 1) + " key, source and move", sampler.loopKeyRoot == roots[k] && sampler.loopKeyMinor
  21433. && sampler.loopKeySource == sources[k] && c.followKey
  21434. && c.keyShift == expect[k] && std::abs (c.pitch - (float) expect[k]) < 1.0e-4f);
  21435. }
  21436. }
  21437. // the key changes: every following loop moves with it (one undo step)
  21438. offline.editSong ([] (lynx::Song& s) { lynx::projectkey::set (s, lynx::projectkey::Key { 9, lynx::projectkey::commonFirst()[1] }); });
  21439. offline.dispatchPendingMessages();
  21440. {
  21441. const auto& song = offline.getSong();
  21442. std::vector<int> shifts;
  21443. for (const auto& c : song.playlist)
  21444. if (c.kind == lynx::ClipKind::audio)
  21445. shifts.push_back (c.keyShift);
  21446. line ("after A minor: " + juce::String (shifts.size() > 2 ? shifts[0] : 99) + " " + juce::String (shifts.size() > 2 ? shifts[1] : 99) + " "
  21447. + juce::String (shifts.size() > 2 ? shifts[2] : 99));
  21448. check ("A minor: the loops move by +2, -5, +5", shifts == std::vector<int> { 2, -5, 5 });
  21449. }
  21450. // the loop tracks in the dock: the switch and what it does
  21451. int loopTrack = -1;
  21452. for (const auto& c : offline.getSong().playlist)
  21453. if (c.kind == lynx::ClipKind::audio && loopTrack < 0)
  21454. loopTrack = c.track;
  21455. playlist.selectTrack (loopTrack);
  21456. offline.dispatchPendingMessages();
  21457. auto* dock = simple->dockForSnapshot();
  21458. if (dock == nullptr)
  21459. {
  21460. juce::File (prefix + "-report.txt").replaceWithText (report + "ERROR no dock\n");
  21461. return;
  21462. }
  21463. simple->trackSelected (loopTrack);
  21464. offline.dispatchPendingMessages();
  21465. const auto shots = [&] (const juce::String& name) {
  21466. offline.dispatchPendingMessages();
  21467. for (float scale : { 1.0f, 2.0f })
  21468. {
  21469. const auto suffix = scale > 1.0f ? juce::String ("@2x") : juce::String();
  21470. writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, scale), name + suffix);
  21471. writeImage (dock->createComponentSnapshot (dock->getLocalBounds(), true, scale), "dock-" + name + suffix);
  21472. }
  21473. };
  21474. const auto menuShot = [&] (const juce::PopupMenu& menu, const juce::String& title, const juce::String& subTitle, const juce::String& name) {
  21475. juce::StringArray names { title };
  21476. std::vector<juce::PopupMenu> menus { menu };
  21477. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  21478. if (it.getItem().subMenu != nullptr && it.getItem().text.startsWith (subTitle))
  21479. {
  21480. names.add (subTitle);
  21481. menus.push_back (*it.getItem().subMenu);
  21482. }
  21483. saveMenus (names, menus, prefix + "-" + name + ".png");
  21484. };
  21485. check ("the dock shows the follow switch for the loop track", dock->followShownForCheck());
  21486. shots ("follow-on");
  21487. {
  21488. int clip = -1;
  21489. for (int i = 0; i < (int) offline.getSong().playlist.size() && clip < 0; ++i)
  21490. if (offline.getSong().playlist[(std::size_t) i].kind == lynx::ClipKind::audio)
  21491. clip = i;
  21492. const auto menu = playlist.getClipMenuForSnapshot (clip);
  21493. bool follow = false, keyItem = false;
  21494. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  21495. {
  21496. follow = follow || (it.getItem().text.startsWith (lynx::tr ("Follow the project key")) && it.getItem().isTicked);
  21497. keyItem = keyItem || it.getItem().text.startsWith (lynx::tr ("Loop key"));
  21498. }
  21499. check ("the clip menu has Follow the project key (ticked) and Loop key", follow && keyItem);
  21500. menuShot (menu, lynx::tr ("Audio clip"), lynx::tr ("Loop key"), "menu-clip-key");
  21501. }
  21502. dock->clickFollowForCheck(); // off: back to its own key
  21503. offline.dispatchPendingMessages();
  21504. {
  21505. float pitch = 99.0f;
  21506. bool following = true;
  21507. for (const auto& c : offline.getSong().playlist)
  21508. if (c.kind == lynx::ClipKind::audio && c.track == loopTrack)
  21509. pitch = c.pitch, following = c.followKey;
  21510. check ("switched off: the loop plays in its own key (pitch 0)", ! following && std::abs (pitch) < 1.0e-6f);
  21511. }
  21512. shots ("follow-off");
  21513. dock->clickFollowForCheck();
  21514. offline.dispatchPendingMessages();
  21515. // --- an instrument track from the tile: a pattern to write into, the Editor tab ------------------------------
  21516. {
  21517. st::Request q;
  21518. q.kind = st::Kind::instrument;
  21519. q.name = "Keys";
  21520. lynx::ChannelDef synth;
  21521. synth.instrument = lynx::InstrumentKind::synth;
  21522. q.channel = synth;
  21523. q.emptyBars = 4;
  21524. st::Result r;
  21525. offline.editSong ([&] (lynx::Song& s) { r = st::addTrack (s, q); });
  21526. offline.dispatchPendingMessages();
  21527. check ("the new Instrument track has an empty 4-bar pattern on it", r.ok() && r.pattern >= 0
  21528. && st::patternOf (offline.getSong(), r.track) == r.pattern
  21529. && offline.getSong().patterns[(std::size_t) r.pattern].notes.empty());
  21530. // a few notes, as the first clicks would write them (A minor: A C E, then G B D)
  21531. offline.editSong ([r] (lynx::Song& s) {
  21532. auto& p = s.patterns[(std::size_t) r.pattern];
  21533. const int keys[] { 57, 60, 64, 67, 71, 74, 69, 72 };
  21534. for (int i = 0; i < 8; ++i)
  21535. {
  21536. lynx::Note n;
  21537. n.channel = r.channels.front();
  21538. n.key = keys[i];
  21539. n.start = (std::int64_t) (i / 3) * lynx::ppq * 2 + (i % 3 == 0 ? 0 : 0);
  21540. n.length = lynx::ppq * 2;
  21541. n.velocity = 0.8f;
  21542. p.notes.push_back (n);
  21543. }
  21544. p.sortNotes();
  21545. });
  21546. offline.dispatchPendingMessages();
  21547. playlist.selectTrack (r.track);
  21548. simple->trackSelected (r.track);
  21549. offline.dispatchPendingMessages();
  21550. check ("the instrument track has the Keyboard and Editor tabs", dock->hasPlayTabsForCheck());
  21551. dock->setTab (lynx::SimpleDock::Tab::editor);
  21552. offline.dispatchPendingMessages();
  21553. check ("the Piano roll is docked in the Editor tab", dock->isEditorDocked());
  21554. check ("on the track's pattern", offline.getSong().currentPattern == r.pattern);
  21555. ui.getPianoRollForSnapshot().scrollToNotes(); // (done asynchronously when it docks)
  21556. shots ("editor");
  21557. dock->clickFoldForCheck (true); // "Only notes in key"
  21558. check ("Only notes in key folds the rows to A minor", ui.getPianoRollForSnapshot().isFoldedToScale());
  21559. ui.getPianoRollForSnapshot().scrollToNotes();
  21560. shots ("editor-in-key");
  21561. dock->clickFoldForCheck (false);
  21562. // --- the keyboard's modes ------------------------------------------------------------------------------
  21563. auto& keyboard = lynx::scalekeys::current();
  21564. const auto saved = keyboard;
  21565. keyboard = {};
  21566. keyboard.lockToKey = true;
  21567. dock->setTab (lynx::SimpleDock::Tab::keyboard);
  21568. if (auto* panel = dock->keyboardPanelForSnapshot())
  21569. {
  21570. lynx::refreshKeyboardPanel (*panel);
  21571. shots ("keys-locked");
  21572. keyboard.lockToKey = false;
  21573. keyboard.mode = lynx::scalekeys::Mode::scaleKeys;
  21574. lynx::refreshKeyboardPanel (*panel);
  21575. shots ("scale-keys");
  21576. keyboard.mode = lynx::scalekeys::Mode::chordPad;
  21577. keyboard.complexity = lynx::scalekeys::Complexity::seventh;
  21578. keyboard.strumMs = 40;
  21579. lynx::refreshKeyboardPanel (*panel);
  21580. shots ("chord-pad");
  21581. }
  21582. check ("the Keyboard tab shows the keyboard panel", dock->keyboardPanelForSnapshot() != nullptr);
  21583. // the same panel as the Touch keyboard window, each mode with a key / pad held
  21584. for (const auto& [mode, name, pressed] : { std::tuple { lynx::scalekeys::Mode::scaleKeys, juce::String ("window-scale-keys"), 4 },
  21585. std::tuple { lynx::scalekeys::Mode::chordPad, juce::String ("window-chord-pad"), 3 } })
  21586. {
  21587. auto panel = lynx::makeKeyboardPanelForSnapshot (offline, mode, pressed, [ch = r.channels.front()] { return ch; });
  21588. panel->setSize (1100, 260);
  21589. for (float scale : { 1.0f, 2.0f })
  21590. writeImage (panel->createComponentSnapshot (panel->getLocalBounds(), true, scale), name + (scale > 1.0f ? "@2x" : ""));
  21591. if (mode == lynx::scalekeys::Mode::chordPad)
  21592. menuShot (lynx::chordPadMenuForSnapshot (*panel, 3), lynx::tr ("Edit chord"), lynx::tr ("Chord type"), "menu-chord-edit");
  21593. }
  21594. // the Chord pad on an FL Studio Mobile chord set (the default set's shape: C Dm Em F G Am B° C)
  21595. {
  21596. 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})");
  21597. check ("an FLM chord set reads as 8 chords (B diminished)", set.size() == 8 && set[6].quality == 3);
  21598. offline.editSong ([set] (lynx::Song& s) { s.keyboardChords = set; });
  21599. keyboard.projectChords = true;
  21600. keyboard.complexity = lynx::scalekeys::Complexity::triad;
  21601. auto panel = lynx::makeKeyboardPanelForSnapshot (offline, lynx::scalekeys::Mode::chordPad, 5, [ch = r.channels.front()] { return ch; });
  21602. panel->setSize (1100, 260);
  21603. for (float scale : { 1.0f, 2.0f })
  21604. writeImage (panel->createComponentSnapshot (panel->getLocalBounds(), true, scale), juce::String ("window-chord-set") + (scale > 1.0f ? "@2x" : ""));
  21605. }
  21606. // the typing keys in each mode (A minor; Z = the root)
  21607. {
  21608. const auto& song = offline.getSong();
  21609. lynx::scalekeys::Settings s;
  21610. s.mode = lynx::scalekeys::Mode::scaleKeys;
  21611. juce::String z;
  21612. for (const int typed : { 60, 62, 64, 65, 67, 69, 71, 72, 61 })
  21613. {
  21614. const auto n = lynx::scalekeys::typedNotes (song, s, typed, 60);
  21615. z << (n.empty() ? juce::String ("-") : juce::String (n.front())) << " ";
  21616. }
  21617. line ("Scale keys, typing C D E F G A B C C#: " + z);
  21618. check ("Scale keys: the white typing keys play A minor from A", z.trim() == "69 71 72 74 76 77 79 81 -");
  21619. s.mode = lynx::scalekeys::Mode::chordPad;
  21620. s.projectChords = false;
  21621. const auto pad = lynx::scalekeys::typedNotes (song, s, 60, 60);
  21622. check ("Chord pad: Z plays A minor (A C E)", pad == std::vector<int> { 69, 72, 76 });
  21623. }
  21624. keyboard = saved;
  21625. }
  21626. // --- the project round trip --------------------------------------------------------------------------------
  21627. {
  21628. const auto json = lynx::ProjectFile::toJson (offline.getSong());
  21629. juce::String error;
  21630. const auto back = lynx::ProjectFile::fromJson (json, error);
  21631. bool same = back.has_value() && back->keyboardChords == offline.getSong().keyboardChords && back->playlist.size() == offline.getSong().playlist.size();
  21632. for (std::size_t i = 0; same && i < back->playlist.size(); ++i)
  21633. same = back->playlist[i].followKey == offline.getSong().playlist[i].followKey && back->playlist[i].keyShift == offline.getSong().playlist[i].keyShift
  21634. && back->playlist[i].pitch == offline.getSong().playlist[i].pitch;
  21635. for (std::size_t c = 0; same && c < back->channels.size(); ++c)
  21636. same = back->channels[c].sampler.loopKeyRoot == offline.getSong().channels[c].sampler.loopKeyRoot
  21637. && back->channels[c].sampler.loopKeySource == offline.getSong().channels[c].sampler.loopKeySource;
  21638. check ("follow, key moves, loop keys and the chord set survive .lynx", same);
  21639. }
  21640. dir.deleteRecursively();
  21641. line (report.contains ("ERROR ") ? "RESULT ERROR" : "RESULT OK");
  21642. juce::File (prefix + "-report.txt").replaceWithText (report);
  21643. }
  21644. void runSimple190dgShot (const juce::String& prefix)
  21645. {
  21646. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  21647. lynx::AudioEngine offline (false);
  21648. lynx::MainComponent ui (offline, false);
  21649. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  21650. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  21651. const auto writeImage = [&prefix] (const juce::Image& image, const juce::String& name) {
  21652. const auto file = juce::File (prefix + "-" + name + ".png");
  21653. file.deleteFile();
  21654. juce::FileOutputStream out (file);
  21655. juce::PNGImageFormat().writeImageToStream (image, out);
  21656. };
  21657. juce::String report;
  21658. const auto line = [&report] (const juce::String& text) { report << text << "\n"; };
  21659. const auto check = [&report] (const juce::String& what, bool ok) { report << (ok ? "OK " : "ERROR ") << what << "\n"; };
  21660. ui.selectTabForSnapshot (2);
  21661. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  21662. offline.dispatchPendingMessages();
  21663. auto* simple = ui.getSimpleWorkflowForSnapshot();
  21664. if (simple == nullptr)
  21665. {
  21666. juce::File (prefix + "-report.txt").replaceWithText ("ERROR no Simple workflow\n");
  21667. return;
  21668. }
  21669. simple->hideChooser();
  21670. offline.editSong ([] (lynx::Song& s) {
  21671. namespace st = lynx::simpletracks;
  21672. st::Request q;
  21673. q.kind = st::Kind::voice;
  21674. q.name = "Lead vocal";
  21675. st::addTrack (s, q);
  21676. q = {};
  21677. q.kind = st::Kind::instrument;
  21678. q.name = "Keys";
  21679. lynx::ChannelDef keys;
  21680. keys.instrument = lynx::InstrumentKind::synth;
  21681. q.channel = keys;
  21682. st::addTrack (s, q);
  21683. });
  21684. offline.dispatchPendingMessages();
  21685. simple->hideChooser();
  21686. auto& playlist = ui.getPlaylistForSnapshot();
  21687. int voiceTrack = -1, keysTrack = -1;
  21688. {
  21689. const auto& song = offline.getSong();
  21690. for (int t = 0; t < (int) song.playlistTracks.size(); ++t)
  21691. if (const auto kind = lynx::simpletracks::kindOf (song, t))
  21692. {
  21693. if (*kind == lynx::simpletracks::Kind::audio && voiceTrack < 0)
  21694. voiceTrack = t;
  21695. else if (*kind == lynx::simpletracks::Kind::instrument && keysTrack < 0)
  21696. keysTrack = t;
  21697. }
  21698. }
  21699. check ("two Simple tracks (voice, keys)", voiceTrack >= 0 && keysTrack >= 0);
  21700. playlist.selectTrack (voiceTrack);
  21701. offline.dispatchPendingMessages();
  21702. auto* dock = simple->dockForSnapshot();
  21703. if (dock == nullptr)
  21704. {
  21705. juce::File (prefix + "-report.txt").replaceWithText (report + "ERROR no dock\n");
  21706. return;
  21707. }
  21708. const auto shots = [&] (const juce::String& name) {
  21709. offline.dispatchPendingMessages();
  21710. for (float scale : { 1.0f, 2.0f })
  21711. {
  21712. const auto suffix = scale > 1.0f ? juce::String ("@2x") : juce::String();
  21713. writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, scale), name + suffix);
  21714. writeImage (dock->createComponentSnapshot (dock->getLocalBounds(), true, scale), "dock-" + name + suffix);
  21715. }
  21716. };
  21717. const auto menuShot = [&] (const juce::PopupMenu& menu, const juce::String& title, const juce::String& subTitle, const juce::String& name) {
  21718. juce::StringArray names { title };
  21719. std::vector<juce::PopupMenu> menus { menu };
  21720. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  21721. if (it.getItem().subMenu != nullptr && it.getItem().text == subTitle)
  21722. {
  21723. names.add (subTitle);
  21724. menus.push_back (*it.getItem().subMenu);
  21725. }
  21726. saveMenus (names, menus, prefix + "-" + name + ".png");
  21727. };
  21728. const auto insert = dock->insertForCheck();
  21729. // --- every one-knob effect as a card, each at a knob position of its own -------------------------------------
  21730. const float at[] { 0.0f, 0.55f, 0.40f, 0.70f, 0.30f, 0.60f, 0.45f, 0.35f, 0.80f };
  21731. for (int id = 1; id <= lynx::goals::count; ++id)
  21732. dock->addOneKnobForCheck (id);
  21733. offline.dispatchPendingMessages();
  21734. for (int id = 1; id <= lynx::goals::count; ++id)
  21735. dock->turnKnobForCheck (id - 1, at[id]);
  21736. offline.dispatchPendingMessages();
  21737. check ("eight one-knob cards on the insert", dock->cardCountForCheck() == 8 && dock->oneKnobCardsForCheck() == 8);
  21738. {
  21739. const auto& fx = offline.getSong().mixer[(std::size_t) insert].effects;
  21740. bool turned = fx.size() == 8;
  21741. for (std::size_t i = 0; turned && i < fx.size(); ++i)
  21742. turned = lynx::goals::active (fx[i]) && std::abs (fx[i].goalAmount - at[i + 1]) < 1.0e-6f;
  21743. check ("each knob wrote its effect's parameters", turned);
  21744. }
  21745. shots ("effects-all");
  21746. offline.dispatchPendingMessages();
  21747. for (int card = 0; card < dock->cardCountForCheck(); ++card)
  21748. {
  21749. const auto area = dock->cardBoundsForSnapshot (card);
  21750. const auto name = juce::String (lynx::goals::name (card + 1)).toLowerCase();
  21751. check ("card " + juce::String (card + 1) + " (" + name + ") is on screen", ! area.isEmpty() && dock->getLocalBounds().contains (area));
  21752. for (float scale : { 1.0f, 2.0f })
  21753. writeImage (dock->createComponentSnapshot (area.expanded (4), true, scale), "card-" + name + (scale > 1.0f ? "@2x" : ""));
  21754. }
  21755. // --- a chain preset with Blend --------------------------------------------------------------------------------
  21756. if (const auto* preset = lynx::chains::find ("Canyon"))
  21757. offline.editSongStructural ([insert, preset] (lynx::Song& s) { lynx::chains::apply (s, insert, *preset); });
  21758. offline.dispatchPendingMessages();
  21759. dock->setBlendForCheck (0.6f);
  21760. offline.dispatchPendingMessages();
  21761. check ("preset Canyon with Blend 60 % (shown as edited)", offline.getSong().mixer[(std::size_t) insert].chainPreset == "Canyon"
  21762. && std::abs (offline.getSong().mixer[(std::size_t) insert].chainBlend - 0.6f) < 1.0e-6f
  21763. && ! lynx::chains::unchanged (offline.getSong(), insert));
  21764. shots ("effects-preset-blend");
  21765. // favourites: the track's preset starred; the menu lists it first
  21766. const auto favFile = lynx::SimpleDock::favouritesFile();
  21767. const auto hadFavourites = favFile.existsAsFile();
  21768. const auto oldFavourites = favFile.loadFileAsString();
  21769. lynx::SimpleDock::setFavouritePreset ("Canyon", true);
  21770. lynx::SimpleDock::setFavouritePreset ("Clear Voice", true);
  21771. lynx::SimpleDock::setFavouritePreset ("Canyon", true); // (twice: once in the list)
  21772. check ("two favourites kept, in order", lynx::SimpleDock::favouritePresets() == juce::StringArray { "Canyon", "Clear Voice" });
  21773. {
  21774. bool first = false, toggle = false;
  21775. const auto menu = dock->presetMenuForSnapshot();
  21776. juce::PopupMenu::MenuItemIterator it (menu);
  21777. if (it.next())
  21778. first = it.getItem().subMenu != nullptr && it.getItem().text.contains (lynx::tr ("Favourites"));
  21779. for (juce::PopupMenu::MenuItemIterator all (menu); all.next();)
  21780. toggle = toggle || all.getItem().text == lynx::tr ("Remove \"{0}\" from favourites", { "Canyon" });
  21781. check ("the Preset menu starts with the favourites and offers to unstar the track's preset", first && toggle);
  21782. menuShot (menu, lynx::tr ("Preset"), juce::String::fromUTF8 ("\xe2\x98\x85 ") + lynx::tr ("Favourites"), "menu-preset-favourites");
  21783. }
  21784. lynx::SimpleDock::setFavouritePreset ("Canyon", false);
  21785. check ("unstarred", lynx::SimpleDock::favouritePresets() == juce::StringArray { "Clear Voice" });
  21786. if (hadFavourites)
  21787. favFile.replaceWithText (oldFavourites);
  21788. else
  21789. favFile.deleteFile();
  21790. // --- the sound picker: a search, and the installed plugins -----------------------------------------------------
  21791. playlist.selectTrack (keysTrack);
  21792. offline.dispatchPendingMessages();
  21793. check ("the Keys track opens on its sound", dock->getTab() == lynx::SimpleDock::Tab::instrument);
  21794. dock->showCategoryForSnapshot ((int) lynx::soundlib::Category::bass);
  21795. dock->setSearchForSnapshot ("sub");
  21796. offline.dispatchPendingMessages();
  21797. line ("search \"sub\" in Bass: " + juce::String (dock->soundRowsForCheck()) + " rows");
  21798. check ("a search narrows the category", dock->soundRowsForCheck() > 0 && dock->soundRowsForCheck() < (int) lynx::soundlib::filter (lynx::soundlib::builtIn(), lynx::soundlib::Category::bass).size());
  21799. shots ("picker-search");
  21800. dock->setSearchForSnapshot ({});
  21801. // a made-up list of installed plugins (nothing is scanned or loaded)
  21802. dock->setPluginsForSnapshot ({ { "VST3-demo-1", "Analog Mono", "Example Audio", "VST3", "Instrument|Synth" },
  21803. { "VST3-demo-2", "Grand Upright", "Example Audio", "VST3", "Instrument|Piano" },
  21804. { "VST3-demo-3", "Beat Kit 808", "Sample Lab", "VST3", "Instrument|Drum" },
  21805. { "CLAP-demo-4", "Orchestra Strings", "Sample Lab", "CLAP", "Instrument|Sampler" },
  21806. { "VST3-demo-5", "Wave Table One", "Example Audio", "VST3", "Instrument|Synth" },
  21807. { "VST-demo-6", "Sub Bass Machine", "Low End", "VST", "Synth" },
  21808. { "VST3-demo-7", "Sample Player", "Sample Lab", "VST3", "Instrument|Sampler" } });
  21809. dock->showCategoryForSnapshot ((int) lynx::soundlib::Category::synths);
  21810. offline.dispatchPendingMessages();
  21811. check ("My plugins: the generic synths and samplers in their own category (" + juce::String (dock->soundRowsForCheck()) + " of 7)", dock->soundRowsForCheck() == 3);
  21812. shots ("picker-plugins");
  21813. line (report.contains ("ERROR ") ? "RESULT ERROR" : "RESULT OK");
  21814. juce::File (prefix + "-report.txt").replaceWithText (report);
  21815. }
  21816. void runSimpleShot (const juce::String& prefix)
  21817. {
  21818. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  21819. lynx::AudioEngine offline (false);
  21820. lynx::MainComponent ui (offline, false);
  21821. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  21822. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  21823. const auto writeImage = [&prefix] (const juce::Image& image, const char* name) {
  21824. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  21825. file.deleteFile();
  21826. juce::FileOutputStream out (file);
  21827. juce::PNGImageFormat().writeImageToStream (image, out);
  21828. };
  21829. const auto write = [&ui, &writeImage] (const char* name) { writeImage (lynx::shot::snapshot (ui), name); };
  21830. // View › Layout style, with its submenu, as it is with `style` chosen
  21831. const auto viewMenu = [&ui] {
  21832. const auto names = ui.getMenuNamesForSnapshot();
  21833. const auto view = names.indexOf (lynx::tr ("View"));
  21834. return ui.getMenuForSnapshot (juce::jmax (0, view));
  21835. };
  21836. const auto saveStyleMenus = [&] (const juce::String& suffix) {
  21837. const auto view = viewMenu();
  21838. juce::StringArray names { lynx::tr ("View") };
  21839. std::vector<juce::PopupMenu> menus { view };
  21840. for (juce::PopupMenu::MenuItemIterator it (view); it.next();)
  21841. if (it.getItem().subMenu != nullptr && it.getItem().text == lynx::tr ("Layout style"))
  21842. {
  21843. names.add (lynx::tr ("Layout style"));
  21844. menus.push_back (*it.getItem().subMenu);
  21845. }
  21846. saveMenus (names, menus, prefix + "-menu-" + suffix + ".png");
  21847. };
  21848. // Settings › General with `style` selected, and its style list
  21849. const auto saveSettings = [&] (lynx::layoutstyle::Style style, const char* name) {
  21850. lynx::SettingsHooks hooks;
  21851. hooks.getGeneral = [style] {
  21852. lynx::GeneralOptions o;
  21853. o.language = lynx::i18n::current();
  21854. o.layoutStyle = (int) style;
  21855. return o;
  21856. };
  21857. auto page = lynx::makeSettingsPanel (offline, lynx::SettingsPage::general, false, hooks);
  21858. const auto image = lynx::shot::paint (*page, lynx::theme::panel, -1, juce::jmin (page->getHeight(), 420));
  21859. writeImage (image, name);
  21860. std::function<juce::ComboBox* (juce::Component&)> find = [&find] (juce::Component& c) -> juce::ComboBox* {
  21861. if (c.getComponentID() == "layoutStyle")
  21862. return dynamic_cast<juce::ComboBox*> (&c);
  21863. for (auto* child : c.getChildren())
  21864. if (auto* box = find (*child))
  21865. return box;
  21866. return nullptr;
  21867. };
  21868. if (auto* box = find (*page); box != nullptr && box->getRootMenu() != nullptr)
  21869. saveMenus (juce::StringArray { lynx::tr ("Layout style") }, std::vector<juce::PopupMenu> { *box->getRootMenu() },
  21870. prefix + "-" + name + "-list.png");
  21871. };
  21872. const auto madeBefore = lynx::SimpleWorkflow::instances.load();
  21873. ui.selectTabForSnapshot (2); // the Playlist panel, maximized (as --gridshot)
  21874. write ("pattern");
  21875. saveStyleMenus ("pattern");
  21876. saveSettings (lynx::layoutstyle::Style::pattern, "settings-pattern");
  21877. const auto madePattern = lynx::SimpleWorkflow::instances.load();
  21878. ui.setLayoutStyle (lynx::layoutstyle::Style::clipLaunch);
  21879. saveStyleMenus ("cliplaunch");
  21880. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  21881. offline.dispatchPendingMessages();
  21882. if (auto* simple = ui.getSimpleWorkflowForSnapshot())
  21883. simple->showChooser(); // (an empty project opens on it by itself; the offline project may hold the default song)
  21884. write ("simple"); // the New track chooser (slice S3)
  21885. if (auto* simple = ui.getSimpleWorkflowForSnapshot())
  21886. {
  21887. simple->showStarterPageForSnapshot();
  21888. write ("simple-starter");
  21889. simple->hideChooser();
  21890. write ("simple-closed");
  21891. // round 190p: a loop keeps time. Two files with the same 4.8 s of audio dropped on the empty Simple timeline:
  21892. // "Guitar loop 100.wav" (2 bars at 100 BPM) lasts 2 bars at the project's tempo, "Guitar take.wav" plays at
  21893. // its own speed. Both are undone again, so the shots after this one are as they were.
  21894. {
  21895. const auto folder = juce::File (prefix + "-loops");
  21896. folder.createDirectory();
  21897. juce::StringArray files;
  21898. for (const auto* name : { "Guitar loop 100.wav", "Guitar take.wav" })
  21899. {
  21900. const auto file = folder.getChildFile (name);
  21901. file.deleteFile();
  21902. const auto rate = 44100.0;
  21903. const auto frames = (int) (4.8 * rate);
  21904. juce::AudioBuffer<float> audio (1, frames);
  21905. for (int i = 0; i < frames; ++i)
  21906. {
  21907. const auto t = (double) i / rate, inBeat = std::fmod (t, 0.6); // a plucked note on every beat at 100 BPM
  21908. audio.setSample (0, i, (float) (0.7 * std::exp (-inBeat * 7.0) * std::sin (juce::MathConstants<double>::twoPi * 196.0 * t)));
  21909. }
  21910. if (auto out = file.createOutputStream())
  21911. if (auto writer = std::unique_ptr<juce::AudioFormatWriter> (juce::WavAudioFormat().createWriterFor (out.get(), rate, 1, 16, {}, 0)))
  21912. {
  21913. out.release();
  21914. writer->writeFromAudioSampleBuffer (audio, 0, frames);
  21915. }
  21916. files.add (file.getFullPathName());
  21917. }
  21918. simple->dropFiles (files, 0);
  21919. offline.dispatchPendingMessages();
  21920. // the clips' waveforms are analysed in the background and drawn once ready (a live window repaints by
  21921. // itself; one off-screen paint came too early and showed empty clips)
  21922. for (const auto& path : files)
  21923. lynx::ui::WaveformCache::getInstance()->find (path, [&offline, path] { return offline.getSampleLibrary().load (path); });
  21924. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (30000);
  21925. offline.dispatchPendingMessages();
  21926. write ("simple-loop");
  21927. const auto& song = offline.getSong();
  21928. juce::String report;
  21929. for (const auto& clip : song.playlist)
  21930. if (clip.kind == lynx::ClipKind::audio)
  21931. report << song.channels[(std::size_t) clip.channel].name << ": " << juce::String ((double) clip.length / lynx::ppq, 3) << " beats, stretch "
  21932. << juce::String (song.channels[(std::size_t) clip.channel].sampler.stretchBeats, 2) << "\n";
  21933. juce::File (prefix + "-loop.txt").replaceWithText ("tempo " + juce::String (song.bpm, 1) + "\n" + report);
  21934. for (int i = 0; i < files.size() && offline.canUndo(); ++i) // (one undo step per dropped file)
  21935. offline.undo();
  21936. offline.dispatchPendingMessages();
  21937. simple->hideChooser();
  21938. }
  21939. // round 190t, slice A: one click on a starter beat adds it, placed for four bars (undone again)
  21940. {
  21941. const auto clipsBefore = offline.getSong().playlist.size();
  21942. const auto tempoBefore = offline.getSong().bpm;
  21943. simple->clickStarterForSnapshot (1);
  21944. offline.dispatchPendingMessages();
  21945. write ("simple-starter-added");
  21946. const auto& song = offline.getSong();
  21947. juce::String report ("tempo " + juce::String (tempoBefore, 1) + " -> " + juce::String (song.bpm, 1) + "\n");
  21948. for (auto i = clipsBefore; i < song.playlist.size(); ++i)
  21949. report << "clip at beat " << juce::String ((double) song.playlist[i].start / lynx::ppq, 2) << ", " << juce::String ((double) song.playlist[i].length / lynx::ppq, 2)
  21950. << " beats, pattern " << song.playlist[i].pattern << ", track " << song.playlist[i].track << "\n";
  21951. juce::File (prefix + "-starter.txt").replaceWithText (report);
  21952. if (song.playlist.size() > clipsBefore && offline.canUndo())
  21953. offline.undo();
  21954. offline.dispatchPendingMessages();
  21955. simple->hideChooser();
  21956. }
  21957. // slice S4: the Simple headers with a few tracks (voice, instrument, drums, an audio file), some levels moved
  21958. offline.editSong ([] (lynx::Song& s) {
  21959. namespace st = lynx::simpletracks;
  21960. st::Request q;
  21961. q.kind = st::Kind::voice;
  21962. q.name = "Lead vocal";
  21963. st::addTrack (s, q);
  21964. q = {};
  21965. q.kind = st::Kind::instrument;
  21966. q.name = "Keys";
  21967. lynx::ChannelDef keys;
  21968. keys.instrument = lynx::InstrumentKind::synth;
  21969. q.channel = keys;
  21970. lynx::Pattern chords;
  21971. for (int i = 0; i < 4; ++i)
  21972. for (int k : { 60, 64, 67 })
  21973. chords.notes.push_back (lynx::Note { (std::int64_t) i * 4 * lynx::ppq, 4 * lynx::ppq - lynx::ppq / 4, 0, k });
  21974. q.pattern = chords;
  21975. const auto r = st::addTrack (s, q);
  21976. q = {};
  21977. q.kind = st::Kind::drums;
  21978. for (auto kind : { lynx::InstrumentKind::kick, lynx::InstrumentKind::snare, lynx::InstrumentKind::hat })
  21979. {
  21980. lynx::ChannelDef c;
  21981. c.instrument = kind;
  21982. c.name = kind == lynx::InstrumentKind::kick ? "Kick" : kind == lynx::InstrumentKind::snare ? "Snare" : "Hat";
  21983. q.kit.push_back (c);
  21984. }
  21985. lynx::Pattern beat;
  21986. const auto hit = [&beat] (int step, int row) { beat.notes.push_back (lynx::Note { (std::int64_t) step * lynx::ticksPerStep, lynx::ticksPerStep, row, 60 }); };
  21987. for (int step = 0; step < 16; step += 2)
  21988. hit (step, 2); // hats on the 8ths, kick on 1 and 3, snare on 2 and 4
  21989. for (int step : { 0, 8 })
  21990. hit (step, 0);
  21991. for (int step : { 4, 12 })
  21992. hit (step, 1);
  21993. q.pattern = beat;
  21994. q.bpm = 96.0;
  21995. st::addTrack (s, q);
  21996. if (r.insert > 0)
  21997. {
  21998. s.mixer[(std::size_t) r.insert].volume = 0.55f;
  21999. s.mixer[(std::size_t) r.insert].pan = -0.4f;
  22000. s.mixer[(std::size_t) r.insert].solo = true;
  22001. }
  22002. });
  22003. offline.dispatchPendingMessages();
  22004. ui.getPlaylistForSnapshot().selectTrack (1);
  22005. write ("simple-tracks");
  22006. // round 190t, slice E: the backup status beside the title tools, in each of its states
  22007. {
  22008. const auto now = juce::Time::currentTimeMillis();
  22009. juce::String states;
  22010. int n = 0;
  22011. for (const auto& text : { lynx::MainComponent::simpleSaveStatusText (true, false, 0, now), lynx::MainComponent::simpleSaveStatusText (true, false, now - 5000, now),
  22012. lynx::MainComponent::simpleSaveStatusText (true, true, now - 125000, now), lynx::MainComponent::simpleSaveStatusText (false, true, 0, now),
  22013. lynx::MainComponent::simpleSaveStatusText (false, false, 0, now) })
  22014. {
  22015. simple->setStatusForSnapshot (text);
  22016. offline.dispatchPendingMessages();
  22017. states << n << ": " << text << "\n";
  22018. writeImage (lynx::shot::snapshot (ui, ui.getLocalBounds().withTop (juce::jmin (ui.getHeight() - 1, 70)).withHeight (juce::jmin (ui.getHeight(), 44))),
  22019. ("status-" + juce::String (n++)).toRawUTF8());
  22020. }
  22021. juce::File (prefix + "-status.txt").replaceWithText (states);
  22022. simple->setStatusForSnapshot (lynx::MainComponent::simpleSaveStatusText (true, true, now - 125000, now));
  22023. offline.dispatchPendingMessages();
  22024. write ("simple-status");
  22025. }
  22026. // slice S8: the Finish dock, empty, then with a look on the Master (Balanced, Normal, a little Tone)
  22027. simple->showFinish();
  22028. offline.dispatchPendingMessages();
  22029. write ("simple-finish-empty");
  22030. offline.editSongStructural ([] (lynx::Song& s) { lynx::looks::apply (s, lynx::MasterLookSettings { lynx::looks::balanced, 0.5f, { 1.5f, 0.0f, 1.0f }, -3.0f }); });
  22031. offline.dispatchPendingMessages();
  22032. simple->showFinish();
  22033. write ("simple-finish");
  22034. simple->hideFinish();
  22035. }
  22036. saveStyleMenus ("simple");
  22037. saveSettings (lynx::layoutstyle::Style::simple, "settings-simple");
  22038. // round 184a S11: the Key panel (no key, then an A minor riff and its guesses) and its menu
  22039. const auto toolbarShot = [&] (const char* name) {
  22040. writeImage (lynx::shot::snapshot (ui, ui.getLocalBounds().withHeight (juce::jmin (ui.getHeight(), 80))), name);
  22041. };
  22042. toolbarShot ("key-none");
  22043. saveMenus (juce::StringArray { lynx::tr ("Key") }, std::vector<juce::PopupMenu> { ui.getKeyMenuForSnapshot() }, prefix + "-key-menu-empty.png");
  22044. offline.editSong ([] (lynx::Song& s) {
  22045. if (s.channels.empty())
  22046. s.channels.resize (1);
  22047. if (s.patterns.empty())
  22048. s.patterns.emplace_back();
  22049. int t = 0;
  22050. for (int k : { 57, 60, 64, 67, 69, 67, 64, 60, 57, 59, 60, 62, 64, 62, 60, 59, 57, 57, 64, 45 })
  22051. {
  22052. lynx::Note n;
  22053. n.channel = 0;
  22054. n.key = k;
  22055. n.start = t * lynx::ppq / 2;
  22056. n.length = k == 57 || k == 45 ? lynx::ppq : lynx::ppq / 2;
  22057. s.patterns[0].notes.push_back (n);
  22058. ++t;
  22059. }
  22060. });
  22061. offline.dispatchPendingMessages();
  22062. saveMenus (juce::StringArray { lynx::tr ("Key") }, std::vector<juce::PopupMenu> { ui.getKeyMenuForSnapshot() }, prefix + "-key-menu-guess.png");
  22063. const auto guesses = lynx::keyguess::guess (offline.getSong(), 3);
  22064. if (! guesses.empty())
  22065. offline.editSong ([k = guesses[0].key] (lynx::Song& s) { lynx::projectkey::set (s, k); });
  22066. offline.dispatchPendingMessages();
  22067. toolbarShot ("key-set");
  22068. write ("simple-key");
  22069. juce::String keyCounts;
  22070. for (const auto& g : guesses)
  22071. keyCounts << "guess " << lynx::projectkey::name (g.key) << " " << g.notesInScale << "/" << g.notes << " score " << g.score << "\n";
  22072. offline.editSong ([] (lynx::Song& s) { lynx::projectkey::set (s, std::nullopt); });
  22073. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
  22074. offline.dispatchPendingMessages();
  22075. toolbarShot ("key-pattern-toolbar");
  22076. write ("pattern-after");
  22077. // round 184a S17: the setup wizard with its Workflow choice — a first start (Pattern selected), then reopened in Simple
  22078. for (int style : { 0, 2 })
  22079. {
  22080. auto wizard = lynx::makeSetupWizardContent (offline, {}, {}, style, {});
  22081. auto image = lynx::shot::paint (*wizard);
  22082. writeImage (image, style == 0 ? "wizard-pattern" : "wizard-simple");
  22083. }
  22084. juce::File (prefix + "-counts.txt").replaceWithText ("simple workflows before " + juce::String (madeBefore) + ", in pattern workflow "
  22085. + juce::String (madePattern) + ", after " + juce::String (lynx::SimpleWorkflow::instances.load())
  22086. + "\nstyle after " + lynx::layoutstyle::id (ui.getLayoutStyle()) + "\n" + keyCounts);
  22087. }
  22088. void runLiveShot190ce (const juce::String& prefix)
  22089. {
  22090. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  22091. lynx::AudioEngine offline (false);
  22092. lynx::MainComponent ui (offline, false);
  22093. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  22094. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  22095. const auto write = [&prefix, &ui, &offline] (const char* name) {
  22096. offline.dispatchPendingMessages();
  22097. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  22098. file.deleteFile();
  22099. juce::FileOutputStream out (file);
  22100. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (ui), out);
  22101. };
  22102. juce::String checks;
  22103. const auto check = [&checks] (const char* what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  22104. // a small library of its own (empty files: only names are shown)
  22105. const auto lib = juce::File (prefix + "-library");
  22106. lib.deleteRecursively();
  22107. for (const auto* path : { "Drums/Kicks/Kick Hard.wav", "Drums/Kicks/Kick Soft.wav", "Drums/Snare Tight.wav", "Drums/Hat Closed.wav",
  22108. "Loops/Break 120.wav", "Loops/Shaker 98.wav", "Textures/Vinyl Noise.wav", "Textures/Rain.wav" })
  22109. lib.getChildFile (path).create();
  22110. auto& browser = ui.getBrowserForSnapshot();
  22111. auto& store = lynx::BrowserComponent::collectionStore();
  22112. store = {};
  22113. const auto item = [&lib] (const char* path) { return lib.getChildFile (path).getFullPathName().toStdString(); };
  22114. ui.setVisible (true);
  22115. lynx::DetailView::shownSetting = lynx::DetailView::devicesPage = true;
  22116. ui.setClipLaunchWorkflow (true);
  22117. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::browser, lynx::workspace::Panel::playlist });
  22118. offline.editSong ([] (lynx::Song& s) {
  22119. if (s.channels.size() < 2)
  22120. s.channels.resize (2);
  22121. s.channels[0].name = "Bass synth";
  22122. s.channels[0].mixerTrack = 2;
  22123. s.channels[1].mixerTrack = 3;
  22124. if (s.mixer.size() < 4)
  22125. s.mixer.resize (4);
  22126. s.mixer[2].name = "Bass";
  22127. s.mixer[2].effects.clear();
  22128. for (auto kind : { lynx::EffectKind::eq, lynx::EffectKind::compressor, lynx::EffectKind::delay })
  22129. {
  22130. lynx::EffectSlot fx;
  22131. fx.kind = kind;
  22132. const auto& info = lynx::effectInfo (kind);
  22133. for (std::size_t k = 0; k < info.params.size() && k < fx.params.size(); ++k)
  22134. fx.params[k] = info.params[k].defaultValue;
  22135. s.mixer[2].effects.push_back (fx);
  22136. }
  22137. s.mixer[2].effects[1].enabled = false; // the compressor: off, at half mix
  22138. s.mixer[2].effects[1].mix = 0.5f;
  22139. while (s.patterns.size() < 2)
  22140. s.patterns.emplace_back();
  22141. s.patterns[0].name = "Bass line";
  22142. lynx::Note note;
  22143. note.channel = 0;
  22144. note.key = 36;
  22145. s.patterns[0].notes = { note };
  22146. s.patterns[0].lengthTicks = 4 * lynx::ppq;
  22147. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 3));
  22148. s.playlistTracks[1].name = "Bass";
  22149. lynx::Clip clip;
  22150. clip.pattern = 0;
  22151. clip.length = 4 * lynx::ppq;
  22152. lynx::launcher::setClip (s, 1, 0, clip);
  22153. }, false);
  22154. offline.dispatchPendingMessages();
  22155. auto* detail = ui.getDetailViewForSnapshot();
  22156. if (detail == nullptr)
  22157. {
  22158. juce::File (prefix + "-checks.txt").replaceWithText ("FAIL no detail view\n");
  22159. return;
  22160. }
  22161. detail->showSelection (1, 0);
  22162. detail->setPage (lynx::DetailView::Page::devices);
  22163. detail->selectCardForCheck (2); // the compressor (card 0 is the instrument)
  22164. write ("01-devices"); // the cards' title buttons: hot-swap, save, fold
  22165. saveMenus (juce::StringArray { "Device (effect card)" }, std::vector<juce::PopupMenu> { detail->cardMenuForSnapshot (2) }, prefix + "-02-device-menu.png");
  22166. // hot-swap on for the compressor: the Browser's bar, the Plugin database's effects, the card's button lit
  22167. const auto compressor = lynx::hotswap::targetOfEffect (offline.getSong(), 2, 1);
  22168. browser.beginHotSwap (compressor);
  22169. write ("03-hotswap-effect");
  22170. check ("hot-swap links the compressor", browser.isHotSwapping() && browser.hotSwapTarget() == compressor);
  22171. // a swap through the Browser itself (the row of LYNX's Reverb, then Enter): the slot keeps its place, its off
  22172. // state and its Mix; the link moves to the new device
  22173. {
  22174. browser.showPluginDatabase ("LYNX SHARE", 0); // (the folder of LYNX's own effects, opened as a click would)
  22175. browser.selectRowForSnapshot (lynx::tr (lynx::effectInfo (lynx::EffectKind::reverb).name));
  22176. write ("03a-hotswap-row"); // the candidate's row selected
  22177. check ("swap: Enter on the Reverb row is taken by hot-swap", browser.hotSwapLoadSelected());
  22178. offline.dispatchPendingMessages();
  22179. const auto& slot = offline.getSong().mixer[2].effects[1];
  22180. // (round 190cy: the device comes in with its own on / off state, on, as in Live 12.4.16; the Mix stays)
  22181. 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);
  22182. check ("swap: three effects as before", offline.getSong().mixer[2].effects.size() == 3);
  22183. check ("swap: the Browser is linked to the new device", browser.isHotSwapping() && browser.hotSwapTarget() == lynx::hotswap::targetOfEffect (offline.getSong(), 2, 1)
  22184. && ! (browser.hotSwapTarget() == compressor));
  22185. write ("03b-hotswap-swapped");
  22186. offline.undo();
  22187. offline.dispatchPendingMessages();
  22188. const auto& back = offline.getSong().mixer[2].effects[1];
  22189. check ("undo: the compressor is back with its instance", back.kind == lynx::EffectKind::compressor && back.instance.id == compressor.instance);
  22190. check ("undo: the Browser is still linked to it", browser.isHotSwapping() && browser.hotSwapTarget() == compressor);
  22191. }
  22192. // round 190cy (Live 12.4.16 live check 190cw shot 02a): hot-swap starts on the device's current preset. The
  22193. // compressor got its settings from a saved preset of LYNX's ("Glue bus", in this run's own settings folder)
  22194. {
  22195. browser.endHotSwap();
  22196. const auto folder = lynx::pluginheader::userFolder (lynx::EffectKind::compressor);
  22197. folder.createDirectory();
  22198. const auto& fx = offline.getSong().mixer[2].effects[1];
  22199. for (const auto* name : { "Glue bus", "Gentle", "Parallel smash" })
  22200. folder.getChildFile (juce::String (name) + ".lynxpreset").replaceWithText (lynx::presets::toText (lynx::EffectKind::compressor, name, fx.params));
  22201. offline.editSong ([] (lynx::Song& s) { s.mixer[2].effects[1].presetName = "Glue bus"; }, false);
  22202. offline.dispatchPendingMessages();
  22203. browser.beginHotSwap (compressor);
  22204. write ("03c-hotswap-current-preset");
  22205. check ("hot-swap starts on the current preset", browser.getSelectedFile() == folder.getChildFile ("Glue bus.lynxpreset"));
  22206. // a preset of the same effect swapped in comes in on (the compressor was off)
  22207. browser.selectRowForSnapshot ("Gentle.lynxpreset");
  22208. check ("swap: the preset row is taken by hot-swap", browser.hotSwapLoadSelected());
  22209. offline.dispatchPendingMessages();
  22210. const auto& now = offline.getSong().mixer[2].effects[1];
  22211. check ("swap: the preset's settings, the device on", now.kind == lynx::EffectKind::compressor && now.presetName == "Gentle" && now.enabled);
  22212. write ("03d-hotswap-preset-swapped");
  22213. offline.undo();
  22214. offline.dispatchPendingMessages();
  22215. check ("undo: the compressor off again", ! offline.getSong().mixer[2].effects[1].enabled);
  22216. browser.endHotSwap();
  22217. check ("hot-swap ended: the preset list goes", ! browser.isHotSwapping());
  22218. browser.beginHotSwap (compressor);
  22219. }
  22220. // linked to the instrument instead
  22221. const auto bass = lynx::hotswap::targetOfChannel (offline.getSong(), 0);
  22222. browser.beginHotSwap (bass);
  22223. detail->selectCardForCheck (0);
  22224. write ("04-hotswap-instrument");
  22225. check ("re-link to the instrument", browser.hotSwapTarget() == bass);
  22226. browser.endHotSwap();
  22227. check ("hot-swap ended", ! browser.isHotSwapping());
  22228. write ("05-hotswap-ended"); // the Browser as it was before
  22229. // the device is deleted while linked: the mode ends by itself
  22230. browser.beginHotSwap (lynx::hotswap::targetOfEffect (offline.getSong(), 2, 2));
  22231. offline.editSong ([] (lynx::Song& s) { s.mixer[2].effects.pop_back(); });
  22232. offline.dispatchPendingMessages();
  22233. check ("deleting the linked device ends hot-swap", ! browser.isHotSwapping());
  22234. offline.undo();
  22235. offline.dispatchPendingMessages();
  22236. // Duplicate (Ctrl+D) of the EQ
  22237. check ("duplicate", detail->duplicateCardForCheck (1));
  22238. offline.dispatchPendingMessages();
  22239. check ("duplicate: four effects, EQ twice", offline.getSong().mixer[2].effects.size() == 4 && offline.getSong().mixer[2].effects[1].kind == lynx::EffectKind::eq
  22240. && offline.getSong().mixer[2].effects[0].instance.id != offline.getSong().mixer[2].effects[1].instance.id);
  22241. write ("06-duplicated");
  22242. // --- collections ---
  22243. browser.showFilterForSnapshot (lib, lynx::browserview::ContentFilter::all);
  22244. ui.waitForBrowserForSnapshot();
  22245. browser.setInCollection (item ("Drums/Kicks/Kick Hard.wav"), 0, true);
  22246. browser.setInCollection (item ("Drums/Snare Tight.wav"), 0, true);
  22247. browser.setInCollection (item ("Loops"), 0, true);
  22248. browser.setTab (lynx::BrowserComponent::starredTab);
  22249. write ("07-starred-only"); // only Starred shown: the tab as it always was
  22250. browser.setInCollection (item ("Drums/Kicks/Kick Hard.wav"), 4, true); // also Blue
  22251. browser.setInCollection (item ("Loops/Break 120.wav"), 4, true);
  22252. browser.setInCollection (item ("Textures/Vinyl Noise.wav"), 3, true);
  22253. browser.setInCollection (item ("Textures/Rain.wav"), 3, true);
  22254. browser.setInCollection (item ("Drums/Hat Closed.wav"), 1, true);
  22255. store.rename (3, "Textures");
  22256. browser.setCollectionShown (1, true);
  22257. browser.setCollectionShown (3, true);
  22258. browser.setCollectionShown (4, true);
  22259. write ("08-collections"); // a heading per collection shown
  22260. check ("collections: four shown", store.shown().size() == 4);
  22261. check ("collections: an item in two", store.mask (item ("Drums/Kicks/Kick Hard.wav")) == 0b10001);
  22262. // round 190cy: the Clip-launch workflow's row menu lists the collections flat, as Live's item menu (shot 05);
  22263. // the Pattern workflow keeps the "Collections" sub-menu
  22264. browser.setLiveItemMenus (false);
  22265. saveMenus (juce::StringArray { "Collections (Pattern workflow: a row's sub-menu)" }, std::vector<juce::PopupMenu> { browser.collectionsMenuForSnapshot (item ("Drums/Kicks/Kick Hard.wav")) },
  22266. prefix + "-09-collections-menu.png");
  22267. browser.setLiveItemMenus (true);
  22268. saveMenus (juce::StringArray { "Collections (Clip-launch workflow: a row's menu)" }, std::vector<juce::PopupMenu> { browser.collectionsMenuForSnapshot (item ("Drums/Kicks/Kick Hard.wav")) },
  22269. prefix + "-09b-collections-flat.png");
  22270. // the key of a hidden collection (6, Purple) labels the row and the collection appears
  22271. check ("hidden collection: not shown before", ! store.isShown (5));
  22272. browser.setInCollection (item ("Textures/Rain.wav"), 5, true);
  22273. check ("hidden collection: its key shows it", store.isShown (5) && store.has (item ("Textures/Rain.wav"), 5));
  22274. write ("08b-hidden-collection-shown");
  22275. saveMenus (juce::StringArray { "Browser options" }, std::vector<juce::PopupMenu> { browser.buildViewMenu() }, prefix + "-10-browser-options.png");
  22276. browser.setTab (lynx::BrowserComponent::allTab);
  22277. write ("11-all-tab-chips"); // the colour chips on the rows of the ALL tab
  22278. browser.setSearchForSnapshot ("textures");
  22279. ui.waitForBrowserForSnapshot();
  22280. write ("12-search-collection-name"); // found by the collection's name
  22281. browser.setSearchForSnapshot ({});
  22282. // the file round trip
  22283. {
  22284. const auto text = store.toText();
  22285. check ("collections: text round trip", lynx::collections::Store::fromText (text) == store);
  22286. }
  22287. store = {};
  22288. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  22289. lib.deleteRecursively();
  22290. }
  22291. void runLinkShot190gl (const juce::String& prefix)
  22292. {
  22293. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  22294. lynx::AudioEngine offline (false);
  22295. lynx::MainComponent ui (offline, false);
  22296. ui.setSize (1600, 900);
  22297. ui.setVisible (true);
  22298. juce::String checks;
  22299. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  22300. const auto writeImage = [&prefix] (const juce::Image& image, const char* name) {
  22301. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  22302. file.deleteFile();
  22303. juce::FileOutputStream out (file);
  22304. juce::PNGImageFormat().writeImageToStream (image, out);
  22305. };
  22306. const auto toolbarShot = [&] (const char* name) {
  22307. ui.tickLinkForSnapshot();
  22308. writeImage (lynx::shot::snapshot (ui, ui.getToolbarBoundsForSnapshot()), name);
  22309. };
  22310. auto& link = offline.getLink();
  22311. auto& transport = offline.getTransport();
  22312. link.deviceStarted (44100.0);
  22313. // the audio callbacks the offline engine has none of: Link's per-block step, in real time
  22314. const auto pump = [&] (double seconds, std::function<bool()> until = {}) {
  22315. const auto end = juce::Time::getMillisecondCounterHiRes() + seconds * 1000.0;
  22316. while (juce::Time::getMillisecondCounterHiRes() < end)
  22317. {
  22318. const auto start = link.beginBlock (transport, 256, 0.0);
  22319. if (start >= 0)
  22320. transport.playing.store (true);
  22321. if (transport.playing.load())
  22322. transport.positionTicks.store (transport.positionTicks.load() + 256 * transport.ticksPerSample());
  22323. juce::Thread::sleep (6);
  22324. if (until && until())
  22325. return true;
  22326. }
  22327. return ! until || until();
  22328. };
  22329. auto peer = lynx::AbletonLink::makeTestPeer (97.0); // the other app in the session (it was there first)
  22330. juce::Thread::sleep (1500); // (a session that started at the same moment as LYNX's could take either tempo)
  22331. using lynx::toolbarlayout::Group;
  22332. // FL's Pattern layout: no Link toggle on a new install
  22333. check ("Pattern layout: the Link toggle is hidden by default", ! ui.getToolbarLayoutForSnapshot().isShown (Group::link));
  22334. toolbarShot ("toolbar-fl-default");
  22335. // shown by hand (Settings › Ableton Link › Show Link Toggle): "Link", off
  22336. auto layout = ui.getToolbarLayoutForSnapshot();
  22337. layout.setShown (Group::link, true);
  22338. ui.setToolbarLayoutForSnapshot (layout);
  22339. toolbarShot ("toolbar-fl-link-off");
  22340. check ("off: the toggle says Link", ui.getLinkToggleForSnapshot().text() == lynx::trc ("@Ableton Link: Link"));
  22341. // on: the session the other peer runs (its tempo, 97 BPM, wins over the project's)
  22342. link.setEnabled (true, offline.getSong().bpm);
  22343. // (a new peer is counted at once; its session's tempo is taken after Link measured it, a moment later)
  22344. const auto joined = pump (8.0, [&] { return link.peers() > 0 && link.startProgress() >= 0.0 && std::abs (link.sessionTempo() - 97.0) < 1e-3; });
  22345. check ("Link on: one peer found", joined && link.peers() == 1);
  22346. check ("Link on: the session's tempo (97 BPM, the first peer's) is the one shown", std::abs (offline.shownTempo() - 97.0) < 1e-3);
  22347. toolbarShot ("toolbar-fl-link-on");
  22348. check ("on with one peer: the toggle says 1 Link", ui.getLinkToggleForSnapshot().text() == lynx::trc ("@Ableton Link: {0} Link").replace ("{0}", "1"));
  22349. check ("stopped with a peer: the position display shows the session's progress", link.startProgress() >= 0.0);
  22350. // the Clip-launch layout: the toggle is shown by default (the reference DAW's "Show Link Toggle": Show)
  22351. ui.setToolbarLayoutForSnapshot (lynx::toolbarlayout::Layout::makeDefault());
  22352. ui.setClipLaunchWorkflow (true);
  22353. check ("Clip-launch layout: the Link toggle is shown by default", ui.getToolbarLayoutForSnapshot().isShown (Group::link));
  22354. pump (0.4);
  22355. toolbarShot ("toolbar-cliplaunch-1link");
  22356. writeImage (lynx::shot::snapshot (ui), "window-cliplaunch");
  22357. // Play: it waits for the session's phase (the play button lit, the progress bar running), then starts
  22358. transport.playing.store (true);
  22359. pump (0.05);
  22360. const auto waited = offline.isLinkWaiting();
  22361. check ("Play with a peer waits for the session's phase", waited);
  22362. toolbarShot ("toolbar-cliplaunch-waiting");
  22363. const auto started = pump (4.0, [&] { return transport.playing.load() && ! offline.isLinkWaiting(); });
  22364. check ("then playback starts on the session's phase", started);
  22365. pump (0.5);
  22366. toolbarShot ("toolbar-cliplaunch-playing");
  22367. check ("playing: no progress bar", link.startProgress() < 0.0);
  22368. // the toggle's drop-down and the Options menu
  22369. saveMenus (juce::StringArray { lynx::trc ("@Ableton Link: Link") }, std::vector<juce::PopupMenu> { ui.getLinkToggleForSnapshot().makeMenu() },
  22370. prefix + "-menu-link.png");
  22371. {
  22372. const auto names = ui.getMenuNamesForSnapshot();
  22373. for (int m = 0; m < names.size(); ++m)
  22374. if (names[m] == lynx::tr ("Options"))
  22375. saveMenus (juce::StringArray { names[m] }, std::vector<juce::PopupMenu> { ui.getMenuForSnapshot (m) }, prefix + "-menu-options.png");
  22376. }
  22377. // Settings › Ableton Link
  22378. {
  22379. lynx::SettingsHooks hooks;
  22380. hooks.linkToggleShown = [] { return true; };
  22381. auto panel = lynx::makeSettingsPanel (offline, lynx::SettingsPage::link, false, hooks);
  22382. panel->setSize (680, 620);
  22383. writeImage (lynx::shot::snapshot (*panel), "settings-link");
  22384. }
  22385. // off: the project's own tempo comes back on the display
  22386. transport.playing.store (false);
  22387. pump (0.1);
  22388. link.setEnabled (false, offline.getSong().bpm);
  22389. pump (0.1);
  22390. toolbarShot ("toolbar-cliplaunch-link-off");
  22391. check ("off: the tempo display shows the project's tempo again", std::abs (offline.shownTempo() - offline.getSong().bpm) < 1e-9);
  22392. const auto stats = link.stats();
  22393. checks << "audio-thread cost of the Link step: mean " << juce::String (stats.meanUs, 2) << " us, max " << juce::String (stats.maxUs, 1)
  22394. << " us over " << (juce::int64) stats.blocks << " blocks\n";
  22395. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  22396. }
  22397. void runMapShot190ef (const juce::String& prefix)
  22398. {
  22399. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  22400. lynx::AudioEngine offline (false);
  22401. lynx::MainComponent ui (offline, false);
  22402. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  22403. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  22404. const auto write = [&prefix] (juce::Component& c, const char* name) {
  22405. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  22406. file.deleteFile();
  22407. juce::FileOutputStream out (file);
  22408. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (c), out);
  22409. };
  22410. juce::String checks;
  22411. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  22412. using namespace lynx::remotemap;
  22413. ui.setVisible (true);
  22414. // the Pattern layout first: Ctrl+M stays FL's metronome there and no map mode starts
  22415. {
  22416. const auto before = offline.getTransport().metronome.load();
  22417. ui.keyPressed (juce::KeyPress ('M', juce::ModifierKeys::ctrlModifier, 0));
  22418. check ("Pattern layout: Ctrl+M is the metronome, no map mode", ui.getMapMode() == Mode::off && offline.getTransport().metronome.load() != before);
  22419. ui.keyPressed (juce::KeyPress ('M', juce::ModifierKeys::ctrlModifier, 0));
  22420. ui.setMapMode (Mode::midi);
  22421. check ("Pattern layout: setMapMode stays off", ui.getMapMode() == Mode::off);
  22422. }
  22423. ui.setClipLaunchWorkflow (true);
  22424. offline.editSong ([] (lynx::Song& s) {
  22425. if (s.mixer.size() < 6)
  22426. s.mixer.resize (6);
  22427. const char* inserts[] { "Master", "Drums", "Bass", "Keys", "Vox", "Reverb" };
  22428. for (int i = 1; i < 6; ++i)
  22429. s.mixer[(std::size_t) i].name = inserts[i];
  22430. const int channels = (int) s.channels.size();
  22431. s.channels.resize ((std::size_t) channels + 3);
  22432. const char* names[] { "Drum kit", "Bass synth", "Keys" };
  22433. for (int k = 0; k < 3; ++k)
  22434. {
  22435. auto& ch = s.channels[(std::size_t) (channels + k)];
  22436. ch.name = names[k];
  22437. ch.instrument = k == 0 ? lynx::InstrumentKind::sampler : lynx::InstrumentKind::synth;
  22438. ch.mixerTrack = k + 1;
  22439. }
  22440. s.mixer[2].effects.clear();
  22441. for (auto kind : { lynx::EffectKind::eq, lynx::EffectKind::compressor })
  22442. {
  22443. lynx::EffectSlot fx;
  22444. fx.kind = kind;
  22445. const auto& info = lynx::effectInfo (kind);
  22446. for (std::size_t k = 0; k < info.params.size() && k < fx.params.size(); ++k)
  22447. fx.params[k] = info.params[k].defaultValue;
  22448. s.mixer[2].effects.push_back (fx);
  22449. }
  22450. while (s.patterns.size() < 3)
  22451. s.patterns.emplace_back();
  22452. const char* patterns[] { "Beat", "Bassline", "Chords" };
  22453. for (int p = 0; p < 3; ++p)
  22454. {
  22455. auto& pattern = s.patterns[(std::size_t) p];
  22456. pattern.name = patterns[p];
  22457. lynx::Note n;
  22458. n.channel = channels + p;
  22459. n.key = 48 + p * 5;
  22460. pattern.notes = { n };
  22461. pattern.lengthTicks = 4 * lynx::ppq;
  22462. }
  22463. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 8));
  22464. const char* tracks[] { "Drums", "Bass", "Keys", "Vox" };
  22465. for (int t = 0; t < 4; ++t)
  22466. s.playlistTracks[(std::size_t) t].name = tracks[t];
  22467. for (int t = 0; t < 3; ++t)
  22468. for (int r = 0; r < 3; ++r)
  22469. {
  22470. lynx::Clip clip;
  22471. clip.pattern = t;
  22472. clip.length = 4 * lynx::ppq;
  22473. lynx::launcher::setClip (s, t, r, clip);
  22474. }
  22475. auto& grid = lynx::launcher::ensureGrid (s);
  22476. const char* scenes[] { "Intro", "Verse", "Drop" };
  22477. grid.scenes.resize (4);
  22478. for (int r = 0; r < 3; ++r)
  22479. grid.scenes[(std::size_t) r].name = scenes[r];
  22480. // some mappings, as the lesson's pictures show them (pads on slots and scenes, knobs on volume and pan)
  22481. assignMidi (s, Target::slot (0, 0), { 0, lynx::linkNoteBase + 36, -1 });
  22482. assignMidi (s, Target::slot (1, 0), { 0, lynx::linkNoteBase + 37, -1 });
  22483. assignMidi (s, Target::sceneLaunch (1), { 0, lynx::linkNoteBase + 44, -1 });
  22484. assignMidi (s, Target::parameter ({ lynx::AutomationTargetKind::mixerVolume, 1, 0, 0 }), { 0, 17, -1 });
  22485. assignMidi (s, Target::parameter ({ lynx::AutomationTargetKind::mixerPan, 1, 0, 0 }), { 0, 16, -1 });
  22486. assignMidi (s, Target::of (lynx::RemoteAction::play), { 0, 118, -1 });
  22487. setRange (s, rows (s, Mode::midi)[0], 0.0f, 0.85f);
  22488. assignKey (s, Target::slot (0, 1), 'A');
  22489. assignKey (s, Target::slot (1, 1), 'S');
  22490. assignKey (s, Target::sceneLaunch (2), '3');
  22491. assignKey (s, Target::parameter ({ lynx::AutomationTargetKind::mixerVolume, 2, 0, 0 }), 'V');
  22492. }, false);
  22493. offline.dispatchPendingMessages();
  22494. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::playlist, lynx::workspace::Panel::browser }); // (no floating Channel Rack over the grid)
  22495. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  22496. offline.dispatchPendingMessages();
  22497. ui.resized();
  22498. if (auto* detail = ui.getDetailViewForSnapshot())
  22499. {
  22500. detail->showSelection (1, 0);
  22501. detail->setPage (lynx::DetailView::Page::devices);
  22502. }
  22503. ui.resized();
  22504. offline.dispatchPendingMessages();
  22505. write (ui, "00-clip-launch-before");
  22506. // Ctrl+M in the Clip-launch layout: MIDI Map Mode (the metronome stays as it was)
  22507. const auto metronome = offline.getTransport().metronome.load();
  22508. ui.keyPressed (juce::KeyPress ('M', juce::ModifierKeys::ctrlModifier, 0));
  22509. check ("Clip-launch layout: Ctrl+M starts MIDI Map Mode", ui.getMapMode() == Mode::midi && offline.getTransport().metronome.load() == metronome);
  22510. auto* overlay = ui.mapOverlayForSnapshot();
  22511. auto* list = ui.mappingBrowserForSnapshot();
  22512. if (overlay == nullptr || list == nullptr)
  22513. {
  22514. juce::File (prefix + "-checks.txt").replaceWithText (checks + "FAIL no overlay\n");
  22515. return;
  22516. }
  22517. overlay->refresh();
  22518. const auto& spots = overlay->spots();
  22519. 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; }); };
  22520. const auto params = [&] (lynx::AutomationTargetKind k) {
  22521. 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; });
  22522. };
  22523. check ("overlay: clip slots (" + juce::String (count (lynx::RemoteAction::clipSlot)) + ")", count (lynx::RemoteAction::clipSlot) >= 12);
  22524. check ("overlay: scene launch buttons (" + juce::String (count (lynx::RemoteAction::sceneLaunch)) + ")", count (lynx::RemoteAction::sceneLaunch) >= 4);
  22525. check ("overlay: track stop buttons", count (lynx::RemoteAction::trackStop) >= 4);
  22526. check ("overlay: Stop all clips, Session Record", count (lynx::RemoteAction::stopAllClips) == 1 && count (lynx::RemoteAction::sessionRecord) == 1);
  22527. check ("overlay: transport play / stop / record / metronome", count (lynx::RemoteAction::play) == 1 && count (lynx::RemoteAction::stop) == 1
  22528. && count (lynx::RemoteAction::record) == 1 && count (lynx::RemoteAction::metronome) == 1);
  22529. check ("overlay: tempo", params (lynx::AutomationTargetKind::tempo) == 1);
  22530. check ("overlay: mixer volume / pan (" + juce::String (params (lynx::AutomationTargetKind::mixerVolume)) + " / " + juce::String (params (lynx::AutomationTargetKind::mixerPan)) + ")",
  22531. params (lynx::AutomationTargetKind::mixerVolume) >= 3 && params (lynx::AutomationTargetKind::mixerPan) >= 3);
  22532. check ("overlay: device knobs (" + juce::String (params (lynx::AutomationTargetKind::effectParam)) + ")", params (lynx::AutomationTargetKind::effectParam) >= 2);
  22533. // a click on Keys' first slot selects it; a MIDI control assigns it (as the engine's catch would)
  22534. for (const auto& spot : spots)
  22535. if (spot.target == Target::slot (2, 0))
  22536. {
  22537. auto source = juce::Desktop::getInstance().getMainMouseSource();
  22538. const auto now = juce::Time::getCurrentTime();
  22539. const auto at = spot.area.getCentre().toFloat();
  22540. overlay->mouseDown (juce::MouseEvent (source, at, juce::ModifierKeys (juce::ModifierKeys::leftButtonModifier), 1.0f, 0.0f, 0.0f, 0.0f, 0.0f,
  22541. overlay, overlay, now, at, now, 1, false));
  22542. break;
  22543. }
  22544. if (spots.empty())
  22545. {
  22546. juce::File (prefix + "-checks.txt").replaceWithText (checks + "FAIL no spots\n");
  22547. return;
  22548. }
  22549. check ("a click selects the slot", overlay->selection() == std::optional<Target> (Target::slot (2, 0)));
  22550. check ("the overlay takes clicks only on elements", overlay->hitTest (spots.front().area.getCentreX(), spots.front().area.getCentreY()) && ! overlay->hitTest (2, ui.getHeight() - 2));
  22551. check ("a pad assigns it", overlay->assignMidi ({ 0, lynx::linkNoteBase + 38, -1 }) && midiOf (offline.getSong(), Target::slot (2, 0)).number == lynx::linkNoteBase + 38);
  22552. check ("the same pad again on track 0 is refused", ! (overlay->select (Target::slot (0, 2)), overlay->assignMidi ({ 0, lynx::linkNoteBase + 36, -1 })));
  22553. overlay->select (Target::slot (2, 0));
  22554. list->setMode (Mode::midi);
  22555. list->selectRow (0);
  22556. ui.resized();
  22557. overlay->refresh();
  22558. write (ui, "01-midi-map-mode");
  22559. check ("Mapping Browser rows (MIDI): " + juce::String ((int) list->rowsShown().size()), list->rowsShown().size() == 7);
  22560. write (*list, "02-mapping-browser-midi");
  22561. saveMenus (juce::StringArray { "Row" }, std::vector<juce::PopupMenu> { list->rowMenu (0) }, prefix + "-03-row-menu.png");
  22562. // Ctrl+K: Key Map Mode; a key assigns the selected element
  22563. ui.keyPressed (juce::KeyPress ('K', juce::ModifierKeys::ctrlModifier, 0));
  22564. check ("Ctrl+K switches to Key Map Mode", ui.getMapMode() == Mode::key && offline.getMapMode() == Mode::key);
  22565. overlay->select (Target::sceneLaunch (0));
  22566. ui.keyPressed (juce::KeyPress ('1', {}, '1'));
  22567. check ("a key assigns the selected scene", keyOf (offline.getSong(), Target::sceneLaunch (0)).key == '1');
  22568. overlay->select (Target::sceneLaunch (1));
  22569. ui.keyPressed (juce::KeyPress ('A', {}, 'a'));
  22570. check ("a key already on a slot is refused for a scene", ! keyOf (offline.getSong(), Target::sceneLaunch (1)).found);
  22571. overlay->refresh();
  22572. write (ui, "04-key-map-mode");
  22573. write (*list, "05-mapping-browser-key");
  22574. {
  22575. // round 190em: Min / Max in the parameter's unit, Path "<track> | Mixer", Name "Track Volume" / "Slot n"
  22576. const lynx::remotemap::Target volume = Target::parameter ({ lynx::AutomationTargetKind::mixerVolume, 2, 0, 0 });
  22577. const auto [path, name] = lynx::mapmode::describe (offline, volume);
  22578. check ("browser: volume row Path / Name = " + path + " / " + name, path == "Bass | Mixer" && name == "Track Volume");
  22579. check ("browser: volume Min / Max = " + lynx::mapmode::rangeText (offline, volume, 0.0f) + " / " + lynx::mapmode::rangeText (offline, volume, 1.0f),
  22580. lynx::mapmode::rangeText (offline, volume, 0.0f) == juce::String::fromUTF8 ("\xe2\x88\x92\xe2\x88\x9e dB")
  22581. && lynx::mapmode::rangeText (offline, volume, 1.0f).endsWith (" dB"));
  22582. const lynx::remotemap::Target pan = Target::parameter ({ lynx::AutomationTargetKind::mixerPan, 1, 0, 0 });
  22583. check ("browser: pan Min / Max = " + lynx::mapmode::rangeText (offline, pan, 0.25f) + " / " + lynx::mapmode::rangeText (offline, pan, 0.5f),
  22584. lynx::mapmode::rangeText (offline, pan, 0.25f) == "50L" && lynx::mapmode::rangeText (offline, pan, 0.5f) == "C"
  22585. && lynx::mapmode::rangeText (offline, pan, 1.0f) == "100R");
  22586. const auto typed = lynx::mapmode::rangeValueOf (offline, volume, "0 dB");
  22587. check ("browser: typing 0 dB", typed.has_value() && std::abs (lynx::mapmode::rangeText (offline, volume, *typed).getDoubleValue()) < 0.15);
  22588. check ("browser: typing 50L", lynx::mapmode::rangeValueOf (offline, pan, "50L") == std::optional<float> (0.25f));
  22589. check ("browser: Key column = " + lynx::mapmode::listKeyText ('V') + ", " + lynx::mapmode::listKeyText ('3'),
  22590. lynx::mapmode::listKeyText ('V') == "Key v" && lynx::mapmode::listKeyText ('3') == "Key 3");
  22591. check ("browser: slot row Name = " + lynx::mapmode::describe (offline, Target::slot (0, 2)).second,
  22592. lynx::mapmode::describe (offline, Target::slot (0, 2)) == std::pair<juce::String, juce::String> ("Drums", "Slot 3"));
  22593. }
  22594. // off again: the key mapping on a parameter toggles it between Min and Max
  22595. ui.keyPressed (juce::KeyPress ('K', juce::ModifierKeys::ctrlModifier, 0));
  22596. check ("Ctrl+K again ends it", ui.getMapMode() == Mode::off && ! overlay->isVisible() && ! list->isVisible());
  22597. const lynx::AutomationTarget keysVolume { lynx::AutomationTargetKind::mixerVolume, 2, 0, 0 };
  22598. // (round 190em, Live 12.4.16: the first press goes to Min, then Max, then Min)
  22599. ui.keyPressed (juce::KeyPress ('V', {}, 'v'));
  22600. check ("the mapped key V moves Bass's volume to Min first", std::abs (offline.currentTargetValue (keysVolume)) < 0.01f);
  22601. ui.keyStateChanged (false); // (V is not down any more: its release)
  22602. ui.keyPressed (juce::KeyPress ('V', {}, 'v'));
  22603. check ("again: to Max", std::abs (offline.currentTargetValue (keysVolume) - 1.0f) < 0.01f);
  22604. ui.keyStateChanged (false);
  22605. ui.keyPressed (juce::KeyPress ('V', {}, 'v'));
  22606. check ("again: to Min", std::abs (offline.currentTargetValue (keysVolume)) < 0.01f);
  22607. ui.keyStateChanged (false);
  22608. // the title bar switches
  22609. ui.setMapMode (Mode::midi);
  22610. write (ui, "06-switches-midi-on");
  22611. ui.setMapMode (Mode::off);
  22612. ui.setClipLaunchWorkflow (false);
  22613. check ("leaving the Clip-launch layout ends the map mode", ui.getMapMode() == Mode::off);
  22614. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  22615. }
  22616. void runSceneShot190ef (const juce::String& prefix)
  22617. {
  22618. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  22619. lynx::AudioEngine offline (false);
  22620. lynx::MainComponent ui (offline, false);
  22621. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  22622. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  22623. const auto write = [&prefix] (juce::Component& c, const char* name) {
  22624. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  22625. file.deleteFile();
  22626. juce::FileOutputStream out (file);
  22627. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (c), out);
  22628. };
  22629. juce::String checks;
  22630. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  22631. ui.setVisible (true);
  22632. lynx::DetailView::shownSetting = false;
  22633. ui.setClipLaunchWorkflow (true);
  22634. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::playlist });
  22635. offline.editSong ([] (lynx::Song& s) {
  22636. const int channels = (int) s.channels.size();
  22637. s.channels.resize ((std::size_t) channels + 3);
  22638. const char* names[] { "Drum kit", "Bass synth", "Keys" };
  22639. for (int k = 0; k < 3; ++k)
  22640. {
  22641. auto& ch = s.channels[(std::size_t) (channels + k)];
  22642. ch.name = names[k];
  22643. ch.instrument = k == 0 ? lynx::InstrumentKind::sampler : lynx::InstrumentKind::synth;
  22644. }
  22645. while (s.patterns.size() < 3)
  22646. s.patterns.emplace_back();
  22647. const char* patterns[] { "Beat", "Bassline", "Chords" };
  22648. for (int p = 0; p < 3; ++p)
  22649. {
  22650. auto& pattern = s.patterns[(std::size_t) p];
  22651. pattern.name = patterns[p];
  22652. lynx::Note n;
  22653. n.channel = channels + p;
  22654. n.key = 48 + p * 5;
  22655. pattern.notes = { n };
  22656. pattern.lengthTicks = 4 * lynx::ppq;
  22657. }
  22658. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 6));
  22659. const char* tracks[] { "Drums", "Bass", "Keys" };
  22660. const std::uint32_t colours[] { 0xFFE0533Bu, 0xFF3B8BE0u, 0xFF46C27Au };
  22661. for (int t = 0; t < 3; ++t)
  22662. {
  22663. s.playlistTracks[(std::size_t) t].name = tracks[t];
  22664. s.playlistTracks[(std::size_t) t].colour = colours[t];
  22665. }
  22666. for (int t = 0; t < 3; ++t)
  22667. for (int r = 0; r < 3; ++r)
  22668. if (! (t == 2 && r == 0))
  22669. {
  22670. lynx::Clip clip;
  22671. clip.pattern = t;
  22672. clip.length = 4 * lynx::ppq;
  22673. lynx::launcher::setClip (s, t, r, clip);
  22674. }
  22675. auto& grid = lynx::launcher::ensureGrid (s);
  22676. grid.scenes.resize (4);
  22677. const char* scenes[] { "Intro", "Verse", "Drop" };
  22678. for (int r = 0; r < 3; ++r)
  22679. grid.scenes[(std::size_t) r].name = scenes[r];
  22680. lynx::session::setSceneTempo (s, 1, 128.0);
  22681. lynx::session::setSceneSignature (s, 1, 3, 4); // (as the live check's "Verse": 3 / 4)
  22682. lynx::session::setSceneSignature (s, 2, 6, 8); // (round 190em: a denominator of its own)
  22683. grid.scenes[2].colour = 0xFF8E5BD6u;
  22684. }, false);
  22685. offline.dispatchPendingMessages();
  22686. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  22687. offline.dispatchPendingMessages();
  22688. ui.resized();
  22689. auto* gridView = ui.getClipGridForSnapshot();
  22690. if (gridView == nullptr)
  22691. {
  22692. juce::File (prefix + "-checks.txt").replaceWithText ("FAIL no grid\n");
  22693. return;
  22694. }
  22695. lynx::clipGridSceneTempoShown() = true;
  22696. lynx::refreshClipGrid (*gridView);
  22697. lynx::selectClipGridScene (*gridView, 1);
  22698. write (*gridView, "01-scene-fields");
  22699. {
  22700. // round 190em: a plain scene's launch triangle in Live's dark grey (#1E1E1E), scene 4 (row 3)
  22701. const auto image = lynx::shot::snapshot (*gridView);
  22702. int dark = 0;
  22703. for (int y = 0; y < image.getHeight(); ++y)
  22704. for (int x = image.getWidth() - 240; x < image.getWidth() - 180; ++x)
  22705. if (const auto p = image.getPixelAt (x, y); y > 3 * 24 + 26 && y < 4 * 24 + 26 && std::abs (p.getRed() - 0x1e) <= 2
  22706. && std::abs (p.getGreen() - 0x1e) <= 2 && std::abs (p.getBlue() - 0x1e) <= 2)
  22707. ++dark;
  22708. check ("plain scene triangle in Live's #1E1E1E (" + juce::String (dark) + " px)", dark >= 20);
  22709. }
  22710. saveMenus (juce::StringArray { "Scene menu (Verse)" }, std::vector<juce::PopupMenu> { lynx::clipGridSceneMenu (*gridView, 1) }, prefix + "-02-scene-menu.png");
  22711. saveMenus (juce::StringArray { "Scene tempo field", "Scene time signature field" },
  22712. std::vector<juce::PopupMenu> { lynx::clipGridSceneFieldMenu (*gridView, 1, 1), lynx::clipGridSceneFieldMenu (*gridView, 2, 2) },
  22713. prefix + "-03-field-menus.png");
  22714. saveMenus (juce::StringArray { "Column title (Bass)" }, std::vector<juce::PopupMenu> { lynx::clipGridHeaderMenu (*gridView, 1) }, prefix + "-04-title-menu.png");
  22715. const auto clipsIn = [&offline] (int row) {
  22716. int n = 0;
  22717. if (const auto& g = offline.getSong().clipGrid)
  22718. for (int t = 0; t < 8; ++t)
  22719. n += lynx::launcher::clipAt (*g, t, row) != nullptr ? 1 : 0;
  22720. return n;
  22721. };
  22722. const auto before = clipsIn (1);
  22723. const auto dup = lynx::duplicateClipGridScene (*gridView, 1);
  22724. offline.dispatchPendingMessages();
  22725. const auto& scenesNow = offline.getSong().clipGrid->scenes;
  22726. check ("duplicate: Verse's copy is row 2, with its clips and tempo", dup == 2 && clipsIn (2) == before && scenesNow.size() > 2
  22727. && scenesNow[2].name == "Verse" && scenesNow[2].tempo == 128.0);
  22728. write (*gridView, "05-scene-duplicated");
  22729. const auto cap = lynx::captureClipGridScene (*gridView, 3, { 0, 2, 1 }); // Drums row 0, Bass row 2, Keys row 1
  22730. offline.dispatchPendingMessages();
  22731. check ("capture: a new row 4 with the three playing clips", cap == 4 && clipsIn (4) == 3);
  22732. {
  22733. const auto& sc = offline.getSong().clipGrid->scenes;
  22734. check ("capture while playing: the new scene is plain (no name, fields off)", sc.size() > 4 && sc[4] == lynx::ClipGridScene {});
  22735. }
  22736. write (*gridView, "06-scene-captured");
  22737. // round 190em: nothing plays: an empty scene like the selected one (name, tempo, signature), selected
  22738. const auto empty = lynx::captureClipGridScene (*gridView, 1, { -1, -1 });
  22739. offline.dispatchPendingMessages();
  22740. {
  22741. const auto& sc = offline.getSong().clipGrid->scenes;
  22742. check ("capture with nothing playing: an empty row 2 named Verse, 128 BPM, 3 / 4", empty == 2 && clipsIn (2) == 0 && sc[2].name == "Verse"
  22743. && sc[2].tempo == 128.0 && sc[2].beatsPerBar == 3 && sc[2].beatUnit == 4);
  22744. }
  22745. write (*gridView, "06b-scene-captured-stopped");
  22746. // round 190em: Capture and Insert while clips play: playback moves to the new row (the runtime view shows what
  22747. // the player reports once the published song holds the moved slots)
  22748. {
  22749. const auto rowsBefore = offline.getSong().clipGrid->scenes.size();
  22750. lynx::selectClipGridScene (*gridView, 0);
  22751. const auto at = lynx::captureClipGridScene (*gridView, 0, { 0, 0, -1 });
  22752. offline.dispatchPendingMessages();
  22753. const auto& g = *offline.getSong().clipGrid;
  22754. check ("capture while playing: row 1 holds the moved playing slots", at == 1 && g.scenes.size() == rowsBefore + 1
  22755. && clipsIn (1) == 2 && clipsIn (0) == 2 && g.scenes[1] == lynx::ClipGridScene {});
  22756. if (auto* runtime = offline.launcherStateForSnapshot())
  22757. for (int t = 0; t < 2; ++t)
  22758. runtime->tracks[(std::size_t) t].playing.store (1);
  22759. lynx::refreshClipGrid (*gridView);
  22760. write (*gridView, "09-capture-playing-moves");
  22761. if (auto* runtime = offline.launcherStateForSnapshot())
  22762. for (int t = 0; t < 2; ++t)
  22763. runtime->tracks[(std::size_t) t].playing.store (-1);
  22764. }
  22765. // round 190em: the fields as "n / d", a selected field, Del = Return to Default
  22766. lynx::clipGridSceneTempoShown() = true;
  22767. lynx::refreshClipGrid (*gridView);
  22768. {
  22769. const auto& sc = offline.getSong().clipGrid->scenes;
  22770. int verse = -1;
  22771. for (int r = 0; r < (int) sc.size() && verse < 0; ++r)
  22772. if (sc[(std::size_t) r].name == "Verse" && sc[(std::size_t) r].tempo > 0.0)
  22773. verse = r;
  22774. lynx::selectClipGridSceneField (*gridView, verse, 1);
  22775. write (*gridView, "10-field-selected");
  22776. gridView->keyPressed (juce::KeyPress (juce::KeyPress::deleteKey));
  22777. offline.dispatchPendingMessages();
  22778. const auto& after = offline.getSong().clipGrid->scenes;
  22779. check ("Del on a selected tempo field returns it to default (scene kept)", verse >= 0 && after.size() == sc.size()
  22780. && after[(std::size_t) verse].tempo == 0.0 && after[(std::size_t) verse].beatsPerBar == 3);
  22781. write (*gridView, "11-field-returned-to-default");
  22782. }
  22783. // round 190em: Capture MIDI to the armed track (Bass), the selected scene's slot, the tempo from the phrase
  22784. {
  22785. offline.stop();
  22786. offline.setGridTrackArmed (1, true, true);
  22787. lynx::selectClipGridScene (*gridView, 0);
  22788. int empty = 0;
  22789. while (lynx::launcher::clipAt (*offline.getSong().clipGrid, 1, empty) != nullptr)
  22790. ++empty;
  22791. const auto now = juce::Time::getMillisecondCounterHiRes();
  22792. const auto beat = 60000.0 / 148.0;
  22793. for (int i = 0; i < 8; ++i)
  22794. {
  22795. const auto at = now - 9.0 * beat + i * beat;
  22796. offline.logPlayedNoteForTest (at, 0, 60 + (i % 4) * 2, 0.8f, true);
  22797. offline.logPlayedNoteForTest (at + beat * 0.5, 0, 60 + (i % 4) * 2, 0.8f, false);
  22798. }
  22799. int placed = -1;
  22800. bool into = true;
  22801. const auto r = offline.captureMidiToSlot (1, empty, placed, into);
  22802. offline.dispatchPendingMessages();
  22803. check ("Capture MIDI: 8 notes into Bass row " + juce::String (placed) + ", tempo " + juce::String (offline.getSong().bpm, 2),
  22804. r.notes == 8 && placed == empty && ! into && std::abs (offline.getSong().bpm - 148.0) < 0.5 && offline.getTransport().playing.load());
  22805. const auto& capturedGrid = *offline.getSong().clipGrid;
  22806. const auto* capturedClip = lynx::launcher::clipAt (capturedGrid, 1, placed);
  22807. const auto* slot = capturedClip != nullptr ? &capturedGrid.slots[(std::size_t) capturedClip->gridSlot] : nullptr;
  22808. check ("Capture MIDI: the clip has no name of its own (blank label, as Live)", slot != nullptr && slot->name.empty() && slot->blankName);
  22809. if (auto* runtime = offline.launcherStateForSnapshot())
  22810. runtime->tracks[1].playing.store (placed);
  22811. lynx::refreshClipGrid (*gridView);
  22812. write (*gridView, "12-capture-midi");
  22813. if (auto* runtime = offline.launcherStateForSnapshot())
  22814. runtime->tracks[1].playing.store (-1);
  22815. offline.stop();
  22816. }
  22817. write (ui, "07-window");
  22818. lynx::clipGridSceneTempoShown() = false;
  22819. lynx::refreshClipGrid (*gridView);
  22820. write (*gridView, "08-fields-off");
  22821. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  22822. }
  22823. void runDrawShot190ef (const juce::String& prefix)
  22824. {
  22825. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  22826. lynx::AudioEngine offline (false);
  22827. lynx::MainComponent ui (offline, false);
  22828. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  22829. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  22830. const auto write = [&prefix] (juce::Component& c, const char* name) {
  22831. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  22832. file.deleteFile();
  22833. juce::FileOutputStream out (file);
  22834. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (c), out);
  22835. };
  22836. juce::String checks;
  22837. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  22838. ui.setVisible (true);
  22839. ui.setClipLaunchWorkflow (true);
  22840. ui.setClipGridView (lynx::PlaylistArea::GridView::song);
  22841. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::playlist });
  22842. lynx::autolanes::setShown (true);
  22843. offline.editSong ([] (lynx::Song& s) {
  22844. if (s.mixer.size() < 4)
  22845. s.mixer.resize (4);
  22846. s.mixer[1].name = "Bass";
  22847. s.mixer[2].name = "Pad";
  22848. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 6));
  22849. s.playlistTracks[0].name = "Bass";
  22850. s.playlistTracks[0].mode = lynx::PlaylistTrackMode::audio;
  22851. s.playlistTracks[0].mixerTrack = 1;
  22852. s.playlistTracks[1].name = "Pad";
  22853. s.playlistTracks[1].mode = lynx::PlaylistTrackMode::audio;
  22854. s.playlistTracks[1].mixerTrack = 2;
  22855. }, false);
  22856. lynx::createAutomationLane (offline, { lynx::AutomationTargetKind::mixerVolume, 1, 0, 0 }, 0);
  22857. lynx::createAutomationLane (offline, { lynx::AutomationTargetKind::mixerPan, 2, 0, 0 }, 1);
  22858. offline.editSong ([] (lynx::Song& s) {
  22859. for (int t = 0; t < 2; ++t)
  22860. if (! s.playlistTracks[(std::size_t) t].lanes.empty())
  22861. s.playlistTracks[(std::size_t) t].lanes[0].height = 110;
  22862. }, false);
  22863. offline.dispatchPendingMessages();
  22864. auto& playlist = ui.getPlaylistForSnapshot();
  22865. playlist.setViewForSnapshot (180.0, 0, 0);
  22866. ui.resized();
  22867. offline.dispatchPendingMessages();
  22868. const auto& song = offline.getSong();
  22869. const auto laneA = song.playlistTracks[0].lanes.empty() ? -1 : song.playlistTracks[0].lanes[0].automation;
  22870. const auto laneB = song.playlistTracks[1].lanes.empty() ? -1 : song.playlistTracks[1].lanes[0].automation;
  22871. check ("two lanes made", laneA >= 0 && laneB >= 0);
  22872. if (laneA < 0 || laneB < 0)
  22873. {
  22874. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  22875. return;
  22876. }
  22877. write (ui, "00-lanes-before");
  22878. const auto before = song.automations[(std::size_t) laneA].points;
  22879. // a drag through the Playlist's own handlers (the events a real mouse sends)
  22880. auto source = juce::Desktop::getInstance().getMainMouseSource();
  22881. const auto now = juce::Time::getCurrentTime();
  22882. const auto stroke = [&] (int track, const std::vector<juce::Point<float>>& path, juce::ModifierKeys extra) {
  22883. const juce::ModifierKeys mods (juce::ModifierKeys::leftButtonModifier | extra.getRawFlags());
  22884. const auto event = [&] (juce::Point<float> p, juce::ModifierKeys m, bool dragged) {
  22885. return juce::MouseEvent (source, p, m, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, &playlist, &playlist, now, path.front(), now, 1, dragged);
  22886. };
  22887. juce::ignoreUnused (track);
  22888. // (the engine joins the edits of one press into one undo step while a button is down)
  22889. const auto held = juce::ModifierKeys::currentModifiers;
  22890. juce::ModifierKeys::currentModifiers = mods;
  22891. playlist.mouseDown (event (path.front(), mods, false));
  22892. for (std::size_t i = 1; i < path.size(); ++i)
  22893. playlist.mouseDrag (event (path[i], mods, true));
  22894. juce::ModifierKeys::currentModifiers = held;
  22895. playlist.mouseUp (event (path.back(), extra, true));
  22896. };
  22897. const auto bodyA = playlist.laneBodyForSnapshot (0, 0), bodyB = playlist.laneBodyForSnapshot (1, 0);
  22898. const auto bar = (double) (4 * lynx::ppq);
  22899. const auto x = [&] (double bars) { return (float) playlist.xOfTickForSnapshot (bars * bar); };
  22900. const auto y = [] (juce::Rectangle<float> body, float v) { return body.getBottom() - v * body.getHeight(); };
  22901. lynx::drawmode::set (true);
  22902. // steps: a rise over bar 1 and a fall over bar 2, at the Playlist's grid (Line, at this zoom)
  22903. std::vector<juce::Point<float>> steps;
  22904. for (int k = 0; k <= 16; ++k)
  22905. steps.push_back ({ x (1.0 + k / 16.0) + 2.0f, y (bodyA, 0.15f + 0.05f * (float) k) });
  22906. for (int k = 0; k <= 16; ++k)
  22907. steps.push_back ({ x (2.0 + k / 16.0) + 2.0f, y (bodyA, 0.95f - 0.05f * (float) k) });
  22908. stroke (0, steps, {});
  22909. const auto& afterSteps = offline.getSong().automations[(std::size_t) laneA].points;
  22910. check ("Draw Mode drag made steps (" + juce::String ((int) afterSteps.size()) + " points)", afterSteps.size() > before.size() + 4);
  22911. bool unchangedOutside = true;
  22912. for (double t = 0.0; t < 6.0 * bar; t += 37.0)
  22913. if ((t < bar - 1.0 || t > 3.1 * bar) && std::abs (lynx::automationCurveAt (before, t) - lynx::automationCurveAt (afterSteps, t)) > 1.0e-4f)
  22914. unchangedOutside = false;
  22915. check ("the curve outside the drawn bars is unchanged", unchangedOutside);
  22916. {
  22917. // flat inside each drawn cell: the values in a cell's first and last tick are the same
  22918. int flatCells = 0, cells = 0;
  22919. for (double t = bar; t < 3.0 * bar; t += lynx::ppq / 4.0)
  22920. {
  22921. ++cells;
  22922. if (std::abs (lynx::automationCurveAt (afterSteps, t + 1.0) - lynx::automationCurveAt (afterSteps, t + lynx::ppq / 4.0 - 1.0)) < 1.0e-5f)
  22923. ++flatCells;
  22924. }
  22925. check ("each sixteenth inside bars 2-3 is flat (" + juce::String (flatCells) + " / " + juce::String (cells) + ")", flatCells == cells);
  22926. }
  22927. // freehand: Alt (no grid) on the pad's pan lane, a wave over bars 1-4
  22928. const auto panBefore = offline.getSong().automations[(std::size_t) laneB].points;
  22929. // (off-screen every press has the same mouse-down time, which the undo history uses to join one press's edits:
  22930. // an edit with no button down in between separates the two strokes, as a real second press does)
  22931. offline.editSong ([] (lynx::Song&) {});
  22932. std::vector<juce::Point<float>> wave;
  22933. for (int k = 0; k <= 60; ++k)
  22934. wave.push_back ({ x (1.0 + 3.0 * k / 60.0), y (bodyB, 0.5f + 0.4f * std::sin ((float) k * 0.3f)) });
  22935. stroke (1, wave, juce::ModifierKeys (juce::ModifierKeys::altModifier));
  22936. const auto& pan = offline.getSong().automations[(std::size_t) laneB].points;
  22937. check ("Alt drag drew freehand (" + juce::String ((int) pan.size()) + " points)", pan.size() > 30);
  22938. playlist.repaint();
  22939. write (ui, "01-draw-mode-steps-and-freehand");
  22940. if (auto* parent = playlist.getParentComponent())
  22941. write (*parent, "01b-playlist");
  22942. // one stroke is one undo step
  22943. offline.undo();
  22944. check ("one undo takes the whole freehand stroke back", offline.getSong().automations[(std::size_t) laneB].points == panBefore);
  22945. // Draw Mode off: the same press adds one point, as before
  22946. lynx::drawmode::set (false);
  22947. const auto countOff = offline.getSong().automations[(std::size_t) laneA].points.size();
  22948. stroke (0, { { x (4.5), y (bodyA, 0.8f) } }, {});
  22949. check ("Draw Mode off: a press adds one point", offline.getSong().automations[(std::size_t) laneA].points.size() == countOff + 1);
  22950. // the Options menu (Clip-launch layout) with the switch
  22951. lynx::drawmode::set (true);
  22952. {
  22953. const auto names = ui.getMenuNamesForSnapshot();
  22954. const auto index = names.indexOf (TRANS ("Options"));
  22955. if (index >= 0)
  22956. saveMenus (juce::StringArray { "Options" }, std::vector<juce::PopupMenu> { ui.getMenuForSnapshot (index) }, prefix + "-02-options-menu.png");
  22957. check ("Options menu found", index >= 0);
  22958. }
  22959. lynx::drawmode::set (false);
  22960. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  22961. }
  22962. void runClipEnvShot190gi (const juce::String& prefix)
  22963. {
  22964. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  22965. lynx::AudioEngine offline (false);
  22966. lynx::MainComponent ui (offline, false);
  22967. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  22968. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  22969. const auto write = [&prefix] (juce::Component& c, const char* name) {
  22970. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  22971. file.deleteFile();
  22972. juce::FileOutputStream out (file);
  22973. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (c), out);
  22974. };
  22975. juce::String checks;
  22976. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  22977. // two files: a sustained pad (4 s, a slow swell, for the envelope over its waveform) and a one-bar loop of clicks
  22978. const auto writeWav = [] (const juce::File& file, int seconds, const std::function<float (int, double)>& fn) {
  22979. const double rate = 48000.0;
  22980. juce::AudioBuffer<float> buffer (2, (int) (rate * seconds));
  22981. for (int ch = 0; ch < 2; ++ch)
  22982. for (int i = 0; i < buffer.getNumSamples(); ++i)
  22983. buffer.setSample (ch, i, fn (i, rate));
  22984. file.deleteFile();
  22985. if (auto out = std::unique_ptr<juce::FileOutputStream> (file.createOutputStream()))
  22986. if (auto* writer = juce::WavAudioFormat().createWriterFor (out.get(), rate, 2, 16, {}, 0))
  22987. {
  22988. out.release();
  22989. std::unique_ptr<juce::AudioFormatWriter> owned (writer);
  22990. owned->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
  22991. }
  22992. return file;
  22993. };
  22994. const auto pad = writeWav (juce::File (prefix + "-pad.wav"), 4, [] (int i, double rate) {
  22995. const auto t = i / rate;
  22996. return (float) (0.45 * (std::sin (juce::MathConstants<double>::twoPi * 220.0 * t) + 0.5 * std::sin (juce::MathConstants<double>::twoPi * 331.0 * t))
  22997. * (0.7 + 0.3 * std::sin (juce::MathConstants<double>::twoPi * 1.5 * t)));
  22998. });
  22999. const auto loop = writeWav (juce::File (prefix + "-loop.wav"), 2, [] (int i, double) {
  23000. const auto k = i % 12000;
  23001. const auto hit = i / 12000;
  23002. return k < 3000 ? (float) (std::sin (k * (hit % 4 == 0 ? 0.05 : 0.3)) * std::exp (-k / 500.0) * 0.8) : 0.0f;
  23003. });
  23004. ui.setVisible (true);
  23005. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::playlist });
  23006. offline.editSong ([&] (lynx::Song& s) {
  23007. const auto add = [&s] (const char* name, const juce::File& file) {
  23008. lynx::ChannelDef ch;
  23009. ch.name = name;
  23010. ch.instrument = lynx::InstrumentKind::audioClip;
  23011. ch.samplePath = file.getFullPathName().toStdString();
  23012. s.channels.push_back (ch);
  23013. return (int) s.channels.size() - 1;
  23014. };
  23015. const auto padChannel = add ("Pad", pad), loopChannel = add ("Loop", loop);
  23016. s.playlist.clear();
  23017. lynx::Clip a;
  23018. a.kind = lynx::ClipKind::audio;
  23019. a.channel = padChannel;
  23020. a.length = 8 * lynx::ppq;
  23021. a.track = 0;
  23022. s.playlist.push_back (a);
  23023. a.track = 1;
  23024. s.playlist.push_back (a);
  23025. lynx::Clip b = a;
  23026. b.channel = loopChannel;
  23027. b.track = 2;
  23028. b.length = 4 * lynx::ppq;
  23029. s.playlist.push_back (b);
  23030. // the first clip: a volume envelope (a swell, a dip, FL's curve modes on two segments)
  23031. auto& e = lynx::clipenv::own (s, s.playlist[0]);
  23032. e.shown = lynx::clipenv::volumeLane;
  23033. e.volume = { { 0, 0.15f, 0.0f, 0 }, { lynx::ppq * 2, 1.0f, -0.6f, 0 }, { lynx::ppq * 4, 1.0f, 0.0f, 0 },
  23034. { lynx::ppq * 5, 0.45f, 0.0f, 2 }, { lynx::ppq * 6, 0.9f, 0.0f, 0 }, { lynx::ppq * 8, 0.9f, 0.0f, 0 } };
  23035. // the second: its pan lane shown (only pan made)
  23036. lynx::clipenv::show (s, s.playlist[1], lynx::clipenv::panLane);
  23037. auto& p = lynx::clipenv::own (s, s.playlist[1]);
  23038. p.pan = { { 0, 0.5f, 0.0f, 0 }, { lynx::ppq * 2, 0.1f, 0.0f, 0 }, { lynx::ppq * 4, 0.9f, 0.0f, 0 }, { lynx::ppq * 6, 0.5f, 0.0f, 0 } };
  23039. if (s.playlistTracks.size() < 3)
  23040. s.playlistTracks.resize (3);
  23041. for (int t = 0; t < 3; ++t)
  23042. s.playlistTracks[(std::size_t) t].height = 96;
  23043. }, false);
  23044. offline.dispatchPendingMessages();
  23045. auto& playlist = ui.getPlaylistForSnapshot();
  23046. playlist.setViewForSnapshot (360.0, 0, 0);
  23047. ui.resized();
  23048. offline.dispatchPendingMessages();
  23049. (void) lynx::shot::snapshot (ui); // (a paint starts the waveform analyses; the shot waits for them)
  23050. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (8000);
  23051. offline.dispatchPendingMessages();
  23052. write (ui, "01-playlist-envelopes");
  23053. // the clip menu: LYNX's extras with Clip envelope ›, Auto-warp, Quantize audio (Auto-warp run from it on the loop)
  23054. {
  23055. const auto menu = playlist.getClipMenuForSnapshot (2);
  23056. const juce::PopupMenu* envelopeMenu = nullptr;
  23057. bool autoWarp = false, quantize = false;
  23058. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  23059. {
  23060. if (it.getItem().text == lynx::tr ("Clip envelope") && it.getItem().subMenu != nullptr)
  23061. envelopeMenu = it.getItem().subMenu.get();
  23062. autoWarp = autoWarp || (it.getItem().text == lynx::tr ("Auto-warp") && it.getItem().isEnabled);
  23063. quantize = quantize || (it.getItem().text == lynx::tr ("Quantize audio") && it.getItem().isEnabled);
  23064. }
  23065. check ("clip menu: Clip envelope submenu, Auto-warp, Quantize audio", envelopeMenu != nullptr && autoWarp && quantize);
  23066. saveMenus (juce::StringArray { lynx::tr ("Audio clip"), lynx::tr ("Clip envelope") },
  23067. std::vector<juce::PopupMenu> { menu, envelopeMenu != nullptr ? *envelopeMenu : juce::PopupMenu() }, prefix + "-02-clip-menu.png");
  23068. check ("Auto-warp from the clip menu places markers", clickMenuItem (menu, lynx::tr ("Auto-warp")));
  23069. offline.dispatchPendingMessages();
  23070. const auto& s = offline.getSong();
  23071. const auto& loopClip = s.playlist[2];
  23072. check ("the loop's channel is warped", s.channels[(std::size_t) loopClip.channel].sampler.warp.size() >= 2
  23073. && s.channels[(std::size_t) loopClip.channel].sampler.keepPitch);
  23074. // the first clip's menu: Show volume envelope ticked
  23075. const auto first = playlist.getClipMenuForSnapshot (0);
  23076. bool ticked = false;
  23077. for (juce::PopupMenu::MenuItemIterator it (first); it.next();)
  23078. if (it.getItem().text == lynx::tr ("Clip envelope") && it.getItem().subMenu != nullptr)
  23079. for (juce::PopupMenu::MenuItemIterator sub (*it.getItem().subMenu); sub.next();)
  23080. ticked = ticked || (sub.getItem().text == lynx::tr ("Show volume envelope") && sub.getItem().isTicked);
  23081. check ("Show volume envelope is ticked on the first clip", ticked);
  23082. }
  23083. // gestures through the Playlist's own handlers
  23084. auto source = juce::Desktop::getInstance().getMainMouseSource();
  23085. const auto now = juce::Time::getCurrentTime();
  23086. const auto press = [&] (juce::Point<float> from, juce::Point<float> to, juce::ModifierKeys button, juce::ModifierKeys extra) {
  23087. const juce::ModifierKeys mods (button.getRawFlags() | extra.getRawFlags());
  23088. const auto event = [&] (juce::Point<float> p, juce::ModifierKeys m, bool dragged) {
  23089. return juce::MouseEvent (source, p, m, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, &playlist, &playlist, now, from, now, 1, dragged);
  23090. };
  23091. const auto held = juce::ModifierKeys::currentModifiers;
  23092. juce::ModifierKeys::currentModifiers = mods;
  23093. playlist.mouseDown (event (from, mods, false));
  23094. if (to != from)
  23095. playlist.mouseDrag (event (to, mods, true));
  23096. juce::ModifierKeys::currentModifiers = held;
  23097. playlist.mouseUp (event (to, extra, to != from));
  23098. };
  23099. const auto x = [&] (double beats) { return (float) playlist.xOfTickForSnapshot (beats * lynx::ppq); };
  23100. {
  23101. const auto body = playlist.curveBodyForSnapshot (0);
  23102. const auto points = offline.getSong().clipEnvelopes[(std::size_t) offline.getSong().playlist[0].envelope].volume.size();
  23103. // [RMB] in the curve's area adds a point there (FL's in-Playlist automation editing, round 165)
  23104. press ({ x (7.0), body.getBottom() - 0.3f * body.getHeight() }, { x (7.0), body.getBottom() - 0.3f * body.getHeight() },
  23105. juce::ModifierKeys::rightButtonModifier, {});
  23106. offline.dispatchPendingMessages();
  23107. const auto& s = offline.getSong();
  23108. const auto* e = lynx::clipenv::of (s, s.playlist[0]);
  23109. check ("[RMB] on the clip's volume lane adds a point", e != nullptr && e->volume.size() == points + 1
  23110. && std::abs (lynx::automationCurveAt (e->volume, 7.0 * lynx::ppq) - 0.3f) < 0.05f);
  23111. // drag that point up with the Pencil
  23112. press ({ x (7.0), body.getBottom() - 0.3f * body.getHeight() }, { x (7.0), body.getBottom() - 0.7f * body.getHeight() },
  23113. juce::ModifierKeys::leftButtonModifier, {});
  23114. offline.dispatchPendingMessages();
  23115. const auto* moved = lynx::clipenv::of (offline.getSong(), offline.getSong().playlist[0]);
  23116. check ("dragging the point moves it", moved != nullptr && std::abs (lynx::automationCurveAt (moved->volume, 7.0 * lynx::ppq) - 0.7f) < 0.05f);
  23117. check ("the edits are undoable", offline.canUndo());
  23118. }
  23119. write (ui, "03-playlist-edited");
  23120. {
  23121. // warp: a double-click on the loop clip's flag strip adds a marker; Alt + drag on its line (mid clip) moves it
  23122. const auto bounds = playlist.clipBoundsForSnapshot (2);
  23123. const auto channelOf = [&] { return offline.getSong().playlist[2].channel; };
  23124. const auto markers = [&] { return offline.getSong().channels[(std::size_t) channelOf()].sampler.warp; };
  23125. const auto before = markers().size();
  23126. const juce::Point<float> strip { x (1.5), (float) bounds.getY() + 13.0f + 3.0f };
  23127. playlist.mouseDoubleClick (juce::MouseEvent (source, strip, juce::ModifierKeys::leftButtonModifier, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, &playlist, &playlist,
  23128. now, strip, now, 2, false));
  23129. offline.dispatchPendingMessages();
  23130. check ("a double-click on the flag strip adds a warp marker", markers().size() == before + 1);
  23131. if (markers().size() != before + 1)
  23132. checks << " (strip seconds " << playlist.warpStripSecondsForSnapshot (2, strip.toInt()) << ", played markers "
  23133. << (int) playlist.warpMarkerCountForSnapshot (2) << ", file seconds " << playlist.clipFileSecondsForSnapshot (2)
  23134. << ", channel markers " << (int) before << ", clip at " << bounds.toString() << ", strip " << strip.toString() << ")\n";
  23135. int added = -1;
  23136. for (int k = 0; k < (int) markers().size(); ++k)
  23137. if (std::abs (markers()[(std::size_t) k].beats - 1.5) < 0.05)
  23138. added = k;
  23139. check ("the marker sits on the beat it was added on", added > 0);
  23140. if (added > 0)
  23141. {
  23142. const juce::Point<float> line { x (1.5), (float) bounds.getCentreY() + 10.0f };
  23143. press (line, line.translated (x (1.75) - x (1.5), 0.0f), juce::ModifierKeys::leftButtonModifier, juce::ModifierKeys::altModifier);
  23144. offline.dispatchPendingMessages();
  23145. check ("Alt + drag on a marker's line moves it", added < (int) markers().size() && std::abs (markers()[(std::size_t) added].beats - 1.75) < 0.05);
  23146. }
  23147. }
  23148. write (ui, "04-playlist-warp");
  23149. // the Clip-launch layout: the Clip View's Envelopes tab of a grid audio clip
  23150. offline.editSong ([&] (lynx::Song& s) {
  23151. auto clip = s.playlist[0];
  23152. clip.start = 0;
  23153. lynx::launcher::setClip (s, 0, 0, clip);
  23154. lynx::launcher::ensureGrid (s).scenes.resize (std::max<std::size_t> (1, lynx::launcher::ensureGrid (s).scenes.size()));
  23155. }, false);
  23156. offline.dispatchPendingMessages();
  23157. const auto shootPanel = [&] (const char* name, bool envelopes, std::uint8_t lane) {
  23158. auto panel = lynx::makeClipAudioPanel (offline, 0, 0);
  23159. if (panel == nullptr)
  23160. return false;
  23161. panel->setSize (1100, 300);
  23162. for (auto* child : panel->getChildren())
  23163. if (auto* b = dynamic_cast<juce::TextButton*> (child); b != nullptr && b->getButtonText() == (envelopes ? lynx::tr ("Envelopes") : lynx::tr ("Sample")))
  23164. if (b->onClick)
  23165. b->onClick();
  23166. if (lane != 0)
  23167. offline.editSong ([lane] (lynx::Song& s) {
  23168. if (s.clipGrid)
  23169. if (auto* c = const_cast<lynx::Clip*> (lynx::launcher::clipAt (*s.clipGrid, 0, 0)); c != nullptr)
  23170. lynx::clipenv::show (s, *c, lane);
  23171. }, false);
  23172. offline.dispatchPendingMessages();
  23173. write (*panel, name);
  23174. return true;
  23175. };
  23176. check ("Clip View: Sample tab", shootPanel ("05-clipview-sample", false, 0));
  23177. check ("Clip View: Envelopes tab, Clip > Gain", shootPanel ("06-clipview-envelopes-gain", true, lynx::clipenv::volumeLane));
  23178. check ("Clip View: Envelopes tab, Mixer > Track Panning", shootPanel ("07-clipview-envelopes-pan", true, lynx::clipenv::panLane));
  23179. {
  23180. const auto* c = offline.getSong().clipGrid ? lynx::launcher::clipAt (*offline.getSong().clipGrid, 0, 0) : nullptr;
  23181. check ("the grid clip keeps the volume envelope", c != nullptr && lynx::clipenv::activeOf (offline.getSong(), *c) != nullptr);
  23182. }
  23183. shootPanel ("08-clipview-sample-again", false, 0); // (the tab choice back to Sample for the next run)
  23184. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  23185. }
  23186. void runLiveFactsShot190gx (const juce::String& prefix)
  23187. {
  23188. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  23189. lynx::AudioEngine offline (false);
  23190. juce::String checks;
  23191. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  23192. // a 1 kHz sine, 20 s at 48 kHz (Live's 190gu clip-envelope stimulus), −9 dBFS
  23193. const auto wav = juce::File (prefix + "-sine1k.wav");
  23194. wav.deleteFile();
  23195. {
  23196. const double rate = 48000.0;
  23197. juce::AudioBuffer<float> buffer (2, (int) (rate * 20.0));
  23198. for (int k = 0; k < buffer.getNumSamples(); ++k)
  23199. for (int ch = 0; ch < 2; ++ch)
  23200. buffer.setSample (ch, k, (float) (0.3535 * std::sin (2.0 * juce::MathConstants<double>::pi * 1000.0 * k / rate)));
  23201. if (auto out = std::unique_ptr<juce::FileOutputStream> (wav.createOutputStream()))
  23202. if (auto* writer = juce::WavAudioFormat().createWriterFor (out.get(), rate, 2, 16, {}, 0))
  23203. {
  23204. out.release();
  23205. std::unique_ptr<juce::AudioFormatWriter> owned (writer);
  23206. owned->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
  23207. }
  23208. }
  23209. offline.editSong ([&wav] (lynx::Song& s) {
  23210. s.bpm = 120.0;
  23211. lynx::ChannelDef ch;
  23212. ch.name = "sine1k";
  23213. ch.instrument = lynx::InstrumentKind::audioClip;
  23214. ch.samplePath = wav.getFullPathName().toStdString();
  23215. s.channels.push_back (ch);
  23216. const auto c = (int) s.channels.size() - 1;
  23217. lynx::clipsample::setWarp (s, c, true, 20.0);
  23218. lynx::warpmodes::setMode (s, c, (int) lynx::StretchMethod::beats);
  23219. lynx::Clip audio;
  23220. audio.kind = lynx::ClipKind::audio;
  23221. audio.channel = c;
  23222. audio.length = 40 * lynx::ppq;
  23223. // Live's Clip Gain staircase of the 190gu render (−1 … 1 in 0.1 steps, 2 beats each), as LYNX lane values
  23224. lynx::ClipEnvelope e;
  23225. for (int k = 0; k <= 20; ++k)
  23226. {
  23227. const auto v = lynx::clipenv::fromLive (lynx::clipenv::volumeLane, -1.0 + 0.1 * k);
  23228. for (const auto at : { 2 * k, 2 * k + 2 })
  23229. {
  23230. lynx::AutomationPoint p;
  23231. p.tick = (std::int64_t) at * lynx::ppq;
  23232. p.value = v;
  23233. e.volume.push_back (p);
  23234. }
  23235. }
  23236. e.shown = lynx::clipenv::volumeLane;
  23237. s.clipEnvelopes.push_back (e);
  23238. audio.envelope = (int) s.clipEnvelopes.size() - 1;
  23239. lynx::launcher::setClip (s, 0, 0, audio);
  23240. lynx::launcher::ensureGrid (s).scenes.resize (1);
  23241. }, false);
  23242. offline.dispatchPendingMessages();
  23243. const auto channelOf = [&] {
  23244. const auto* c = lynx::warpmodes::gridAudioClip (const_cast<lynx::Song&> (offline.getSong()), 0, 0);
  23245. return c != nullptr ? c->channel : -1;
  23246. };
  23247. const auto shoot = [&] (const char* name, int w, int h, int tab) {
  23248. auto panel = lynx::makeClipAudioPanel (offline, 0, 0);
  23249. if (panel == nullptr)
  23250. return std::unique_ptr<juce::Component>();
  23251. panel->setSize (w, h);
  23252. if (tab != 0)
  23253. for (auto* child : panel->getChildren())
  23254. if (auto* b = dynamic_cast<juce::TextButton*> (child); b != nullptr && b->getButtonText() == (tab == 2 ? lynx::tr ("Envelopes") : lynx::tr ("Sample")))
  23255. if (b->onClick)
  23256. b->onClick();
  23257. offline.dispatchPendingMessages();
  23258. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  23259. file.deleteFile();
  23260. juce::FileOutputStream out (file);
  23261. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (*panel), out);
  23262. return panel;
  23263. };
  23264. const auto visibleText = [] (juce::Component& panel, const juce::String& text) {
  23265. for (auto* child : panel.getChildren())
  23266. if (auto* b = dynamic_cast<juce::TextButton*> (child); b != nullptr && b->getButtonText() == text)
  23267. return b->isVisible();
  23268. return false;
  23269. };
  23270. const auto setMode = [&] (int method) {
  23271. offline.editSong ([&] (lynx::Song& s) { lynx::warpmodes::setMode (s, channelOf(), method); }, false);
  23272. offline.dispatchPendingMessages();
  23273. };
  23274. check ("01 Beats (Preserve label + chooser, loop icon + Transient Envelope)", shoot ("01-audio-beats", 900, 250, 1) != nullptr);
  23275. setMode ((int) lynx::StretchMethod::tones);
  23276. check ("02 Tones (Grain Size 30.00)", shoot ("02-audio-tones", 900, 250, 1) != nullptr);
  23277. setMode ((int) lynx::StretchMethod::texture);
  23278. check ("03 Texture (Grain Size 65.00, Flux only when it plays)", shoot ("03-audio-texture", 900, 250, 1) != nullptr);
  23279. if constexpr (lynx::warpmodes::complexProPlays)
  23280. {
  23281. offline.editSong ([&] (lynx::Song& s) { lynx::warpmodes::setComplexPro (s, channelOf()); }, false);
  23282. offline.dispatchPendingMessages();
  23283. check ("04 Complex Pro (Formants 100.00, Envelope 128)", shoot ("04-audio-complex-pro", 900, 250, 1) != nullptr);
  23284. }
  23285. else
  23286. {
  23287. setMode ((int) lynx::StretchMethod::complex);
  23288. check ("04 Complex (nothing under the chooser)", shoot ("04-audio-complex", 900, 250, 1) != nullptr);
  23289. }
  23290. setMode ((int) lynx::StretchMethod::beats);
  23291. {
  23292. auto panel = shoot ("05-envelopes-clip-gain-staircase", 1390, 420, 2);
  23293. check ("05 Envelopes tab shown on a warped clip", panel != nullptr && visibleText (*panel, lynx::tr ("Envelopes")));
  23294. }
  23295. offline.editSong ([&] (lynx::Song& s) { lynx::clipsample::setWarp (s, channelOf(), false, 20.0); }, false);
  23296. offline.dispatchPendingMessages();
  23297. {
  23298. auto panel = shoot ("06-unwarped-sample-only", 1390, 420, 2);
  23299. check ("06 an unwarped clip has no Envelopes tab (Live)", panel != nullptr && ! visibleText (*panel, lynx::tr ("Envelopes"))
  23300. && visibleText (*panel, lynx::tr ("Sample")));
  23301. }
  23302. // the law: Live's staircase values round trip through the lane values
  23303. bool law = true;
  23304. for (int k = 0; k <= 20; ++k)
  23305. {
  23306. const auto L = -1.0 + 0.1 * k;
  23307. law = law && std::abs (lynx::clipenv::toLive (lynx::clipenv::volumeLane, lynx::clipenv::fromLive (lynx::clipenv::volumeLane, L)) - L) < 2.0e-3;
  23308. }
  23309. check ("Clip Gain values round trip (Live → lane → Live)", law);
  23310. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  23311. }
  23312. void runWarpShot190fm (const juce::String& prefix)
  23313. {
  23314. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  23315. lynx::AudioEngine offline (false);
  23316. juce::String checks;
  23317. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  23318. // a one-bar loop of clicks (2 s at 48 kHz) for the audio clips
  23319. const auto wav = juce::File (prefix + "-loop.wav");
  23320. wav.deleteFile();
  23321. {
  23322. const double rate = 48000.0;
  23323. juce::AudioBuffer<float> buffer (2, (int) (rate * 2.0));
  23324. buffer.clear();
  23325. for (int hit = 0; hit < 8; ++hit)
  23326. for (int k = 0; k < 3000; ++k)
  23327. for (int ch = 0; ch < 2; ++ch)
  23328. buffer.setSample (ch, hit * 12000 + k, (float) (std::sin (k * (hit % 4 == 0 ? 0.05 : 0.3)) * std::exp (-k / 500.0) * 0.8));
  23329. if (auto out = std::unique_ptr<juce::FileOutputStream> (wav.createOutputStream()))
  23330. if (auto* writer = juce::WavAudioFormat().createWriterFor (out.get(), rate, 2, 16, {}, 0))
  23331. {
  23332. out.release();
  23333. std::unique_ptr<juce::AudioFormatWriter> owned (writer);
  23334. owned->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
  23335. }
  23336. }
  23337. offline.editSong ([&wav] (lynx::Song& s) {
  23338. lynx::ChannelDef ch;
  23339. ch.name = "Loop";
  23340. ch.instrument = lynx::InstrumentKind::audioClip;
  23341. ch.samplePath = wav.getFullPathName().toStdString();
  23342. s.channels.push_back (ch);
  23343. const auto c = (int) s.channels.size() - 1;
  23344. lynx::clipsample::setWarp (s, c, true, 2.0);
  23345. lynx::warpmodes::setMode (s, c, (int) lynx::StretchMethod::beats); // (keeps the pitch: Beats, not Re-Pitch)
  23346. lynx::Clip audio;
  23347. audio.kind = lynx::ClipKind::audio;
  23348. audio.channel = c;
  23349. audio.length = 4 * lynx::ppq;
  23350. lynx::launcher::setClip (s, 0, 0, audio);
  23351. lynx::launcher::setClip (s, 0, 1, audio); // (a second clip on the same channel: O16)
  23352. lynx::launcher::ensureGrid (s).scenes.resize (2);
  23353. }, false);
  23354. offline.dispatchPendingMessages();
  23355. const auto shoot = [&] (const char* name) {
  23356. auto panel = lynx::makeClipAudioPanel (offline, 0, 0);
  23357. if (panel == nullptr)
  23358. return false;
  23359. panel->setSize (900, 250);
  23360. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  23361. file.deleteFile();
  23362. juce::FileOutputStream out (file);
  23363. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (*panel), out);
  23364. return true;
  23365. };
  23366. const auto channelOf = [&] (int scene) {
  23367. const auto* c = lynx::warpmodes::gridAudioClip (const_cast<lynx::Song&> (offline.getSong()), 0, scene);
  23368. return c != nullptr ? c->channel : -1;
  23369. };
  23370. const auto beatsOn = [&] { const auto& sm = offline.getSong().channels[(std::size_t) channelOf (0)].sampler; return sm.keepPitch && sm.stretchMethod == lynx::StretchMethod::beats; };
  23371. check ("01 Beats panel (defaults: Transients, Back-and-Forth, 100)", beatsOn() && shoot ("01-beats-defaults"));
  23372. offline.editSong ([&] (lynx::Song& s) {
  23373. const auto c = lynx::warpmodes::ownChannelForGridClip (s, 0, 0);
  23374. lynx::warpmodes::setPreserve (s, c, 3);
  23375. lynx::warpmodes::setLoopMode (s, c, 0);
  23376. lynx::warpmodes::setEnvelope (s, c, 40.0);
  23377. }, false);
  23378. offline.dispatchPendingMessages();
  23379. check ("O16: the first clip moved to its own channel, the second kept the old one", channelOf (0) != channelOf (1) && channelOf (0) >= 0 && channelOf (1) >= 0);
  23380. check ("02 Beats panel (1/8, Loop Off, 40)", beatsOn() && shoot ("02-beats-set"));
  23381. offline.editSong ([&] (lynx::Song& s) { lynx::warpmodes::setMode (s, channelOf (0), (int) lynx::StretchMethod::tones); }, false);
  23382. offline.dispatchPendingMessages();
  23383. check ("03 Tones panel (Grain Size 30)", shoot ("03-tones"));
  23384. offline.editSong ([&] (lynx::Song& s) {
  23385. lynx::warpmodes::setMode (s, channelOf (0), (int) lynx::StretchMethod::texture);
  23386. lynx::warpmodes::setGrain (s, channelOf (0), 120.0);
  23387. }, false);
  23388. offline.dispatchPendingMessages();
  23389. check ("04 Texture panel (Grain Size 120)", shoot ("04-texture"));
  23390. check ("Texture grain kept 120, Tones grain still 30", offline.getSong().channels[(std::size_t) channelOf (0)].sampler.warpModes.textureGrain == 120.0f
  23391. && offline.getSong().channels[(std::size_t) channelOf (0)].sampler.warpModes.tonesGrain == 30.0f);
  23392. offline.editSong ([&] (lynx::Song& s) { lynx::warpmodes::setMode (s, channelOf (0), (int) lynx::StretchMethod::complex); }, false);
  23393. offline.dispatchPendingMessages();
  23394. check ("05 Complex panel (no settings row)", shoot ("05-complex"));
  23395. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  23396. }
  23397. void runLiveShot190dr (const juce::String& prefix)
  23398. {
  23399. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  23400. lynx::AudioEngine offline (false);
  23401. lynx::MainComponent ui (offline, false);
  23402. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  23403. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  23404. const auto write = [&prefix] (juce::Component& c, const char* name) {
  23405. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  23406. file.deleteFile();
  23407. juce::FileOutputStream out (file);
  23408. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (c), out);
  23409. };
  23410. juce::String checks;
  23411. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  23412. // a two-bar loop of clicks for the audio clip
  23413. const auto wav = juce::File (prefix + "-loop.wav");
  23414. wav.deleteFile();
  23415. {
  23416. const double rate = 48000.0;
  23417. juce::AudioBuffer<float> buffer (2, (int) (rate * 4.0));
  23418. buffer.clear();
  23419. for (int hit = 0; hit < 16; ++hit)
  23420. for (int k = 0; k < 3000 && hit * 12000 + k < buffer.getNumSamples(); ++k)
  23421. for (int ch = 0; ch < 2; ++ch)
  23422. buffer.setSample (ch, hit * 12000 + k, (float) (std::sin (k * (hit % 4 == 0 ? 0.05 : 0.3)) * std::exp (-k / 500.0) * 0.8));
  23423. if (auto out = std::unique_ptr<juce::FileOutputStream> (wav.createOutputStream()))
  23424. if (auto* writer = juce::WavAudioFormat().createWriterFor (out.get(), rate, 2, 16, {}, 0))
  23425. {
  23426. out.release();
  23427. std::unique_ptr<juce::AudioFormatWriter> owned (writer);
  23428. owned->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
  23429. }
  23430. }
  23431. ui.setVisible (true);
  23432. lynx::DetailView::shownSetting = true;
  23433. lynx::DetailView::devicesPage = false;
  23434. ui.setClipLaunchWorkflow (true);
  23435. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::browser, lynx::workspace::Panel::playlist });
  23436. ui.getPlaylistForSnapshot().addAudioClipAtPlayhead (wav);
  23437. offline.dispatchPendingMessages();
  23438. int audioChannel = -1;
  23439. offline.editSong ([&audioChannel] (lynx::Song& s) {
  23440. lynx::Clip audio;
  23441. if (! s.playlist.empty())
  23442. {
  23443. audio = s.playlist.front();
  23444. audioChannel = audio.channel;
  23445. s.playlist.clear();
  23446. }
  23447. const int channels = (int) s.channels.size();
  23448. s.channels.resize ((std::size_t) channels + 3);
  23449. const char* names[] { "Drum kit", "Bass synth", "Keys" };
  23450. for (int k = 0; k < 3; ++k)
  23451. {
  23452. auto& ch = s.channels[(std::size_t) (channels + k)];
  23453. ch.name = names[k];
  23454. ch.instrument = k == 0 ? lynx::InstrumentKind::sampler : lynx::InstrumentKind::synth;
  23455. ch.mixerTrack = k + 1;
  23456. }
  23457. if (audioChannel >= 0)
  23458. s.channels[(std::size_t) audioChannel].mixerTrack = 5;
  23459. if (s.mixer.size() < 8)
  23460. s.mixer.resize (8);
  23461. const char* inserts[] { "Master", "Drums", "Bass", "Keys", "Vox", "Loop", "Reverb", "Delay" };
  23462. for (int i = 1; i < 8; ++i)
  23463. s.mixer[(std::size_t) i].name = inserts[i];
  23464. s.mixer[1].volume = lynx::sessionmixer::positionForDb (-3.0);
  23465. s.mixer[2].pan = 0.3f;
  23466. s.mixer[2].effects.clear();
  23467. for (auto kind : { lynx::EffectKind::eq, lynx::EffectKind::compressor, lynx::EffectKind::delay })
  23468. {
  23469. lynx::EffectSlot fx;
  23470. fx.kind = kind;
  23471. const auto& info = lynx::effectInfo (kind);
  23472. for (std::size_t k = 0; k < info.params.size() && k < fx.params.size(); ++k)
  23473. fx.params[k] = info.params[k].defaultValue;
  23474. s.mixer[2].effects.push_back (fx);
  23475. }
  23476. s.mixer[3].muted = true; // the Keys' activator off
  23477. s.mixer[4].inputChannel = 0;
  23478. s.mixer[4].inputStereo = true;
  23479. s.mixer[4].monitor = lynx::InputMonitor::automatic;
  23480. s.mixer[4].effects.clear();
  23481. {
  23482. lynx::EffectSlot fx;
  23483. fx.kind = lynx::EffectKind::reverb;
  23484. s.mixer[4].effects.push_back (fx);
  23485. }
  23486. s.mixer[5].solo = true;
  23487. 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 } })
  23488. {
  23489. lynx::MixerSend send;
  23490. send.target = to;
  23491. send.level = lynx::faderGain (level);
  23492. s.mixer[(std::size_t) from].sends.push_back (send);
  23493. }
  23494. while (s.patterns.size() < 3)
  23495. s.patterns.emplace_back();
  23496. const char* patterns[] { "Beat", "Bassline", "Chords" };
  23497. for (int p = 0; p < 3; ++p)
  23498. {
  23499. auto& pattern = s.patterns[(std::size_t) p];
  23500. pattern.name = patterns[p];
  23501. lynx::Note n;
  23502. n.channel = channels + p;
  23503. n.key = 48 + p * 5;
  23504. pattern.notes = { n };
  23505. pattern.lengthTicks = 4 * lynx::ppq;
  23506. }
  23507. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 8));
  23508. const char* tracks[] { "Drums", "Bass", "Keys", "Vox", "Loop", "FX" };
  23509. for (int t = 0; t < 6; ++t)
  23510. s.playlistTracks[(std::size_t) t].name = tracks[t];
  23511. s.playlistTracks[3].mode = lynx::PlaylistTrackMode::audio;
  23512. s.playlistTracks[3].mixerTrack = 4;
  23513. for (int t = 0; t < 3; ++t)
  23514. for (int r = 0; r < 3; ++r)
  23515. if (! (t == 2 && r == 0))
  23516. {
  23517. lynx::Clip clip;
  23518. clip.pattern = t;
  23519. clip.length = 4 * lynx::ppq;
  23520. lynx::launcher::setClip (s, t, r, clip);
  23521. }
  23522. if (audioChannel >= 0)
  23523. {
  23524. lynx::clipsample::setWarp (s, audioChannel, true, 4.0); // (Warp on, as a dropped loop in Live)
  23525. audio.track = 4;
  23526. audio.start = 0;
  23527. lynx::launcher::setClip (s, 4, 0, audio);
  23528. lynx::launcher::setClip (s, 4, 1, audio);
  23529. }
  23530. auto& grid = lynx::launcher::ensureGrid (s);
  23531. const char* scenes[] { "Intro", "Verse", "Drop" };
  23532. grid.scenes.resize (5);
  23533. for (int r = 0; r < 3; ++r)
  23534. grid.scenes[(std::size_t) r].name = scenes[r];
  23535. }, false);
  23536. offline.dispatchPendingMessages();
  23537. offline.setGridTrackArmed (3, true);
  23538. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  23539. offline.dispatchPendingMessages();
  23540. ui.resized();
  23541. auto* gridView = ui.getClipGridForSnapshot();
  23542. auto* mixer = gridView != nullptr ? lynx::clipGridMixer (*gridView) : nullptr;
  23543. auto* detail = ui.getDetailViewForSnapshot();
  23544. if (gridView == nullptr || mixer == nullptr || detail == nullptr)
  23545. {
  23546. juce::File (prefix + "-checks.txt").replaceWithText ("FAIL no grid, mixer or detail view\n");
  23547. return;
  23548. }
  23549. // the meters: a level per insert, as a playing song leaves them (offscreen nothing plays), two ticks
  23550. const auto levels = [&] {
  23551. for (int k = 0; k < 2; ++k)
  23552. {
  23553. const float peaks[] { 0.9f, 0.5f, 0.7f, 0.0f, 0.3f, 0.45f, 0.2f, 0.12f };
  23554. for (int i = 0; i < 8; ++i)
  23555. offline.getMeters().accumulate (i, peaks[i], peaks[i] * 0.85f);
  23556. mixer->tick();
  23557. }
  23558. };
  23559. if (auto* runtime = offline.launcherStateForSnapshot())
  23560. {
  23561. runtime->tracks[0].playing.store (1);
  23562. runtime->tracks[0].progress.store (0.3f);
  23563. runtime->tracks[1].playing.store (1);
  23564. runtime->tracks[1].progress.store (0.3f);
  23565. runtime->tracks[4].playing.store (0);
  23566. runtime->tracks[4].progress.store (0.5f);
  23567. runtime->running.store (true);
  23568. }
  23569. levels();
  23570. gridView->resized();
  23571. write (ui, "01-session-mixer");
  23572. write (*gridView, "01b-grid-alone");
  23573. using Part = lynx::SessionMixerComponent::Part;
  23574. check ("mixer: Sends rows are the two buses (Reverb 6, Delay 7)", mixer->sendTargets() == std::vector<int> { 6, 7 });
  23575. check ("mixer: the arm buttons moved into the Volume section", mixer->armsShown());
  23576. check ("mixer: Drums strip has activator, solo, arm, pan, volume", ! mixer->partBounds (0, Part::activator).isEmpty() && ! mixer->partBounds (0, Part::solo).isEmpty()
  23577. && ! mixer->partBounds (0, Part::arm).isEmpty() && ! mixer->partBounds (0, Part::pan).isEmpty()
  23578. && ! mixer->partBounds (0, Part::volume).isEmpty());
  23579. check ("mixer: Vox strip (audio track) has Audio From, its channel, Monitor and Audio To", ! mixer->partBounds (3, Part::inType).isEmpty()
  23580. && ! mixer->partBounds (3, Part::inChannel).isEmpty()
  23581. && ! mixer->partBounds (3, Part::monAuto).isEmpty()
  23582. && ! mixer->partBounds (3, Part::output).isEmpty());
  23583. check ("mixer: Bass strip (instrument) shows MIDI From, no Monitor", mixer->partBounds (1, Part::monIn).isEmpty() && ! mixer->partBounds (1, Part::output).isEmpty());
  23584. check ("mixer: FX strip (no clips) has no activator but an arm", mixer->partBounds (5, Part::activator).isEmpty() && ! mixer->partBounds (5, Part::arm).isEmpty());
  23585. check ("mixer: Main strip has volume and pan, no activator", ! mixer->partBounds (-2, Part::volume).isEmpty() && mixer->partBounds (-2, Part::activator).isEmpty());
  23586. {
  23587. const auto hit = mixer->hitAt (mixer->partBounds (2, Part::solo).getCentre());
  23588. check ("mixer: a click on the Keys' S is its solo", hit.column == 2 && hit.part == Part::solo);
  23589. const auto send = mixer->hitAt (mixer->partBounds (1, Part::send, 1).getCentre());
  23590. check ("mixer: the Bass' second knob is its send to Delay", send.column == 1 && send.part == Part::send && send.row == 1);
  23591. }
  23592. {
  23593. juce::PopupMenu menu;
  23594. mixer->addViewItems (menu);
  23595. saveMenus (juce::StringArray { "Mixer (footer button)" }, std::vector<juce::PopupMenu> { menu }, prefix + "-02-mixer-view-menu.png");
  23596. }
  23597. offline.editSong ([] (lynx::Song& s) { lynx::launcher::ensureGrid (s).mixerView.trackOptions = true; }, false);
  23598. offline.dispatchPendingMessages();
  23599. gridView->resized();
  23600. levels();
  23601. write (*gridView, "03-mixer-track-options");
  23602. offline.editSong ([] (lynx::Song& s) {
  23603. auto& v = lynx::launcher::ensureGrid (s).mixerView;
  23604. v.trackOptions = v.io = v.sends = false;
  23605. }, false);
  23606. offline.dispatchPendingMessages();
  23607. gridView->resized();
  23608. levels();
  23609. write (*gridView, "04-mixer-volume-only");
  23610. offline.editSong ([] (lynx::Song& s) { lynx::launcher::ensureGrid (s).mixerView.shown = false; }, false);
  23611. offline.dispatchPendingMessages();
  23612. gridView->resized();
  23613. write (*gridView, "05-mixer-hidden");
  23614. check ("mixer hidden: the arm buttons are back in the status row", ! mixer->armsShown() && mixer->getHeight() == 0);
  23615. offline.editSong ([] (lynx::Song& s) { lynx::launcher::ensureGrid (s).mixerView = {}; }, false);
  23616. offline.dispatchPendingMessages();
  23617. gridView->resized();
  23618. // the Clip page of the Loop clip (track 4, scene 0) while it plays: Warp on, the Set buttons lit, the title
  23619. detail->showSelection (4, 0);
  23620. detail->setPage (lynx::DetailView::Page::clip);
  23621. offline.editSong ([] (lynx::Song&) {}, false); // (a change message: the Clip panel reads the playing state)
  23622. offline.dispatchPendingMessages();
  23623. write (ui, "06-clip-audio-warp-on");
  23624. if (audioChannel >= 0)
  23625. {
  23626. const auto beforeLength = lynx::launcher::clipAt (*offline.getSong().clipGrid, 4, 0)->length;
  23627. offline.editSong ([audioChannel] (lynx::Song& s) { lynx::clipsample::setWarp (s, audioChannel, false, 4.0); });
  23628. offline.dispatchPendingMessages();
  23629. write (ui, "07-clip-audio-warp-off");
  23630. check ("warp off: the channel plays at its own speed", ! lynx::clipsample::isWarped (offline.getSong().channels[(std::size_t) audioChannel].sampler));
  23631. offline.undo();
  23632. offline.dispatchPendingMessages();
  23633. check ("warp: undo gives the clip back as it was", lynx::launcher::clipAt (*offline.getSong().clipGrid, 4, 0)->length == beforeLength
  23634. && lynx::clipsample::isWarped (offline.getSong().channels[(std::size_t) audioChannel].sampler));
  23635. // Set (start) at the play position, half way: one undo step
  23636. const auto clipBefore = *lynx::launcher::clipAt (*offline.getSong().clipGrid, 4, 0);
  23637. offline.editSong ([] (lynx::Song& s) {
  23638. for (auto& c : s.clipGrid->clips)
  23639. if (c.track == 4 && c.gridSlot >= 0 && s.clipGrid->slots[(std::size_t) c.gridSlot].scene == 0)
  23640. lynx::clipsample::setStartAt (c, lynx::clipsample::playPosition (c, 0.5f));
  23641. });
  23642. const auto& after = *lynx::launcher::clipAt (*offline.getSong().clipGrid, 4, 0);
  23643. check ("set start: the clip starts half way and ends where it did", after.offset == clipBefore.offset + clipBefore.length / 2
  23644. && after.offset + after.length == clipBefore.offset + clipBefore.length);
  23645. offline.undo();
  23646. offline.dispatchPendingMessages();
  23647. }
  23648. // a MIDI clip's Clip page too (the Set buttons are there for every clip), playing through a groove of the pool
  23649. offline.editSong ([] (lynx::Song& s) {
  23650. const auto& bank = lynx::groove::factoryBank();
  23651. if (bank.size() > 9)
  23652. lynx::groove::setClipGroove (s, 0, 1, lynx::groove::add (s.grooves, bank[9].groove));
  23653. }, false);
  23654. detail->showSelection (0, 1);
  23655. offline.editSong ([] (lynx::Song&) {}, false);
  23656. offline.dispatchPendingMessages();
  23657. write (ui, "08-clip-midi-set-buttons");
  23658. // the Device View of Bass (insert 2): its compressor dragged onto Keys (insert 3), then Ctrl-dragged onto Vox
  23659. detail->showSelection (1, 0);
  23660. detail->setPage (lynx::DetailView::Page::devices);
  23661. offline.dispatchPendingMessages();
  23662. write (ui, "09-devices-bass-before");
  23663. lynx::setClipGridDeviceDropForSnapshot (*gridView, 2);
  23664. write (ui, "10-device-dragged-over-keys");
  23665. lynx::setClipGridDeviceDropForSnapshot (*gridView, -1);
  23666. int fromId = 0;
  23667. {
  23668. const auto& s = offline.getSong();
  23669. fromId = (int) (s.mixer[2].effects[1].instance.id & 0x7fffffff);
  23670. }
  23671. offline.editSongStructural ([] (lynx::Song& s) { lynx::detailchain::moveEffectToInsert (s, 2, 1, 3, false); });
  23672. offline.dispatchPendingMessages();
  23673. check ("drag to Keys: the compressor moved (same device)", offline.getSong().mixer[2].effects.size() == 2 && offline.getSong().mixer[3].effects.size() == 1
  23674. && (int) (offline.getSong().mixer[3].effects[0].instance.id & 0x7fffffff) == fromId);
  23675. detail->showSelection (2, 1);
  23676. offline.dispatchPendingMessages();
  23677. write (ui, "11-devices-keys-after-move");
  23678. offline.editSongStructural ([] (lynx::Song& s) { lynx::detailchain::moveEffectToInsert (s, 2, 0, 4, true); });
  23679. offline.dispatchPendingMessages();
  23680. check ("Ctrl-drag to Vox: a copy of the EQ after its reverb, Bass keeps its own", offline.getSong().mixer[4].effects.size() == 2
  23681. && offline.getSong().mixer[4].effects[1].kind == lynx::EffectKind::eq
  23682. && offline.getSong().mixer[2].effects[0].kind == lynx::EffectKind::eq);
  23683. offline.undo();
  23684. offline.undo();
  23685. offline.dispatchPendingMessages();
  23686. check ("undo twice: Bass has its three devices again, Keys none", offline.getSong().mixer[2].effects.size() == 3 && offline.getSong().mixer[3].effects.empty()
  23687. && offline.getSong().mixer[4].effects.size() == 1);
  23688. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  23689. wav.deleteFile();
  23690. }
  23691. void runWarpShot (const juce::String& prefix)
  23692. {
  23693. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  23694. lynx::AudioEngine offline (false);
  23695. lynx::MainComponent ui (offline, false);
  23696. ui.setSize (1600, 900);
  23697. const auto write = [&prefix] (juce::Component& c, const char* name) {
  23698. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  23699. file.deleteFile();
  23700. juce::FileOutputStream out (file);
  23701. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (c), out);
  23702. };
  23703. // a two-bar loop of clicks, a little off the grid (what Quantize is for)
  23704. const auto wav = juce::File (prefix + "-loop.wav");
  23705. wav.deleteFile();
  23706. {
  23707. const double rate = 44100.0;
  23708. juce::AudioBuffer<float> buffer (1, (int) (rate * 4.0));
  23709. buffer.clear();
  23710. for (int hit = 0; hit < 8; ++hit)
  23711. {
  23712. const auto at = (int) ((hit * 0.5 + (hit % 3) * 0.035) * rate);
  23713. for (int k = 0; k < 4000 && at + k < buffer.getNumSamples(); ++k)
  23714. buffer.setSample (0, at + k, (float) (std::sin (k * (hit % 2 ? 0.25 : 0.06)) * std::exp (-k / 700.0) * 0.8));
  23715. }
  23716. if (auto out = std::unique_ptr<juce::FileOutputStream> (wav.createOutputStream()))
  23717. if (auto* writer = juce::WavAudioFormat().createWriterFor (out.get(), rate, 1, 16, {}, 0))
  23718. {
  23719. out.release();
  23720. std::unique_ptr<juce::AudioFormatWriter> owned (writer);
  23721. owned->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
  23722. }
  23723. }
  23724. ui.setVisible (true);
  23725. lynx::DetailView::shownSetting = true;
  23726. ui.selectTabForSnapshot (2);
  23727. ui.setLayoutStyle (lynx::layoutstyle::Style::clipLaunch);
  23728. lynx::autolanes::setShown (true);
  23729. ui.getPlaylistForSnapshot().addAudioClipAtPlayhead (wav);
  23730. offline.dispatchPendingMessages();
  23731. int channel = -1;
  23732. offline.editSong ([&channel] (lynx::Song& s) {
  23733. if (s.playlist.empty())
  23734. return;
  23735. auto audio = s.playlist.front();
  23736. channel = audio.channel;
  23737. audio.track = 1;
  23738. s.playlist.front() = audio;
  23739. for (int k = 1; k < 3; ++k)
  23740. {
  23741. auto more = audio;
  23742. more.start = audio.start + k * 8 * lynx::ppq;
  23743. s.playlist.push_back (more);
  23744. }
  23745. while (s.patterns.size() < 1)
  23746. s.patterns.emplace_back();
  23747. for (int t = 2; t < 5; ++t)
  23748. for (int k = 0; k < 4; ++k)
  23749. {
  23750. lynx::Clip c;
  23751. c.pattern = 0;
  23752. c.track = t;
  23753. c.start = k * 4 * lynx::ppq;
  23754. c.length = 4 * lynx::ppq;
  23755. s.playlist.push_back (c);
  23756. }
  23757. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 6));
  23758. s.playlistTracks[1].name = "Loop";
  23759. s.playlistTracks[2].name = "Drums";
  23760. s.playlistTracks[3].name = "Kick";
  23761. s.playlistTracks[4].name = "Hats";
  23762. s.playlistTracks[4].folded = true;
  23763. lynx::noteedit::groupWithAbove (s, 3);
  23764. lynx::noteedit::groupWithAbove (s, 4);
  23765. lynx::arrange::makeGroupBus (s, 3);
  23766. lynx::autolanes::addLane (s, 1, { lynx::AutomationTargetKind::tempo, 0, 0, 0 }, "Tempo", lynx::valueFromTempo (s.bpm));
  23767. if (! s.automations.empty())
  23768. s.automations.back().points = { { 0, lynx::valueFromTempo (120.0), 0.0f }, { 8 * lynx::ppq, lynx::valueFromTempo (120.0), 0.0f },
  23769. { 12 * lynx::ppq, lynx::valueFromTempo (180.0), 0.0f }, { 16 * lynx::ppq, lynx::valueFromTempo (140.0), 0.0f } };
  23770. s.addMarker ({ 4 * lynx::ppq, "Verse", 0, 0 });
  23771. s.addMarker ({ 8 * lynx::ppq, {}, 3, 4 });
  23772. s.addMarker ({ 14 * lynx::ppq, {}, 4, 4 });
  23773. s.loopStart = 4 * lynx::ppq;
  23774. s.loopEnd = 12 * lynx::ppq;
  23775. s.loopOff = true;
  23776. s.tempoViewLow = 60.0; // the tempo lane's range
  23777. s.tempoViewHigh = 200.0;
  23778. std::stable_sort (s.playlist.begin(), s.playlist.end(), [] (const lynx::Clip& a, const lynx::Clip& b) { return a.start < b.start; });
  23779. // the same audio in the clip grid, for the Clip page
  23780. lynx::Clip slot = audio;
  23781. slot.start = 0;
  23782. slot.pitch = -2.25f;
  23783. slot.gain = 0.7f;
  23784. lynx::launcher::setClip (s, 1, 0, slot);
  23785. // a few warp markers, as Quantize leaves them
  23786. if (channel >= 0 && channel < (int) s.channels.size())
  23787. {
  23788. auto& sampler = s.channels[(std::size_t) channel].sampler;
  23789. lynx::warpedit::ensureMarkers (sampler, 4.0, s.bpm);
  23790. std::vector<double> attacks;
  23791. for (int hit = 1; hit < 8; ++hit)
  23792. attacks.push_back (hit * 0.5 + (hit % 3) * 0.035);
  23793. lynx::warptools::quantize (sampler, attacks, 0.0, 4.0, 0.5, 1.0);
  23794. lynx::warpedit::syncLength (sampler, 4.0);
  23795. }
  23796. }, false);
  23797. offline.dispatchPendingMessages();
  23798. ui.resized();
  23799. write (ui, "arrangement-loop-off");
  23800. offline.editSong ([] (lynx::Song& s) { s.loopOff = false; }, false);
  23801. offline.dispatchPendingMessages();
  23802. write (ui, "arrangement-loop-on");
  23803. juce::String facts;
  23804. {
  23805. const auto& s = offline.getSong();
  23806. facts << "channel " << channel << ", warp markers " << (channel >= 0 ? (int) s.channels[(std::size_t) channel].sampler.warp.size() : -1)
  23807. << ", group bus insert " << lynx::arrange::groupBus (s, 3) << ", folded track 4: " << (lynx::arrange::isFolded (s, 4) ? 1 : 0) << "\n";
  23808. }
  23809. if (auto* detail = ui.getDetailViewForSnapshot())
  23810. {
  23811. detail->showSelection (1, 0);
  23812. detail->setPage (lynx::DetailView::Page::clip);
  23813. offline.dispatchPendingMessages();
  23814. write (ui, "clip-audio");
  23815. }
  23816. if (channel >= 0)
  23817. if (auto editor = lynx::makeAudioEditorPanel (offline, channel, 0, true))
  23818. {
  23819. editor->setSize (1120, 600);
  23820. write (*editor, "audio-editor-warp");
  23821. // round 190cy (Live 12.4.16 live check 190cw shot 09): a plain drag of marker 3 holds it two sixteenths
  23822. // later (its audio goes there); Shift + drag slides the audio under it. Round 190db: the Clip-launch
  23823. // workflow draws the warped clip in beats, so the held drag shows the audio stretched around the marker
  23824. // (plain) or slid under it, its attack later (Shift, to the right as in Live's shot)
  23825. const auto& w = offline.getSong().channels[(std::size_t) channel].sampler.warp;
  23826. if (w.size() > 4)
  23827. {
  23828. lynx::holdAudioEditorWarpDragForSnapshot (*editor, 3, w[3].beats + 0.5, false);
  23829. write (*editor, "audio-editor-drag-stretch");
  23830. lynx::holdAudioEditorWarpDragForSnapshot (*editor, 3, w[3].seconds - 0.12, true);
  23831. write (*editor, "audio-editor-drag-slide");
  23832. }
  23833. // the same clip in file time (the Pattern workflow's view, or "Show the audio in beats" off)
  23834. if (auto inFileTime = lynx::makeAudioEditorPanel (offline, channel, 0, true))
  23835. {
  23836. inFileTime->setSize (1120, 600);
  23837. lynx::setAudioEditorBeatTimeForSnapshot (*inFileTime, 0);
  23838. write (*inFileTime, "audio-editor-file-time");
  23839. if (w.size() > 4)
  23840. {
  23841. lynx::holdAudioEditorWarpDragForSnapshot (*inFileTime, 3, w[3].beats + 0.5, false);
  23842. write (*inFileTime, "audio-editor-file-time-drag");
  23843. }
  23844. }
  23845. }
  23846. // round 190cy (Live 12.4.16 live check 190cw shot 02): ÷2 from the editor of the first Playlist clip halves that
  23847. // clip's length with the markers' beats; ÷2 on the grid clip's Clip page halves the grid clip
  23848. {
  23849. const auto lengthOf = [&offline] (int index) { return index < (int) offline.getSong().playlist.size() ? offline.getSong().playlist[(std::size_t) index].length : -1; };
  23850. const auto gridLength = [&offline] {
  23851. const auto& s = offline.getSong();
  23852. const auto* c = s.clipGrid ? lynx::launcher::clipAt (*s.clipGrid, 1, 0) : nullptr;
  23853. return c != nullptr ? c->length : (std::int64_t) -1;
  23854. };
  23855. const auto first = [&offline] {
  23856. const auto& s = offline.getSong();
  23857. for (int i = 0; i < (int) s.playlist.size(); ++i)
  23858. if (s.playlist[(std::size_t) i].kind == lynx::ClipKind::audio)
  23859. return i;
  23860. return -1;
  23861. }();
  23862. facts << "halve: playlist clip " << first << " length " << lengthOf (first);
  23863. if (first >= 0)
  23864. if (auto editor = lynx::makeAudioEditorPanel (offline, offline.getSong().playlist[(std::size_t) first].channel, first, true))
  23865. {
  23866. lynx::scaleAudioEditorTempoForSnapshot (*editor, 0.5);
  23867. offline.dispatchPendingMessages();
  23868. }
  23869. facts << " -> " << lengthOf (first) << "; grid clip length " << gridLength();
  23870. if (channel >= 0)
  23871. if (auto editor = lynx::makeAudioEditorPanel (offline, channel, -1, true))
  23872. {
  23873. lynx::setAudioEditorGridClip (*editor, 1, 0);
  23874. lynx::scaleAudioEditorTempoForSnapshot (*editor, 0.5);
  23875. offline.dispatchPendingMessages();
  23876. }
  23877. facts << " -> " << gridLength() << "\n";
  23878. ui.resized();
  23879. write (ui, "arrangement-halved");
  23880. // Duplicate Time over beats 4-8 holding the locator "Verse" (beat 4): a second "Verse" at beat 8
  23881. offline.editSong ([] (lynx::Song& s) { lynx::arrange::duplicateTime (s, 4 * lynx::ppq, 8 * lynx::ppq); });
  23882. offline.dispatchPendingMessages();
  23883. int verses = 0;
  23884. for (const auto& m : offline.getSong().markers())
  23885. verses += m.name == "Verse" ? 1 : 0;
  23886. facts << "duplicate time: locators named Verse " << verses << "\n";
  23887. write (ui, "arrangement-duplicated-time");
  23888. }
  23889. juce::File (prefix + "-facts.txt").replaceWithText (facts);
  23890. lynx::autolanes::setShown (false);
  23891. }
  23892. void runMtShot190fm (const juce::String& prefix)
  23893. {
  23894. lynx::AudioEngine offline (false);
  23895. offline.editSong ([] (lynx::Song& s) {
  23896. if (s.patterns.empty())
  23897. s.patterns.emplace_back();
  23898. s.patterns[0].notes.clear();
  23899. s.patterns[0].lengthTicks = 4 * lynx::ppq;
  23900. s.currentPattern = 0;
  23901. }, false);
  23902. lynx::MidiToolsPanel panel (offline, [] {
  23903. lynx::MidiToolsPanel::Target t;
  23904. t.pattern = 0;
  23905. t.grid = lynx::ppq / 4;
  23906. t.channel = 0;
  23907. t.length = 4 * lynx::ppq; // one bar, no time selection
  23908. return t;
  23909. });
  23910. panel.setSize (lynx::MidiToolsPanel::panelWidth, lynx::MidiToolsPanel::panelHeight);
  23911. panel.setSection (lynx::MidiToolsPanel::generateSection);
  23912. panel.setGenerateShotSettingsForSnapshot();
  23913. const auto write = [&prefix] (const juce::Image& image, const juce::String& name) {
  23914. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  23915. file.deleteFile();
  23916. juce::FileOutputStream out (file);
  23917. juce::PNGImageFormat().writeImageToStream (image, out);
  23918. };
  23919. std::vector<juce::Image> images;
  23920. juce::String checks;
  23921. for (int g = 0; g < lynx::midigen::Settings::toolCount; ++g)
  23922. {
  23923. panel.setGenerator (g);
  23924. const auto name = juce::String (lynx::midigen::toolName (g)).toLowerCase();
  23925. images.push_back (lynx::shot::paint (panel, lynx::theme::colour::bg2));
  23926. write (images.back(), "generate-" + name);
  23927. panel.generateNow();
  23928. offline.dispatchPendingMessages();
  23929. const auto made = (int) offline.getSong().patterns[0].notes.size();
  23930. offline.undo();
  23931. offline.dispatchPendingMessages();
  23932. const auto after = (int) offline.getSong().patterns[0].notes.size();
  23933. checks << name << ": generated " << made << " notes, after undo " << after << (made > 0 && after == 0 ? " OK" : " FAIL") << "\n";
  23934. }
  23935. // the five side by side (6 px apart, on the window's background)
  23936. const auto gap = juce::roundToInt (6.0f * lynx::shot::scale());
  23937. int width = gap, height = 0;
  23938. for (const auto& image : images)
  23939. {
  23940. width += image.getWidth() + gap;
  23941. height = std::max (height, image.getHeight());
  23942. }
  23943. juce::Image strip (juce::Image::RGB, width, height + 2 * gap, true);
  23944. {
  23945. juce::Graphics g (strip);
  23946. g.fillAll (lynx::theme::colour::bg0);
  23947. int x = gap;
  23948. for (const auto& image : images)
  23949. {
  23950. g.drawImageAt (image, x, gap);
  23951. x += image.getWidth() + gap;
  23952. }
  23953. }
  23954. write (strip, "generate-panels");
  23955. checks << "settings saved with the project: " << (offline.getSong().midiGenerate.stacksOptions.sequence.size() == 2 ? "OK" : "FAIL") << "\n";
  23956. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  23957. }
  23958. void runDetailShot (const juce::String& prefix)
  23959. {
  23960. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  23961. lynx::AudioEngine offline (false);
  23962. lynx::MainComponent ui (offline, false);
  23963. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  23964. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  23965. const auto write = [&prefix, &ui] (const char* name) {
  23966. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  23967. file.deleteFile();
  23968. juce::FileOutputStream out (file);
  23969. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (ui), out);
  23970. };
  23971. ui.setVisible (true); // (not on the desktop: only so the Clip page sees itself shown and docks the Piano roll)
  23972. lynx::DetailView::shownSetting = lynx::DetailView::devicesPage = true;
  23973. ui.selectTabForSnapshot (2); // the Playlist panel, maximized
  23974. offline.editSong ([] (lynx::Song& s) {
  23975. if (s.channels.size() < 2)
  23976. s.channels.resize (2);
  23977. s.channels[0].name = "Bass synth";
  23978. s.channels[0].mixerTrack = 2;
  23979. s.channels[1].mixerTrack = 3;
  23980. if (s.mixer.size() < 4)
  23981. s.mixer.resize (4);
  23982. s.mixer[2].name = "Bass";
  23983. s.mixer[2].effects.clear();
  23984. for (auto kind : { lynx::EffectKind::eq, lynx::EffectKind::compressor, lynx::EffectKind::reverb, lynx::EffectKind::delay })
  23985. {
  23986. lynx::EffectSlot fx;
  23987. fx.kind = kind;
  23988. const auto& info = lynx::effectInfo (kind);
  23989. for (std::size_t k = 0; k < info.params.size() && k < fx.params.size(); ++k)
  23990. fx.params[k] = info.params[k].defaultValue;
  23991. fx.enabled = kind != lynx::EffectKind::compressor; // one switched off
  23992. s.mixer[2].effects.push_back (fx);
  23993. }
  23994. while (s.patterns.size() < 2)
  23995. s.patterns.emplace_back();
  23996. s.patterns[0].name = "Bass line";
  23997. s.patterns[0].notes.clear();
  23998. for (int n = 0; n < 4; ++n)
  23999. {
  24000. lynx::Note note;
  24001. note.channel = 0;
  24002. note.start = n * lynx::ppq;
  24003. note.key = 36 + (n % 2) * 7;
  24004. s.patterns[0].notes.push_back (note);
  24005. }
  24006. s.patterns[0].lengthTicks = 4 * lynx::ppq;
  24007. lynx::PatternEvents lane; // a volume swell for the Envelopes tab (slice 3)
  24008. lane.target = lynx::AutomationTarget { lynx::AutomationTargetKind::channelVolume, 0 };
  24009. for (int e = 0; e < 16; ++e)
  24010. lane.events.push_back ({ e * lynx::ppq / 4, 0.3f + 0.6f * (float) e / 15.0f });
  24011. s.patterns[0].events = { lane };
  24012. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 3));
  24013. s.playlistTracks[1].name = "Bass";
  24014. }, false);
  24015. offline.dispatchPendingMessages();
  24016. write ("pattern"); // Pattern workflow: no detail view exists
  24017. ui.setClipLaunchWorkflow (true);
  24018. offline.editSong ([] (lynx::Song& s) {
  24019. lynx::Clip clip;
  24020. clip.pattern = 0;
  24021. clip.length = 4 * lynx::ppq;
  24022. lynx::launcher::setClip (s, 1, 0, clip);
  24023. }, false);
  24024. offline.dispatchPendingMessages();
  24025. juce::String counts;
  24026. if (auto* detail = ui.getDetailViewForSnapshot())
  24027. {
  24028. detail->showSelection (1, 0);
  24029. detail->setPage (lynx::DetailView::Page::devices);
  24030. write ("devices");
  24031. counts << "cards " << detail->cardCountForCheck() << ", insert " << detail->chainInsertForCheck() << ", channel " << detail->chainChannelForCheck() << "\n";
  24032. detail->toggleFoldForCheck (3); // the reverb (card 0 is the instrument)
  24033. write ("folded");
  24034. counts << "folded card 3: " << (detail->isFoldedForCheck (3) ? 1 : 0) << "\n";
  24035. detail->showSelection (2, 0); // an empty track
  24036. write ("empty-track");
  24037. detail->showSelection (1, 0);
  24038. detail->setPage (lynx::DetailView::Page::clip);
  24039. offline.dispatchPendingMessages();
  24040. ui.getPianoRollForSnapshot().scrollToNotes(); // (the app does it on the message loop, which this shot doesn't run)
  24041. write ("clip"); // slice 2: the Piano roll docked here
  24042. {
  24043. // round 190s: the Transform panel with each MIDI tool, then Arpeggiate applied (and undone again)
  24044. auto& tools = detail->midiToolsForSnapshot();
  24045. for (int t = 0; t < lynx::MidiToolsPanel::toolCount; ++t)
  24046. {
  24047. tools.setTool (t);
  24048. write (("clip-mt-" + juce::String (lynx::MidiToolsPanel::toolName (t)).toLowerCase()).toRawUTF8());
  24049. }
  24050. // round 190aa: the pages again with the settings of the Live shots they are compared with
  24051. tools.setAuto (false);
  24052. tools.setLiveShotSettingsForSnapshot();
  24053. for (int t : { (int) lynx::MidiToolsPanel::chop, (int) lynx::MidiToolsPanel::quantize, (int) lynx::MidiToolsPanel::timeWarp })
  24054. {
  24055. tools.setTool (t);
  24056. write (("clip-mt-" + juce::String (lynx::MidiToolsPanel::toolName (t)).toLowerCase() + "-set").toRawUTF8());
  24057. }
  24058. tools.setAuto (true);
  24059. tools.setTool (lynx::MidiToolsPanel::arpeggiate);
  24060. tools.transformNow();
  24061. offline.dispatchPendingMessages();
  24062. write ("clip-mt-applied");
  24063. counts << "midi tools: arpeggiate made " << (int) offline.getSong().patterns[0].notes.size() << " notes of 4\n";
  24064. offline.undo();
  24065. offline.dispatchPendingMessages();
  24066. counts << "midi tools: undo gives " << (int) offline.getSong().patterns[0].notes.size() << " notes\n";
  24067. }
  24068. counts << "piano roll docked: " << (ui.getPianoRollForSnapshot().getParentComponent() != nullptr
  24069. && ui.getPianoRollForSnapshot().getParentComponent()->getParentComponent() == detail ? 1 : 0) << "\n";
  24070. detail->setClipTab (true); // slice 3: the pattern's events in the Envelopes tab
  24071. offline.dispatchPendingMessages();
  24072. write ("envelopes");
  24073. detail->setClipTab (false);
  24074. detail->setPage (lynx::DetailView::Page::devices);
  24075. // round 183c-card: an Audio Effect Rack in the chain draws as its own card (the rack's view, Rand / Map in its
  24076. // title bar), as Live's Device View shows a rack
  24077. offline.editSong ([] (lynx::Song& s) { s.mixer[2].effects.insert (s.mixer[2].effects.begin() + 1, shotRack()); }, false);
  24078. offline.dispatchPendingMessages();
  24079. detail->showSelection (2, 0);
  24080. detail->showSelection (1, 0);
  24081. write ("devices-rack");
  24082. counts << "rack card: cards " << detail->cardCountForCheck() << "\n";
  24083. offline.editSong ([] (lynx::Song& s) { s.mixer[2].effects.erase (s.mixer[2].effects.begin() + 1); }, false);
  24084. offline.dispatchPendingMessages();
  24085. counts << "piano roll back in its panel: " << (ui.getPianoRollForSnapshot().getParentComponent() != nullptr
  24086. && ui.getPianoRollForSnapshot().getParentComponent()->getParentComponent() != detail ? 1 : 0) << "\n";
  24087. }
  24088. else
  24089. counts << "no detail view\n";
  24090. ui.setClipLaunchWorkflow (false);
  24091. offline.dispatchPendingMessages();
  24092. write ("pattern-after");
  24093. juce::File (prefix + "-counts.txt").replaceWithText (counts);
  24094. }
  24095. void runPerfShot (const juce::String& prefix, const juce::String& projectPath)
  24096. {
  24097. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  24098. lynx::AudioEngine offline (false);
  24099. {
  24100. lynx::MainComponent ui (offline, false);
  24101. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  24102. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  24103. if (projectPath.isNotEmpty())
  24104. ui.openFile (juce::File (projectPath));
  24105. offline.dispatchPendingMessages();
  24106. // LYNX_PERFSHOT_PREPARE=1: Tools › Macros › Prepare for performance mode first (16 one-bar columns)
  24107. if (juce::SystemStats::getEnvironmentVariable ("LYNX_PERFSHOT_PREPARE", {}) == "1")
  24108. offline.editSong ([] (lynx::Song& s) { lynx::perf::prepareForPerformance (s, 16, 4 * lynx::ppq); }, false);
  24109. offline.editSong ([] (lynx::Song& s) { s.performanceMode = true; s.mode = lynx::PlayMode::song; }, false);
  24110. offline.dispatchPendingMessages();
  24111. // what the Player would publish: on each of the first tracks with zone clips, one clip playing (part way)
  24112. // and on every other one the next clip waiting for its sync point
  24113. const auto& song = offline.getSong();
  24114. auto& live = offline.performanceStateForSnapshot();
  24115. const auto zone = lynx::perf::zoneClips (song);
  24116. int lastTrack = -1, launched = 0;
  24117. for (const auto index : zone)
  24118. {
  24119. const auto& c = song.playlist[(std::size_t) index];
  24120. if (c.track == lastTrack || c.track >= lynx::perf::maxTracks)
  24121. continue;
  24122. lastTrack = c.track;
  24123. std::int64_t clips[64];
  24124. const auto n = lynx::perf::trackZoneClips (song, zone, c.track, clips, 64);
  24125. auto& view = live.tracks[(std::size_t) c.track];
  24126. view.playing.store (clips[(std::size_t) ((launched % 3) % n)]);
  24127. view.progress.store (0.2f + 0.15f * (float) (launched % 5));
  24128. if (launched % 2 == 1 && n > 1)
  24129. view.pending.store (clips[(std::size_t) ((launched % 3 + 1) % n)]);
  24130. ++launched;
  24131. }
  24132. live.anyPlaying.store (launched > 0);
  24133. ui.selectTabForSnapshot (2);
  24134. offline.dispatchPendingMessages();
  24135. auto& playlist = ui.getPlaylistForSnapshot();
  24136. savePng (lynx::shot::snapshot (playlist), prefix + "-playlist-song.png");
  24137. playlist.runAction ("playlist.zoomPerformance"); // as FL opens these demos: the zone fills the view
  24138. offline.dispatchPendingMessages();
  24139. saveSnapshot (ui, prefix + "-playlist.png");
  24140. savePng (lynx::shot::snapshot (playlist), prefix + "-playlist-only.png");
  24141. // patcherize: the first insert with effects (all of them) and the first channel that can be
  24142. auto patched = offline.getSong();
  24143. for (int t = 0; t < (int) patched.mixer.size(); ++t)
  24144. if (lynx::patcherize::slotsForAll (patched, t).size() > 1)
  24145. {
  24146. lynx::patcherize::patcherizeSlots (patched, t, 0, true);
  24147. break;
  24148. }
  24149. for (int c = 0; c < (int) patched.channels.size(); ++c)
  24150. if (lynx::patcherize::patcherizeChannel (patched, c))
  24151. break;
  24152. juce::String error;
  24153. lynx::ProjectFile::save (patched, juce::File (prefix + "-patcherized.lynx"), error);
  24154. }
  24155. }
  24156. void runPatcherShot (const juce::String& prefix, const juce::String& projectPath)
  24157. {
  24158. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  24159. lynx::AudioEngine offline (false);
  24160. {
  24161. lynx::MainComponent ui (offline, false);
  24162. ui.setSize (1280, 720);
  24163. if (projectPath.isNotEmpty())
  24164. ui.openFile (juce::File (projectPath));
  24165. else
  24166. {
  24167. auto song = lynx::Song::makeDefault();
  24168. song.mixer.resize (4);
  24169. auto slot = lynx::makeEffectSlot (lynx::EffectKind::patcher);
  24170. slot.patcher.wires.clear();
  24171. for (auto [kind, x, y] : { std::tuple { lynx::EffectKind::frequencySplitter, 200.0f, 60.0f }, { lynx::EffectKind::reverb, 420.0f, 0.0f },
  24172. { lynx::EffectKind::fruityDelay3, 420.0f, 120.0f }, { lynx::EffectKind::peakController, 200.0f, 260.0f } })
  24173. {
  24174. lynx::PatchNode n;
  24175. n.effect = lynx::makeEffectSlot (kind);
  24176. n.x = x;
  24177. n.y = y;
  24178. slot.patcher.nodes.push_back (n);
  24179. }
  24180. { // round 165c: a Hardware Insert node (its editor opens from the node)
  24181. lynx::PatchNode n;
  24182. n.effect = lynx::makeEffectSlot (lynx::EffectKind::hardwareInsert);
  24183. n.x = 420.0f, n.y = 260.0f;
  24184. slot.patcher.nodes.push_back (n);
  24185. }
  24186. auto wire = [&] (int from, int fromPort, int to, int toPort, float gain = 1.0f, lynx::PatchWire::Kind kind = lynx::PatchWire::Kind::audio) {
  24187. lynx::PatchWire w;
  24188. w.kind = kind;
  24189. w.from = from, w.fromPort = fromPort, w.to = to, w.toPort = toPort, w.gain = gain;
  24190. slot.patcher.wires.push_back (w);
  24191. };
  24192. wire (lynx::patchFromHost, 0, 0, 0);
  24193. wire (0, 1, 1, 0);
  24194. wire (0, 3, 2, 0, 0.5f);
  24195. wire (1, 0, lynx::patchToHost, 0);
  24196. wire (2, 0, lynx::patchToHost, 0);
  24197. wire (lynx::patchFromHost, 1, 3, 0);
  24198. wire (3, 1, 2, 2, 1.0f, lynx::PatchWire::Kind::control);
  24199. wire (0, 2, lynx::patchToHost, 1, 0.7f);
  24200. // round 171b (issue #65): a Surface knob on the reverb's parameter input 1, the reverb's parameter 0 out to
  24201. // the delay's parameter input 2 (FL's Inputs / Outputs › Parameters)
  24202. {
  24203. lynx::SurfaceControl knob;
  24204. knob.name = "Knob 1";
  24205. knob.value = 0.6f;
  24206. slot.patcher.surface = { knob };
  24207. slot.patcher.surfaceX = 200.0f, slot.patcher.surfaceY = 380.0f;
  24208. lynx::patcher::setParamInput (slot.patcher, 1, 1, true, "Reverb - 2");
  24209. lynx::patcher::setParamOutput (slot.patcher, 1, 0, true);
  24210. lynx::patcher::setParamInput (slot.patcher, 2, 2, true, "Delay - 3");
  24211. wire (lynx::patchSurface, 0, 1, 1, 1.0f, lynx::PatchWire::Kind::control);
  24212. wire (1, lynx::patchParamOutput (0), 2, 2, 1.0f, lynx::PatchWire::Kind::control);
  24213. }
  24214. slot.patcher.outputTracks = { 3 };
  24215. slot.patcher.inputX = -20.0f;
  24216. slot.patcher.outputX = 660.0f;
  24217. song.mixer[1].effects = { slot };
  24218. lynx::ChannelDef ch;
  24219. ch.name = "Patcher";
  24220. ch.instrument = lynx::InstrumentKind::patcher;
  24221. lynx::PatchNode synth, chorus;
  24222. synth.generator = true;
  24223. synth.channel.instrument = lynx::InstrumentKind::synth;
  24224. synth.channel.name = "Synth";
  24225. synth.x = 220.0f;
  24226. chorus.effect = lynx::makeEffectSlot (lynx::EffectKind::chorus);
  24227. chorus.x = 420.0f;
  24228. // round 162: a MIDI Out node between the "MIDI port 5" pin and "To LYNX" MIDI port 3, an Envelope Controller
  24229. // on the notes moving the chorus
  24230. lynx::PatchNode midiOut, envelope;
  24231. midiOut.generator = envelope.generator = true;
  24232. midiOut.channel.instrument = lynx::InstrumentKind::midiOut;
  24233. midiOut.channel.name = "MIDI Out";
  24234. lynx::midictl::writeMidiOut (midiOut.channel.pluginState, { 3, 0, 0, -1, -1 });
  24235. midiOut.x = 220.0f, midiOut.y = 160.0f;
  24236. envelope.channel.instrument = lynx::InstrumentKind::controller;
  24237. envelope.channel.name = "Envelope Controller";
  24238. envelope.channel.controllerState = lynx::writeEnvelopeController (lynx::defaultEnvelopeController());
  24239. envelope.x = 220.0f, envelope.y = 260.0f;
  24240. lynx::PatchNode osc; // round 164f: an FL engine node (its editor opens from the node)
  24241. osc.generator = true;
  24242. osc.channel = lynx::natives::makeChannel (lynx::InstrumentKind::threeosc, lynx::flStudioAccess()).value_or (lynx::ChannelDef {});
  24243. osc.channel.instrument = lynx::InstrumentKind::threeosc;
  24244. osc.channel.name = "3x Osc";
  24245. osc.x = 420.0f, osc.y = 260.0f;
  24246. // round 165c: Keyboard Controller, SoundFont player, Granulizer and Dashboard nodes (their editors open from the node)
  24247. lynx::PatchNode keys, soundfont, granulizer, dashboard;
  24248. keys.generator = soundfont.generator = granulizer.generator = dashboard.generator = true;
  24249. keys.channel.instrument = lynx::InstrumentKind::controller;
  24250. keys.channel.name = "Keyboard Controller";
  24251. {
  24252. lynx::KeyboardControllerData ramp;
  24253. for (std::size_t k = 0; k < ramp.keys.size(); ++k)
  24254. ramp.keys[k] = (float) k / (float) (ramp.keys.size() - 1);
  24255. lynx::writeKeyboardController (ramp, keys.channel.controllerState);
  24256. }
  24257. soundfont.channel = lynx::sf::makeChannel();
  24258. granulizer.channel = lynx::natives::makeChannel (lynx::InstrumentKind::granulizer, lynx::flStudioAccess()).value_or (lynx::ChannelDef {});
  24259. granulizer.channel.instrument = lynx::InstrumentKind::granulizer;
  24260. granulizer.channel.name = "Fruity Granulizer";
  24261. dashboard.channel.instrument = lynx::InstrumentKind::dashboard;
  24262. dashboard.channel.name = "Dashboard";
  24263. dashboard.channel.patcher.surface = lynx::surface::starterControls();
  24264. keys.x = 20.0f, keys.y = 440.0f;
  24265. soundfont.x = 220.0f, soundfont.y = 440.0f;
  24266. granulizer.x = 420.0f, granulizer.y = 440.0f;
  24267. dashboard.x = 20.0f, dashboard.y = 540.0f;
  24268. // and a Layer node playing the SoundFont and Granulizer nodes on its Children pin (crossfaded)
  24269. lynx::PatchNode layerNode;
  24270. layerNode.generator = true;
  24271. layerNode.channel.instrument = lynx::InstrumentKind::layer;
  24272. layerNode.channel.name = "Layer";
  24273. layerNode.channel.layer.crossfade = true;
  24274. layerNode.channel.layer.fade = 0.35f;
  24275. layerNode.x = 220.0f, layerNode.y = 540.0f;
  24276. ch.patcher.nodes = { synth, chorus, midiOut, envelope, osc, keys, soundfont, granulizer, dashboard, layerNode };
  24277. lynx::PatchWire notes, a, b, portIn, portOut, envNotes, envControl;
  24278. notes.kind = lynx::PatchWire::Kind::midi, notes.to = 0;
  24279. a.from = 0, a.to = 1;
  24280. b.from = 1;
  24281. portIn.kind = lynx::PatchWire::Kind::midi, portIn.fromPort = lynx::patchMidiPortPin (5), portIn.to = 2;
  24282. portOut.kind = lynx::PatchWire::Kind::midi, portOut.from = 2, portOut.to = lynx::patchToHost, portOut.toPort = 3;
  24283. envNotes.kind = lynx::PatchWire::Kind::midi, envNotes.to = 3;
  24284. envControl.kind = lynx::PatchWire::Kind::control, envControl.from = 3, envControl.to = 1, envControl.toPort = 0;
  24285. lynx::PatchWire oscNotes, oscOut;
  24286. oscNotes.kind = lynx::PatchWire::Kind::midi, oscNotes.to = 4;
  24287. oscOut.from = 4;
  24288. lynx::PatchWire layerNotes, layerToFont, layerToGrains, fontOut, grainsOut;
  24289. layerNotes.kind = layerToFont.kind = layerToGrains.kind = lynx::PatchWire::Kind::midi;
  24290. layerNotes.to = 9;
  24291. layerToFont.from = 9, layerToFont.to = 6;
  24292. layerToGrains.from = 9, layerToGrains.to = 7;
  24293. fontOut.from = 6;
  24294. grainsOut.from = 7;
  24295. ch.patcher.wires = { notes, a, b, portIn, portOut, envNotes, envControl, oscNotes, oscOut, layerNotes, layerToFont, layerToGrains, fontOut, grainsOut };
  24296. ch.patcher.fromMidiPorts = { 1, 5 };
  24297. ch.patcher.toMidiPorts = { 3 };
  24298. ch.patcher.outputX = 640.0f;
  24299. song.channels.push_back (ch);
  24300. // LYNX_PATCHERSHOT_SAVE=file.lynx: the demo as a project (a GUI check of the same Patchers, round 164f)
  24301. if (const auto save = juce::SystemStats::getEnvironmentVariable ("LYNX_PATCHERSHOT_SAVE", {}); save.isNotEmpty())
  24302. {
  24303. if (! song.patterns.empty())
  24304. for (int k = 0; k < 4; ++k)
  24305. 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 });
  24306. juce::String error;
  24307. lynx::ProjectFile::save (song, juce::File (save), error);
  24308. // round 171b: the saved Patchers come back the same (parameter ports, event cables, published)
  24309. juce::String report;
  24310. if (const auto loaded = lynx::ProjectFile::load (juce::File (save), error))
  24311. {
  24312. const auto same = loaded->mixer.size() > 1 && ! loaded->mixer[1].effects.empty()
  24313. && loaded->mixer[1].effects[0].patcher == song.mixer[1].effects[0].patcher;
  24314. const auto& d = loaded->mixer.size() > 1 && ! loaded->mixer[1].effects.empty() ? loaded->mixer[1].effects[0].patcher : lynx::PatcherDoc {};
  24315. report << "patcher round trip: " << (same ? "OK" : "DIFFERENT") << "\n";
  24316. if (! same && loaded->mixer.size() > 1 && ! loaded->mixer[1].effects.empty())
  24317. {
  24318. const auto& a = song.mixer[1].effects[0].patcher;
  24319. report << "wires " << (a.wires == d.wires ? "same" : "differ") << ", published " << (a.published == d.published ? "same" : "differ")
  24320. << ", surface " << (a.surface == d.surface ? "same" : "differ") << "\n";
  24321. for (std::size_t n = 0; n < std::min (a.nodes.size(), d.nodes.size()); ++n)
  24322. if (! (a.nodes[n] == d.nodes[n]))
  24323. report << "node " << (int) n << " differs: ports " << (a.nodes[n].paramIns == d.nodes[n].paramIns && a.nodes[n].paramOuts == d.nodes[n].paramOuts ? "same" : "differ")
  24324. << ", effect " << (a.nodes[n].effect == d.nodes[n].effect ? "same" : "differ") << ", xy "
  24325. << (a.nodes[n].x == d.nodes[n].x && a.nodes[n].y == d.nodes[n].y ? "same" : "differ") << "\n";
  24326. }
  24327. for (int n = 0; n < (int) d.nodes.size(); ++n)
  24328. report << "node " << n << " paramIns " << (int) d.nodes[(std::size_t) n].paramIns.size() << " paramOuts "
  24329. << (int) d.nodes[(std::size_t) n].paramOuts.size() << "\n";
  24330. for (const auto& w : d.wires)
  24331. if (w.kind == lynx::PatchWire::Kind::control)
  24332. report << "control " << w.from << ":" << w.fromPort << " -> " << w.to << ":" << w.toPort << "\n";
  24333. for (const auto& p : d.published)
  24334. report << "published " << p.node << ":" << p.param << " " << juce::String::fromUTF8 (p.name.c_str()) << "\n";
  24335. }
  24336. else
  24337. report << "patcher round trip: load failed: " << error << "\n";
  24338. juce::File (prefix + "-roundtrip.txt").replaceWithText (report);
  24339. }
  24340. offline.setSong (std::move (song));
  24341. }
  24342. offline.dispatchPendingMessages();
  24343. const auto& song = offline.getSong();
  24344. auto shootOpen = [&] (const juce::String& name) {
  24345. for (int k = 0; k < juce::TopLevelWindow::getNumTopLevelWindows(); ++k)
  24346. if (auto* w = dynamic_cast<juce::DocumentWindow*> (juce::TopLevelWindow::getTopLevelWindow (k)))
  24347. if (w->getName().startsWith (lynx::tr ("Patcher")) && w->getContentComponent() != nullptr)
  24348. {
  24349. auto* c = w->getContentComponent();
  24350. savePng (lynx::shot::snapshot (*c), prefix + name);
  24351. delete w;
  24352. return;
  24353. }
  24354. };
  24355. int shots = 0;
  24356. for (int t = 0; t < (int) song.mixer.size() && shots < 12; ++t)
  24357. for (int s = 0; s < (int) song.mixer[(std::size_t) t].effects.size(); ++s)
  24358. if (song.mixer[(std::size_t) t].effects[(std::size_t) s].kind == lynx::EffectKind::patcher)
  24359. {
  24360. lynx::PatcherWindows::openSlot (offline, t, s);
  24361. shootOpen ("-insert" + juce::String (t) + "-slot" + juce::String (s) + ".png");
  24362. // each built-in node's editor, as a double-click opens it (round 165c)
  24363. lynx::PatcherWindows::shootNodeEditors (offline, false, t, s, [&] (const juce::Image& image, int n) {
  24364. savePng (image, prefix + "-insert" + juce::String (t) + "-slot" + juce::String (s) + "-node" + juce::String (n) + ".png");
  24365. });
  24366. ++shots;
  24367. if (shots == 1) // its menus (round 162)
  24368. lynx::PatcherWindows::shootMenus (offline, false, t, s, [&] (const juce::Image& image, const juce::String& name) {
  24369. savePng (image, prefix + "-menu-" + name + ".png");
  24370. });
  24371. }
  24372. for (int c = 0; c < (int) song.channels.size(); ++c)
  24373. if (song.channels[(std::size_t) c].instrument == lynx::InstrumentKind::patcher)
  24374. {
  24375. lynx::PatcherWindows::openChannel (offline, c);
  24376. shootOpen ("-channel" + juce::String (c) + ".png");
  24377. // each node's editor, as a double-click opens it (round 164f; every built-in node since round 165c)
  24378. lynx::PatcherWindows::shootNodeEditors (offline, true, c, 0, [&] (const juce::Image& image, int n) {
  24379. savePng (image, prefix + "-channel" + juce::String (c) + "-node" + juce::String (n) + ".png");
  24380. });
  24381. lynx::PatcherWindows::shootMenus (offline, true, c, 0, [&] (const juce::Image& image, const juce::String& name) {
  24382. savePng (image, prefix + "-channel" + juce::String (c) + "-menu-" + name + ".png");
  24383. });
  24384. }
  24385. }
  24386. }
  24387. // Issue #64: FL's letter keys in a plugin menu (quickpick::showMenu), checked on the real menu windows
  24388. struct TypeAheadTest final : private juce::Timer
  24389. {
  24390. juce::File out;
  24391. juce::StringArray log;
  24392. int step = 0, picked = 0;
  24393. bool ok = true, menuShown = false;
  24394. std::unique_ptr<juce::DocumentWindow> owner;
  24395. juce::PopupMenu pending;
  24396. static juce::String highlighted()
  24397. {
  24398. if (auto* window = juce::Component::getCurrentlyModalComponent())
  24399. for (auto* child : window->getChildren())
  24400. if (auto* h = child->getAccessibilityHandler(); h != nullptr && h->hasFocus (false))
  24401. return h->getTitle();
  24402. return "(none)";
  24403. }
  24404. static void press (const juce::KeyPress& key)
  24405. {
  24406. if (auto* window = juce::Component::getCurrentlyModalComponent())
  24407. if (auto* peer = window->getPeer())
  24408. peer->handleKeyPress (key);
  24409. }
  24410. void expect (const juce::String& what, const juce::String& got, const juce::String& wanted)
  24411. {
  24412. const auto good = got == wanted;
  24413. ok = ok && good;
  24414. log.add ((good ? "ok " : "FAIL ") + what + ": " + got + (good ? juce::String() : " (wanted " + wanted + ")"));
  24415. }
  24416. void start()
  24417. {
  24418. juce::PopupMenu menu, sub;
  24419. auto item = [this] (juce::PopupMenu& m, int id, const char* text, bool enabled = true) {
  24420. m.addItem (text, enabled, false, [this, id] { picked = id; });
  24421. };
  24422. menu.addSectionHeader ("LYNX SHARE");
  24423. item (menu, 1, "Echoform");
  24424. item (menu, 2, "EQ");
  24425. item (menu, 3, "Halo");
  24426. menu.addSectionHeader ("Misc");
  24427. item (menu, 4, "Effector");
  24428. item (menu, 5, "Exciter (unavailable)", false);
  24429. item (sub, 10, "Delay");
  24430. item (sub, 11, "Edison");
  24431. item (sub, 12, "Eventide");
  24432. menu.addSubMenu ("Tree", sub);
  24433. // the menu belongs to a window in the foreground, as when the user right-clicks a mixer slot (JUCE closes a
  24434. // menu of a background process at once)
  24435. owner = std::make_unique<juce::DocumentWindow> ("LYNX type-ahead test", juce::Colours::black, 0);
  24436. owner->setBounds (200, 200, 300, 200);
  24437. owner->setVisible (true);
  24438. lynx::forceForegroundForTest (*owner);
  24439. pending = menu; // shown once the window is up and active (X11 maps and activates it asynchronously)
  24440. startTimer (300);
  24441. }
  24442. void timerCallback() override
  24443. {
  24444. const auto e = juce::KeyPress ('e', {}, 'e');
  24445. if (step == 0 && owner != nullptr && ! menuShown)
  24446. {
  24447. menuShown = true;
  24448. lynx::forceForegroundForTest (*owner);
  24449. lynx::quickpick::showMenu (pending, juce::PopupMenu::Options().withTargetComponent (owner.get()), {});
  24450. return;
  24451. }
  24452. switch (step++)
  24453. {
  24454. case 0: expect ("menu open", juce::String ((int) (juce::Component::getCurrentlyModalComponent() != nullptr)), "1"); break;
  24455. case 1: press (e); expect ("e", highlighted(), "Echoform"); break;
  24456. case 2: press (e); expect ("e again", highlighted(), "EQ"); break;
  24457. case 3: press (juce::KeyPress ('E', juce::ModifierKeys::shiftModifier, 'E')); expect ("E (shift)", highlighted(), "Effector"); break;
  24458. case 4: press (e); expect ("e wraps (skips the disabled one)", highlighted(), "Echoform"); break;
  24459. case 5: press (juce::KeyPress ('m', {}, 'm')); expect ("m (only a heading starts with it: no move)", highlighted(), "Echoform"); break;
  24460. case 6: press (juce::KeyPress (juce::KeyPress::downKey)); expect ("down arrow", highlighted(), "EQ"); break;
  24461. case 7: press (e); expect ("e after the arrow", highlighted(), "Effector"); break;
  24462. case 8: press (juce::KeyPress ('t', {}, 't')); expect ("t", highlighted(), "Tree"); break;
  24463. case 9: press (juce::KeyPress (juce::KeyPress::rightKey)); break; // opens the submenu (it takes the keys)
  24464. case 10: press (e); expect ("e in the submenu", highlighted(), "Edison"); break;
  24465. case 11: press (e); expect ("e again in the submenu", highlighted(), "Eventide"); break;
  24466. case 12: expect ("nothing picked by the letters", juce::String (picked), "0"); press (juce::KeyPress (juce::KeyPress::returnKey)); break;
  24467. case 13: break;
  24468. default:
  24469. expect ("Enter closed the menu", juce::String ((int) (juce::Component::getCurrentlyModalComponent() == nullptr)), "1");
  24470. expect ("Enter picked", juce::String (picked), "12");
  24471. stopTimer();
  24472. owner.reset();
  24473. log.add (ok ? "result=OK" : "result=FAIL");
  24474. out.replaceWithText (log.joinIntoString ("\n") + "\n");
  24475. juce::JUCEApplication::getInstance()->setApplicationReturnValue (ok ? 0 : 1);
  24476. juce::JUCEApplication::quit();
  24477. return;
  24478. }
  24479. }
  24480. };
  24481. std::unique_ptr<TypeAheadTest> typeAheadTest;
  24482. struct ChooserTest final : private juce::Timer
  24483. {
  24484. juce::File out, file;
  24485. juce::StringArray log;
  24486. std::unique_ptr<juce::FileChooser> chooser;
  24487. double started = 0;
  24488. bool shot = false, done = false;
  24489. void start()
  24490. {
  24491. log.add ("LYNX_FILE_DIALOG=" + juce::SystemStats::getEnvironmentVariable ("LYNX_FILE_DIALOG", {}));
  24492. log.add ("native=" + juce::String ((int) lynx::ui::filechooser::nativeDialogs()));
  24493. chooser = lynx::ui::makeFileChooser ("Open audio file", file.getParentDirectory(), "*.wav;*.flac");
  24494. started = juce::Time::getMillisecondCounterHiRes();
  24495. lynx::ui::launchChooser (chooser, juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectFiles,
  24496. [this] (const juce::FileChooser& fc) { finish (fc.getResult()); });
  24497. startTimer (200);
  24498. }
  24499. static juce::FileChooserDialogBox* builtInDialog()
  24500. {
  24501. for (int i = 0; i < juce::Desktop::getInstance().getNumComponents(); ++i)
  24502. if (auto* box = dynamic_cast<juce::FileChooserDialogBox*> (juce::Desktop::getInstance().getComponent (i)); box != nullptr && box->isShowing())
  24503. return box;
  24504. return nullptr;
  24505. }
  24506. static juce::FileBrowserComponent* findBrowser (juce::Component& c)
  24507. {
  24508. if (auto* b = dynamic_cast<juce::FileBrowserComponent*> (&c))
  24509. return b;
  24510. for (auto* child : c.getChildren())
  24511. if (auto* b = findBrowser (*child))
  24512. return b;
  24513. return nullptr;
  24514. }
  24515. void timerCallback() override
  24516. {
  24517. if (done)
  24518. return;
  24519. if (auto* box = builtInDialog(); box != nullptr && ! shot)
  24520. {
  24521. shot = true;
  24522. log.add ("built-in dialog shown after " + juce::String (juce::roundToInt (juce::Time::getMillisecondCounterHiRes() - started)) + " ms");
  24523. const auto image = lynx::shot::snapshot (*box);
  24524. juce::FileOutputStream png (out.getSiblingFile (out.getFileName() + ".png"));
  24525. if (png.openedOk())
  24526. {
  24527. png.setPosition (0), png.truncate();
  24528. juce::PNGImageFormat().writeImageToStream (image, png);
  24529. }
  24530. if (auto* browser = findBrowser (*box))
  24531. {
  24532. browser->setRoot (file.getParentDirectory());
  24533. browser->setFileName (file.getFileName());
  24534. log.add ("typed " + file.getFileName());
  24535. box->exitModalState (1);
  24536. }
  24537. else
  24538. log.add ("no file browser in the dialog");
  24539. }
  24540. if (juce::Time::getMillisecondCounterHiRes() - started > 30000.0)
  24541. finish ({}, "timeout");
  24542. }
  24543. void finish (const juce::File& result, const juce::String& why = {})
  24544. {
  24545. if (done)
  24546. return;
  24547. done = true;
  24548. stopTimer();
  24549. log.add ("callback after " + juce::String (juce::roundToInt (juce::Time::getMillisecondCounterHiRes() - started)) + " ms: "
  24550. + (why.isNotEmpty() ? why : result.getFullPathName().isEmpty() ? juce::String ("(no file)") : result.getFullPathName()));
  24551. log.add ("native now=" + juce::String ((int) lynx::ui::filechooser::nativeDialogs()));
  24552. const auto ok = result == file && result.existsAsFile();
  24553. log.add (ok ? "result=OK" : "result=FAIL");
  24554. out.replaceWithText (log.joinIntoString ("\n") + "\n");
  24555. juce::JUCEApplication::getInstance()->setApplicationReturnValue (ok ? 0 : 1);
  24556. juce::MessageManager::callAsync ([] { juce::JUCEApplication::quit(); });
  24557. }
  24558. };
  24559. std::unique_ptr<ChooserTest> chooserTest;
  24560. void runChooserTest (const juce::File& out, const juce::File& file)
  24561. {
  24562. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  24563. chooserTest = std::make_unique<ChooserTest>();
  24564. chooserTest->out = out;
  24565. chooserTest->file = file;
  24566. chooserTest->start();
  24567. }
  24568. void runTypeAheadTest (const juce::File& out)
  24569. {
  24570. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  24571. typeAheadTest = std::make_unique<TypeAheadTest>();
  24572. typeAheadTest->out = out;
  24573. typeAheadTest->start();
  24574. }
  24575. void runStabilityShot (const juce::String& folder)
  24576. {
  24577. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  24578. const juce::File dir (folder);
  24579. dir.createDirectory();
  24580. {
  24581. lynx::AudioEngine offline (false);
  24582. const auto save = [&dir] (std::unique_ptr<juce::Component> c, const juce::String& name) {
  24583. juce::Component frame;
  24584. frame.setSize (c->getWidth(), c->getHeight());
  24585. frame.setOpaque (true);
  24586. if (c->isOnDesktop()) // (an AlertWindow: never shown, so it takes no foreground)
  24587. c->removeFromDesktop();
  24588. frame.addAndMakeVisible (*c);
  24589. c->setTopLeftPosition (0, 0);
  24590. const auto image = lynx::shot::paint (frame, lynx::theme::panel);
  24591. const auto file = dir.getChildFile (name);
  24592. file.deleteFile();
  24593. juce::PNGImageFormat png;
  24594. if (auto out = file.createOutputStream())
  24595. png.writeImageToStream (image, *out);
  24596. };
  24597. save (lynx::PluginWindows::makeCrashPromptPanel ("Serum", false), "crash-prompt.png");
  24598. save (lynx::PluginWindows::makeCrashPromptPanel ("Serum", true), "crash-prompt-onload.png");
  24599. save (lynx::PluginWindows::makeCrashNoticePanel ("Serum", true), "crash-notice.png");
  24600. save (lynx::makePluginManagerPanel (offline, false), "plugin-manager.png");
  24601. save (lynx::makePluginMonitorPanel (offline), "plugin-monitor.png");
  24602. }
  24603. setApplicationReturnValue (0);
  24604. quit();
  24605. }
  24606. void runSnapshot (const juce::String& prefix, const juce::String& projectPath)
  24607. {
  24608. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  24609. // LYNX_SNAPSHOT_THEME=file.lynxtheme: the pictures in that theme (round 162d)
  24610. if (const auto themeFile = juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_THEME", {}); themeFile.isNotEmpty())
  24611. if (const auto spec = lynx::themeui::loadFile (juce::File (themeFile)))
  24612. lynx::themeui::apply (*spec, false);
  24613. {
  24614. lynx::AudioEngine offline (false);
  24615. lynx::MainComponent ui (offline, false); // default layout and keys, nothing saved
  24616. // LYNX_SNAPSHOT_SIZE=WxH (default 1280x720)
  24617. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1280x720"), "x", "");
  24618. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  24619. if (projectPath.isNotEmpty())
  24620. ui.openFile (juce::File (projectPath));
  24621. offline.dispatchPendingMessages(); // change notifications are asynchronous
  24622. ui.waitForBrowserForSnapshot();
  24623. // the workspace desktop: the default layout, then with the Piano Roll and Mixer floating too
  24624. // (and a sample hint in the status strip, as when hovering a knob)
  24625. ui.showDesktopForSnapshot (false);
  24626. ui.setMetersForSnapshot (0.23, (std::int64_t) 412 << 20, 6);
  24627. offline.dispatchPendingMessages();
  24628. saveSnapshot (ui, prefix + "-desktop.png");
  24629. // the first start: the setup wizard over the main window (round 140), also on a small screen (it scrolls)
  24630. {
  24631. const auto size = ui.getBounds();
  24632. ui.showSetupWizard();
  24633. offline.dispatchPendingMessages();
  24634. saveSnapshot (ui, prefix + "-desktop-setup.png");
  24635. ui.setSize (1024, 600);
  24636. offline.dispatchPendingMessages();
  24637. saveSnapshot (ui, prefix + "-desktop-setup-small.png");
  24638. ui.closeSetupWizardForSnapshot();
  24639. ui.setBounds (size);
  24640. offline.dispatchPendingMessages();
  24641. }
  24642. // the start-up desktop and the toolbar at the usual window sizes: the untouched default layout
  24643. // follows the window (default rects, not scaled ones); panels drop from the toolbar by priority
  24644. {
  24645. const auto size = ui.getBounds();
  24646. for (const auto& [w, h] : std::vector<std::pair<int, int>> { { 1280, 720 }, { 1366, 768 }, { 1600, 900 }, { 1920, 1080 }, { 2560, 1440 }, { 3840, 2160 } })
  24647. {
  24648. ui.setSize (w, h);
  24649. offline.dispatchPendingMessages();
  24650. saveSnapshot (ui, prefix + "-desktop-" + juce::String (w) + ".png");
  24651. saveArea (ui, ui.getToolbarBoundsForSnapshot(), prefix + "-toolbar-" + juce::String (w) + ".png");
  24652. if (w == 1920) // the rack scrolled to its last steps: the controls column stays in view (round 90)
  24653. {
  24654. ui.scrollRackForSnapshot (100000);
  24655. offline.dispatchPendingMessages();
  24656. saveSnapshot (ui, prefix + "-desktop-rack-scrolled.png");
  24657. ui.scrollRackForSnapshot (0);
  24658. }
  24659. }
  24660. // the toolbar with small and large icons, and a customized one (groups hidden and reordered)
  24661. ui.setSize (1600, 900);
  24662. for (auto [iconSize, name] : { std::pair { lynx::toolbarlayout::IconSize::small, "small" }, { lynx::toolbarlayout::IconSize::large, "large" } })
  24663. {
  24664. auto layout = lynx::toolbarlayout::Layout::makeDefault();
  24665. layout.iconSize = iconSize;
  24666. ui.setToolbarLayoutForSnapshot (layout);
  24667. saveArea (ui, ui.getToolbarBoundsForSnapshot(), prefix + "-toolbar-" + name + "-1600.png");
  24668. }
  24669. {
  24670. auto layout = lynx::toolbarlayout::Layout::makeDefault();
  24671. layout.move (lynx::toolbarlayout::Group::windows, -3);
  24672. layout.setShown (lynx::toolbarlayout::Group::record, false);
  24673. layout.setShown (lynx::toolbarlayout::Group::meters, false);
  24674. ui.setToolbarLayoutForSnapshot (layout);
  24675. saveArea (ui, ui.getToolbarBoundsForSnapshot(), prefix + "-toolbar-custom-1600.png");
  24676. }
  24677. {
  24678. // round 170e: the toolbar after a knob was moved: the last tweaked read-out (its caption) and the snap magnet
  24679. ui.setSize (1920, 1080); // the read-out needs room beside the hint bar
  24680. ui.setToolbarLayoutForSnapshot (lynx::toolbarlayout::Layout::makeDefault());
  24681. lynx::AutomationTarget t;
  24682. t.kind = lynx::AutomationTargetKind::mixerVolume;
  24683. t.index = 0;
  24684. offline.noteTweaked (t);
  24685. ui.refreshTweakReadoutForSnapshot();
  24686. offline.dispatchPendingMessages();
  24687. saveArea (ui, ui.getToolbarBoundsForSnapshot(), prefix + "-toolbar-tweak-1920.png");
  24688. ui.setSize (1600, 900);
  24689. }
  24690. {
  24691. // the toolbar's edit mode (round 115): outlined panels and the tray of panels under it
  24692. ui.setToolbarLayoutForSnapshot (lynx::toolbarlayout::Layout::makeDefault());
  24693. auto layout = lynx::toolbarlayout::Layout::makeDefault();
  24694. layout.setShown (lynx::toolbarlayout::Group::meters, false);
  24695. ui.setToolbarLayoutForSnapshot (layout);
  24696. ui.setToolbarEditingForSnapshot (true);
  24697. offline.dispatchPendingMessages();
  24698. saveArea (ui, ui.getToolbarBoundsForSnapshot().withHeight (ui.getToolbarAndTrayHeightForSnapshot()), prefix + "-toolbar-edit-1600.png");
  24699. ui.setToolbarEditingForSnapshot (false);
  24700. // Ctrl+F11: only the menu and the hint bar
  24701. layout = lynx::toolbarlayout::Layout::makeDefault();
  24702. layout.visible = false;
  24703. ui.setToolbarLayoutForSnapshot (layout);
  24704. saveArea (ui, ui.getLocalBounds().withHeight (120), prefix + "-toolbar-hidden-1600.png");
  24705. }
  24706. ui.setToolbarLayoutForSnapshot (lynx::toolbarlayout::Layout::makeDefault());
  24707. // quick tips: the toolbar and title bars with a few name bubbles, and every tip on one sheet
  24708. offline.dispatchPendingMessages();
  24709. saveQuickTips (ui, prefix);
  24710. ui.setBounds (size);
  24711. offline.dispatchPendingMessages();
  24712. }
  24713. // the hint bar: a value control while it is dragged (live value), a gesture line with mouse and key
  24714. // glyphs, and a text too long for one line (two lines)
  24715. {
  24716. const auto toolbar = ui.getToolbarBoundsForSnapshot().withWidth (juce::jmin (ui.getWidth(), 900));
  24717. const lynx::ui::Hint hints[] = {
  24718. { lynx::tr ("Volume") + " - " + lynx::tr ("drag (Ctrl: fine), wheel, Alt+click resets"), "-3.2 dB", true, true },
  24719. { lynx::tr ("Piano Roll: [LMB] add a note, drag to move [RMB] delete [Ctrl][LMB] drag to select [Ctrl][Wheel] zoom"), {}, false, false },
  24720. { lynx::tr ("Global snap: the grid of the Piano Roll and Playlist (when they follow it) and the quantise of recorded notes "
  24721. "[LMB] choose [Wheel] step [RMB] length of new notes [Backspace] snap on/off [Alt] while dragging: no snap"), {}, false, true },
  24722. };
  24723. for (int i = 0; i < 3; ++i)
  24724. {
  24725. ui.setHintForSnapshot (hints[i], i == 0);
  24726. saveArea (ui, toolbar, prefix + "-hint-" + juce::String (i + 1) + ".png");
  24727. }
  24728. }
  24729. ui.showDesktopForSnapshot (true);
  24730. ui.setHintForSnapshot ({ lynx::tr ("Volume") + " - " + lynx::tr ("drag (Ctrl: fine), wheel, Alt+click resets"), "78%", true, true });
  24731. saveSnapshot (ui, prefix + "-desktop-all.png");
  24732. ui.selectTabForSnapshot (0);
  24733. saveSnapshot (ui, prefix + "-rack.png");
  24734. {
  24735. // a pattern with piano-roll notes: those rows show a miniature instead of steps (round 90)
  24736. int found = -1;
  24737. const auto before = offline.getSong().currentPattern;
  24738. {
  24739. const auto& song = offline.getSong();
  24740. for (int p = 0; p < (int) song.patterns.size() && found < 0; ++p)
  24741. for (int c = 0; c < (int) song.channels.size() && found < 0; ++c)
  24742. if (lynx::showsNotePreview (song.patterns[(std::size_t) p], c))
  24743. found = p;
  24744. }
  24745. if (found >= 0)
  24746. {
  24747. offline.editSong ([found] (lynx::Song& s) { s.currentPattern = found; }, false);
  24748. offline.dispatchPendingMessages();
  24749. saveSnapshot (ui, prefix + "-rack-preview.png");
  24750. offline.editSong ([before] (lynx::Song& s) { s.currentPattern = before; }, false);
  24751. offline.dispatchPendingMessages();
  24752. }
  24753. }
  24754. ui.selectTabForSnapshot (1);
  24755. saveSnapshot (ui, prefix + "-pianoroll.png");
  24756. {
  24757. // View › Keyboard style › Piano keys (round 190j, discussion #136), also with tall keys
  24758. auto& roll = ui.getPianoRollForSnapshot();
  24759. lynx::PianoRollComponent::keyStyle = lynx::pianokeys::Style::piano;
  24760. roll.repaint();
  24761. saveSnapshot (ui, prefix + "-pianoroll-pianokeys.png");
  24762. lynx::PianoRollComponent::keyStyle = lynx::pianokeys::Style::flat;
  24763. roll.repaint();
  24764. // round 190j (discussion #10): the toolbar in a narrow window: the chord stamp as an icon button, and
  24765. // the menu button still there
  24766. for (int narrower : { 150, 270, 330 })
  24767. {
  24768. roll.squeezeToolbarForSnapshot (narrower);
  24769. saveSnapshot (ui, prefix + "-pianoroll-narrow" + juce::String (narrower) + ".png");
  24770. roll.squeezeToolbarForSnapshot (-narrower);
  24771. }
  24772. }
  24773. if (const auto strip = ui.getToolStripAreaForSnapshot (false); ! strip.isEmpty())
  24774. saveArea (ui, strip, prefix + "-pianoroll-tools.png");
  24775. // the editors' mouse feel: the hovered note / clip edge (grip, outline) and its hint in the hint bar
  24776. ui.setHintForSnapshot (ui.getPianoRollForSnapshot().hoverForSnapshot());
  24777. saveSnapshot (ui, prefix + "-pianoroll-hover.png");
  24778. {
  24779. // a pattern with note Chance or a Velocity Range (round 187c): the Piano roll with those lanes
  24780. const auto& song = offline.getSong();
  24781. const auto& notes = song.patterns[(std::size_t) std::clamp (song.currentPattern, 0, (int) song.patterns.size() - 1)].notes;
  24782. if (std::any_of (notes.begin(), notes.end(), [] (const lynx::Note& n) { return n.hasChance(); }))
  24783. {
  24784. auto& roll = ui.getPianoRollForSnapshot();
  24785. ui.setHintForSnapshot ({});
  24786. for (const auto& [lane, name] : { std::pair { lynx::PianoRollComponent::laneChance, "chance" },
  24787. { lynx::PianoRollComponent::laneVelocityRange, "velrange" },
  24788. { lynx::PianoRollComponent::laneVelocity, "velocity" } })
  24789. {
  24790. roll.setLaneForSnapshot (lane);
  24791. offline.dispatchPendingMessages();
  24792. saveSnapshot (ui, prefix + "-pianoroll-" + name + ".png");
  24793. }
  24794. }
  24795. }
  24796. ui.selectTabForSnapshot (2);
  24797. saveSnapshot (ui, prefix + "-playlist.png");
  24798. if (const auto strip = ui.getToolStripAreaForSnapshot (true); ! strip.isEmpty())
  24799. saveArea (ui, strip, prefix + "-playlist-tools.png");
  24800. ui.setHintForSnapshot (ui.getPlaylistForSnapshot().hoverForSnapshot());
  24801. saveSnapshot (ui, prefix + "-playlist-hover.png");
  24802. ui.setHintForSnapshot ({ lynx::tr ("Volume") + " - " + lynx::tr ("drag (Ctrl: fine), wheel, Alt+click resets"), "78%", true, true });
  24803. // the Playlist with a time selection over bars 2-3 (it selects the clips it touches) and the Knife tool
  24804. ui.getPlaylistForSnapshot().setTimeSelectionForSnapshot (1, 3);
  24805. ui.getPlaylistForSnapshot().setToolForSnapshot (lynx::EditTool::knife);
  24806. offline.dispatchPendingMessages();
  24807. saveSnapshot (ui, prefix + "-playlist-timesel.png");
  24808. ui.getPlaylistForSnapshot().setToolForSnapshot (lynx::EditTool::pencil);
  24809. // round 177b: automation lanes on (two lanes under track 2: a volume ramp and a pan wobble)
  24810. {
  24811. const auto before = offline.getSong();
  24812. offline.editSong ([] (lynx::Song& s) {
  24813. s.loopStart = s.loopEnd = 0; // (no time selection in this one)
  24814. const auto bar = s.barTicks();
  24815. const auto vol = lynx::autolanes::addLane (s, 1, { lynx::AutomationTargetKind::mixerVolume, 1, 0, 0 }, "Insert 1 - Volume", 0.3f);
  24816. s.automations[(std::size_t) vol].points = { { 0, 0.3f, 0.0f }, { bar * 2, 0.8f, 0.4f }, { bar * 4, 0.6f, 0.0f } };
  24817. const auto pan = lynx::autolanes::addLane (s, 1, { lynx::AutomationTargetKind::mixerPan, 1, 0, 0 }, "Insert 1 - Pan", 0.5f);
  24818. 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 } };
  24819. }, false);
  24820. lynx::autolanes::setShown (true);
  24821. ui.getPlaylistForSnapshot().resized();
  24822. offline.dispatchPendingMessages();
  24823. saveSnapshot (ui, prefix + "-playlist-lanes.png");
  24824. lynx::autolanes::setShown (false);
  24825. offline.editSong ([before] (lynx::Song& s) { s = before; }, false);
  24826. offline.dispatchPendingMessages();
  24827. }
  24828. // round 104: a folded track group (FL's thin member rows) and the Picker's audio tab
  24829. {
  24830. int header = -1;
  24831. for (int t = 0; t < (int) offline.getSong().playlistTracks.size() && header < 0; ++t)
  24832. if (lynx::noteedit::isGroupHeader (offline.getSong(), t))
  24833. header = t;
  24834. if (header >= 0)
  24835. {
  24836. offline.editSong ([header] (lynx::Song& s) { lynx::noteedit::setGroupCollapsed (s, header, true); }, false);
  24837. offline.dispatchPendingMessages();
  24838. saveSnapshot (ui, prefix + "-playlist-group-folded.png");
  24839. offline.editSong ([header] (lynx::Song& s) { lynx::noteedit::setGroupCollapsed (s, header, false); }, false);
  24840. }
  24841. ui.getPickerForSnapshot().setView (1);
  24842. offline.dispatchPendingMessages();
  24843. saveSnapshot (ui, prefix + "-playlist-picker-audio.png");
  24844. ui.getPickerForSnapshot().setView (0);
  24845. }
  24846. // round 104: the Channel Rack filtered to its first filter group
  24847. if (! offline.getSong().channelGroups.empty())
  24848. {
  24849. ui.selectTabForSnapshot (0);
  24850. ui.getRackForSnapshot().setFilterGroup (0);
  24851. offline.dispatchPendingMessages();
  24852. saveSnapshot (ui, prefix + "-rack-filter.png");
  24853. ui.getRackForSnapshot().setFilterGroup (-1);
  24854. }
  24855. ui.selectTabForSnapshot (3);
  24856. // LYNX_SNAPSHOT_ARRANGE=1 (round 186c): Mixer menu › "Arrange inserts like the Playlist" first
  24857. if (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_ARRANGE", {}) == "1")
  24858. {
  24859. offline.editSong ([] (lynx::Song& s) { lynx::mixerops::arrangeLikePlaylist (s); });
  24860. offline.dispatchPendingMessages();
  24861. }
  24862. // LYNX_SNAPSHOT_TRACK=n: shows the effects of that mixer track
  24863. if (const auto track = juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_TRACK", {}); track.isNotEmpty())
  24864. {
  24865. ui.selectMixerTrackForSnapshot (track.getIntValue(),
  24866. juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SLOT", "-1").getIntValue());
  24867. offline.dispatchPendingMessages();
  24868. }
  24869. saveSnapshot (ui, prefix + "-mixer.png");
  24870. // round 190am: LYNX's two mixer extras, before and after (the demo project leaves most inserts unused). The
  24871. // loudness panel shows a real measurement of 12 s of a test tone (a 1 kHz sine at -14 dBFS after a quieter
  24872. // stretch, pushed through the Master's tap as the audio thread does)
  24873. {
  24874. auto& strips = ui.getMixerForSnapshot().getStripsForSnapshot();
  24875. saveSnapshot (ui, prefix + "-mixer190am-before.png");
  24876. strips.setShowUsedOnly (true);
  24877. offline.dispatchPendingMessages();
  24878. saveSnapshot (ui, prefix + "-mixer190am-usedonly.png");
  24879. strips.setShowUsedOnly (false);
  24880. strips.setShowLoudness (true);
  24881. {
  24882. const double sr = 48000.0;
  24883. std::vector<float> tone (480);
  24884. auto& tap = offline.getMeters().loudness;
  24885. for (int block = 0; block < 1200; ++block)
  24886. {
  24887. const auto gain = std::pow (10.0, (block < 400 ? -20.0 : -14.0) / 20.0);
  24888. for (int i = 0; i < 480; ++i)
  24889. tone[(std::size_t) i] = (float) (gain * std::sin (2.0 * juce::MathConstants<double>::pi * 1000.0 * (block * 480 + i) / sr));
  24890. tap.push (tone.data(), tone.data(), 480, sr);
  24891. }
  24892. }
  24893. strips.refreshLoudnessForSnapshot();
  24894. offline.dispatchPendingMessages();
  24895. saveSnapshot (ui, prefix + "-mixer190am-loudness.png");
  24896. for (const auto l : { lynx::mixerlayout::Layout::compact, lynx::mixerlayout::Layout::extraLarge })
  24897. {
  24898. const auto was = lynx::MixerStrips::layout;
  24899. strips.setLayout (l);
  24900. offline.dispatchPendingMessages();
  24901. saveSnapshot (ui, prefix + "-mixer190am-loudness-" + juce::String ((int) l) + ".png");
  24902. strips.setLayout (was);
  24903. }
  24904. strips.setShowUsedOnly (true);
  24905. offline.dispatchPendingMessages();
  24906. saveSnapshot (ui, prefix + "-mixer190am-both.png");
  24907. strips.setShowUsedOnly (false);
  24908. strips.setShowLoudness (false);
  24909. offline.dispatchPendingMessages();
  24910. }
  24911. // round 168h (issue #52): FL's 8 Mixer layouts
  24912. {
  24913. const auto before = lynx::MixerStrips::layout;
  24914. for (int l = 0; l < lynx::mixerlayout::layoutCount; ++l)
  24915. {
  24916. ui.getMixerForSnapshot().getStripsForSnapshot().setLayout ((lynx::mixerlayout::Layout) l);
  24917. offline.dispatchPendingMessages();
  24918. saveSnapshot (ui, prefix + "-mixer168h-" + juce::String (l) + ".png");
  24919. }
  24920. ui.getMixerForSnapshot().getStripsForSnapshot().setLayout (before);
  24921. offline.dispatchPendingMessages();
  24922. }
  24923. // round 163: the Mixer at short heights (UI zoom 150%+): the EQ folds, then the effects panel scrolls
  24924. {
  24925. const auto size = ui.getBounds();
  24926. for (auto h : { 450, 560, 680, 820 })
  24927. {
  24928. ui.setSize (size.getWidth(), h);
  24929. offline.dispatchPendingMessages();
  24930. saveSnapshot (ui, prefix + "-mixer163-" + juce::String (h) + ".png");
  24931. }
  24932. ui.setBounds (size);
  24933. offline.dispatchPendingMessages();
  24934. }
  24935. // round 170b (Busy Works Beats' review): inserts 1-3 selected and routed together to insert 4, a single effect
  24936. // moved down into slot 2 (FL's slot places), and the plugin menus grouped by category, LYNX SHARE first
  24937. {
  24938. const auto before = offline.getSong();
  24939. offline.editSong ([] (lynx::Song& s) {
  24940. if (s.mixer.size() < 5)
  24941. return;
  24942. s.mixer[1].effects.clear();
  24943. lynx::EffectSlot fx;
  24944. fx.kind = lynx::EffectKind::compressor;
  24945. s.mixer[1].effects.push_back (fx);
  24946. lynx::mixerops::moveEffectBy (s, 1, 0, 1);
  24947. lynx::mixerops::switchSelectedRoute (s, { 1, 2, 3 }, 4, true);
  24948. });
  24949. ui.selectMixerTrackForSnapshot (1);
  24950. ui.getMixerForSnapshot().getStripsForSnapshot().setSelection ({ 1, 2, 3 }, 1);
  24951. offline.dispatchPendingMessages();
  24952. saveSnapshot (ui, prefix + "-mixer170b.png");
  24953. juce::PopupMenu effects, generators;
  24954. lynx::quickpick::addFolderGroups (effects, offline, std::function<void (lynx::EffectSlot)> ([] (lynx::EffectSlot) {}));
  24955. lynx::quickpick::addFolderViewItems (effects, offline);
  24956. lynx::quickpick::addGeneratorMenu (generators, offline, [] (lynx::ChannelDef) {}, {}, nullptr, nullptr);
  24957. lynx::quickpick::addFolderViewItems (generators, offline);
  24958. saveMenus (juce::StringArray { "Mixer slot: add an effect", "Channel Rack: add" }, { effects, generators }, prefix + "-menus170b.png");
  24959. // round 190bf (fl190be Q3): the Channel Rack's "+" menu in FL's three views, with two root entries (plugins
  24960. // at the top of the database, in no folder) and the Categories / Simple / Tree switch at the end
  24961. {
  24962. auto& host = offline.getPluginHost();
  24963. const auto keep = host.databaseFolders();
  24964. auto folders = keep;
  24965. int added = 0;
  24966. for (const auto& e : lynx::quickpick::generatorEntries (offline))
  24967. if (e.folder == 3 && e.available && added < 2) // (installed plugins: FL's root entries are such)
  24968. {
  24969. folders.top.insert (e.key);
  24970. ++added;
  24971. }
  24972. for (const auto& e : lynx::quickpick::generatorEntries (offline))
  24973. if (e.folder != 3 && added < 2)
  24974. {
  24975. folders.top.insert (e.key);
  24976. ++added;
  24977. }
  24978. static const char* const views[] { "categories", "simple", "tree" };
  24979. for (int v = 0; v < 3; ++v)
  24980. {
  24981. folders.view = v;
  24982. host.setDatabaseFolders (folders);
  24983. juce::PopupMenu plus;
  24984. lynx::quickpick::addGeneratorMenu (plus, offline, [] (lynx::ChannelDef) {}, {}, nullptr, nullptr);
  24985. lynx::quickpick::addFolderViewItems (plus, offline);
  24986. saveMenus (juce::StringArray { juce::String ("Channel Rack +: ") + views[v] }, { plus }, prefix + "-menus190bf-" + views[v] + ".png");
  24987. }
  24988. host.setDatabaseFolders (keep);
  24989. }
  24990. offline.setSong (before);
  24991. offline.dispatchPendingMessages();
  24992. }
  24993. // standalone windows, with the theme background
  24994. auto saveWindow = [&prefix] (std::unique_ptr<juce::Component> c, const juce::String& name) {
  24995. juce::Component frame;
  24996. frame.setSize (c->getWidth(), c->getHeight());
  24997. frame.setOpaque (true);
  24998. // an AlertWindow is built on the desktop: shown there first, it would take the foreground from whoever has it
  24999. // (TopLevelWindow::visibilityChanged calls toFront (true)). Off the desktop, its control that showing it would
  25000. // have focused (what grabKeyboardFocus picks) is marked, so the picture keeps that control's focus ring
  25001. if (c->isOnDesktop())
  25002. {
  25003. c->removeFromDesktop();
  25004. auto* focus = c.get();
  25005. for (int depth = 0; focus != nullptr && depth < 32; ++depth)
  25006. {
  25007. if (focus->getWantsKeyboardFocus() && (focus->isEnabled() || focus == c.get()))
  25008. {
  25009. focus->getProperties().set ("lynxSnapshotFocus", true);
  25010. break;
  25011. }
  25012. auto traverser = focus->createKeyboardFocusTraverser();
  25013. focus = traverser != nullptr ? traverser->getDefaultComponent (focus) : nullptr;
  25014. }
  25015. }
  25016. frame.addAndMakeVisible (*c);
  25017. c->setTopLeftPosition (0, 0);
  25018. checkTextFit (*c, name.fromFirstOccurrenceOf ("-", false, false).upToLastOccurrenceOf (".", false, false));
  25019. auto image = lynx::shot::paint (frame, lynx::theme::panel);
  25020. const auto file = lynx::shot::file (juce::File (prefix + name));
  25021. file.deleteFile();
  25022. juce::PNGImageFormat png;
  25023. if (auto out = file.createOutputStream())
  25024. png.writeImageToStream (image, *out);
  25025. };
  25026. saveWindow (lynx::makeExportPanel (offline), "-export.png");
  25027. saveWindow (lynx::makeExportPanel (offline, 1), "-export-mp3.png");
  25028. saveWindow (lynx::makeExportPanel (offline, 3), "-export-flac-stems.png");
  25029. {
  25030. // REA round 165f-mixer: the mixer track's Track latency / routing submenus, Disk recording, PDC, and the
  25031. // Export window for "Render selected tracks to wave file(s)"
  25032. const auto before = offline.getSong();
  25033. offline.editSong ([] (lynx::Song& s) {
  25034. if (s.mixer.size() > 3)
  25035. {
  25036. s.mixer[1].latencyMs = 5.0f;
  25037. s.mixer[1].latencyBypass = lynx::LatencyBypass::whenRecordingOrStopped;
  25038. s.mixer[2].latencyMs = -1.5f;
  25039. }
  25040. });
  25041. offline.dispatchPendingMessages();
  25042. auto& strips = ui.getMixerForSnapshot().getStripsForSnapshot();
  25043. strips.setSelection ({ 1, 2, 3 }, 1);
  25044. const auto menu = strips.buildMenu (1);
  25045. juce::StringArray names { "Mixer track" };
  25046. std::vector<juce::PopupMenu> menus { menu };
  25047. const auto latencyPrefix = lynx::tr ("Track latency: {0}", { juce::String() });
  25048. const juce::String wanted[] = { lynx::tr ("Selected tracks ⇄ this track"), lynx::tr ("Disk recording"),
  25049. lynx::tr ("Plugin delay compensation") };
  25050. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  25051. {
  25052. const auto& item = it.getItem();
  25053. if (item.subMenu != nullptr && (item.text.startsWith (latencyPrefix) || std::find (std::begin (wanted), std::end (wanted), item.text) != std::end (wanted)))
  25054. {
  25055. names.add (item.text.upToFirstOccurrenceOf (":", false, false));
  25056. menus.push_back (*item.subMenu);
  25057. }
  25058. }
  25059. saveMenus (names, menus, prefix + "-menus165-mixer.png");
  25060. saveWindow (lynx::makeExportPanelForTracks (offline, { 1, 2, 3 }), "-export165-tracks.png");
  25061. offline.setSong (before);
  25062. offline.dispatchPendingMessages();
  25063. }
  25064. saveSplashFrames (prefix);
  25065. saveIconSheet (prefix + "-icons.png", 1.0f);
  25066. saveIconSheet (prefix + "-icons-150.png", 1.5f);
  25067. saveWindow (lynx::MainComponent::makeHelpContent(), "-help.png");
  25068. saveWindow (lynx::ui::makeTrackIconGrid (5, {}), "-trackicons168h.png"); // round 168h: the icon picker
  25069. saveWindow (std::make_unique<lynx::toolbar::CustomizePanel> (lynx::toolbarlayout::Layout::makeDefault()), "-customize-toolbar.png");
  25070. // two moved controls: Tools › Last tweaked and Add › Automation for last tweaked parameter show them (REA round 143)
  25071. offline.noteTweaked ({ lynx::AutomationTargetKind::channelVolume, 0 });
  25072. offline.noteTweaked ({ lynx::AutomationTargetKind::mixerVolume, 0 });
  25073. saveMenus (ui, prefix + "-menus.png");
  25074. {
  25075. // the windows' own menus (title bars) and the toolbar's recording menu
  25076. juce::StringArray names;
  25077. std::vector<juce::PopupMenu> menus;
  25078. for (auto [panel, name] : { std::pair { lynx::workspace::Panel::playlist, "Playlist" }, { lynx::workspace::Panel::channelRack, "Channel Rack" },
  25079. { lynx::workspace::Panel::pianoRoll, "Piano Roll" }, { lynx::workspace::Panel::mixer, "Mixer" },
  25080. { lynx::workspace::Panel::browser, "Browser" } })
  25081. {
  25082. names.add (name);
  25083. menus.push_back (ui.getPanelMenuForSnapshot (panel));
  25084. }
  25085. names.add ("Recording");
  25086. menus.push_back (ui.getRecordMenuForSnapshot());
  25087. names.add ("Toolbar");
  25088. menus.push_back (ui.getToolbarMenuForSnapshot());
  25089. saveMenus (names, menus, prefix + "-panel-menus.png");
  25090. }
  25091. // round 189e: the Playlist menu's Edit and Select submenus (FL's items and order) and the header drop question
  25092. saveMenus (juce::StringArray { "Playlist: Edit", "Playlist: Select" },
  25093. std::vector<juce::PopupMenu> { ui.getPlaylistForSnapshot().editMenu(), ui.getPlaylistForSnapshot().selectMenu() },
  25094. prefix + "-playlist-edit189e.png");
  25095. saveWindow (lynx::PlaylistComponent::makeHeaderDropDialog(), "-header-drop189e.png");
  25096. {
  25097. // round 189i: FL's fade handle menu (right-click on an audio clip's fade handle), on the song's first audio
  25098. // clip, or on one added for the shot
  25099. const auto before = offline.getSong();
  25100. auto clipIndex = -1;
  25101. for (std::size_t i = 0; i < before.playlist.size() && clipIndex < 0; ++i)
  25102. if (before.playlist[i].kind == lynx::ClipKind::audio)
  25103. clipIndex = (int) i;
  25104. if (clipIndex < 0)
  25105. {
  25106. auto song = before;
  25107. lynx::ChannelDef channel;
  25108. channel.instrument = lynx::InstrumentKind::audioClip;
  25109. channel.name = "Audio clip";
  25110. song.channels.push_back (channel);
  25111. lynx::Clip clip;
  25112. clip.kind = lynx::ClipKind::audio;
  25113. clip.channel = (int) song.channels.size() - 1;
  25114. clip.length = lynx::ppq * 4;
  25115. song.playlist.push_back (clip);
  25116. clipIndex = (int) song.playlist.size() - 1;
  25117. offline.setSong (song);
  25118. offline.dispatchPendingMessages();
  25119. }
  25120. saveMenus (juce::StringArray { "Fade handle" },
  25121. std::vector<juce::PopupMenu> { ui.getPlaylistForSnapshot().fadeHandleMenu (clipIndex, 1) },
  25122. prefix + "-fade-handle189i.png");
  25123. if (offline.getSong().playlist.size() != before.playlist.size())
  25124. {
  25125. offline.setSong (before);
  25126. offline.dispatchPendingMessages();
  25127. }
  25128. }
  25129. {
  25130. // round 189n: FL's gain handle menu with two overlapping clips selected (Normalize selection individually / as a
  25131. // group) and the later clip's fade in menu (Create crossfade enabled); FL shots in /mnt/e/lynx-work/flgap189n
  25132. const auto before = offline.getSong();
  25133. auto song = before;
  25134. lynx::ChannelDef channel;
  25135. channel.instrument = lynx::InstrumentKind::audioClip;
  25136. channel.name = "Audio clip";
  25137. song.channels.push_back (channel);
  25138. int lane = 0;
  25139. for (const auto& c : song.playlist)
  25140. lane = std::max (lane, c.track + 1);
  25141. for (int k = 0; k < 2; ++k)
  25142. {
  25143. lynx::Clip clip;
  25144. clip.kind = lynx::ClipKind::audio;
  25145. clip.channel = (int) song.channels.size() - 1;
  25146. clip.track = lane;
  25147. clip.start = k * lynx::ppq * 3;
  25148. clip.length = lynx::ppq * 4;
  25149. song.playlist.push_back (clip);
  25150. }
  25151. const auto second = (int) song.playlist.size() - 1;
  25152. song.autoCrossfades = true; // FL's capture: Thief has Automatic crossfades on
  25153. offline.setSong (song);
  25154. offline.dispatchPendingMessages();
  25155. auto& playlist = ui.getPlaylistForSnapshot();
  25156. playlist.selectForSnapshot ({ second - 1, second });
  25157. auto gain = playlist.gainMenu (second);
  25158. auto fadeIn = playlist.fadeHandleMenu (second, 0); // (both selected, as in FL's capture)
  25159. playlist.selectForSnapshot ({});
  25160. saveMenus (juce::StringArray { "Gain handle, 2 selected", "Fade in, overlapping" },
  25161. std::vector<juce::PopupMenu> { gain, fadeIn }, prefix + "-fade-gain189n.png");
  25162. // round 189o: the audio clip menu with both overlapping clips selected (FL's Fades › Crossfade selected
  25163. // shown) and with none selected (hidden)
  25164. playlist.selectForSnapshot ({ second - 1, second });
  25165. auto clipSelected = playlist.getClipMenuForSnapshot (second);
  25166. playlist.selectForSnapshot ({});
  25167. auto clipAlone = playlist.getClipMenuForSnapshot (second);
  25168. saveMenus (juce::StringArray { "Audio clip, 2 selected", "Audio clip, none selected" },
  25169. std::vector<juce::PopupMenu> { clipSelected, clipAlone }, prefix + "-xfadesel189o.png");
  25170. offline.setSong (before);
  25171. offline.dispatchPendingMessages();
  25172. }
  25173. {
  25174. // REA round 143: the piano roll Tools menu, a Playlist track menu and a mixer insert menu (FL's layouts)
  25175. std::vector<juce::PopupMenu> menus { ui.getPianoRollForSnapshot().getToolsMenuForSnapshot(),
  25176. ui.getPlaylistForSnapshot().getTrackMenuForSnapshot (0),
  25177. ui.getMixerForSnapshot().getStripsForSnapshot().buildMenu (1) };
  25178. saveMenus (juce::StringArray { "Piano roll tools", "Playlist track", "Mixer track" }, menus, prefix + "-menus143.png");
  25179. // round 190as: the Piano roll's scripts (FL's Tools › Scripts column) and a script's form
  25180. saveMenus (juce::StringArray { "Piano roll scripts" }, std::vector<juce::PopupMenu> { ui.getPianoRollForSnapshot().getScriptsMenuForSnapshot() },
  25181. prefix + "-prscripts-menu.png");
  25182. {
  25183. lynx::prscript::Score score;
  25184. const auto out = lynx::prscript::run (lynx::prscript::builtins().front().source, score, {});
  25185. if (out.status == lynx::prscript::Outcome::Status::needsForm)
  25186. {
  25187. lynx::ScriptPanel::Options options;
  25188. options.acceptText = lynx::tr ("Accept");
  25189. saveWindow (std::make_unique<lynx::ScriptPanel> (out.form, [] (const lynx::scriptform::Form&) {}, [] (const lynx::scriptform::Form&) {},
  25190. nullptr, options),
  25191. "-prscript-form.png");
  25192. }
  25193. }
  25194. // round 190j (discussion #10): the Piano roll menu's Chord stamp list
  25195. saveMenus (juce::StringArray { "Chord stamp" }, std::vector<juce::PopupMenu> { ui.getPianoRollForSnapshot().getStampMenuForSnapshot() },
  25196. prefix + "-stamp-menu.png");
  25197. // round 167l: the channel menu ("Lock active/mute state")
  25198. if (! offline.getSong().channels.empty())
  25199. saveMenus (juce::StringArray { "Channel" }, std::vector<juce::PopupMenu> { ui.getRackForSnapshot().getChannelMenuForSnapshot (0) }, prefix + "-channel-menu.png");
  25200. // round 163: menu density, compact (default) and comfortable, on a Browser folder menu
  25201. {
  25202. juce::PopupMenu folder;
  25203. folder.addSectionHeader ("Documents");
  25204. folder.addItem (1, "Expand all");
  25205. folder.addItem (2, "Collapse all");
  25206. folder.addSeparator();
  25207. folder.addItem (3, "Refresh");
  25208. folder.addSectionHeader ("System");
  25209. folder.addItem (4, "Open");
  25210. folder.addItem (5, "Copy the file path");
  25211. folder.addSectionHeader ("Tags");
  25212. folder.addItem (6, "Starred", true, true);
  25213. folder.addSeparator();
  25214. folder.addItem (7, "Add folder...");
  25215. const auto wasCompact = lynx::theme::menus::compact();
  25216. lynx::theme::menus::setCompact (true);
  25217. saveMenus (juce::StringArray { "Compact" }, { folder }, prefix + "-menu163-compact.png");
  25218. lynx::theme::menus::setCompact (false);
  25219. saveMenus (juce::StringArray { "Comfortable" }, { folder }, prefix + "-menu163-comfortable.png");
  25220. lynx::theme::menus::setCompact (wasCompact);
  25221. }
  25222. // and the clip menus of the first pattern, audio and automation clips of the project
  25223. juce::StringArray clipNames;
  25224. std::vector<juce::PopupMenu> clipMenus;
  25225. for (auto [kind, name] : { std::pair { lynx::ClipKind::pattern, "Pattern clip" }, { lynx::ClipKind::audio, "Audio clip" },
  25226. { lynx::ClipKind::automation, "Automation clip" } })
  25227. for (int c = 0; c < (int) offline.getSong().playlist.size(); ++c)
  25228. if (offline.getSong().playlist[(std::size_t) c].kind == kind)
  25229. {
  25230. clipNames.add (name);
  25231. clipMenus.push_back (ui.getPlaylistForSnapshot().getClipMenuForSnapshot (c));
  25232. break;
  25233. }
  25234. if (! clipMenus.empty())
  25235. saveMenus (clipNames, clipMenus, prefix + "-menus143-clips.png");
  25236. }
  25237. auto saveAlert = [&] (std::unique_ptr<juce::AlertWindow> alert, const juce::String& name) {
  25238. alert->setOpaque (true);
  25239. saveWindow (std::move (alert), name);
  25240. };
  25241. saveAlert (ui.makeConfirmDiscardWindow(), "-confirm.png");
  25242. saveAlert (lynx::MainComponent::makeAboutWindow(), "-about.png");
  25243. saveAlert (lynx::support::makeSupportWindow(), "-support.png"); // round 190fq: Help › Support LYNX SHARE...
  25244. saveAlert (lynx::makeNameAndColourDialog (lynx::tr ("Rename pattern"), "Pattern 2", lynx::lynxPalette()[6]), "-rename.png");
  25245. saveAlert (lynx::makeRecordChoiceDialog(), "-record-dialog.png");
  25246. // round 190ah: Online Sessions — a guest's "go back in?" at start-up, the host's question at a guest's file limit
  25247. saveAlert (lynx::liveui::makeRejoinDialog ("Ana", juce::Time (2026, 10, 10, 21, 40).toString (true, true, false, true)), "-live-rejoin.png");
  25248. saveAlert (lynx::liveui::makeMediaLimitDialog ("Pedro", (juce::int64) 1010 << 20, (juce::int64) 1 << 30), "-live-media-limit.png");
  25249. saveAlert (lynx::makeSamplePitchDialog (7.25f, true, true), "-sample-pitch.png"); // round 163c
  25250. saveAlert (lynx::makeGradientColourDialog (juce::Colour (0xffe5383b), juce::Colour (0xff3a7bd5), 8), "-gradient.png"); // round 177a
  25251. saveAlert (lynx::makeMidiImportDialog(), "-midi-import-dialog.png"); // File › Import › MIDI file (REA round 143)
  25252. // round 186c: FL's mixer "Delete" questions and its Settings › General › Manage messages menu
  25253. saveAlert (lynx::makeFlMessageDialog ({ lynx::tr ("Delete tracks"), lynx::tr ("This will |delete| {0} selected mixer track(s). Are you sure?", { "1" }),
  25254. { lynx::tr ("Yes"), lynx::tr ("No") }, true }),
  25255. "-delete-tracks.png");
  25256. saveAlert (lynx::makeFlMessageDialog ({ lynx::tr ("Playlist tracks"),
  25257. lynx::tr ("One or more mixer tracks that will be deleted are connected to instrument/audio tracks.") + "\n"
  25258. + lynx::tr ("Do you want to unlink the tracks and channels or delete them?"),
  25259. { lynx::tr ("Delete tracks and channels"), lynx::tr ("Unlink tracks and channels"), lynx::tr ("Cancel") }, false }),
  25260. "-delete-tracks-linked.png");
  25261. saveMenus (juce::StringArray { "Manage messages" }, std::vector<juce::PopupMenu> { lynx::messages::manageMenu() }, prefix + "-manage-messages.png");
  25262. saveWindow (lynx::makeSetupWizardContent (offline, {}, {}), "-setup.png");
  25263. saveWindow (lynx::crashreporter::makeDialogForSnapshot (false), "-crash-report.png"); // round 159
  25264. saveWindow (lynx::crashreporter::makeDialogForSnapshot (true), "-report-problem.png");
  25265. // round 166b: the update bar in its states (available, downloading, failed, ready) and the release notes window
  25266. {
  25267. struct Bars final : juce::Component
  25268. {
  25269. Bars()
  25270. {
  25271. constexpr int h = lynx::updater::UpdateBar::height;
  25272. setSize (1100, 6 * (h + 6));
  25273. for (int state = 0; state < 6; ++state) // (round 190gh: 4 going back, 5 went back)
  25274. {
  25275. bars[state].setBounds (0, state * (h + 6), getWidth(), h);
  25276. bars[state].showForSnapshot (state);
  25277. addAndMakeVisible (bars[state]);
  25278. }
  25279. }
  25280. lynx::updater::UpdateBar bars[6];
  25281. };
  25282. saveWindow (std::make_unique<Bars>(), "-update-bar.png");
  25283. saveWindow (lynx::updater::makeReleaseNotesForSnapshot(), "-update-notes.png");
  25284. // round 190gh (B23): Help › Test audio output... in its states
  25285. for (int state = 0; state < 5; ++state)
  25286. saveWindow (lynx::makeAudioCheckForSnapshot (offline, state), "-audio-check-" + juce::String (state) + ".png");
  25287. }
  25288. saveWindow (lynx::makeMissingFilesPanel (lynx::missingFilesSnapshotInfo(), 0, 1), "-missing-files.png");
  25289. saveWindow (lynx::makeMissingFilesPanel (lynx::missingFilesSnapshotInfo(), 1), "-missing-plugins.png");
  25290. saveWindow (lynx::makeMissingFilesPanel (lynx::missingFilesSnapshotInfo(), 2), "-missing-found.png");
  25291. {
  25292. // the Settings pages, with credits like a project imported from FL would carry
  25293. offline.editSong ([] (lynx::Song& s) {
  25294. s.info = { "Night Drive", "LYNX SHARE demo", "Synthwave", "https://lynx-share.com",
  25295. "Made with LYNX SHARE.\nDrums and bass from the Channel Rack, pads from the Browser.", false };
  25296. }, false);
  25297. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::project), "-settings-project.png");
  25298. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::info), "-settings-info.png");
  25299. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::files), "-settings-files.png");
  25300. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::general), "-settings-general.png");
  25301. {
  25302. // round 189o: the whole General page (the Editing and Plugins sections hold FL's "Monophonic painting in
  25303. // piano roll" and "Limit the number of open plugin editors")
  25304. auto tall = lynx::makeSettingsPanel (offline, lynx::SettingsPage::general);
  25305. tall->setSize (tall->getWidth(), 3200);
  25306. saveWindow (std::move (tall), "-settings-general-tall189o.png");
  25307. }
  25308. {
  25309. // the whole General page (round 186a: the Startup section is below the first screen)
  25310. auto tall = lynx::makeSettingsPanel (offline, lynx::SettingsPage::general);
  25311. tall->setSize (tall->getWidth(), 1500);
  25312. saveWindow (std::move (tall), "-settings-general-tall.png");
  25313. }
  25314. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::theme), "-settings-theme.png");
  25315. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::extras), "-settings-extras.png"); // round 190am
  25316. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::audio), "-settings-audio.png");
  25317. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::midi), "-settings-midi.png");
  25318. {
  25319. // round 190bj (QA): the MIDI page in a small window keeps each row's switch and device name
  25320. auto small = lynx::makeSettingsPanel (offline, lynx::SettingsPage::midi);
  25321. small->setSize (390, 390);
  25322. saveWindow (std::move (small), "-settings-midi-small.png");
  25323. }
  25324. {
  25325. // round 190bj (QA): the Apex Limiter's window content at its default size, as sized before (JUCE's ratio
  25326. // on the whole window: the status row cut off) and now
  25327. lynx::AudioEngine apexEngine (false);
  25328. lynx::Song song;
  25329. song.mixer.resize (2);
  25330. song.mixer[0].name = "Master";
  25331. song.mixer[1].name = "Insert 1";
  25332. song.mixer[1].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::apexLimiter));
  25333. apexEngine.setSong (std::move (song));
  25334. apexEngine.dispatchPendingMessages();
  25335. savePng (lynx::ProEditorWindows::windowContentForSnapshot (apexEngine, 1, 0, true), prefix + "-apex-window-before190bj.png");
  25336. savePng (lynx::ProEditorWindows::windowContentForSnapshot (apexEngine, 1, 0, false), prefix + "-apex-window.png");
  25337. }
  25338. saveWindow (lynx::makePluginManagerPanel (offline, false), "-plugin-manager.png");
  25339. // round 190gg: the crash prompt and a plugin window's crash notice, with "Always run ... in a separate process"
  25340. saveWindow (lynx::PluginWindows::makeCrashPromptPanel ("Serum", false), "-plugin-crash-prompt.png");
  25341. saveWindow (lynx::PluginWindows::makeCrashNoticePanel ("Serum", true), "-plugin-crash-notice.png");
  25342. saveWindow (lynx::makeShortcutManagerPanel (false), "-shortcuts.png");
  25343. }
  25344. {
  25345. // round 84: New project, Clip properties, Arrangements, Plugin performance monitor, Touch keyboard
  25346. saveWindow (lynx::makeNewProjectPanel(), "-new-project.png");
  25347. const auto& clips = offline.getSong().playlist;
  25348. for (int i = 0; i < (int) clips.size(); ++i)
  25349. if (clips[(std::size_t) i].kind == lynx::ClipKind::pattern)
  25350. {
  25351. saveWindow (lynx::makeClipPropertiesPanel (offline, i, { i, (i + 1) % (int) clips.size() }), "-clip-properties.png");
  25352. break;
  25353. }
  25354. for (int i = 0; i < (int) clips.size(); ++i)
  25355. if (clips[(std::size_t) i].kind == lynx::ClipKind::audio)
  25356. {
  25357. saveWindow (lynx::makeClipPropertiesPanel (offline, i, { i }), "-clip-properties-audio.png");
  25358. break;
  25359. }
  25360. if (offline.getSong().arrangements.size() < 2)
  25361. offline.editSong ([] (lynx::Song& s) {
  25362. const auto current = s.currentArrangement;
  25363. s.addArrangement ("Radio edit", true);
  25364. s.addArrangement ("Intro loop");
  25365. s.selectArrangement (current);
  25366. }, false);
  25367. saveWindow (lynx::makeArrangementsPanel (offline), "-arrangements.png");
  25368. saveWindow (lynx::makePluginMonitorPanel (offline), "-plugin-monitor.png");
  25369. saveWindow (lynx::makeTouchKeyboardPanel (offline), "-touch-keyboard.png");
  25370. }
  25371. {
  25372. // round 142: the Newtone / Newtime editors on a synthetic sung line (A3 B3 C4 · E4), one note moved
  25373. const auto wav = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-snapshot-newtone.wav");
  25374. {
  25375. juce::AudioBuffer<float> line (1, 44100 * 2);
  25376. const double hz[] = { 220.0, 246.94, 261.63, 0.0, 329.63 };
  25377. double ph = 0.0;
  25378. for (int i = 0; i < line.getNumSamples(); ++i)
  25379. {
  25380. const auto f0 = hz[std::min (4, i / 17640)];
  25381. 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;
  25382. float v = 0.0f;
  25383. for (int h = 1; f0 > 0.0 && h < 8; ++h)
  25384. v += (float) (0.3 / h * std::sin (h * ph));
  25385. line.setSample (0, i, v);
  25386. }
  25387. wav.deleteFile();
  25388. juce::WavAudioFormat format;
  25389. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  25390. if (auto* w = out != nullptr ? format.createWriterFor (out.get(), 44100.0, 1, 16, {}, 0) : nullptr)
  25391. {
  25392. out.release();
  25393. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  25394. writer->writeFromAudioSampleBuffer (line, 0, line.getNumSamples());
  25395. }
  25396. }
  25397. if (const auto sample = offline.getSampleLibrary().load (wav.getFullPathName()))
  25398. {
  25399. auto notes = lynx::newtonefx::analyseNotes (*sample);
  25400. if (notes.pitches.size() > 1)
  25401. notes.pitches[1].shift = 2.0;
  25402. lynx::newtonefx::WarpMap warp;
  25403. warp.frames = (std::int64_t) sample->frames();
  25404. warp.markers = { { 22050, 33075 } };
  25405. int at = 0;
  25406. offline.editSong ([&] (lynx::Song& song) {
  25407. if (song.mixer.size() < 2)
  25408. song.mixer.resize (2);
  25409. auto& fx = song.mixer[1].effects;
  25410. auto tone = lynx::makeEffectSlot (lynx::EffectKind::newtone);
  25411. tone.samplePath = wav.getFullPathName().toStdString();
  25412. tone.state = lynx::newtonefx::writeNative (notes);
  25413. auto time = lynx::makeEffectSlot (lynx::EffectKind::newtime);
  25414. time.samplePath = tone.samplePath;
  25415. time.state = lynx::newtonefx::writeWarp (warp);
  25416. at = (int) fx.size();
  25417. fx.push_back (tone);
  25418. fx.push_back (time);
  25419. }, false);
  25420. saveWindow (lynx::makeNewtoneEditor (offline, 1, at), "-newtone.png");
  25421. saveWindow (lynx::makeNewtoneEditor (offline, 1, at + 1), "-newtime.png");
  25422. offline.editSong ([at] (lynx::Song& song) {
  25423. auto& fx = song.mixer[1].effects;
  25424. fx.erase (fx.begin() + at, fx.begin() + at + 2);
  25425. }, false);
  25426. }
  25427. }
  25428. if (! offline.getSong().automations.empty())
  25429. {
  25430. auto editor = lynx::makeAutomationEditor (offline, 0);
  25431. editor->setSize (760, 300);
  25432. saveWindow (std::move (editor), "-automation.png");
  25433. // round 177b: the same clip in FL's LFO mode: FL's defaults, then one shaped state (the UI gate pairs)
  25434. const auto before = offline.getSong().automations[0].lfo;
  25435. const auto lfoShot = [&offline, &saveWindow] (std::function<void (lynx::AutomationLfo&)> set, const char* suffix) {
  25436. offline.editSong ([&set] (lynx::Song& song) {
  25437. auto& lfo = song.automations[0].lfo;
  25438. lfo = lynx::AutomationLfo {};
  25439. lfo.on = true;
  25440. set (lfo);
  25441. }, false);
  25442. auto lfoEditor = lynx::makeAutomationEditor (offline, 0);
  25443. lfoEditor->setSize (760, 346);
  25444. saveWindow (std::move (lfoEditor), suffix);
  25445. };
  25446. lfoShot ([] (lynx::AutomationLfo&) {}, "-automation-lfo.png");
  25447. lfoShot ([] (lynx::AutomationLfo& lfo) {
  25448. // the state set through FL's own UI for the UI gate (TNS 50 %, SKEW 25 %, PW 25 %, two points), as FL saved it
  25449. lfo.tension = 64;
  25450. lfo.skew = 32;
  25451. lfo.pulseWidth = 28;
  25452. lfo.amp = { { 0, 0.6716f, 0.0f }, { (std::int64_t) (lynx::ppq * 1.4128), 0.9204f, 0.0f } };
  25453. }, "-automation-lfo-shape.png");
  25454. offline.editSong ([before] (lynx::Song& song) { song.automations[0].lfo = before; }, false);
  25455. }
  25456. // round 177b: LYNX's modulators window, with one routed modulator
  25457. {
  25458. offline.editSong ([] (lynx::Song& song) {
  25459. lynx::Modulator m;
  25460. m.name = "LFO 1";
  25461. m.shape = lynx::ModShape::triangle;
  25462. m.routes = { { { lynx::AutomationTargetKind::mixerVolume, 1, 0, 0 }, 0.25f }, { { lynx::AutomationTargetKind::mixerPan, 1, 0, 0 }, -0.5f } };
  25463. song.modulators.push_back (m);
  25464. lynx::Modulator r;
  25465. r.name = "LFO 2";
  25466. r.shape = lynx::ModShape::smoothRandom;
  25467. r.sync = false;
  25468. r.hz = 0.5;
  25469. song.modulators.push_back (r);
  25470. }, false);
  25471. auto mods = lynx::makeModulatorsPanel (offline);
  25472. mods->setSize (720, 360);
  25473. saveWindow (std::move (mods), "-modulators.png");
  25474. offline.editSong ([] (lynx::Song& song) { song.modulators.clear(); }, false);
  25475. }
  25476. saveWindow (lynx::makeChannelSettingsPanel (offline, 0), "-sampler.png");
  25477. // the channel window frame (REA round 143b): header strip + tabs; the Misc tab of the first channel and of a synth
  25478. saveWindow (lynx::makeChannelFrame (offline, 0), "-channel-frame.png");
  25479. saveWindow (lynx::makeChannelFrame (offline, 0, -1), "-channel-misc.png");
  25480. for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
  25481. if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::synth)
  25482. {
  25483. saveWindow (lynx::makeChannelSettingsPanel (offline, c), "-synth.png");
  25484. saveWindow (lynx::makeChannelModulationPanel (offline, c), "-modulation.png");
  25485. break;
  25486. }
  25487. for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
  25488. if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::controller)
  25489. {
  25490. saveWindow (lynx::makeChannelSettingsPanel (offline, c), "-controller.png");
  25491. break;
  25492. }
  25493. for (const auto kind : { lynx::InstrumentKind::sakura, lynx::InstrumentKind::drumpad })
  25494. for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
  25495. if (offline.getSong().channels[(std::size_t) c].instrument == kind)
  25496. {
  25497. saveWindow (lynx::makeChannelSettingsPanel (offline, c), kind == lynx::InstrumentKind::sakura ? "-sakura.png" : "-drumpad.png");
  25498. break;
  25499. }
  25500. // round 180c: Fruity Slicer's editor
  25501. for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
  25502. if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::fruityslicer)
  25503. {
  25504. saveWindow (lynx::makeChannelSettingsPanel (offline, c), "-fruityslicer.png");
  25505. // rounds 190f / 190m: its Envelope / instrument page, one picture per target
  25506. saveWindow (lynx::makeChannelFrame (offline, c, 1), "-fruityslicer-envelope.png");
  25507. for (const auto& [target, name] : std::vector<std::pair<int, const char*>> { { 0, "panning" }, { 2, "modx" }, { 3, "mody" }, { 4, "pitch" } })
  25508. {
  25509. auto frame = lynx::makeChannelFrame (offline, c, 1);
  25510. lynx::showFlVoiceTarget (*frame, target);
  25511. saveWindow (std::move (frame), juce::String ("-fruityslicer-envelope-") + name + ".png");
  25512. }
  25513. break;
  25514. }
  25515. // round 190r: Slicex's editor
  25516. for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
  25517. if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::slicex)
  25518. {
  25519. saveWindow (lynx::makeChannelSettingsPanel (offline, c), "-slicex.png");
  25520. break;
  25521. }
  25522. // round 190q: FPC's editor
  25523. for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
  25524. if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::fpc)
  25525. {
  25526. saveWindow (lynx::makeChannelSettingsPanel (offline, c), "-fpc.png");
  25527. break;
  25528. }
  25529. // parametric EQ: the one with the most pronounced curve (in an imported .flp, with FL's settings)
  25530. {
  25531. int bestTrack = -1, bestSlot = -1;
  25532. double bestShape = -1.0;
  25533. const auto& mixer = offline.getSong().mixer;
  25534. for (int t = 0; t < (int) mixer.size(); ++t)
  25535. for (int s = 0; s < (int) mixer[(std::size_t) t].effects.size(); ++s)
  25536. if (const auto& fx = mixer[(std::size_t) t].effects[(std::size_t) s]; fx.kind == lynx::EffectKind::parametricEq)
  25537. {
  25538. double shape = 0.0;
  25539. for (double hz = 30.0; hz < 18000.0; hz *= 1.5)
  25540. shape += std::abs (lynx::peq::responseDb (fx.params, 48000.0, hz));
  25541. if (shape > bestShape)
  25542. {
  25543. bestShape = shape;
  25544. bestTrack = t;
  25545. bestSlot = s;
  25546. }
  25547. }
  25548. if (bestTrack >= 0)
  25549. saveWindow (lynx::makeParametricEqEditor (offline, bestTrack, bestSlot), "-peq.png");
  25550. }
  25551. // Note inspector for the Piano Roll's notes (its selection, or all of the channel's notes)
  25552. if (auto inspector = ui.getPianoRollForSnapshot().makeNoteInspectorForSnapshot())
  25553. saveWindow (std::move (inspector), "-noteinspector.png");
  25554. if (auto inspector = ui.getPianoRollForSnapshot().makeNoteInspectorForSnapshot (true))
  25555. saveWindow (std::move (inspector), "-noteinspector-one.png");
  25556. // workflow P2: note tool dialogs (they preview on the pattern; each one puts the notes back when destroyed)
  25557. {
  25558. auto& roll = ui.getPianoRollForSnapshot();
  25559. const std::pair<lynx::NoteTool, const char*> tools[] = { { lynx::NoteTool::strum, "-tool-strum.png" },
  25560. { lynx::NoteTool::arpeggiate, "-tool-arpeggiate.png" },
  25561. { lynx::NoteTool::flip, "-tool-flip.png" },
  25562. { lynx::NoteTool::randomise, "-tool-randomise.png" },
  25563. { lynx::NoteTool::scaleLevels, "-tool-scalelevels.png" },
  25564. { lynx::NoteTool::limit, "-tool-limit.png" },
  25565. { lynx::NoteTool::quantize, "-tool-quantize.png" },
  25566. { lynx::NoteTool::chop, "-tool-chop.png" },
  25567. { lynx::NoteTool::flam, "-tool-flam.png" },
  25568. { lynx::NoteTool::lfo, "-tool-lfo.png" },
  25569. { lynx::NoteTool::claw, "-tool-claw.png" },
  25570. { lynx::NoteTool::articulate, "-tool-articulate.png" },
  25571. { lynx::NoteTool::riffMachine, "-tool-riff.png" },
  25572. { lynx::NoteTool::chordProgression, "-tool-chords.png" } };
  25573. for (const auto& [tool, name] : tools)
  25574. saveWindow (lynx::makeNoteToolPanel (offline, tool, roll.noteIndicesForSnapshot(), roll.gridForSnapshot()), name);
  25575. }
  25576. // round 83: the event editor, with sample events on the selected channel's volume (removed afterwards)
  25577. {
  25578. const lynx::AutomationTarget volume { lynx::AutomationTargetKind::channelVolume, offline.getSelectedChannel() };
  25579. const auto before = offline.getSong().patterns[(std::size_t) offline.getSong().currentPattern].events;
  25580. offline.editSong ([&] (lynx::Song& s) {
  25581. auto& lane = lynx::eventedit::laneFor (s.patterns[(std::size_t) s.currentPattern], volume);
  25582. lynx::eventedit::line (lane, 0, lynx::ppq * 2, 0.2f, 0.9f, lynx::ticksPerStep);
  25583. lynx::prtools::LfoOptions lfo;
  25584. lfo.startSpeed = 7 * 4096; // one beat
  25585. lynx::eventedit::applyLfo (lane, lynx::ppq * 2, lynx::ppq * 4, lfo, lynx::ticksPerStep);
  25586. }, false);
  25587. saveWindow (lynx::makeEventEditor (offline, volume), "-eventeditor.png");
  25588. offline.editSong ([&] (lynx::Song& s) { s.patterns[(std::size_t) s.currentPattern].events = before; }, false);
  25589. // issue #86: the same editor on the Tempo target, with the project's own Tempo events (a sample ramp if none)
  25590. const lynx::AutomationTarget tempo { lynx::AutomationTargetKind::tempo, 0 };
  25591. offline.editSong ([&] (lynx::Song& s) {
  25592. auto& lane = lynx::eventedit::laneFor (s.patterns[(std::size_t) s.currentPattern], tempo);
  25593. if (lane.events.empty())
  25594. lynx::eventedit::line (lane, 0, lynx::ppq * 2, 0.05f, 0.11f, lynx::ticksPerStep);
  25595. }, false);
  25596. saveWindow (lynx::makeEventEditor (offline, tempo), "-eventeditor-tempo.png");
  25597. {
  25598. auto compact = lynx::makeEventEditor (offline, tempo); // the toolbar in a small window
  25599. compact->setSize (640, 300);
  25600. saveWindow (std::move (compact), "-eventeditor-tempo-small.png");
  25601. auto narrowest = lynx::makeEventEditor (offline, tempo); // the tool window's lower limit
  25602. narrowest->setSize (400, 300);
  25603. saveWindow (std::move (narrowest), "-eventeditor-tempo-narrowest.png");
  25604. }
  25605. offline.editSong ([&] (lynx::Song& s) { s.patterns[(std::size_t) s.currentPattern].events = before; }, false);
  25606. }
  25607. // round 86: the audio editor with a synthetic drum loop (markers, a region, a loop), waveform and spectrogram,
  25608. // and its menu items (-audioeditor-menu.txt)
  25609. {
  25610. namespace ae = lynx::audioedit;
  25611. ae::Document d;
  25612. d.title = "Drum loop";
  25613. d.audio.sampleRate = 44100.0;
  25614. const auto frames = (std::size_t) (44100 * 2);
  25615. d.audio.channels.assign (2, std::vector<float> (frames, 0.0f));
  25616. std::uint32_t seed = 7;
  25617. for (int hit = 0; hit < 8; ++hit)
  25618. {
  25619. const auto at = (std::size_t) hit * frames / 8;
  25620. const auto kick = hit % 2 == 0;
  25621. double phase = 0.0;
  25622. for (std::size_t i = 0; i < 12000 && at + i < frames; ++i)
  25623. {
  25624. seed = seed * 1664525u + 1013904223u;
  25625. const auto noise = (float) (seed >> 8) / 16777216.0f - 0.5f;
  25626. const auto t = (double) i / 44100.0;
  25627. phase += 2.0 * 3.141592653589793 * (kick ? 45.0 + 160.0 * std::exp (-t * 30.0) : 190.0) / 44100.0;
  25628. const auto body = (float) std::sin (phase) * (float) std::exp (-t * (kick ? 9.0 : 22.0));
  25629. const auto v = kick ? 0.85f * body : 0.35f * body + 0.6f * noise * (float) std::exp (-t * 18.0);
  25630. d.audio.channels[0][at + i] += v;
  25631. d.audio.channels[1][at + i] += kick ? v : v * 0.8f + 0.1f * noise * (float) std::exp (-t * 30.0);
  25632. }
  25633. }
  25634. ae::addMarker (d, (std::int64_t) frames / 8, "Snare");
  25635. ae::addRegion (d, { (std::int64_t) frames / 2, (std::int64_t) frames * 3 / 4 }, "Fill");
  25636. ae::setLoop (d, { 0, (std::int64_t) frames });
  25637. auto wave = lynx::makeAudioEditorForSnapshot (offline, d, false);
  25638. juce::File (prefix + "-audioeditor-menu.txt").replaceWithText (lynx::audioEditorMenuForSnapshot (*wave).joinIntoString ("\n") + "\n");
  25639. saveWindow (std::move (wave), "-audioeditor.png");
  25640. saveWindow (lynx::makeAudioEditorForSnapshot (offline, d, true), "-audioeditor-spectrum.png");
  25641. }
  25642. // warp markers (round 175a, M3): the audio editor of the first audio clip whose channel has warp markers,
  25643. // opened as the Playlist opens it, with its warp lane
  25644. {
  25645. const auto& song = offline.getSong();
  25646. for (int i = 0; i < (int) song.playlist.size(); ++i)
  25647. {
  25648. const auto& c = song.playlist[(std::size_t) i];
  25649. if (c.kind == lynx::ClipKind::audio && juce::isPositiveAndBelow (c.channel, (int) song.channels.size())
  25650. && song.channels[(std::size_t) c.channel].sampler.warp.size() >= 3)
  25651. {
  25652. if (auto panel = lynx::makeAudioEditorPanel (offline, c.channel, i, true))
  25653. saveWindow (std::move (panel), "-audioeditor-warp.png");
  25654. break;
  25655. }
  25656. }
  25657. }
  25658. // the tempo tapper after five steady taps (round 132)
  25659. saveWindow (lynx::makeTempoTapperForSnapshot (offline, 5, 128.0), "-tempotapper.png");
  25660. // the Channel Rack's piano-roll view (round 132)
  25661. ui.selectTabForSnapshot (0);
  25662. ui.getRackForSnapshot().setPianoRollView (true);
  25663. offline.dispatchPendingMessages();
  25664. saveSnapshot (ui, prefix + "-rack-pianoroll-view.png");
  25665. ui.getRackForSnapshot().setPianoRollView (false);
  25666. // the Channel Rack with the step graph lane (velocity), and the Euclidean fill window
  25667. ui.selectTabForSnapshot (0);
  25668. ui.getRackForSnapshot().setGraphLevelForSnapshot (0);
  25669. offline.dispatchPendingMessages();
  25670. saveSnapshot (ui, prefix + "-rack-graph.png");
  25671. ui.getRackForSnapshot().setGraphLevelForSnapshot (1);
  25672. saveSnapshot (ui, prefix + "-rack-graph-pan.png");
  25673. ui.getRackForSnapshot().toggleGraphLanes();
  25674. saveWindow (ui.getRackForSnapshot().makeEuclideanPanel (0), "-euclidean.png");
  25675. // the Mixer with three inserts selected and one armed for recording
  25676. ui.selectTabForSnapshot (3);
  25677. if (offline.getSong().mixer.size() > 4)
  25678. {
  25679. ui.getMixerForSnapshot().getStripsForSnapshot().setSelection ({ 1, 2, 3 }, 2);
  25680. offline.setInsertArmed (3, true);
  25681. offline.dispatchPendingMessages();
  25682. saveSnapshot (ui, prefix + "-mixer-multi.png");
  25683. // the armed insert with an audio input (its input row in the side panel, the level bar on the strip)
  25684. offline.editSong ([] (lynx::Song& s) { s.mixer[3].inputChannel = 0; });
  25685. ui.getMixerForSnapshot().selectTrack (3);
  25686. offline.dispatchPendingMessages();
  25687. saveSnapshot (ui, prefix + "-mixer-input.png");
  25688. offline.undo();
  25689. offline.setInsertArmed (3, false);
  25690. ui.getMixerForSnapshot().getStripsForSnapshot().setSelection ({}, 0);
  25691. }
  25692. // the Mixer's routing lane: an insert with sends selected (send knobs and wires)
  25693. if (offline.getSong().mixer.size() > 6)
  25694. {
  25695. int source = -1;
  25696. for (int t = 1; t < (int) offline.getSong().mixer.size() && source < 0; ++t)
  25697. if (! offline.getSong().mixer[(std::size_t) t].sends.empty())
  25698. source = t;
  25699. const auto temporary = source < 0;
  25700. if (temporary) // the demo has no sends: add two for the picture
  25701. {
  25702. source = 1;
  25703. 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); });
  25704. }
  25705. ui.getMixerForSnapshot().selectTrack (source);
  25706. offline.dispatchPendingMessages();
  25707. saveSnapshot (ui, prefix + "-mixer-sends.png");
  25708. if (temporary)
  25709. offline.editSong ([] (lynx::Song& s) { s.setRoute (1, 5, false); s.setRoute (1, 6, false); s.setRoute (4, 1, false); });
  25710. ui.getMixerForSnapshot().selectTrack (0);
  25711. }
  25712. // the Playlist with ripple editing on
  25713. ui.selectTabForSnapshot (2);
  25714. ui.getPlaylistForSnapshot().setRipple (true);
  25715. saveSnapshot (ui, prefix + "-playlist-ripple.png");
  25716. ui.getPlaylistForSnapshot().setRipple (false);
  25717. // FL's legacy Pattern Blocks (round 170f, issue #60): the section under the clip tracks, a row per pattern
  25718. {
  25719. const auto saved = offline.getSong();
  25720. offline.editSong ([] (lynx::Song& s) {
  25721. s.patternBlocksOn = true;
  25722. while (s.patterns.size() < 5) // a few rows to show (Drums, Bass...: copies of the demo's pattern)
  25723. lynx::clonePattern (s, (int) s.patterns.size() - 1);
  25724. const auto rows = juce::jmin (6, (int) s.patterns.size());
  25725. for (int r = 0; r < rows; ++r)
  25726. lynx::patternblocks::paintRange (s, r, (std::int64_t) (r % 3) * 4 * lynx::ppq * 2,
  25727. (std::int64_t) (8 + r * 2) * 4 * lynx::ppq);
  25728. }, false);
  25729. offline.dispatchPendingMessages();
  25730. saveSnapshot (ui, prefix + "-playlist-blocks.png");
  25731. // issue #127 (PR #132 and our follow-up): the Playlist's pencil, brush and eraser on the blocks, driven
  25732. // with real mouse events on the view. One picture per tool, and the gestures' results in
  25733. // <prefix>-playlist-blocks-tools.txt ("OK", or the checks that failed).
  25734. if (auto* blocks = ui.getPlaylistForSnapshot().getBlocksViewForSnapshot())
  25735. {
  25736. juce::StringArray failed;
  25737. const auto expect = [&failed] (bool ok, const char* what) { if (! ok) failed.add (what); };
  25738. const auto bar = offline.getSong().barTicks();
  25739. offline.editSong ([bar] (lynx::Song& s) {
  25740. s.blocks.clear();
  25741. for (std::size_t r = 0; r < 4 && r < s.patterns.size(); ++r)
  25742. s.patterns[r].lengthTicks = r == 1 ? 2 * bar : bar; // row 2 holds a 2-bar pattern
  25743. }, false);
  25744. offline.dispatchPendingMessages();
  25745. const auto source = juce::Desktop::getInstance().getMainMouseSource();
  25746. const juce::ModifierKeys left (juce::ModifierKeys::leftButtonModifier), right (juce::ModifierKeys::rightButtonModifier);
  25747. juce::Point<float> pressedAt;
  25748. const auto event = [&] (int row, std::int64_t tick, juce::ModifierKeys mods) {
  25749. const auto at = blocks->pointForSnapshot (row, tick).toFloat();
  25750. const auto now = juce::Time::getCurrentTime();
  25751. return juce::MouseEvent (source, at, mods, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, blocks, blocks, now, pressedAt, now, 1, false);
  25752. };
  25753. const auto press = [&] (int row, std::int64_t tick, juce::ModifierKeys mods) {
  25754. pressedAt = blocks->pointForSnapshot (row, tick).toFloat();
  25755. blocks->mouseDown (event (row, tick, mods));
  25756. };
  25757. const auto dragTo = [&] (int row, std::int64_t tick, juce::ModifierKeys mods) { blocks->mouseDrag (event (row, tick, mods)); };
  25758. const auto release = [&] (int row, std::int64_t tick) { blocks->mouseUp (event (row, tick, {})); };
  25759. // the starts of row `row`'s blocks, as "0,2,5" (bars from 0)
  25760. const auto rowBars = [&] (int row) {
  25761. juce::StringArray bars;
  25762. for (const auto& b : offline.getSong().blocks)
  25763. if (b.pattern == row)
  25764. bars.add (juce::String (b.start / bar) + (b.start % bar != 0 ? "+" : ""));
  25765. return bars.joinIntoString (",");
  25766. };
  25767. auto& tools = ui.getPlaylistForSnapshot();
  25768. // Pencil: a press on empty space places one block that follows the mouse along its row
  25769. tools.setToolForSnapshot (lynx::EditTool::pencil);
  25770. press (0, 2 * bar + 40, left);
  25771. expect (rowBars (0) == "2", "pencil: a press places one block");
  25772. dragTo (2, 5 * bar + 40, left); // (over another row: the block stays in its own)
  25773. release (2, 5 * bar + 40);
  25774. expect (rowBars (0) == "5" && rowBars (2).isEmpty(), "pencil: the placed block follows the drag in its row");
  25775. // a 2-bar block grabbed by its second bar keeps that bar under the mouse (it used to jump a bar)
  25776. press (1, 1 * bar + 40, left);
  25777. release (1, 1 * bar + 40);
  25778. expect (rowBars (1) == "1", "pencil: a click places the 2-bar block");
  25779. press (1, 2 * bar + 40, left);
  25780. dragTo (1, 2 * bar + bar / 2, left);
  25781. expect (rowBars (1) == "1", "move: a small move on the grabbed bar leaves the block in place");
  25782. dragTo (1, 4 * bar + 40, left);
  25783. release (1, 4 * bar + 40);
  25784. expect (rowBars (1) == "3", "move: the grabbed bar stays under the mouse");
  25785. offline.dispatchPendingMessages();
  25786. saveSnapshot (ui, prefix + "-playlist-blocks-pencil.png");
  25787. // Brush: a drag over empty space paints a run; a press on a block moves it
  25788. tools.setToolForSnapshot (lynx::EditTool::brush);
  25789. press (2, 0, left);
  25790. dragTo (2, 3 * bar + 40, left);
  25791. release (2, 3 * bar + 40);
  25792. expect (rowBars (2) == "0,1,2,3", "brush: a drag paints a run");
  25793. press (2, 3 * bar + 40, left);
  25794. dragTo (2, 6 * bar + 40, left);
  25795. release (2, 6 * bar + 40);
  25796. expect (rowBars (2) == "0,1,2,6", "brush: a press on a block moves it");
  25797. offline.dispatchPendingMessages();
  25798. saveSnapshot (ui, prefix + "-playlist-blocks-brush.png");
  25799. // Eraser, and the right button with any tool: only the blocks under the mouse, row by row
  25800. offline.editSong ([bar] (lynx::Song& s) {
  25801. for (int r = 0; r < 4 && r < (int) s.patterns.size(); ++r)
  25802. lynx::patternblocks::place (s, r, 8 * bar);
  25803. }, false);
  25804. offline.dispatchPendingMessages();
  25805. expect (rowBars (0) == "5,8" && rowBars (3) == "8", "eraser: the column is set up");
  25806. saveSnapshot (ui, prefix + "-playlist-blocks-eraser-before.png");
  25807. tools.setToolForSnapshot (lynx::EditTool::eraser);
  25808. press (0, 8 * bar + 40, left);
  25809. expect (rowBars (0) == "5" && rowBars (1) == "3,8" && rowBars (2) == "0,1,2,6,8" && rowBars (3) == "8",
  25810. "eraser: a click takes only the block under the mouse");
  25811. dragTo (1, 8 * bar + 60, left); // down one row: that row's block goes too, the rows below stay
  25812. release (1, 8 * bar + 60);
  25813. expect (rowBars (1) == "3" && rowBars (2) == "0,1,2,6,8" && rowBars (3) == "8", "eraser: the drag erases the rows it crosses, no others");
  25814. tools.setToolForSnapshot (lynx::EditTool::pencil);
  25815. press (3, 8 * bar + 40, right);
  25816. release (3, 8 * bar + 40);
  25817. expect (rowBars (3).isEmpty() && rowBars (2) == "0,1,2,6,8", "right click: erases only the block under the mouse");
  25818. offline.dispatchPendingMessages();
  25819. saveSnapshot (ui, prefix + "-playlist-blocks-eraser.png");
  25820. juce::File (prefix + "-playlist-blocks-tools.txt").replaceWithText (failed.isEmpty() ? juce::String ("OK\n") : "ERROR\n" + failed.joinIntoString ("\n") + "\n");
  25821. }
  25822. offline.editSong ([saved] (lynx::Song& s) { s = saved; }, false);
  25823. offline.dispatchPendingMessages();
  25824. }
  25825. // quick-add palette, and the Browser searching
  25826. saveWindow (ui.makeQuickAddForSnapshot(), "-quickadd.png");
  25827. ui.showDesktopForSnapshot (false);
  25828. ui.getBrowserForSnapshot().setSearchForSnapshot ("kick");
  25829. offline.dispatchPendingMessages();
  25830. saveSnapshot (ui, prefix + "-browser-search.png");
  25831. ui.getBrowserForSnapshot().setSearchForSnapshot ({});
  25832. ui.getBrowserForSnapshot().selectFirstSampleForSnapshot(); // the tree with a sample selected and its waveform
  25833. offline.dispatchPendingMessages();
  25834. saveSnapshot (ui, prefix + "-browser-tree.png");
  25835. // the Browser's PROJECT tab: the patterns, generators and audio files of the project in their colours
  25836. ui.getBrowserForSnapshot().showProjectForSnapshot();
  25837. offline.dispatchPendingMessages();
  25838. saveSnapshot (ui, prefix + "-browser-project.png");
  25839. ui.getBrowserForSnapshot().showPluginDatabaseForSnapshot(); // round 142: the Plugin database's FL engines
  25840. offline.dispatchPendingMessages();
  25841. saveSnapshot (ui, prefix + "-browser-plugins.png");
  25842. // round 190bf (fl190be Q1): the Plugin database's right-click menus, a folder's and an entry's (FL's System group)
  25843. saveMenus (juce::StringArray { "Plugin database: folder", "Plugin database: entry" }, ui.getBrowserForSnapshot().pluginDatabaseMenusForSnapshot(),
  25844. prefix + "-browser190bf-menus.png");
  25845. ui.getBrowserForSnapshot().setTab (lynx::BrowserComponent::allTab);
  25846. saveWindow (ui.getBrowserForSnapshot().makeFoldersPanelForSnapshot(), "-browser-folders.png"); // round 164
  25847. {
  25848. // round 164: the content filter leaves out the folders with nothing to list (a small library)
  25849. const auto lib = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-snapshot-library");
  25850. lib.deleteRecursively();
  25851. for (const auto* path : { "Drums/Kicks/kick 1.wav", "Drums/Kicks/kick 2.wav", "Drums/snare.wav", "Keys/pad.sf2", "Presets/Synth/lead.fst",
  25852. "Projects/beat.flp", "Projects/MIDI/chords.mid", "Notes/readme.txt", "Empty/Nothing/.keep" })
  25853. lib.getChildFile (path).create();
  25854. ui.showDesktopForSnapshot (false);
  25855. ui.getBrowserForSnapshot().showFilterForSnapshot (lib, lynx::browserview::ContentFilter::all);
  25856. offline.dispatchPendingMessages();
  25857. saveSnapshot (ui, prefix + "-browser164-all.png");
  25858. ui.getBrowserForSnapshot().showFilterForSnapshot (lib, lynx::browserview::ContentFilter::samples);
  25859. offline.dispatchPendingMessages();
  25860. saveSnapshot (ui, prefix + "-browser164-samples.png");
  25861. ui.getBrowserForSnapshot().showFilterForSnapshot (lib, lynx::browserview::ContentFilter::projects);
  25862. offline.dispatchPendingMessages();
  25863. saveSnapshot (ui, prefix + "-browser164-projects.png");
  25864. lib.deleteRecursively();
  25865. ui.getBrowserForSnapshot().resetViewForSnapshot();
  25866. }
  25867. {
  25868. // round 190as: "Find similar samples" on a small library of kicks, hats and pads (LYNX_SNAPSHOT_SIMILAR =
  25869. // "<folder>|<file>" lists a real folder instead)
  25870. auto lib = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-snapshot-similar");
  25871. auto query = lib.getChildFile ("Drums/Kicks/Kick 2.wav");
  25872. const auto real = juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIMILAR", {});
  25873. const auto made = real.isEmpty();
  25874. if (made)
  25875. {
  25876. lib.deleteRecursively();
  25877. juce::Random random (190);
  25878. const auto write = [&] (const juce::String& path, char kind, int v) {
  25879. const auto rate = 44100.0;
  25880. const auto frames = (int) (rate * (kind == 'k' ? 0.35 : kind == 'h' ? 0.09 : 2.5));
  25881. juce::AudioBuffer<float> audio (1, frames);
  25882. double phase = 0.0;
  25883. float last = 0.0f;
  25884. for (int i = 0; i < frames; ++i)
  25885. {
  25886. const auto t = i / rate;
  25887. float x = 0.0f;
  25888. if (kind == 'k')
  25889. {
  25890. phase += juce::MathConstants<double>::twoPi * ((46.0 + 3.0 * v) + 150.0 * std::exp (-t * 35.0)) / rate;
  25891. x = (float) (std::sin (phase) * std::exp (-t * (8.0 + v)));
  25892. }
  25893. else if (kind == 'h')
  25894. {
  25895. const auto n = random.nextFloat() * 2.0f - 1.0f;
  25896. x = (n - last) * 0.5f * (float) std::exp (-t * (50.0 + 12.0 * v));
  25897. last = n;
  25898. }
  25899. else
  25900. {
  25901. const auto base = 220.0 * std::pow (2.0, v / 12.0);
  25902. x = (float) (0.25 * std::min (1.0, t / 0.4) * std::min (1.0, (2.5 - t) / 0.5)
  25903. * (std::sin (juce::MathConstants<double>::twoPi * base * t) + std::sin (juce::MathConstants<double>::twoPi * base * 1.5 * t)));
  25904. }
  25905. audio.setSample (0, i, 0.8f * x);
  25906. }
  25907. const auto file = lib.getChildFile (path);
  25908. file.getParentDirectory().createDirectory();
  25909. juce::WavAudioFormat wav;
  25910. if (auto out = file.createOutputStream())
  25911. if (auto writer = std::unique_ptr<juce::AudioFormatWriter> (wav.createWriterFor (out.release(), rate, 1, 16, {}, 0)))
  25912. writer->writeFromAudioSampleBuffer (audio, 0, frames);
  25913. };
  25914. for (int v = 1; v <= 5; ++v)
  25915. {
  25916. write ("Drums/Kicks/Kick " + juce::String (v) + ".wav", 'k', v);
  25917. write ("Drums/Hats/Hat " + juce::String (v) + ".wav", 'h', v);
  25918. write ("Keys/Pad " + juce::String (v) + ".wav", 'p', v);
  25919. }
  25920. }
  25921. else
  25922. {
  25923. lib = juce::File (real.upToFirstOccurrenceOf ("|", false, false));
  25924. query = juce::File (real.fromFirstOccurrenceOf ("|", false, false));
  25925. }
  25926. ui.showDesktopForSnapshot (false);
  25927. ui.getBrowserForSnapshot().showFilterForSnapshot (lib, lynx::browserview::ContentFilter::all);
  25928. ui.getBrowserForSnapshot().findSimilarForSnapshot (query, lib);
  25929. offline.dispatchPendingMessages();
  25930. saveSnapshot (ui, prefix + "-browser-similar.png");
  25931. ui.getBrowserForSnapshot().setSearchForSnapshot ({});
  25932. if (made)
  25933. lib.deleteRecursively();
  25934. ui.getBrowserForSnapshot().resetViewForSnapshot();
  25935. }
  25936. // the undo history after a few edits
  25937. offline.editSong ([] (lynx::Song& s) { s.bpm += 1.0; });
  25938. offline.editSong ([] (lynx::Song& s) { if (! s.channels.empty()) s.channels[0].muted = ! s.channels[0].muted; });
  25939. offline.editSong ([] (lynx::Song& s) { if (! s.patterns.empty()) s.patterns[(std::size_t) s.currentPattern].notes.push_back ({}); });
  25940. offline.undo();
  25941. saveWindow (lynx::makeHistoryPanel (offline), "-history.png");
  25942. // spectral waveforms: a synthetic beat (kick, hats, a chord, a noise riser) as audio clips in spectral
  25943. // colours, zoomed in, classic and stereo; the same file in the Sampler editor and the Browser preview
  25944. {
  25945. const juce::File wav (prefix + "-wavedemo.wav");
  25946. writeWaveDemo (wav, offline.getSong().bpm);
  25947. const auto path = wav.getFullPathName();
  25948. const auto pathUtf8 = path.toStdString();
  25949. int samplerChannel = -1, firstTrack = 0;
  25950. offline.editSong ([&] (lynx::Song& s) {
  25951. for (const auto& clip : s.playlist)
  25952. firstTrack = std::max (firstTrack, clip.track + 1);
  25953. lynx::ChannelDef audio;
  25954. audio.name = "Beat (audio)";
  25955. audio.instrument = lynx::InstrumentKind::audioClip;
  25956. audio.samplePath = pathUtf8;
  25957. s.channels.push_back (audio);
  25958. const auto audioChannel = (int) s.channels.size() - 1;
  25959. lynx::ChannelDef sampler = audio;
  25960. sampler.name = "Beat (sampler)";
  25961. sampler.instrument = lynx::InstrumentKind::sampler;
  25962. sampler.sampler.regionStart = 0.06f;
  25963. sampler.sampler.regionEnd = 0.94f;
  25964. s.channels.push_back (sampler);
  25965. samplerChannel = (int) s.channels.size() - 1;
  25966. const auto bar = s.barTicks();
  25967. const auto whole = (std::int64_t) std::llround (8.0 * s.bpm / 60.0 * lynx::ppq);
  25968. lynx::Clip clip;
  25969. clip.kind = lynx::ClipKind::audio;
  25970. clip.channel = audioChannel;
  25971. clip.track = firstTrack;
  25972. clip.length = whole;
  25973. s.playlist.push_back (clip);
  25974. clip.track = firstTrack + 1; // a slice of it, later in the song
  25975. clip.start = bar;
  25976. clip.offset = bar;
  25977. clip.length = 2 * bar;
  25978. s.playlist.push_back (clip);
  25979. // taller rows for the audio (tracks can be resized: P18)
  25980. if ((int) s.playlistTracks.size() < firstTrack + 2)
  25981. s.playlistTracks.resize ((std::size_t) firstTrack + 2);
  25982. s.playlistTracks[(std::size_t) firstTrack].height = 80;
  25983. s.playlistTracks[(std::size_t) firstTrack + 1].height = 60;
  25984. });
  25985. offline.dispatchPendingMessages();
  25986. auto& cache = *lynx::ui::WaveformCache::getInstance();
  25987. cache.find (path, [&offline, path] { return offline.getSampleLibrary().load (path); });
  25988. cache.waitUntilIdle (30000);
  25989. ui.selectTabForSnapshot (2);
  25990. auto& playlist = ui.getPlaylistForSnapshot();
  25991. playlist.setTimeSelectionForSnapshot (0, 0);
  25992. {
  25993. // the Playlist alone (the floating Channel Rack would cover the clips)
  25994. auto saveSnapshot = [&playlist] (juce::Component&, const juce::String& file) { saveArea (playlist, playlist.getLocalBounds(), file); };
  25995. playlist.setViewForSnapshot (180.0, 0, std::max (0, firstTrack - 3));
  25996. saveSnapshot (ui, prefix + "-playlist-audio.png");
  25997. playlist.setViewForSnapshot (1400.0, 0, std::max (0, firstTrack - 3));
  25998. saveSnapshot (ui, prefix + "-playlist-audio-zoom.png");
  25999. lynx::ui::WaveformCache::stereo = true;
  26000. saveSnapshot (ui, prefix + "-playlist-audio-stereo.png");
  26001. lynx::ui::WaveformCache::stereo = false;
  26002. lynx::ui::WaveformCache::spectral = true;
  26003. playlist.setViewForSnapshot (180.0, 0, std::max (0, firstTrack - 3));
  26004. saveSnapshot (ui, prefix + "-playlist-audio-spectral.png");
  26005. lynx::ui::WaveformCache::spectral = false;
  26006. playlist.setViewForSnapshot (40.0, 0, 0);
  26007. saveSnapshot (ui, prefix + "-playlist-audio-far.png");
  26008. // LYNX_SNAPSHOT_AUDIO=a.wav;b.wav...: real audio as clips (default-height tracks, one tall,
  26009. // a fade, a reversed copy), at three zoom levels
  26010. if (const auto files = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_AUDIO", {}), ";", "");
  26011. ! files.isEmpty())
  26012. {
  26013. const auto realTrack = firstTrack + 2;
  26014. std::vector<juce::String> paths;
  26015. for (const auto& f : files)
  26016. if (juce::File (f.trim()).existsAsFile())
  26017. paths.push_back (f.trim());
  26018. offline.editSong ([&] (lynx::Song& s) {
  26019. const auto bar = s.barTicks();
  26020. const std::uint32_t colours[] = { 0, 0xffd9a441, 0xff6fb36a, 0xffb06fd0, 0xff5fb7c9, 0xffd06f6f };
  26021. for (std::size_t i = 0; i < paths.size(); ++i)
  26022. {
  26023. lynx::ChannelDef audio;
  26024. audio.name = juce::File (paths[i]).getFileNameWithoutExtension().toStdString();
  26025. audio.instrument = lynx::InstrumentKind::audioClip;
  26026. audio.samplePath = paths[i].toStdString();
  26027. audio.colour = colours[i % 6];
  26028. audio.sampler.stretchBeats = i % 2 == 0 ? 16.0f : 0.0f; // fitted to 4 bars, or as recorded
  26029. audio.sampler.keepPitch = true;
  26030. s.channels.push_back (audio);
  26031. lynx::Clip clip;
  26032. clip.kind = lynx::ClipKind::audio;
  26033. clip.channel = (int) s.channels.size() - 1;
  26034. clip.track = realTrack + (int) i;
  26035. clip.length = 4 * bar;
  26036. clip.fadeIn = i == 1 ? bar / 2 : 0;
  26037. s.playlist.push_back (clip);
  26038. clip.start = 4 * bar;
  26039. clip.fadeIn = 0;
  26040. clip.fadeOut = i == 0 ? bar : 0;
  26041. s.playlist.push_back (clip);
  26042. }
  26043. if ((int) s.playlistTracks.size() < realTrack + (int) paths.size())
  26044. s.playlistTracks.resize ((std::size_t) realTrack + paths.size());
  26045. if (! paths.empty())
  26046. s.playlistTracks[(std::size_t) realTrack].height = 90;
  26047. });
  26048. offline.dispatchPendingMessages();
  26049. for (const auto& path2 : paths)
  26050. cache.find (path2, [&offline, path2] { return offline.getSampleLibrary().load (path2); });
  26051. cache.waitUntilIdle (60000);
  26052. playlist.setViewForSnapshot (160.0, 0, std::max (0, realTrack - 4));
  26053. saveSnapshot (ui, prefix + "-playlist-real.png");
  26054. playlist.setViewForSnapshot (700.0, 0, std::max (0, realTrack - 1));
  26055. saveSnapshot (ui, prefix + "-playlist-real-zoom.png");
  26056. playlist.setViewForSnapshot (2400.0, 0, std::max (0, realTrack - 1));
  26057. saveSnapshot (ui, prefix + "-playlist-real-close.png");
  26058. playlist.setViewForSnapshot (50.0, 0, std::max (0, realTrack - 4));
  26059. saveSnapshot (ui, prefix + "-playlist-real-far.png");
  26060. // the clip menu of the first real clip
  26061. if (const auto menu = playlist.getClipMenuForSnapshot ((int) offline.getSong().playlist.size() - (int) paths.size() * 2); menu.getNumItems() > 0)
  26062. saveMenus (juce::StringArray { "Audio clip" }, std::vector<juce::PopupMenu> { menu }, prefix + "-clip-menu-audio.png");
  26063. if (const auto menu = playlist.getClipMenuForSnapshot (0); menu.getNumItems() > 0)
  26064. saveMenus (juce::StringArray { "Pattern clip" }, std::vector<juce::PopupMenu> { menu }, prefix + "-clip-menu-pattern.png");
  26065. // the clip menu's actions, run through the menu itself; results in -clip-actions.txt
  26066. {
  26067. juce::StringArray log;
  26068. auto clipOf = [&offline] (const std::string& channelName, int nth) {
  26069. const auto& sg = offline.getSong();
  26070. for (int i = 0; i < (int) sg.playlist.size(); ++i)
  26071. {
  26072. const auto& c = sg.playlist[(std::size_t) i];
  26073. if (c.kind == lynx::ClipKind::audio && c.channel >= 0 && sg.channels[(std::size_t) c.channel].name == channelName && nth-- == 0)
  26074. return i;
  26075. }
  26076. return -1;
  26077. };
  26078. std::function<bool (const juce::PopupMenu&, const juce::String&)> run = [&run] (const juce::PopupMenu& m, const juce::String& text) {
  26079. for (juce::PopupMenu::MenuItemIterator it (m); it.next();)
  26080. {
  26081. auto& item = it.getItem();
  26082. if (item.subMenu != nullptr && run (*item.subMenu, text))
  26083. return true;
  26084. // (without the menu mnemonic's mark: FL's underlined letters, round 190dz)
  26085. if (item.text.removeCharacters (juce::String::charToString (1)).startsWith (text) && item.isEnabled && item.action)
  26086. {
  26087. item.action();
  26088. return true;
  26089. }
  26090. }
  26091. return false;
  26092. };
  26093. auto act = [&] (const std::string& name, int nth, const juce::String& text) {
  26094. const auto clip = clipOf (name, nth);
  26095. const auto ok = clip >= 0 && run (playlist.getClipMenuForSnapshot (clip), text);
  26096. offline.dispatchPendingMessages();
  26097. return ok;
  26098. };
  26099. auto channelOf = [&] (const std::string& name) -> const lynx::ChannelDef* {
  26100. for (const auto& c : offline.getSong().channels)
  26101. if (c.name == name)
  26102. return &c;
  26103. return nullptr;
  26104. };
  26105. auto check = [&log] (const juce::String& what, bool ok) { log.add ((ok ? "OK " : "FAIL ") + what); };
  26106. const auto names = [&] { std::vector<std::string> n; for (auto& p2 : paths) n.push_back (juce::File (p2).getFileNameWithoutExtension().toStdString()); return n; }();
  26107. if (names.size() >= 4)
  26108. {
  26109. const auto channelsBefore = offline.getSong().channels.size();
  26110. check ("Reverse", act (names[2], 0, lynx::tr ("Reverse")) && channelOf (names[2])->sampler.reverse);
  26111. offline.undo();
  26112. offline.dispatchPendingMessages();
  26113. check ("Reverse undone", ! channelOf (names[2])->sampler.reverse);
  26114. act (names[2], 0, lynx::tr ("Reverse"));
  26115. check ("Make unique", act (names[3], 1, lynx::tr ("Make unique")) && offline.getSong().channels.size() == channelsBefore + 1
  26116. && channelOf (names[3] + " #2") != nullptr);
  26117. check ("Fit to tempo, resample", act (names[1], 0, lynx::tr ("Fit to tempo, resample ({0})", { juce::String() }).upToFirstOccurrenceOf ("(", false, false))
  26118. && channelOf (names[1])->sampler.stretchBeats > 0.0f && ! channelOf (names[1])->sampler.keepPitch);
  26119. const auto gainBefore = offline.getSong().playlist[(std::size_t) clipOf (names[0], 1)].gain;
  26120. check ("Normalize", act (names[0], 1, lynx::tr ("Normalize"))
  26121. && offline.getSong().playlist[(std::size_t) clipOf (names[0], 1)].gain != gainBefore);
  26122. const auto clipsBefore = offline.getSong().playlist.size();
  26123. check ("Split here", act (names[3], 0, lynx::tr ("Split here")) && offline.getSong().playlist.size() == clipsBefore + 1);
  26124. check ("Mute", act (names[0], 0, lynx::tr ("Mute")) && offline.getSong().playlist[(std::size_t) clipOf (names[0], 0)].muted);
  26125. check ("Copy + Paste here", act (names[0], 0, lynx::tr ("Copy")) && act (names[0], 1, lynx::tr ("Paste here"))
  26126. && offline.getSong().playlist.size() == clipsBefore + 2);
  26127. check ("Delete", act (names[0], 2, lynx::tr ("Delete")) && offline.getSong().playlist.size() == clipsBefore + 1);
  26128. check ("Chop to grid", act (names[3], 0, lynx::tr ("Chop to grid")) && offline.getSong().playlist.size() > clipsBefore + 1);
  26129. }
  26130. playlist.setViewForSnapshot (160.0, 0, std::max (0, realTrack - 4));
  26131. saveSnapshot (ui, prefix + "-playlist-real-actions.png");
  26132. juce::File (prefix + "-clip-actions.txt").replaceWithText (log.joinIntoString ("\n") + "\n");
  26133. }
  26134. }
  26135. }
  26136. saveWindow (lynx::makeChannelSettingsPanel (offline, samplerChannel), "-sampler-wave.png");
  26137. ui.showDesktopForSnapshot (false);
  26138. ui.getBrowserForSnapshot().showPreviewForSnapshot (wav);
  26139. saveSnapshot (ui, prefix + "-browser-preview.png");
  26140. }
  26141. }
  26142. // round 165o: every Label / button / tick box whose text the drawing squeezes below its minimum scale or cuts
  26143. // (an ellipsis), per language: `LYNX --lang de --snapshot shots/de` -> shots/de-textfit.txt
  26144. juce::File (prefix + "-textfit.txt").replaceWithText (textFitLog().joinIntoString ("\n") + "\n");
  26145. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  26146. quit();
  26147. }
  26148. // --snapshot: 8 s of a synthetic stereo beat whose parts sit in different bands (kick = low, chord = mid,
  26149. // hats and the noise riser = high), to show the spectral waveform colours
  26150. static void writeWaveDemo (const juce::File& file, double bpm)
  26151. {
  26152. constexpr double rate = 44100.0;
  26153. const auto frames = (int) (8.0 * rate);
  26154. juce::AudioBuffer<float> buffer (2, frames);
  26155. buffer.clear();
  26156. auto* l = buffer.getWritePointer (0);
  26157. auto* r = buffer.getWritePointer (1);
  26158. const auto beat = 60.0 / juce::jlimit (40.0, 300.0, bpm);
  26159. std::uint32_t noise = 0x9e3779b9u;
  26160. auto white = [&noise] {
  26161. noise ^= noise << 13;
  26162. noise ^= noise >> 17;
  26163. noise ^= noise << 5;
  26164. return (float) (noise & 0xffffff) / (float) 0x800000 - 1.0f;
  26165. };
  26166. float previous = 0.0f;
  26167. for (int i = 0; i < frames; ++i)
  26168. {
  26169. const auto t = i / rate;
  26170. const auto inBeat = std::fmod (t, beat);
  26171. const auto bar = (int) (t / (beat * 4.0));
  26172. float left = 0.0f, right = 0.0f;
  26173. // kick on every beat: a falling sine
  26174. {
  26175. const auto phase = 2.0 * juce::MathConstants<double>::pi * (48.0 * inBeat + 4.0 * (1.0 - std::exp (-inBeat * 30.0)));
  26176. const auto k = (float) (std::sin (phase) * std::exp (-inBeat * 7.0)) * 0.85f;
  26177. left += k;
  26178. right += k;
  26179. }
  26180. // hats on the off-beats: high-passed noise bursts, a little to the right
  26181. {
  26182. const auto h = std::fmod (t + beat * 0.5, beat);
  26183. const auto n = white();
  26184. const auto hp = (n - previous) * 0.5f;
  26185. previous = n;
  26186. const auto hat = hp * (float) std::exp (-h * 45.0) * 0.55f;
  26187. left += hat * 0.6f;
  26188. right += hat;
  26189. }
  26190. // a chord in the second and third bars (mid band)
  26191. if (bar == 1 || bar == 2)
  26192. {
  26193. const auto env = (float) std::min (1.0, std::min (t - beat * 4.0, beat * 12.0 - t) * 8.0);
  26194. float chord = 0.0f;
  26195. for (const auto hz : { 523.25, 659.25, 783.99 })
  26196. chord += (float) (std::sin (2.0 * juce::MathConstants<double>::pi * hz * t) + 0.3 * std::sin (4.0 * juce::MathConstants<double>::pi * hz * t));
  26197. left += chord * 0.09f * std::max (0.0f, env);
  26198. right += chord * 0.09f * std::max (0.0f, env);
  26199. }
  26200. // a white-noise riser over the last two seconds (high band)
  26201. if (t > 6.0)
  26202. {
  26203. const auto rise = (float) ((t - 6.0) / 2.0);
  26204. left += white() * 0.4f * rise * rise;
  26205. right += white() * 0.4f * rise * rise;
  26206. }
  26207. l[i] = left;
  26208. r[i] = right;
  26209. }
  26210. buffer.applyGain (0.9f / juce::jmax (1.0e-6f, buffer.getMagnitude (0, frames)));
  26211. file.deleteFile();
  26212. juce::WavAudioFormat wav;
  26213. if (std::unique_ptr<juce::AudioFormatWriter> writer { wav.createWriterFor (file.createOutputStream().release(), rate, 2, 24, {}, 0) })
  26214. writer->writeFromAudioSampleBuffer (buffer, 0, frames);
  26215. }
  26216. // the menu bar's menus side by side, drawn with the LookAndFeel as they appear when opened
  26217. static void saveMenus (lynx::MainComponent& ui, const juce::String& path)
  26218. {
  26219. const auto names = ui.getMenuNamesForSnapshot();
  26220. std::vector<juce::PopupMenu> source;
  26221. for (int m = 0; m < names.size(); ++m)
  26222. source.push_back (ui.getMenuForSnapshot (m));
  26223. saveMenus (names, source, path);
  26224. }
  26225. // menus side by side, each under its name
  26226. static void saveMenus (const juce::StringArray& names, const std::vector<juce::PopupMenu>& source, const juce::String& path)
  26227. {
  26228. auto& lf = juce::LookAndFeel::getDefaultLookAndFeel();
  26229. struct Laid
  26230. {
  26231. juce::PopupMenu menu;
  26232. int width = 0, height = 0;
  26233. };
  26234. std::vector<Laid> menus;
  26235. const auto border = lf.getPopupMenuBorderSize();
  26236. for (int m = 0; m < names.size(); ++m)
  26237. {
  26238. Laid laid { source[(std::size_t) m] };
  26239. int width = 160, height = 2 * border;
  26240. for (juce::PopupMenu::MenuItemIterator it (laid.menu); it.next();)
  26241. {
  26242. const auto& item = it.getItem();
  26243. int w = 0, h = 0;
  26244. lf.getIdealPopupMenuItemSize (item.text, item.isSeparator, item.isSectionHeader ? -1 : 0, w, h);
  26245. if (item.isSectionHeader) h += h / 2; // as JUCE does
  26246. if (item.shortcutKeyDescription.isNotEmpty() || item.text.containsChar ('\t'))
  26247. w += 90;
  26248. width = juce::jmax (width, w + 10);
  26249. height += h;
  26250. }
  26251. laid.width = width;
  26252. laid.height = height;
  26253. menus.push_back (std::move (laid));
  26254. }
  26255. int totalWidth = 16, totalHeight = 0;
  26256. for (const auto& l : menus)
  26257. {
  26258. totalWidth += l.width + 16;
  26259. totalHeight = juce::jmax (totalHeight, l.height + 32);
  26260. }
  26261. auto image = lynx::shot::canvas (totalWidth, totalHeight);
  26262. {
  26263. juce::Graphics g (image);
  26264. lynx::shot::logical (g);
  26265. g.fillAll (lynx::theme::colour::bg1);
  26266. int x = 16;
  26267. for (int m = 0; m < (int) menus.size(); ++m)
  26268. {
  26269. const auto& l = menus[(std::size_t) m];
  26270. g.setColour (lynx::theme::colour::textSecondary);
  26271. g.setFont (lynx::theme::font (lynx::theme::type::small, true));
  26272. g.drawText (names[m], x, 0, l.width, 24, juce::Justification::centredLeft);
  26273. {
  26274. juce::Graphics::ScopedSaveState state (g);
  26275. g.reduceClipRegion (x, 24, l.width, l.height);
  26276. g.setOrigin (x, 24);
  26277. lf.drawPopupMenuBackground (g, l.width, l.height);
  26278. int y = border;
  26279. bool first = true;
  26280. for (juce::PopupMenu::MenuItemIterator it (l.menu); it.next();)
  26281. {
  26282. const auto& item = it.getItem();
  26283. int w = 0, h = 0;
  26284. lf.getIdealPopupMenuItemSize (item.text, item.isSeparator, item.isSectionHeader ? -1 : 0, w, h);
  26285. if (item.isSectionHeader) h += h / 2; // as JUCE does
  26286. const juce::Rectangle<int> r (0, y, l.width, h);
  26287. auto text = item.text, shortcut = item.shortcutKeyDescription;
  26288. if (text.containsChar ('\t'))
  26289. {
  26290. shortcut = text.fromFirstOccurrenceOf ("\t", false, false);
  26291. text = text.upToFirstOccurrenceOf ("\t", false, false);
  26292. }
  26293. if (item.isSectionHeader)
  26294. lf.drawPopupMenuSectionHeader (g, r, text);
  26295. else
  26296. lf.drawPopupMenuItem (g, r, item.isSeparator, item.isEnabled, first && ! item.isSeparator && m == 0, item.isTicked,
  26297. item.subMenu != nullptr, text, shortcut, item.image.get(), nullptr);
  26298. first = false;
  26299. y += h;
  26300. }
  26301. }
  26302. x += l.width + 16;
  26303. }
  26304. }
  26305. const auto file = lynx::shot::file (juce::File (path));
  26306. file.deleteFile();
  26307. juce::PNGImageFormat png;
  26308. if (auto out = file.createOutputStream())
  26309. png.writeImageToStream (image, *out);
  26310. }
  26311. static void writePng (const juce::Image& image, const juce::String& path)
  26312. {
  26313. const auto file = lynx::shot::file (juce::File (path));
  26314. file.deleteFile();
  26315. juce::PNGImageFormat png;
  26316. if (auto out = file.createOutputStream())
  26317. png.writeImageToStream (image, *out);
  26318. }
  26319. // the splash screen: one settled frame, and a strip of frames through its animation
  26320. static void saveSplashFrames (const juce::String& prefix)
  26321. {
  26322. lynx::SplashScreen splash;
  26323. splash.setStatus (lynx::tr ("Loading the workspace..."));
  26324. splash.setTimeForSnapshot (1.6);
  26325. writePng (lynx::shot::snapshot (splash), prefix + "-splash.png");
  26326. const double times[] = { 0.10, 0.22, 0.29, 0.40, 0.58, 0.75, 1.00, 1.30 };
  26327. const auto w = lynx::SplashScreen::width / 2, h = lynx::SplashScreen::height / 2;
  26328. auto strip = lynx::shot::canvas (4 * (w + 8) + 8, 2 * (h + 8) + 8);
  26329. {
  26330. juce::Graphics g (strip);
  26331. lynx::shot::logical (g);
  26332. g.fillAll (lynx::theme::colour::bg1);
  26333. for (int i = 0; i < 8; ++i)
  26334. {
  26335. splash.setTimeForSnapshot (times[i]);
  26336. const auto frame = lynx::shot::snapshot (splash);
  26337. g.drawImage (frame, 8 + (i % 4) * (w + 8), 8 + (i / 4) * (h + 8), w, h, 0, 0, frame.getWidth(), frame.getHeight());
  26338. }
  26339. }
  26340. writePng (strip, prefix + "-splash-frames.png");
  26341. }
  26342. // every icon at 16, 20 and 24 px (at `scale`, e.g. 1.5 for a 150% display), in the toolbar's
  26343. // colours: at rest, hovered and switched on
  26344. static void saveIconSheet (const juce::String& path, float scale)
  26345. {
  26346. scale *= lynx::shot::scale();
  26347. const int sizes[] = { 16, 20, 24 };
  26348. const int cell = 34, columns = 3 * 3, labelWidth = 110;
  26349. const auto w = labelWidth + columns * cell + 16, h = lynx::iconCount * cell + 16;
  26350. juce::Image image (juce::Image::ARGB, juce::roundToInt ((float) w * scale), juce::roundToInt ((float) h * scale), true);
  26351. {
  26352. juce::Graphics g (image); // (drawing is flushed when it goes out of scope)
  26353. g.addTransform (juce::AffineTransform::scale (scale));
  26354. g.fillAll (lynx::theme::colour::bg3);
  26355. g.setFont (lynx::theme::font (lynx::theme::type::small));
  26356. for (int i = 1; i < lynx::iconCount; ++i)
  26357. {
  26358. const auto y = 8 + (i - 1) * cell;
  26359. g.setColour (lynx::theme::colour::textDisabled);
  26360. g.drawText (juce::String (i), 8, y, labelWidth - 8, cell, juce::Justification::centredLeft);
  26361. for (int v = 0; v < 3; ++v)
  26362. for (int s = 0; s < 3; ++s)
  26363. {
  26364. const juce::Rectangle<float> box ((float) (labelWidth + (v * 3 + s) * cell), (float) y, (float) cell, (float) cell);
  26365. const auto bg = v == 2 ? lynx::theme::colour::accent : v == 1 ? lynx::theme::colour::bg5 : lynx::theme::colour::bg3;
  26366. g.setColour (bg);
  26367. g.fillRoundedRectangle (box.reduced (2.0f), 4.0f);
  26368. const auto fg = v == 2 ? lynx::theme::colour::onAccent : v == 1 ? lynx::theme::colour::textPrimary
  26369. : lynx::theme::colour::textSecondary.brighter (0.25f);
  26370. lynx::icons::draw (g, (lynx::Icon) i, box.withSizeKeepingCentre ((float) sizes[s], (float) sizes[s]), fg);
  26371. }
  26372. }
  26373. }
  26374. writePng (image, path);
  26375. }
  26376. // a part of a component (e.g. the main toolbar)
  26377. static void saveArea (juce::Component& c, juce::Rectangle<int> area, const juce::String& path)
  26378. {
  26379. const auto file = lynx::shot::file (juce::File (path));
  26380. file.deleteFile();
  26381. juce::PNGImageFormat png;
  26382. if (auto out = file.createOutputStream())
  26383. png.writeImageToStream (lynx::shot::snapshot (c, area), *out);
  26384. }
  26385. static void savePng (const juce::Image& image, const juce::String& path)
  26386. {
  26387. const auto file = lynx::shot::file (juce::File (path));
  26388. file.deleteFile();
  26389. juce::PNGImageFormat png;
  26390. if (auto out = file.createOutputStream())
  26391. png.writeImageToStream (image, *out);
  26392. }
  26393. // -toolbar-tips.png: the top of the window with the bubbles of a few controls as they appear under the
  26394. // mouse; -tips-sheet.png: every quick tip of the window, to check names, shortcuts and translations
  26395. static void saveQuickTips (lynx::MainComponent& ui, const juce::String& prefix)
  26396. {
  26397. const auto tips = ui.getQuickTipsForSnapshot();
  26398. const auto top = juce::Rectangle<int> (0, 0, ui.getWidth(), juce::jmin (ui.getHeight(), ui.getToolbarBoundsForSnapshot().getHeight() + 72));
  26399. auto image = lynx::shot::snapshot (ui, top);
  26400. {
  26401. juce::Graphics g (image);
  26402. lynx::shot::logical (g);
  26403. const juce::String shown[] = { lynx::tr ("Pattern mode"), lynx::tr ("Play"), lynx::tr ("Metronome"), lynx::tr ("Mixer"), lynx::tr ("Save project"),
  26404. lynx::tr ("Window options"), lynx::tr ("Close") };
  26405. std::vector<juce::Rectangle<int>> used;
  26406. for (const auto& [area, tip] : tips)
  26407. {
  26408. const auto name = tip.upToFirstOccurrenceOf ("\t", false, false);
  26409. if (std::find (std::begin (shown), std::end (shown), name) == std::end (shown))
  26410. continue;
  26411. const auto bubble = lynx::ui::quickTipBounds (tip, area, top);
  26412. if (std::any_of (used.begin(), used.end(), [&] (const auto& r) { return r.intersects (bubble); }))
  26413. continue;
  26414. used.push_back (bubble);
  26415. g.setColour (juce::Colours::white.withAlpha (0.075f)); // the hovered control
  26416. g.fillRoundedRectangle (area.toFloat().reduced (0.5f), lynx::theme::radius::md);
  26417. lynx::ui::paintQuickTip (g, bubble.toFloat(), tip);
  26418. }
  26419. }
  26420. savePng (image, prefix + "-toolbar-tips.png");
  26421. // the sheet: bubbles in rows
  26422. const int width = 900;
  26423. int x = 12, y = 12;
  26424. std::vector<std::pair<juce::Rectangle<int>, juce::String>> placed;
  26425. for (const auto& [area, tip] : tips)
  26426. {
  26427. auto r = lynx::ui::quickTipSize (tip);
  26428. if (x + r.getWidth() > width - 12)
  26429. {
  26430. x = 12;
  26431. y += r.getHeight() + 10;
  26432. }
  26433. placed.emplace_back (r.withPosition (x, y), tip);
  26434. x += r.getWidth() + 10;
  26435. }
  26436. auto sheet = lynx::shot::canvas (width, y + 20 + 12);
  26437. {
  26438. juce::Graphics g (sheet);
  26439. lynx::shot::logical (g);
  26440. g.fillAll (lynx::theme::colour::bg3);
  26441. for (const auto& [r, tip] : placed)
  26442. lynx::ui::paintQuickTip (g, r.toFloat(), tip);
  26443. }
  26444. savePng (sheet, prefix + "-tips-sheet.png");
  26445. }
  26446. static juce::StringArray& textFitLog()
  26447. {
  26448. static juce::StringArray log;
  26449. return log;
  26450. }
  26451. // drawFittedText would shrink `text` below `minScale` or cut it: fewer visible glyphs than the text has
  26452. static bool textIsCut (const juce::Font& font, const juce::String& text, juce::Rectangle<int> area, int maxLines, float minScale)
  26453. {
  26454. if (text.trim().isEmpty() || area.getWidth() <= 4 || area.getHeight() <= 4)
  26455. return false;
  26456. auto visible = [] (juce::GlyphArrangement& ga) {
  26457. int n = 0;
  26458. for (int i = 0; i < ga.getNumGlyphs(); ++i)
  26459. n += ga.getGlyph (i).isWhitespace() ? 0 : 1;
  26460. return n;
  26461. };
  26462. juce::GlyphArrangement fitted, full;
  26463. fitted.addFittedText (font, text, 0.0f, 0.0f, (float) area.getWidth(), (float) area.getHeight(), juce::Justification::centredLeft,
  26464. juce::jmax (1, maxLines), minScale);
  26465. full.addLineOfText (font, text, 0.0f, 0.0f);
  26466. return visible (fitted) < visible (full);
  26467. }
  26468. // walks the visible components under `root` and logs the texts that don't fit (labels, text buttons, tick boxes)
  26469. static void checkTextFit (juce::Component& root, const juce::String& where)
  26470. {
  26471. std::function<void (juce::Component&)> visit = [&] (juce::Component& c) {
  26472. if (! c.isVisible() || c.getWidth() <= 0 || c.getHeight() <= 0)
  26473. return;
  26474. juce::String text;
  26475. bool cut = false;
  26476. if (auto* label = dynamic_cast<juce::Label*> (&c); label != nullptr && ! label->isBeingEdited())
  26477. {
  26478. const auto font = label->getLookAndFeel().getLabelFont (*label);
  26479. const auto area = label->getBorderSize().subtractedFrom (label->getLocalBounds());
  26480. text = label->getText();
  26481. cut = textIsCut (font, text, area, juce::jmax (1, (int) ((float) area.getHeight() / font.getHeight())),
  26482. label->getMinimumHorizontalScale());
  26483. }
  26484. else if (auto* toggle = dynamic_cast<juce::ToggleButton*> (&c))
  26485. {
  26486. const auto tick = juce::jmin (16.0f, (float) c.getHeight() - 4.0f);
  26487. text = toggle->getButtonText();
  26488. cut = textIsCut (juce::Font (lynx::theme::font (juce::jmin ((float) lynx::theme::type::body, (float) c.getHeight() * 0.75f))), text,
  26489. c.getLocalBounds().withTrimmedLeft (juce::roundToInt (tick) + 8).withTrimmedRight (2), 2, 0.85f);
  26490. }
  26491. else if (auto* button = dynamic_cast<juce::TextButton*> (&c);
  26492. button != nullptr && (int) button->getProperties().getWithDefault (lynx::theme::LookAndFeel::iconProperty, 0) == 0)
  26493. {
  26494. text = button->getButtonText();
  26495. cut = textIsCut (button->getLookAndFeel().getTextButtonFont (*button, button->getHeight()), text,
  26496. button->getLocalBounds().reduced (juce::jmin (8, button->getWidth() / 6), 0), 2, 0.85f);
  26497. }
  26498. if (cut)
  26499. {
  26500. juce::String path;
  26501. for (auto* p = &c; p != nullptr && p != &root; p = p->getParentComponent())
  26502. if (p->getName().isNotEmpty())
  26503. path = p->getName() + (path.isEmpty() ? "" : "/") + path;
  26504. const auto line = where + " | " + juce::String (c.getWidth()) + "x" + juce::String (c.getHeight()) + " | " + text.replace ("\n", "\\n")
  26505. + (path.isEmpty() ? juce::String() : " | " + path);
  26506. textFitLog().addIfNotAlreadyThere (line);
  26507. }
  26508. for (auto* child : c.getChildren())
  26509. visit (*child);
  26510. };
  26511. visit (root);
  26512. }
  26513. static void saveSnapshot (juce::Component& c, const juce::String& path)
  26514. {
  26515. checkTextFit (c, juce::File (path).getFileNameWithoutExtension());
  26516. const auto file = lynx::shot::file (juce::File (path));
  26517. file.deleteFile();
  26518. juce::PNGImageFormat png;
  26519. if (auto out = file.createOutputStream())
  26520. png.writeImageToStream (lynx::shot::snapshot (c), *out);
  26521. }
  26522. class MainWindow final : public juce::DocumentWindow
  26523. {
  26524. public:
  26525. MainWindow (const juce::String& name, lynx::AudioEngine& engine)
  26526. : DocumentWindow (name, lynx::theme::window, DocumentWindow::allButtons, false)
  26527. {
  26528. // (round 190hd) one desktop window, made with the native title bar: before, JUCE made one with its own title
  26529. // bar and setUsingNativeTitleBar made it again (~20-35 ms each, the Direct2D context included)
  26530. setUsingNativeTitleBar (true);
  26531. addToDesktop();
  26532. setIcon (lynx::logoImage());
  26533. startupTrace.mark (" window: its desktop window (native title bar), icon");
  26534. content = new lynx::MainComponent (engine);
  26535. setContentOwned (content, true);
  26536. startupTrace.mark (" window: content set");
  26537. setResizable (true, true);
  26538. setResizeLimits (800, 400, 10000, 10000);
  26539. // ~88% of the main display's usable area (at least the UI's design size, but never larger than the
  26540. // display: the AppImage catalog test runs on an 800x600 screen)
  26541. if (const auto* display = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay())
  26542. {
  26543. const auto area = display->userArea;
  26544. const auto fit = [] (int design, int available) {
  26545. return juce::jmin (available, juce::jmax (design, (int) (available * 0.88)));
  26546. };
  26547. setSize (fit (getWidth(), area.getWidth()), fit (getHeight(), area.getHeight()));
  26548. }
  26549. centreWithSize (getWidth(), getHeight());
  26550. // where it was last time (round 167v); the first start opens maximized, the Playlist filling the screen
  26551. // with the Browser at the left and the Channel Rack above it, like FL Studio's first start
  26552. const auto saved = stateFile().loadFileAsString().trim();
  26553. // (LYNX_TEST_MODE keeps the fixed-size window scripted checks expect, unless LYNX_TEST_MAXIMIZE=1)
  26554. const auto firstStart = saved.isEmpty()
  26555. && (! lynx::platform::testMode() || juce::SystemStats::getEnvironmentVariable ("LYNX_TEST_MAXIMIZE", {}) == "1");
  26556. maximiseOnReveal = firstStart || saved.startsWithIgnoreCase ("fs");
  26557. if (saved.isNotEmpty())
  26558. restoreWindowStateFromString (saved.startsWithIgnoreCase ("fs") ? saved.substring (2).trim() : saved);
  26559. }
  26560. // Shows the window (built hidden while the splash screen is up).
  26561. void reveal()
  26562. {
  26563. if (lynx::uitrace::enabled()) // LYNX_TRACE_UI: the frames per second and the longest gap in ui.log (round 173f)
  26564. watchFrames ({});
  26565. setVisible (true);
  26566. lynx::applyWindowChrome (*this);
  26567. lynx::fitWindowOnScreen (*this); // a size saved at another UI zoom still fits (round 163)
  26568. if (maximiseOnReveal)
  26569. setFullScreen (true); // (a title-bar window: maximized, the taskbar stays)
  26570. toFront (true);
  26571. content->grabKeyboardFocus();
  26572. // issue #62: the detached panels restored with the layout (built before this window was shown): their saved
  26573. // place and above it, once the window manager has placed this one
  26574. juce::Timer::callAfterDelay (250, [safe = juce::Component::SafePointer<MainWindow> (this)] {
  26575. if (safe != nullptr)
  26576. safe->content->restoreDetachedWindows();
  26577. });
  26578. }
  26579. // Runs `then` once, right after the window's next frame (round 190go: the audio device opens behind the
  26580. // window's first frame, not before it); at the latest after 300 ms (a window that paints nothing: minimised).
  26581. void whenPainted (std::function<void()> then)
  26582. {
  26583. afterPaint = std::move (then);
  26584. afterPaintPosted = false;
  26585. repaint();
  26586. juce::Timer::callAfterDelay (300, [safe = juce::Component::SafePointer<MainWindow> (this)] {
  26587. if (safe != nullptr)
  26588. safe->runAfterPaint();
  26589. });
  26590. }
  26591. void runAfterPaint()
  26592. {
  26593. if (auto then = std::exchange (afterPaint, nullptr))
  26594. then();
  26595. }
  26596. // The window's place and maximized state for the next start (main-window.txt in the settings folder).
  26597. void saveState() { stateFile().replaceWithText (getWindowStateAsString()); }
  26598. static juce::File stateFile() { return lynx::PluginHost::settingsFolder().getChildFile ("main-window.txt"); }
  26599. void openFile (const juce::File& file) { content->openFile (file); }
  26600. lynx::MainComponent& getContent() { return *content; }
  26601. void showSetupWizard() { content->showSetupWizard(); }
  26602. void confirmDiscard (std::function<void()> then) { content->confirmDiscard (std::move (then)); }
  26603. void closeButtonPressed() override { JUCEApplication::getInstance()->systemRequestedQuit(); }
  26604. // Every frame the window paints, with its dirty area (ui/FrameProbe.h; --uiperf, LYNX_TRACE_UI). The trace keeps
  26605. // counting when --uiperf watches too.
  26606. void watchFrames (std::function<void (double, juce::Rectangle<int>)> callback)
  26607. {
  26608. if (probe == nullptr)
  26609. {
  26610. probe = std::make_unique<lynx::ui::FrameProbe>();
  26611. Component::addAndMakeVisible (*probe); // (ResizableWindow hides the plain overload)
  26612. probe->setBounds (getLocalBounds());
  26613. }
  26614. probe->onFrame = [callback = std::move (callback)] (double now, juce::Rectangle<int> area) {
  26615. if (lynx::uitrace::enabled())
  26616. lynx::uitrace::frame (now);
  26617. if (callback)
  26618. callback (now, area);
  26619. };
  26620. }
  26621. void resized() override
  26622. {
  26623. DocumentWindow::resized();
  26624. if (probe != nullptr)
  26625. probe->setBounds (getLocalBounds());
  26626. }
  26627. // --uiperf: the time of each frame the window paints (its own paint, then every child's, up to the last)
  26628. std::function<void (double)> onFrame;
  26629. void paint (juce::Graphics& g) override
  26630. {
  26631. if (onFrame)
  26632. frameStart = juce::Time::getMillisecondCounterHiRes();
  26633. DocumentWindow::paint (g);
  26634. }
  26635. void paintOverChildren (juce::Graphics& g) override
  26636. {
  26637. DocumentWindow::paintOverChildren (g);
  26638. if (afterPaint != nullptr && ! std::exchange (afterPaintPosted, true)) // (the frame is presented first)
  26639. juce::MessageManager::callAsync ([safe = juce::Component::SafePointer<MainWindow> (this)] {
  26640. if (safe != nullptr)
  26641. safe->runAfterPaint();
  26642. });
  26643. if (onFrame && frameStart > 0.0)
  26644. onFrame (juce::Time::getMillisecondCounterHiRes() - frameStart);
  26645. frameStart = 0.0;
  26646. }
  26647. private:
  26648. lynx::MainComponent* content = nullptr; // owned by the window
  26649. std::unique_ptr<lynx::ui::FrameProbe> probe; // (on top of the content; see watchFrames)
  26650. double frameStart = 0.0;
  26651. bool maximiseOnReveal = false;
  26652. std::function<void()> afterPaint; // (whenPainted)
  26653. bool afterPaintPosted = false;
  26654. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MainWindow)
  26655. };
  26656. lynx::theme::LookAndFeel lookAndFeel;
  26657. std::unique_ptr<lynx::AudioEngine> engine;
  26658. std::unique_ptr<lynx::RemoteControl> remoteControl;
  26659. std::unique_ptr<juce::XmlElement> savedDeviceState; // --rtstress: the user's device before this run's --type/--buffer
  26660. // Hidden test mode --asiodll "<driver.dll>[|{CLSID}]" (REA round 97): an ASIO driver loaded straight from its file,
  26661. // without registering it, listed as the driver type "ASIO driver file". True when one was added.
  26662. bool addDriverFileDeviceType()
  26663. {
  26664. const auto args = juce::JUCEApplication::getCommandLineParameterArray();
  26665. const auto i = args.indexOf ("--asiodll");
  26666. if (i < 0 || i + 1 >= args.size() || engine == nullptr)
  26667. return false;
  26668. auto& devices = engine->getDeviceManager();
  26669. devices.getAvailableDeviceTypes(); // creates the standard types first
  26670. for (auto* t : devices.getAvailableDeviceTypes())
  26671. if (t->getTypeName() == lynx::dllAsioTypeName)
  26672. return true;
  26673. auto type = lynx::makeDllAsioDeviceType (args[i + 1].unquoted());
  26674. if (type == nullptr)
  26675. return false;
  26676. devices.addAudioDeviceType (std::move (type));
  26677. return true;
  26678. }
  26679. void restoreSavedDeviceState()
  26680. {
  26681. if (engine != nullptr)
  26682. engine->restoreAudioDeviceState (savedDeviceState.get());
  26683. }
  26684. std::unique_ptr<MainWindow> mainWindow;
  26685. std::unique_ptr<juce::Timer> perf; // --uiperf
  26686. std::unique_ptr<lynx::StartupSplash> splash;
  26687. static constexpr double landingSeconds = 1.05; // the logo's drop (SplashScreen::remainingDuration's `landing`)
  26688. std::shared_future<std::pair<juce::Image, double>> graphicsDeviceJob; // (round 190hd) holds the graphics device
  26689. bool graphicsDeviceMarked = false, windowRevealed = false;
  26690. std::future<std::shared_ptr<const lynx::SampleData>> startupSampleJob; // (round 190go: the built-in start-up sound)
  26691. bool startedAfterWindow = false, startupSoundPlayed = false;
  26692. double splashDuration = lynx::SplashScreen::minimumDuration; // seconds of its clock (round 121: from the process start)
  26693. lynx::StartupOptions startupOptions;
  26694. juce::File fileToOpen;
  26695. bool startupFileHandled = false;
  26696. bool startWithoutPlugins = false; // --no-plugins project.lynx (round 190ap)
  26697. juce::File openTimeReport; // --opentime
  26698. int openTimeIdleSeconds = 10;
  26699. };
  26700. START_JUCE_APPLICATION (LynxApplication)