Main.cpp 1.7 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596
  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/PerfProjects.h"
  62. #include "core/ShowcaseSong.h"
  63. #include "core/RenderAhead.h"
  64. #include "core/SynthPresets.h"
  65. #include "core/FlWrapper.h"
  66. #include "engine/AudioEngine.h"
  67. #include "engine/ProjectDowngrade.h"
  68. #include "core/ClipLauncher.h"
  69. #include "core/DirectWaveState.h"
  70. #include "core/MixSnapshots.h"
  71. #include "core/VoiceShift.h"
  72. #include "core/TempoMarkers.h"
  73. #include "engine/RemoteControl.h"
  74. #include "engine/RemoteError.h"
  75. #include "ui/RemoteControlSettings.h"
  76. #include "engine/PreviewPlayer.h"
  77. #include "engine/Metronome.h"
  78. #include "engine/AudioLogger.h"
  79. #include "engine/DllAsioDevice.h"
  80. #include "engine/PipeWireDevice.h"
  81. #include "platform/LinuxRealtime.h"
  82. #include "engine/PowerHints.h"
  83. #include "engine/Exporter.h"
  84. #include "engine/FlStudioExport.h"
  85. #include "engine/MidiFileIo.h"
  86. #include "engine/PluginHost.h"
  87. #include "engine/Vst3NoteTuning.h"
  88. #include "engine/PluginSandbox.h"
  89. #include "engine/Bridge32Test.h"
  90. #include "engine/ClapFormat.h"
  91. #include "engine/ClapTeardownTest.h"
  92. #include "core/EdisonFx.h"
  93. #include "engine/ProjectFile.h"
  94. #include "ui/RemoteControl.h"
  95. #include "core/FlControlMenus.h"
  96. #include "core/PlaylistOps.h"
  97. #include "core/Sha256.h"
  98. #include "engine/SessionPack.h"
  99. #include "engine/LiveTest.h"
  100. #include "engine/ShortExportTest.h"
  101. #include "core/SessionIds.h"
  102. #include "core/SessionParts.h"
  103. #include "engine/SampleLibrary.h"
  104. #include "engine/Text.h"
  105. #include "platform/FileTypes.h"
  106. #include "platform/Package.h"
  107. #include "core/AlsExport.h"
  108. #include "core/AlsImport.h"
  109. #include "core/PianoRollScript.h"
  110. #include "ui/ScriptPanel.h"
  111. #include "ui/AlsExportDialog.h"
  112. #include "ui/LiveRemoteUi.h"
  113. #include "ui/GamepadInput.h"
  114. #include "ui/SettingsPages.h"
  115. #include "ui/OtherAppsExport.h"
  116. #include "ui/TimerWhileShowing.h"
  117. #include "ui/MixerBasicsCheck.h"
  118. #include "ui/VideoPlayerView.h"
  119. #include "ui/VideoMedia.h"
  120. #include "ui/VideoTracks.h"
  121. #include "ui/AdrWindow.h"
  122. #include "ui/PlaylistComponent.h"
  123. #include "ui/PictureCheck.h"
  124. #include "ui/PatternBlocksView.h"
  125. #include "ui/PaintAB.h"
  126. #include <typeinfo>
  127. #include "ui/PatcherEditor.h"
  128. #include "ui/VisualEditors.h"
  129. #include "ui/FlExtraEditors.h"
  130. #include "ui/VisualGl.h"
  131. #include "ui/DanceView.h"
  132. #include "ui/PluginPresetMenu.h"
  133. #include "ui/GeneratorPresetMenu.h"
  134. #include "core/GeneratorPresets.h"
  135. #include "ui/PluginWindow.h"
  136. #include "ui/Motion.h"
  137. #include "ui/NativeChild.h"
  138. #include "ui/Workspace.h"
  139. #include "ui/PluginThumbs.h"
  140. #include "ui/ClipProperties.h"
  141. #include "ui/NewProjectDialog.h"
  142. #include "ui/PluginMonitorWindow.h"
  143. #include "ui/TouchKeyboard.h"
  144. #include "ui/AutomationUi.h"
  145. #include "ui/PluginSkin.h"
  146. #include "ui/ChannelSettings.h"
  147. #include "ui/TempoDetectionDialog.h"
  148. #include "ui/AudioClipboard.h"
  149. #include "ui/FlVoicePanel.h"
  150. #include "ui/SlicexEditor.h"
  151. #include "ui/DirectWaveEditor.h"
  152. #include "ui/FruitySlicerEditor.h"
  153. #include "core/GrossBeat.h"
  154. #include "core/LynxBanks.h"
  155. #include "core/NativeEngines.h"
  156. #include "ui/ControllerEditors.h"
  157. #include "ui/NewtoneEditor.h"
  158. #include "core/NewtoneFx.h"
  159. #include "core/FormulaController.h"
  160. #include "core/MidiControls.h"
  161. #include "core/FlSynths.h"
  162. #include "core/SoundFont.h"
  163. #include "core/Sfz.h"
  164. #include "core/Slicex.h"
  165. #include "ui/Dialogs.h"
  166. #include "ui/FileChoosers.h"
  167. #include "ui/TrackIcons.h"
  168. #include "core/RackOps.h"
  169. #include "core/Layer.h"
  170. #include "core/XyController.h"
  171. #include "core/FlCurve.h"
  172. #include "core/ControlSurface.h"
  173. #include "core/VoltageController.h"
  174. #include "ui/Controllers164.h"
  175. #include "core/StandIns.h"
  176. #include "ui/ExportDialog.h"
  177. #include "ui/QuickAddPalette.h"
  178. #include "ui/I18n.h"
  179. #include "ui/MainComponent.h"
  180. #include "ui/SimpleDock.h"
  181. #include "core/ScaleKeys.h"
  182. #include "core/KeyFollow.h"
  183. #include "core/SoundLibrary.h"
  184. #include "ui/MidiToolsPanel.h"
  185. #include "ui/FrameProbe.h"
  186. #include "ui/MotionOverlay.h"
  187. #include "ui/UiTrace.h"
  188. #include "core/MixerOps.h"
  189. #include "ui/QuickPick.h"
  190. #include "core/NoteTools.h"
  191. #include "engine/ProjectPackage.h"
  192. #include "ui/SetupWizard.h"
  193. #include "engine/FlStudio.h"
  194. #include "ui/HistoryPanel.h"
  195. #include "ui/VersionsPanel.h"
  196. #include "ui/CleanVoiceMenu.h"
  197. #include "ui/LyricsPanel.h"
  198. #include "ui/ReferenceMatchPanel.h"
  199. #include "ui/StartFromPanel.h"
  200. #include "ui/FirstSongTour.h"
  201. #include "ui/PluginsOffPanel.h"
  202. #include "ui/MissingFilesDialog.h"
  203. #include "ui/SettingsDialog.h"
  204. #include "ui/PluginManager.h"
  205. #include "ui/ShortcutManager.h"
  206. #include "ui/NoteToolDialogs.h"
  207. #include "ui/EventEditor.h"
  208. #include "ui/AudioEditor.h"
  209. #include "ui/TempoTapper.h"
  210. #include "core/EventEdit.h"
  211. #include "core/FacetEq.h"
  212. #include "ui/FacetEqEditor.h"
  213. #include "core/RackRenderer.h"
  214. #include "ui/ProEditors.h"
  215. #include "ui/ParametricEqEditor.h"
  216. #include "ui/PluginEditors.h"
  217. #include "core/PluginLayout.h"
  218. #include "core/EffectPresets.h"
  219. #include "ui/PluginHeader.h"
  220. #include "core/Vfx.h"
  221. #include "core/TransistorBass.h"
  222. #include "ui/Splash.h"
  223. #include "ui/Theme.h"
  224. #include "ui/ThemeSettings.h"
  225. #include "ui/WaveformView.h"
  226. #include "ui/WindowOwner.h"
  227. #include "ui/PluginKeysTest.h"
  228. #include "ui/Toolbar.h"
  229. #include "ui/ToolWindow.h"
  230. #include "platform/CrashGuard.h"
  231. #include "ui/CrashReporter.h"
  232. #include "ui/Updater.h"
  233. #include "ui/AudioCheck.h"
  234. #include "ui/StemExtract.h"
  235. #include "ui/AudioToMidi.h"
  236. #include "ui/ShotScale.h"
  237. #include "core/Links.h"
  238. #include <algorithm>
  239. #include <atomic>
  240. #include <exception>
  241. #include <chrono>
  242. #include <cstdio>
  243. #include <ctime>
  244. #include <cstdlib>
  245. #include <future>
  246. #include <mutex>
  247. #include <thread>
  248. namespace
  249. {
  250. lynx::AudioEngine* crashEngine = nullptr;
  251. // Startup trace (REA round 116): with LYNX_TRACE_STARTUP set, the time of each startup step since the C++ runtime
  252. // started is written to %APPDATA%\LYNX\startup.log (the loader's own time before that is not included).
  253. struct StartupTrace
  254. {
  255. using clock = std::chrono::steady_clock;
  256. const clock::time_point t0 = clock::now(); // static initialisation: no JUCE yet, standard library only
  257. const std::chrono::system_clock::time_point t0System = std::chrono::system_clock::now(); // (round 190hd: vs the process's creation)
  258. // (round 190go: always kept, as a field-readable start-up timeline; written to startup.log 5 s and 15 s after the
  259. // window — with LYNX_TRACE_STARTUP set, at every step as before, so a start that hangs still leaves its last step)
  260. const bool on = true;
  261. const bool eachStep = std::getenv ("LYNX_TRACE_STARTUP") != nullptr;
  262. juce::String text;
  263. clock::time_point last = t0;
  264. std::int64_t lastPrivate = 0;
  265. double seconds() const { return std::chrono::duration<double> (clock::now() - t0).count(); } // since the process started
  266. void mark (const char* step)
  267. {
  268. if (! on)
  269. return;
  270. const auto now = clock::now();
  271. const auto ms = [] (clock::duration d) { return std::chrono::duration<double, std::milli> (d).count(); };
  272. // (round 190gd: the process's memory after each step too, so the log says where the megabytes of a start go)
  273. const auto mb = [] (std::int64_t bytes) { return juce::String ((double) bytes / 1048576.0, 1).paddedLeft (' ', 7); };
  274. const auto priv = lynx::toolbar::PerformanceMeter::processPrivateBytes();
  275. const auto ws = lynx::toolbar::PerformanceMeter::processMemoryBytes();
  276. text << juce::String (ms (now - t0), 1).paddedLeft (' ', 8) << " ms +" << juce::String (ms (now - last), 1).paddedLeft (' ', 7)
  277. << " private " << mb (priv) << " MB (+" << mb (priv - lastPrivate).trim() << ") ws " << mb (ws) << " MB " << step << "\n";
  278. lastPrivate = priv;
  279. last = now;
  280. if (eachStep)
  281. write();
  282. }
  283. void write() const { lynx::platform::settingsFile ("startup.log").replaceWithText (text); }
  284. };
  285. StartupTrace startupTrace;
  286. void startupMarkHook (const char* step) { startupTrace.mark (step); }
  287. juce::File crashFolderForTest; // --faulttest: where the crash file goes instead of the settings' autosave folder
  288. // Crashed: try to save the project and write the backtrace (like FL's "emergency save").
  289. void onCrash (void* exceptionPointers)
  290. {
  291. // (round 190ci: once. The hook for stacks Windows cannot walk, crashguard::setUnwalkableFaultHandler, may have run
  292. // this before the top-level filter does)
  293. static std::atomic<bool> reported { false };
  294. if (reported.exchange (true))
  295. return;
  296. const auto folder = crashFolderForTest != juce::File() ? crashFolderForTest : lynx::platform::settingsFile ("autosave");
  297. folder.createDirectory();
  298. const auto stamp = juce::Time::getCurrentTime().formatted ("%Y-%m-%d %H-%M-%S");
  299. // JUCE's backtrace (named frames only), then every frame of the faulting thread as module+offset (round 157a: a
  300. // release LYNX.exe has no symbols, so its own frames were missing from the file)
  301. folder.getChildFile ("crash " + stamp + ".txt").replaceWithText (juce::SystemStats::getStackBacktrace() + "\n--- frames (module+offset)\n"
  302. + juce::String::fromUTF8 (lynx::crashguard::exceptionBacktrace (exceptionPointers).c_str()));
  303. lynx::crashguard::note (("crashed: backtrace in autosave\\crash " + stamp + ".txt").toStdString());
  304. if (crashEngine != nullptr)
  305. {
  306. juce::String error;
  307. lynx::ProjectFile::save (crashEngine->getSong(), folder.getChildFile ("recovered " + stamp + lynx::ProjectFile::extension), error);
  308. }
  309. }
  310. juce::File sessionsFolder()
  311. {
  312. return lynx::PluginHost::settingsFolder().getChildFile ("sessions");
  313. }
  314. // Sessions of earlier runs whose process is gone without closing (a fail-fast, a crash, a forced end): each is appended
  315. // to %APPDATA%\LYNX\crash-history.log and its file removed. Returns the last step of the newest one ("" when none).
  316. juce::StringArray uncleanSteps; // the newest unclean session's steps (without their times)
  317. juce::String uncleanSessionText; // the newest unclean session's whole file (round 159: the crash report reads it)
  318. // What the newest unclean session tells (round 157a): the plugin whose editor was opening / shown when it ended, and
  319. // whether its crash file blames a graphics driver
  320. struct UncleanCause
  321. {
  322. juce::String editorPlugin; // the last steps were that plugin's editor
  323. bool gpuDriver = false; // the crash file's top frames are in a GPU driver / Direct3D / Direct2D module
  324. juce::String driverModule;
  325. };
  326. UncleanCause uncleanCause()
  327. {
  328. UncleanCause cause;
  329. juce::File crashFile;
  330. for (int i = uncleanSteps.size(); --i >= 0 && i >= uncleanSteps.size() - 4;)
  331. {
  332. const auto& step = uncleanSteps[i];
  333. if (step.startsWith ("crashed: backtrace in "))
  334. crashFile = lynx::platform::settingsFolder().getChildFile (step.fromFirstOccurrenceOf ("backtrace in ", false, false).replaceCharacter ('\\', '/'));
  335. for (const auto* prefix : { "opening the editor of ", "editor open: ", "editor shown: " })
  336. if (cause.editorPlugin.isEmpty() && step.startsWith (prefix))
  337. cause.editorPlugin = step.fromFirstOccurrenceOf (prefix, false, false).trim();
  338. if (step.startsWith ("closing the editor of ") || step.startsWith ("loaded plugin") || step.startsWith ("opening project"))
  339. break; // older steps than these did not end the session
  340. }
  341. // issue #32 (round 174a): a plugin whose editor already faulted in this session (caught, LYNX went on) is the
  342. // likely cause when the session then ended without a word: offer it a separate process too
  343. for (int i = uncleanSteps.size(); --i >= 0 && cause.editorPlugin.isEmpty();)
  344. if (const auto editor = lynx::crashreport::parseEditorCrashStep (uncleanSteps[i].toStdString()); ! editor.plugin.empty())
  345. cause.editorPlugin = juce::String::fromUTF8 (editor.plugin.c_str());
  346. if (crashFile.existsAsFile())
  347. {
  348. // the first frames after the crash handler's own (the "--- frames" part lists the faulting thread)
  349. auto text = crashFile.loadFileAsString();
  350. if (text.contains ("--- frames"))
  351. text = text.fromFirstOccurrenceOf ("--- frames", false, false);
  352. auto lines = juce::StringArray::fromLines (text);
  353. int looked = 0;
  354. for (const auto& line : lines)
  355. {
  356. const auto module = line.fromFirstOccurrenceOf (": ", false, false).upToFirstOccurrenceOf ("+", false, false).trim().toLowerCase();
  357. if (module.isEmpty() || ! module.endsWith (".dll"))
  358. continue;
  359. if (++looked > 12)
  360. break;
  361. for (const auto* driver : { "igd", "ig9icd", "ig7icd", "igxelp", "nvwgf2um", "nvoglv", "nvd3dum", "atidxx", "atio6axx", "amdxx", "aticfx",
  362. "d3d11.dll", "d3d10warp", "dxgi.dll", "d2d1.dll", "opengl32.dll", "dcomp.dll" })
  363. if (module.startsWith (driver))
  364. {
  365. cause.gpuDriver = true;
  366. cause.driverModule = module;
  367. break;
  368. }
  369. if (cause.gpuDriver)
  370. break;
  371. }
  372. }
  373. return cause;
  374. }
  375. juce::String collectUncleanSessions()
  376. {
  377. juce::String lastStep;
  378. juce::Time newest;
  379. for (const auto& file : sessionsFolder().findChildFiles (juce::File::findFiles, false, "session-*.txt"))
  380. {
  381. const auto text = file.loadFileAsString();
  382. juce::StringPairArray values;
  383. juce::StringArray steps;
  384. for (const auto& line : juce::StringArray::fromLines (text))
  385. {
  386. if (line.startsWith ("step="))
  387. steps.add (line.fromFirstOccurrenceOf ("=", false, false));
  388. else if (line.contains ("="))
  389. values.set (line.upToFirstOccurrenceOf ("=", false, false), line.fromFirstOccurrenceOf ("=", false, false));
  390. }
  391. const auto pid = (std::uint32_t) values["pid"].getLargeIntValue();
  392. const auto start = (std::uint64_t) values["start"].getLargeIntValue();
  393. if (pid == lynx::crashguard::processId() || lynx::crashguard::processRunning (pid, start))
  394. continue; // this run, or another LYNX window still open
  395. lynx::PluginHost::settingsFolder().getChildFile ("crash-history.log")
  396. .appendText (juce::Time::getCurrentTime().toISO8601 (true) + " previous session ended without closing\n" + text + "\n");
  397. file.deleteFile();
  398. if (const auto modified = file.getLastModificationTime(); lastStep.isEmpty() || modified > newest)
  399. {
  400. newest = modified;
  401. lastStep = steps.isEmpty() ? juce::String ("start-up") : steps[steps.size() - 1].fromFirstOccurrenceOf (" ", false, false);
  402. uncleanSessionText = text;
  403. uncleanSteps.clear();
  404. for (const auto& step : steps)
  405. uncleanSteps.add (step.fromFirstOccurrenceOf (" ", false, false));
  406. }
  407. }
  408. return lastStep;
  409. }
  410. } // namespace
  411. // --uiperf (round 173f, discussion #10): a mixer fader dragged up and down with the mouse while the pattern plays. A
  412. // high-resolution timer delivers 125 moves a second to the message thread through the window's own mouse path
  413. // (ComponentPeer::handleMouseEvent), at most one waiting at a time as Windows does with WM_MOUSEMOVE; every frame the
  414. // window paints tells whether it covered the fader. Measured: how long a move waited for the message thread, the time
  415. // from a move to the first frame that shows the fader after it (input → paint), and whether the value stays put when
  416. // the mouse is released.
  417. struct UiPerfDrag final : public std::enable_shared_from_this<UiPerfDrag>,
  418. private juce::HighResolutionTimer
  419. {
  420. ~UiPerfDrag() override { stopTimer(); }
  421. void start (juce::Component& windowIn, juce::Component& strips, juce::Rectangle<int> rail, lynx::AudioEngine* engineIn, int trackIn)
  422. {
  423. window = &windowIn;
  424. engine = engineIn;
  425. track = trackIn;
  426. railInWindow = window->getLocalArea (&strips, rail);
  427. watch = railInWindow.expanded (6, 40); // the cap, its tip above and the dB read-out below
  428. visible = strips.isShowing() && window->getLocalArea (&strips, strips.getLocalBounds()).contains (railInWindow.getCentre());
  429. const auto volume = engine->getSong().mixer[(std::size_t) track].volume;
  430. x = (float) railInWindow.getCentreX();
  431. startY = (float) railInWindow.getBottom() - volume * (float) railInWindow.getHeight(); // on the cap: no jump
  432. amplitude = 0.4f * (float) railInWindow.getHeight();
  433. centreY = juce::jlimit ((float) railInWindow.getY() + amplitude, (float) railInWindow.getBottom() - amplitude, startY);
  434. t0 = juce::Time::getMillisecondCounterHiRes();
  435. inject (x, startY, false);
  436. juce::ModifierKeys::currentModifiers = juce::ModifierKeys (juce::ModifierKeys::leftButtonModifier);
  437. inject (x, startY, true);
  438. active = true;
  439. startTimer (8);
  440. }
  441. // message thread
  442. void framePainted (double now, juce::Rectangle<int> area)
  443. {
  444. if (pending.empty() || ! area.intersects (watch))
  445. return;
  446. for (const auto t : pending)
  447. latencies.push_back (now - t);
  448. pending.clear();
  449. ++framesOverFader;
  450. }
  451. // the moves end; as in the reporter's clip, the song is stopped while the button is still down
  452. juce::String stop()
  453. {
  454. stopTimer();
  455. active = false;
  456. valueAtRelease = engine->getSong().mixer[(std::size_t) track].volume;
  457. engine->stop();
  458. juce::String text;
  459. text << " drag of insert " << track << "'s fader" << (visible ? "" : " (NOT VISIBLE)") << ": " << moves << " moves handled, " << dropped
  460. << " folded into the next (the message thread still busy with the previous one)\n"
  461. << " move waited for the message thread: " << describe (queueDelays) << "\n"
  462. << " input -> paint (move to the first frame over the fader): " << describe (latencies) << ", " << framesOverFader
  463. << " frames over the fader\n";
  464. return text;
  465. }
  466. juce::String release()
  467. {
  468. const auto now = engine->getSong().mixer[(std::size_t) track].volume;
  469. juce::ModifierKeys::currentModifiers = {};
  470. inject (x, lastY, false);
  471. return " song stopped, button still down: fader " + juce::String (now, 4) + " (" + juce::String (valueAtRelease, 4) + " at the last move) "
  472. + (std::abs (now - valueAtRelease) < 1.0e-4f ? "kept" : "CHANGED") + "\n";
  473. }
  474. juce::String released() const
  475. {
  476. const auto now = engine->getSong().mixer[(std::size_t) track].volume;
  477. return " after the release: fader " + juce::String (now, 4) + " (" + juce::String (valueAtRelease, 4) + " when released) "
  478. + (std::abs (now - valueAtRelease) < 1.0e-4f ? "kept" : "CHANGED") + "\n";
  479. }
  480. private:
  481. juce::Component* window = nullptr;
  482. lynx::AudioEngine* engine = nullptr;
  483. int track = 1;
  484. juce::Rectangle<int> railInWindow, watch;
  485. bool visible = false;
  486. float x = 0.0f, startY = 0.0f, centreY = 0.0f, amplitude = 0.0f, lastY = 0.0f;
  487. double t0 = 0.0;
  488. std::atomic<bool> active { false }, posted { false };
  489. std::atomic<int> dropped { 0 };
  490. int moves = 0, framesOverFader = 0;
  491. float valueAtRelease = 0.0f;
  492. std::vector<double> pending, latencies, queueDelays;
  493. static juce::String describe (std::vector<double> v)
  494. {
  495. if (v.empty())
  496. return "none";
  497. std::sort (v.begin(), v.end());
  498. const auto at = [&v] (double q) { return v[std::min (v.size() - 1, (std::size_t) (q * (double) v.size()))]; };
  499. return "p50 " + juce::String (at (0.5), 1) + " / p95 " + juce::String (at (0.95), 1) + " / p99 " + juce::String (at (0.99), 1) + " / max "
  500. + juce::String (v.back(), 1) + " ms";
  501. }
  502. void inject (float px, float py, bool down)
  503. {
  504. lastY = py;
  505. if (auto* peer = window != nullptr ? window->getPeer() : nullptr)
  506. {
  507. const auto local = peer->globalToLocal (window->localPointToGlobal (juce::Point<float> (px, py)));
  508. peer->handleMouseEvent (juce::MouseInputSource::InputSourceType::mouse, local,
  509. down ? juce::ModifierKeys (juce::ModifierKeys::leftButtonModifier) : juce::ModifierKeys(),
  510. juce::MouseInputSource::defaultPressure, juce::MouseInputSource::defaultOrientation,
  511. juce::Time::currentTimeMillis());
  512. }
  513. }
  514. void hiResTimerCallback() override
  515. {
  516. if (! active.load())
  517. return;
  518. if (posted.exchange (true))
  519. {
  520. ++dropped;
  521. return;
  522. }
  523. const auto postedAt = juce::Time::getMillisecondCounterHiRes();
  524. juce::MessageManager::callAsync ([self = shared_from_this(), postedAt] {
  525. self->posted = false;
  526. if (! self->active.load())
  527. return;
  528. const auto now = juce::Time::getMillisecondCounterHiRes();
  529. self->queueDelays.push_back (now - postedAt);
  530. // up and down ~1.3 times a second, like the reporter's hand
  531. const auto y = self->centreY + self->amplitude * (float) std::sin (2.0 * juce::MathConstants<double>::pi * 1.3 * (now - self->t0) / 1000.0);
  532. self->inject (self->x, y, true);
  533. self->pending.push_back (postedAt);
  534. ++self->moves;
  535. });
  536. }
  537. };
  538. class LynxApplication final : public juce::JUCEApplication
  539. {
  540. public:
  541. const juce::String getApplicationName() override { return JUCE_APPLICATION_NAME_STRING; }
  542. const juce::String getApplicationVersion() override { return JUCE_APPLICATION_VERSION_STRING; }
  543. // the plugin scan runs copies of LYNX as child processes
  544. bool moreThanOneInstanceAllowed() override { return true; }
  545. // A file handed to the running application. macOS does this for every Finder double-click, "Open With" and Dock drop,
  546. // also the one that starts LYNX (its argv has no file). On Windows and Linux a second start is a second process
  547. // (moreThanOneInstanceAllowed) with the file as an argument, so this is not called there. Only the first file of a
  548. // multiple selection opens: a project replaces the one before it. (D#92, round 180a)
  549. void anotherInstanceStarted (const juce::String& commandLine) override
  550. {
  551. const auto files = lynx::safety::filesInCommandLine (commandLine.toStdString());
  552. if (files.empty())
  553. return;
  554. const auto file = juce::File::getCurrentWorkingDirectory().getChildFile (juce::String::fromUTF8 (files.front().c_str()));
  555. if (! startupFileHandled) // still starting: openStartupFile takes it, nothing to ask about yet
  556. {
  557. fileToOpen = file;
  558. return;
  559. }
  560. if (mainWindow != nullptr)
  561. {
  562. mainWindow->toFront (true);
  563. mainWindow->getContent().openFileRequest (file);
  564. }
  565. }
  566. void initialise (const juce::String& commandLine) override
  567. {
  568. // round 166b: the copy of LYNX.exe that installs an update (ui/Updater.h) waits, installs, starts LYNX again
  569. if (commandLine.contains ("--apply-update") && lynx::updater::runApplyHelper (juce::StringArray::fromTokens (commandLine, true)))
  570. {
  571. updateHelper = true;
  572. quit();
  573. return;
  574. }
  575. // Windows, LYNX.exe in a folder with accents: run again from its ASCII short path (Waves editors crash otherwise)
  576. if (int code = 0; lynx::platform::relaunchFromAsciiPath (code))
  577. {
  578. relaunched = true;
  579. setApplicationReturnValue (code);
  580. quit();
  581. return;
  582. }
  583. // a crash in any mode (UI, command line) writes its backtrace to %APPDATA%\LYNX\autosave
  584. juce::SystemStats::setApplicationCrashHandler (onCrash);
  585. // rollup 0.1.28 (REA 190hb action 4, FL's "Init DWM"): the compositor on MMCSS, steadier frames under CPU load
  586. // (Windows; LYNX_DWM_MMCSS=0 leaves it off)
  587. lynx::powerhints::enableCompositorMmcss();
  588. // round 190ci: also for a fault on a stack Windows cannot walk, which never reaches that handler (Windows)
  589. lynx::crashguard::setUnwalkableFaultHandler (onCrash);
  590. if (const auto args = juce::StringArray::fromTokens (commandLine, true); args.contains ("--faulttest"))
  591. {
  592. // LYNX.exe --faulttest plain|unwalkable <folder> (round 190ci): ends by an access violation on purpose,
  593. // before any window, so that --selftest can check that the crash file gets written (into <folder>)
  594. const auto i = args.indexOf ("--faulttest");
  595. crashFolderForTest = juce::File (args[i + 2].unquoted());
  596. lynx::crashguard::quietCrashReports();
  597. // round 190dt: guarded / guarded-libc = LYNX's own fault inside a guarded plugin call (Linux / macOS): it must
  598. // reach the crash handler like any other; a return means the guard swallowed it
  599. // round 190gg: thread / thread-libc = a fault on a thread of LYNX's own, with LYNX's executable watched as
  600. // a plugin's module: it must not be parked as a plugin's thread
  601. if (args[i + 1].startsWith ("thread"))
  602. {
  603. lynx::crashguard::faultOnOwnThreadForTest (args[i + 1] == "thread-libc");
  604. crashFolderForTest.getChildFile ("swallowed.txt").replaceWithText ("parked");
  605. lynx::crashguard::exitNow (4);
  606. }
  607. if (args[i + 1].startsWith ("guarded"))
  608. {
  609. const auto code = lynx::crashguard::faultInGuardedCallForTest (args[i + 1] == "guarded-libc");
  610. crashFolderForTest.getChildFile ("swallowed.txt").replaceWithText (lynx::crashguard::describe (code));
  611. lynx::crashguard::exitNow (4);
  612. }
  613. lynx::crashguard::faultForTest (args[i + 1] == "unwalkable");
  614. }
  615. lynx::crashguard::hardenSignals(); // issue #115: stack overflows and SIGTERM / SIGHUP leave a trace (Linux / macOS)
  616. // SFZ instruments (round 167o): their FLAC / OGG / AIFF / MP3 samples through JUCE's readers
  617. lynx::sfz::setDecoder ([] (const std::string& path, lynx::sfz::Audio& out) {
  618. juce::AudioFormatManager formats;
  619. formats.registerBasicFormats();
  620. std::unique_ptr<juce::AudioFormatReader> reader (formats.createReaderFor (juce::File (juce::String::fromUTF8 (path.c_str()))));
  621. if (reader == nullptr || reader->lengthInSamples <= 0 || reader->lengthInSamples > (1 << 28) || reader->numChannels == 0)
  622. return false;
  623. const auto frames = (int) reader->lengthInSamples;
  624. juce::AudioBuffer<float> buffer ((int) std::min (2u, reader->numChannels), frames);
  625. if (! reader->read (&buffer, 0, frames, 0, true, buffer.getNumChannels() > 1))
  626. return false;
  627. out.channels.clear();
  628. for (int ch = 0; ch < buffer.getNumChannels(); ++ch)
  629. out.channels.emplace_back (buffer.getReadPointer (ch), buffer.getReadPointer (ch) + frames);
  630. out.sampleRate = reader->sampleRate;
  631. out.loopStart = out.loopEnd = -1;
  632. return true;
  633. });
  634. // child process of a sandboxed plugin: no window or audio of its own
  635. if (lynx::runPluginSandboxWorker (commandLine))
  636. {
  637. lynx::crashguard::quietCrashReports();
  638. sandboxChild = true;
  639. return;
  640. }
  641. // --shot-scale <v> / --shot-suffix <text> (round 190bi, ui/ShotScale.h): the pixel scale and file-name suffix of every
  642. // picture route, taken out here so the routes' own arguments keep their places
  643. const auto args = lynx::shot::takeArguments (juce::StringArray::fromTokens (commandLine, true));
  644. // interface language: saved in %APPDATA%\LYNX\language.txt; --lang pt-BR overrides it for this run
  645. lynx::i18n::initialise (args);
  646. // interface font: saved in Settings › General; --uifont "Name" overrides it for this run
  647. const auto uiFontArg = args.indexOf ("--uifont");
  648. lookAndFeel.applyInterfaceFont (lynx::i18n::current(), uiFontArg >= 0 ? args[uiFontArg + 1].unquoted() : juce::String());
  649. // text size (issue #189): saved in Settings › General; --textsize 125 overrides it for this run
  650. const auto textSizeArg = args.indexOf ("--textsize");
  651. lynx::theme::setTextSize (textSizeArg >= 0 ? args[textSizeArg + 1].getIntValue() : lynx::theme::savedTextSize());
  652. if (args.contains ("--showcase"))
  653. {
  654. // LYNX's own demo project (README screenshots): --showcase output.lynx [pattern]
  655. const auto i = args.indexOf ("--showcase");
  656. runShowcase (args[i + 1].unquoted(), args[i + 2].getIntValue());
  657. return;
  658. }
  659. if (args.contains ("--demosongs"))
  660. {
  661. // round 190dv: LYNX's two short genre demos (core/DemoSongs.h) as .lynx files: --demosongs <folder>
  662. // (resources/demos/ in the repository)
  663. const auto i = args.indexOf ("--demosongs");
  664. runDemoSongs (args[i + 1].unquoted());
  665. return;
  666. }
  667. if (args.contains ("--perfgen"))
  668. {
  669. // round perfgate190id: the big-project performance gate's synthetic projects (core/PerfProjects.h) as .lynx
  670. // files with their WAVs: --perfgen <folder> [report.txt] [name,name...]; the save and load times in the report
  671. const auto i = args.indexOf ("--perfgen");
  672. const auto report = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  673. const auto only = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  674. runPerfGen (args[i + 1].unquoted(), report, only);
  675. return;
  676. }
  677. if (args.contains ("--sandboxtest"))
  678. {
  679. const auto i = args.indexOf ("--sandboxtest");
  680. runSandboxTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  681. return;
  682. }
  683. if (args.contains ("--bridge32test"))
  684. {
  685. // LYNX.exe --bridge32test "LYNX Test Synth 32.dll" report.txt [--compare "LYNX Test Synth.dll"] (round 176a):
  686. // the 32-bit plugin bridge (engine/Bridge32Test.cpp)
  687. const auto i = args.indexOf ("--bridge32test");
  688. const auto compare = args.contains ("--compare") ? args[args.indexOf ("--compare") + 1].unquoted() : juce::String();
  689. setApplicationReturnValue (lynx::runBridge32Test (args[i + 1].unquoted(), args[i + 2].unquoted(), compare));
  690. quit();
  691. return;
  692. }
  693. if (args.contains ("--rtstress"))
  694. {
  695. // LYNX.exe --rtstress project.(flp|lynx) report.txt [seconds] [--buffer N] [--type "driver type"] [--device "output"]
  696. // [--no-window] [--record take.wav]: the real app (window, audio device) plays the project and reports the callbacks
  697. // that missed their deadline (REA round 87); --type/--device pick another driver for this run only (round 97);
  698. // --record also records the input during the run, like Rec + Play, and moves the take to take.wav (round 106)
  699. const auto i = args.indexOf ("--rtstress");
  700. const auto seconds = args[i + 3].getDoubleValue();
  701. const auto buffer = args.contains ("--buffer") ? args[args.indexOf ("--buffer") + 1].getIntValue() : 0;
  702. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  703. const auto option = [&args] (const char* name) { return args.contains (name) ? args[args.indexOf (name) + 1].unquoted() : juce::String(); };
  704. runRealtimeStress (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()), seconds > 0.0 ? seconds : 30.0, buffer,
  705. option ("--type"), option ("--device"), option ("--record"));
  706. return;
  707. }
  708. if (args.contains ("--renderaheadtest"))
  709. {
  710. // LYNX --renderaheadtest report.txt [project.flp|.lynx ...] [--buffer N] [--seconds S] (round 190gq): the engine's
  711. // own device callback (a stand-in device driven block by block, as --cliplooptest) plays the showcase song (from
  712. // the start, round a loop region that wraps mid-block, in Pattern mode) and each project with Options › Audio
  713. // settings › "Render ahead" off, then on. The two outputs must be the same to the bit, nothing rendered ahead
  714. // may be dropped, and most blocks must come from the ring. No window, no audio device.
  715. const auto i = args.indexOf ("--renderaheadtest");
  716. juce::StringArray projects;
  717. for (int k = i + 2; k < args.size() && ! args[k].startsWith ("--"); ++k)
  718. projects.add (args[k].unquoted());
  719. const auto buffer = args.contains ("--buffer") ? args[args.indexOf ("--buffer") + 1].getIntValue() : 128;
  720. const auto seconds = args.contains ("--seconds") ? args[args.indexOf ("--seconds") + 1].getDoubleValue() : 12.0;
  721. runRenderAheadTest (juce::File (args[i + 1].unquoted()), projects, juce::jlimit (16, 2048, buffer), seconds > 0.0 ? seconds : 12.0);
  722. return;
  723. }
  724. if (args.contains ("--cliplooptest"))
  725. {
  726. // LYNX --cliplooptest report.txt [export.wav] (round 167q, issue #25: 0.1.21 drew the repeats of a stretched
  727. // pattern clip but played the pattern once). The real engine's device callback (a stand-in device, driven
  728. // block by block) plays a synth's 1-bar pattern in a 4-bar clip: every repeat must sound as bar 1, also
  729. // starting inside a repeat, after a jump mid-clip and in a loop region; the WAV export (written to
  730. // export.wav and read back) the same. With the LYNX extra off, bars 2-4 must be silent (FL's behaviour).
  731. const auto i = args.indexOf ("--cliplooptest");
  732. runClipLoopTest (juce::File (args[i + 1].unquoted()), args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? juce::File (args[i + 2].unquoted()) : juce::File());
  733. return;
  734. }
  735. if (args.contains ("--devicechangetest"))
  736. {
  737. // LYNX --devicechangetest report.txt [switches] [--plugin file]... (round 190c, issue #134: changing the
  738. // output device with a project open crashed LYNX). The engine plays a project of every instrument and effect
  739. // it can make here on stand-in devices with real callback threads, while the output device, its sample
  740. // rate and its buffer size change the way Settings > Audio changes them (8 kHz mono to 192 kHz, buffers of
  741. // 32 to 16384 samples, a device plugged in, the open one unplugged, one that refuses to open). After every
  742. // change the song must sound, finite, at the new rate. No window, no real audio or MIDI device.
  743. const auto i = args.indexOf ("--devicechangetest");
  744. const juce::File report (args[i + 1].unquoted());
  745. const auto switches = args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? args[i + 2].getIntValue() : 0;
  746. juce::StringArray plugins;
  747. for (int k = 0; k + 1 < args.size(); ++k)
  748. if (args[k] == "--plugin")
  749. plugins.add (args[k + 1].unquoted());
  750. auto text = std::make_shared<juce::String>();
  751. // --quick: the selftest's handful of instruments and effects instead of every one
  752. const auto result = lynx::AudioEngine::deviceChangeSelfTest (switches > 0 ? switches : 40, ! args.contains ("--quick"), plugins, [report, text] (const juce::String& line) {
  753. *text << line << "\n";
  754. report.replaceWithText (*text + "(running)\n"); // what was reached, if it crashes
  755. });
  756. *text << "device_change=" << result << "\nresult=" << (result.startsWith ("OK") ? "OK" : "FAILED") << "\n";
  757. report.replaceWithText (*text);
  758. setApplicationReturnValue (result.startsWith ("OK") ? 0 : 1);
  759. quit();
  760. return;
  761. }
  762. if (args.contains ("--exportparitytest") || args.contains ("--midihotplugtest"))
  763. {
  764. // LYNX --exportparitytest report.txt (round 190gh, B7): the export against playback through a stand-in audio
  765. // device, stems adding up to the mix with one length, the PDC trim. LYNX --midihotplugtest report.txt (B8):
  766. // MIDI devices plugged in and out (stand-in device lists) while messages arrive. No window.
  767. const auto parity = args.contains ("--exportparitytest");
  768. const auto i = args.indexOf (parity ? "--exportparitytest" : "--midihotplugtest");
  769. const juce::File report (args[i + 1].unquoted());
  770. juce::String text;
  771. const auto result = parity ? lynx::AudioEngine::exportParitySelfTest ([&text] (const juce::String& line) { text << line << "\n"; })
  772. : lynx::AudioEngine::midiHotplugSelfTest();
  773. text << (parity ? "export_parity=" : "midi_hotplug=") << result << "\nresult=" << (result.startsWith ("OK") ? "OK" : "FAILED") << "\n";
  774. report.replaceWithText (text);
  775. setApplicationReturnValue (result.startsWith ("OK") ? 0 : 1);
  776. quit();
  777. return;
  778. }
  779. if (args.contains ("--shortexportstress"))
  780. {
  781. // LYNX --shortexportstress report.txt [count] [--seed N] [--no-realtime] [--plugin file] (round 190hn, issue #138): `count`
  782. // random export settings over short sounds at the very start of the song, each exported again a bar later; a
  783. // file that comes out silent or quieter fails (engine/ShortExportTest.h). No window.
  784. const auto i = args.indexOf ("--shortexportstress");
  785. const juce::File report (args[i + 1].unquoted());
  786. const auto count = args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? args[i + 2].getIntValue() : 200;
  787. const auto s = args.indexOf ("--seed");
  788. const auto seed = s >= 0 && s + 1 < args.size() ? args[s + 1].getLargeIntValue() : juce::Time::currentTimeMillis();
  789. auto text = std::make_shared<juce::String>();
  790. const auto pl = args.indexOf ("--plugin");
  791. lynx::shortexport::stress (count, seed, ! args.contains ("--no-realtime"), pl >= 0 && pl + 1 < args.size() ? args[pl + 1].unquoted() : juce::String(),
  792. [report, text] (const juce::String& line) {
  793. *text << line << "\n";
  794. report.replaceWithText (*text + "(running)\n");
  795. },
  796. [this, report, text] (juce::String result) {
  797. *text << "short_export_stress=" << result << "\nresult=" << (result.startsWith ("OK") ? "OK" : "FAILED") << "\n";
  798. report.replaceWithText (*text);
  799. setApplicationReturnValue (result.startsWith ("OK") ? 0 : 1);
  800. quit();
  801. });
  802. return;
  803. }
  804. if (args.contains ("--shortexporttest"))
  805. {
  806. // LYNX --shortexporttest report.txt [repeats] [--plugin file]... (round 190c, issue #138: a short note at
  807. // the very start of the Playlist exported quiet). Every instrument LYNX can make here, and a synth with
  808. // effects, tail modes, normalising and other rates, exported through the Export window's path (the job
  809. // made on the message thread, run on its own thread, the message loop running) with a 2-second note at
  810. // tick 0 and again with it at bar 2: the note must come out the same. No window.
  811. const auto i = args.indexOf ("--shortexporttest");
  812. const juce::File report (args[i + 1].unquoted());
  813. const auto repeats = args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? args[i + 2].getIntValue() : 0;
  814. juce::StringArray plugins;
  815. for (int k = 0; k + 1 < args.size(); ++k)
  816. if (args[k] == "--plugin")
  817. plugins.add (args[k + 1].unquoted());
  818. auto text = std::make_shared<juce::String>();
  819. lynx::shortexport::run (! args.contains ("--quick"), repeats > 0 ? repeats : 3, plugins, // (--quick: a handful of instruments, round 190hn)
  820. [report, text] (const juce::String& line) {
  821. *text << line << "\n";
  822. report.replaceWithText (*text + "(running)\n");
  823. },
  824. [this, report, text] (juce::String result) {
  825. *text << "short_export=" << result << "\nresult=" << (result.startsWith ("OK") ? "OK" : "FAILED") << "\n";
  826. report.replaceWithText (*text);
  827. setApplicationReturnValue (result.startsWith ("OK") ? 0 : 1);
  828. quit();
  829. });
  830. return;
  831. }
  832. if (args.contains ("--slicexedittest"))
  833. {
  834. // LYNX --slicexedittest project script.txt report.txt [png-prefix] (round 190aj): the Slicex editor of the
  835. // project's first Slicex channel, off screen, driven by the script's commands (ui/SlicexEditor.h; mouse
  836. // gestures at fractions of the deck's width, the menu entries, shortcuts). The report holds each command
  837. // and what the state held after it; "shot <name>" writes <png-prefix><name>.png.
  838. const auto i = args.indexOf ("--slicexedittest");
  839. runSlicexEditTest (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()), juce::File (args[i + 3].unquoted()),
  840. args.size() > i + 4 ? args[i + 4].unquoted() : juce::String());
  841. return;
  842. }
  843. if (args.contains ("--dwedittest"))
  844. {
  845. // LYNX --dwedittest project script.txt report.txt [png-prefix] (round 190hz): the DirectWave editor of the
  846. // project's first DirectWave channel, off screen, driven by the script's commands (ui/DirectWaveEditor.h);
  847. // "shot <name>" writes <png-prefix><name>.png. A project path "new" makes a new DirectWave channel.
  848. const auto i = args.indexOf ("--dwedittest");
  849. runDirectWaveEditTest (args[i + 1].unquoted(), juce::File (args[i + 2].unquoted()), juce::File (args[i + 3].unquoted()),
  850. args.size() > i + 4 ? args[i + 4].unquoted() : juce::String());
  851. return;
  852. }
  853. if (args.contains ("--slicexkeytest"))
  854. {
  855. // LYNX --slicexkeytest report.txt (round 190ac): what a click on the Slicex editor's keyboard sends
  856. // (AudioEngine::sendLiveNote on the channel, velocity 100/128) through the real engine's device callback
  857. // (a stand-in device, driven block by block): the key's region must sound, on the channel's mixer meter
  858. // too, another key must play another region, and the note-off must end it.
  859. runSlicexKeyTest (juce::File (args[args.indexOf ("--slicexkeytest") + 1].unquoted()));
  860. return;
  861. }
  862. if (args.contains ("--countinrectest"))
  863. {
  864. // LYNX --countinrectest report.txt (round 170d, the Busy Works video: the chord on the downbeat after the
  865. // pre-count was lost). The real engine's device callback (a stand-in device: 48 kHz, blocks of 512, 256
  866. // samples of output latency) records a Song-mode take from bar 3 with a 1-bar count-in. Pass 1 finds where
  867. // the metronome's bar-3 click is heard; pass 2 plays MIDI notes stamped at the times they are heard around
  868. // 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
  869. // LYNX's MIDI input. Every note must land on the tick it was heard at (the chord on bar 3).
  870. const auto i = args.indexOf ("--countinrectest");
  871. runCountInRecordTest (juce::File (args[i + 1].unquoted()));
  872. return;
  873. }
  874. if (args.contains ("--bendrectest"))
  875. {
  876. // LYNX --bendrectest report.txt [song|pattern] (round 167a, issue #12): pitch bend recording end to end. A
  877. // controller's pitch wheel is injected into LYNX's MIDI input (as a device would send it) while recording
  878. // plays: a held note and a wheel sweep 0 → full up → full down → centre. The recorded lane (pattern mode) or
  879. // automation clip (song mode) of the channel's pitch bend must follow the sweep.
  880. const auto i = args.indexOf ("--bendrectest");
  881. const auto songMode = args.size() > i + 2 && args[i + 2] == "song";
  882. runBendRecordTest (juce::File (args[i + 1].unquoted()), songMode);
  883. return;
  884. }
  885. if (args.contains ("--rectest"))
  886. {
  887. // LYNX --rectest report.txt [seconds] [--type T] [--device D] [--input I] [--loop] [--buffer N]
  888. // (round 163): records a click track through a loopback (cable, interface loopback or PipeWire's
  889. // pw-loopback): pings the round trip, plays a click on every beat from an audio clip, records it on Insert 1,
  890. // stops, and checks every recorded click's song position on the Playlist against its beat (samples).
  891. // --loop: loop recording over bars 2-4 (take lanes). --punch: punch in/out on bars 3-4 with 1 bar of pre-roll
  892. // and 1 of post-roll (playback stops by itself after the post-roll).
  893. const auto i = args.indexOf ("--rectest");
  894. const auto option = [&args] (const char* name) { return args.contains (name) ? args[args.indexOf (name) + 1].unquoted() : juce::String(); };
  895. const auto seconds = args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? args[i + 2].getDoubleValue() : 20.0;
  896. runRecordTest (juce::File (args[i + 1].unquoted()), seconds > 0.0 ? seconds : 20.0, option ("--type"), option ("--device"), option ("--input"),
  897. args.contains ("--loop") ? 1 : args.contains ("--punch") ? 2 : 0, option ("--pdc").getIntValue(), option ("--buffer").getIntValue());
  898. return;
  899. }
  900. if (args.contains ("--hwinserttest"))
  901. {
  902. // LYNX --hwinserttest report.txt [seconds] [--type T] [--device D] [--input I] [--buffer N] (round 164d): a
  903. // hardware insert through a loopback cable (output pair 1-2 -> input pair 1-2; the Master plays nowhere, so
  904. // the cable carries the send only). The same click track plays on two inserts: Insert 1 through the
  905. // hardware insert (panned left), Insert 2 dry (panned right). The insert's own ping measures the round
  906. // trip, PDC delays the dry path by it, and every click of the Master's left side must sit on the same
  907. // sample as the right side's.
  908. const auto i = args.indexOf ("--hwinserttest");
  909. const auto option = [&args] (const char* name) { return args.contains (name) ? args[args.indexOf (name) + 1].unquoted() : juce::String(); };
  910. const auto seconds = args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? args[i + 2].getDoubleValue() : 10.0;
  911. // round 165c: --patcher puts the insert inside a Patcher on Insert 1; --bounce file.wav then exports the song in real
  912. // time through the device (Export › "Render through the hardware in real time") and offline, and compares them
  913. runHwInsertTest (juce::File (args[i + 1].unquoted()), seconds > 0.0 ? seconds : 10.0, option ("--type"), option ("--device"), option ("--input"),
  914. option ("--buffer").getIntValue(), args.contains ("--patcher"),
  915. args.contains ("--bounce") ? juce::File (option ("--bounce")) : juce::File());
  916. return;
  917. }
  918. if (args.contains ("--uiperf"))
  919. {
  920. // LYNX --uiperf project.(flp|lynx) report.txt: the heavy UI cases in the real window, every frame timed (round 161)
  921. const auto i = args.indexOf ("--uiperf");
  922. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  923. runUiPerf (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()));
  924. return;
  925. }
  926. if (args.contains ("--cachetest"))
  927. {
  928. // LYNX --cachetest project.(flp|lynx) report.txt (round 174f): the Playlist's cached picture against exact
  929. // paints after zooms, scrolls and repaints, off screen (no window)
  930. const auto i = args.indexOf ("--cachetest");
  931. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  932. runCacheTest (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()));
  933. return;
  934. }
  935. if (args.contains ("--picturetest"))
  936. {
  937. // LYNX --picturetest report.txt [project.(flp|lynx)] (round 190bm): the Playlist and the Mixer drawn through
  938. // their cached pictures at 100-300 %, into native and software targets, against straight paints; off
  939. // screen (no window)
  940. const auto i = args.indexOf ("--picturetest");
  941. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  942. runPictureTest (juce::File (args[i + 1].unquoted()), i + 2 < args.size() ? juce::File (args[i + 2].unquoted()) : juce::File());
  943. return;
  944. }
  945. if (args.contains ("--timertest"))
  946. {
  947. // LYNX --timertest report.txt (round 174f): ui::TimerWhileShowing through hide / show / minimise (opens a small window)
  948. runTimerTest (juce::File (args[args.indexOf ("--timertest") + 1].unquoted()));
  949. return;
  950. }
  951. if (args.contains ("--livepeer"))
  952. {
  953. // LYNX --livepeer host|guest|rejoin <folder> [--relay URL] [--code CODE|@file]: one computer's side of a live
  954. // session between two real computers, no window (round 190ah)
  955. setApplicationReturnValue (lynx::livetest::runPeer (args));
  956. quit();
  957. return;
  958. }
  959. if (args.contains ("--livetest"))
  960. {
  961. // LYNX --livetest report.txt [--relay URL]: a live session of four peers over the relay (round 169b)
  962. setApplicationReturnValue (lynx::livetest::run (args));
  963. quit();
  964. return;
  965. }
  966. if (args.contains ("--selftest"))
  967. {
  968. const auto i = args.indexOf ("--selftest");
  969. runSelfTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  970. return;
  971. }
  972. if (args.contains ("--scan-one"))
  973. {
  974. // child process of the plugin scan (see PluginHost::scan)
  975. const auto i = args.indexOf ("--scan-one");
  976. // no crash dialogs from the plugin being examined; and once the result is written, the process ends without
  977. // unloading it: a Waves shell crashed in its own teardown at exit (Intel GPU driver fail-fast, 0xC0000409),
  978. // which showed Windows' crash dialog and made the scan reject the whole shell (round 111)
  979. lynx::crashguard::quietCrashReports();
  980. lynx::PluginHost::scanOneFile (args[i + 1].unquoted(), args[i + 2].unquoted(), juce::File (args[i + 3].unquoted()));
  981. lynx::crashguard::exitNow (0);
  982. }
  983. if (args.contains ("--splashshot"))
  984. {
  985. // LYNX --splashshot <folder> (round 190hd): the splash card drawn as the JUCE card is and as the card on its own
  986. // thread is (ui/Splash.h), side by side; no window
  987. const auto shots = lynx::writeSplashShots (juce::File (args[args.indexOf ("--splashshot") + 1].unquoted()));
  988. setApplicationReturnValue (shots.size() == 20 ? 0 : 1);
  989. quit();
  990. return;
  991. }
  992. if (args.contains ("--browser-indexer"))
  993. {
  994. // round 190hd: the Browser's indexer, a low-priority child of the LYNX window (BrowserComponent.h): no window,
  995. // no session, no audio; it ends with its parent
  996. lynx::crashguard::quietCrashReports();
  997. lynx::crashguard::exitNow (lynx::BrowserComponent::runIndexerProcess (args));
  998. }
  999. if (args.contains ("--packageinfo"))
  1000. {
  1001. // round 165n: the Microsoft Store (MSIX) build's identity and folders (platform/Package.h); the release
  1002. // workflow runs it inside the installed test package
  1003. juce::File (args[args.indexOf ("--packageinfo") + 1].unquoted()).replaceWithText (lynx::platform::packageReport());
  1004. quit();
  1005. return;
  1006. }
  1007. if (args.contains ("--paths"))
  1008. {
  1009. // diagnostics: folders LYNX searches
  1010. const auto programs = juce::File::getSpecialLocation (juce::File::globalApplicationsDirectory);
  1011. juce::String report;
  1012. report << "programs=" << programs.getFullPathName() << "\n";
  1013. for (const auto& dir : programs.getChildFile ("Image-Line").findChildFiles (juce::File::findDirectories, false, "FL Studio*"))
  1014. report << "fl=" << dir.getFullPathName() << " packs=" << (int) dir.getChildFile ("Data").getChildFile ("Patches").getChildFile ("Packs").isDirectory() << "\n";
  1015. juce::File (args[args.indexOf ("--paths") + 1].unquoted()).replaceWithText (report);
  1016. quit();
  1017. return;
  1018. }
  1019. if (args.contains ("--fldb"))
  1020. {
  1021. // diagnostics: LYNX.exe --fldb report.txt [project.flp]: the FL Studio installation, its plugin database,
  1022. // the suggested plugin folders and, for a project, how each of its plugins resolves (read-only)
  1023. const auto i = args.indexOf ("--fldb");
  1024. const auto fl = lynx::findFlStudio();
  1025. lynx::PluginHost host (false);
  1026. juce::String report;
  1027. report << "install=" << fl.installDir.getFullPathName() << "\nuserdata=" << fl.userData.getFullPathName() << "\n";
  1028. for (const auto& f : fl.vstFolders)
  1029. report << "flvstfolder=" << f << "\n";
  1030. report << "dbfiles=" << host.flPluginDatabaseFiles() << " entries=" << (int) host.flPluginDatabase().entries().size() << "\n";
  1031. for (const auto& e : host.flPluginDatabase().entries())
  1032. report << " entry: " << juce::String::fromUTF8 (e.name.c_str()) << " | " << juce::String::fromUTF8 (e.path.c_str()) << " | role=" << e.role << "\n";
  1033. const auto suggested = host.suggestedFolders();
  1034. for (int k = 0; k < suggested.getNumPaths(); ++k)
  1035. report << "folder=" << suggested[k].getFullPathName() << "\n";
  1036. if (const juce::File project (args[i + 2].unquoted()); project.existsAsFile())
  1037. {
  1038. juce::MemoryBlock data;
  1039. project.loadFileAsData (data);
  1040. try
  1041. {
  1042. for (const auto& use : lynx::flpForeignPlugins (flp::parseProject ({ static_cast<const std::uint8_t*> (data.getData()), data.getSize() })))
  1043. {
  1044. juce::String how;
  1045. const auto d = host.findForeign (use.plugin, use.instrument, &how);
  1046. const auto* entry = host.flPluginDatabase().match (use.plugin, use.instrument);
  1047. report << "plugin: " << juce::String::fromUTF8 (use.plugin.name.c_str()) << " -> "
  1048. << (d ? d->fileOrIdentifier + " (" + how + ")" : juce::String ("not known"))
  1049. << (entry != nullptr ? " | fl db: " + juce::String::fromUTF8 (entry->path.c_str()) : juce::String()) << "\n";
  1050. }
  1051. const auto uses = lynx::flpForeignPlugins (flp::parseProject ({ static_cast<const std::uint8_t*> (data.getData()), data.getSize() }));
  1052. const auto candidates = host.filesToScanFor (uses);
  1053. report << "scan_candidates=" << candidates.joinIntoString (";") << "\n";
  1054. if (args.contains ("--scan"))
  1055. {
  1056. // the targeted scan an open would run (child processes; the user's plugin list is not touched)
  1057. report << "scanned_new=" << host.scanFiles (candidates, {}) << "\n";
  1058. for (const auto& use : uses)
  1059. {
  1060. juce::String how;
  1061. const auto d = host.findForeign (use.plugin, use.instrument, &how);
  1062. report << "after_scan: " << juce::String::fromUTF8 (use.plugin.name.c_str()) << " -> "
  1063. << (d ? d->fileOrIdentifier + " (" + how + ")" : juce::String ("not known")) << "\n";
  1064. }
  1065. }
  1066. }
  1067. catch (const flp::Error& e)
  1068. {
  1069. report << "error=" << e.what() << "\n";
  1070. }
  1071. }
  1072. juce::File (args[i + 1].unquoted()).replaceWithText (report);
  1073. quit();
  1074. return;
  1075. }
  1076. if (args.contains ("--midisync-test"))
  1077. {
  1078. // LYNX --midisync-test report.txt ["output device"] ["input device"] (round 165f): MIDI clock timing
  1079. const auto i = args.indexOf ("--midisync-test");
  1080. const auto out = args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  1081. const auto in = args.size() > i + 3 && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  1082. juce::File (args[i + 1].unquoted()).replaceWithText (lynx::MidiSyncIo::selfTest (out, in));
  1083. quit();
  1084. return;
  1085. }
  1086. if (args.contains ("--linktest"))
  1087. {
  1088. // LYNX --linktest report.txt [seconds] [peer] (round 190gl): Ableton Link with simulated audio callbacks; with
  1089. // "peer" a second Link peer in this process, else a peer on the network (Ableton's LinkHut) is expected
  1090. const auto i = args.indexOf ("--linktest");
  1091. const auto seconds = args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? args[i + 2].getDoubleValue() : 20.0;
  1092. const auto ownPeer = args.contains ("peer");
  1093. juce::File (args[i + 1].unquoted()).replaceWithText (juce::String (lynx::AbletonLink::selfTest (seconds > 0.0 ? seconds : 20.0, ownPeer)));
  1094. quit();
  1095. return;
  1096. }
  1097. if (args.contains ("--devices") || args.contains ("--dispositivos")) // --dispositivos: legacy alias
  1098. {
  1099. // diagnostics: driver types and output devices JUCE offers (without opening any)
  1100. juce::AudioDeviceManager manager;
  1101. juce::String report;
  1102. manager.getAvailableDeviceTypes();
  1103. if (auto pipeWire = lynx::makePipeWireDeviceType()) // Linux: LYNX's own PipeWire client (round 161)
  1104. manager.addAudioDeviceType (std::move (pipeWire));
  1105. #if JUCE_LINUX
  1106. report << lynx::describePipeWire() << "\n";
  1107. #endif
  1108. for (auto* type : manager.getAvailableDeviceTypes())
  1109. {
  1110. type->scanForDevices();
  1111. report << "type=" << type->getTypeName() << "\n";
  1112. for (const auto& name : type->getDeviceNames (false))
  1113. report << " output=" << name << "\n";
  1114. for (const auto& name : type->getDeviceNames (true))
  1115. report << " input=" << name << "\n";
  1116. }
  1117. for (const auto& d : juce::MidiInput::getAvailableDevices())
  1118. report << "midi-in=" << d.name << "\n";
  1119. for (const auto& d : juce::MidiOutput::getAvailableDevices())
  1120. report << "midi-out=" << d.name << "\n";
  1121. const auto flag = args.contains ("--devices") ? args.indexOf ("--devices") : args.indexOf ("--dispositivos");
  1122. juce::File (args[flag + 1].unquoted()).replaceWithText (report);
  1123. quit();
  1124. return;
  1125. }
  1126. if (args.contains ("--devicetest"))
  1127. {
  1128. // LYNX.exe --devicetest "type" "device" report.txt ["input device"] [--buffer N] [--roundtrip]: opens that output device (and, with the
  1129. // 4th argument, an input: "*" = the same device / the driver's default input), receives 1 s of callbacks
  1130. // writing silence, closes it and reports rate, block size, latency, callbacks and the input channels with
  1131. // their peak level (driver check, no sound). --roundtrip: clicks out, found again on input 1 through a loopback
  1132. // cable / PipeWire link: the round-trip latency (3 s)
  1133. const auto i = args.indexOf ("--devicetest");
  1134. const auto typeName = args[i + 1].unquoted(), deviceName = args[i + 2].unquoted();
  1135. auto inputName = args.size() > i + 4 && ! args[i + 4].startsWith ("--") ? args[i + 4].unquoted() : juce::String();
  1136. const auto wantInput = inputName.isNotEmpty();
  1137. juce::String report;
  1138. const juce::File reportFile (args[i + 3].unquoted());
  1139. auto step = [&] (const juce::String& line) { report << line << "\n"; reportFile.replaceWithText (report); }; // progress survives a driver that ends the process
  1140. step ("step=start");
  1141. juce::AudioDeviceManager manager;
  1142. manager.getAvailableDeviceTypes();
  1143. if (auto pipeWire = lynx::makePipeWireDeviceType())
  1144. manager.addAudioDeviceType (std::move (pipeWire));
  1145. std::unique_ptr<juce::AudioIODevice> device;
  1146. for (auto* type : manager.getAvailableDeviceTypes())
  1147. if (type->getTypeName() == typeName)
  1148. {
  1149. type->scanForDevices();
  1150. if (wantInput && type->hasSeparateInputsAndOutputs())
  1151. {
  1152. const auto inputs = type->getDeviceNames (true);
  1153. if (inputName == "*" || ! inputs.contains (inputName))
  1154. {
  1155. const auto index = type->getDefaultDeviceIndex (true);
  1156. inputName = juce::isPositiveAndBelow (index, inputs.size()) ? inputs[index] : juce::String();
  1157. }
  1158. for (const auto& n : inputs)
  1159. step ("input_device=" + n);
  1160. step ("input_chosen=" + inputName);
  1161. }
  1162. else if (wantInput)
  1163. inputName = deviceName;
  1164. step ("step=create");
  1165. device.reset (type->createDevice (deviceName, type->hasSeparateInputsAndOutputs() ? inputName : juce::String()));
  1166. step ("step=created");
  1167. }
  1168. struct Silence final : juce::AudioIODeviceCallback
  1169. {
  1170. std::atomic<int> calls { 0 }, inputs { 0 };
  1171. std::array<std::atomic<float>, 64> peaks {};
  1172. // --roundtrip (round 161): a click every quarter second on the outputs, found again on input 1 through a
  1173. // loopback; the delays in samples
  1174. bool roundtrip = false;
  1175. int period = 12000;
  1176. std::int64_t position = 0, lastClick = -1;
  1177. std::vector<int> delays;
  1178. void audioDeviceIOCallbackWithContext (const float* const* in, int numIn, float* const* out, int channels, int n,
  1179. const juce::AudioIODeviceCallbackContext&) override
  1180. {
  1181. for (int c = 0; c < channels; ++c)
  1182. if (out[c] != nullptr)
  1183. juce::FloatVectorOperations::clear (out[c], n);
  1184. if (roundtrip)
  1185. {
  1186. for (int i = 0; i < n; ++i)
  1187. {
  1188. if (numIn > 0 && in[0] != nullptr && lastClick >= 0 && std::abs (in[0][i]) > 0.5f)
  1189. {
  1190. if (delays.size() < delays.capacity())
  1191. delays.push_back ((int) (position + i - lastClick));
  1192. lastClick = -1;
  1193. }
  1194. if ((position + i) % period == 0 && position + i > 0)
  1195. {
  1196. for (int c = 0; c < channels; ++c)
  1197. if (out[c] != nullptr)
  1198. out[c][i] = 0.9f;
  1199. lastClick = position + i;
  1200. }
  1201. }
  1202. position += n;
  1203. }
  1204. inputs.store (numIn);
  1205. for (int c = 0; c < juce::jmin (numIn, 64); ++c)
  1206. if (in[c] != nullptr)
  1207. {
  1208. const auto range = juce::FloatVectorOperations::findMinAndMax (in[c], n);
  1209. const auto peak = juce::jmax (std::abs (range.getStart()), std::abs (range.getEnd()));
  1210. if (peak > peaks[(std::size_t) c].load())
  1211. peaks[(std::size_t) c].store (peak);
  1212. }
  1213. ++calls;
  1214. }
  1215. void audioDeviceAboutToStart (juce::AudioIODevice*) override {}
  1216. void audioDeviceStopped() override {}
  1217. } silence;
  1218. bool ok = false;
  1219. if (device == nullptr)
  1220. step ("error=device not found");
  1221. else
  1222. {
  1223. step ("step=open");
  1224. juce::BigInteger outputs;
  1225. outputs.setRange (0, 2, true);
  1226. const auto rates = device->getAvailableSampleRates();
  1227. const auto rate = device->getCurrentSampleRate() > 0 ? device->getCurrentSampleRate()
  1228. : rates.contains (48000.0) ? 48000.0 : rates.isEmpty() ? 44100.0 : rates[0];
  1229. step ("rates=" + juce::String (rates.size()) + " chosen=" + juce::String (rate) + " default_block=" + juce::String (device->getDefaultBufferSize()));
  1230. juce::BigInteger inputs;
  1231. if (wantInput)
  1232. {
  1233. const auto names = device->getInputChannelNames();
  1234. step ("input_channels=" + juce::String (names.size()));
  1235. for (int c = 0; c < names.size(); ++c)
  1236. step (" in" + juce::String (c + 1) + "=" + names[c]);
  1237. inputs.setRange (0, juce::jmin (64, names.size()), true);
  1238. }
  1239. // --buffer N: ask for that block size (REA round 97 latency survey); default: the driver's default
  1240. const auto wantedBlock = args.contains ("--buffer") ? args[args.indexOf ("--buffer") + 1].getIntValue() : 0;
  1241. const auto error = device->open (inputs, outputs, rate, wantedBlock > 0 ? wantedBlock : device->getDefaultBufferSize());
  1242. if (error.isNotEmpty())
  1243. step ("error=" + error);
  1244. else
  1245. {
  1246. step ("step=start_callbacks");
  1247. silence.roundtrip = args.contains ("--roundtrip");
  1248. silence.period = juce::jmax (1, (int) (rate / 4));
  1249. silence.delays.reserve (64);
  1250. device->start (&silence);
  1251. juce::Thread::sleep (silence.roundtrip ? 3000 : 1000);
  1252. device->stop();
  1253. if (silence.roundtrip)
  1254. {
  1255. auto d = silence.delays;
  1256. std::sort (d.begin(), d.end());
  1257. report << "roundtrip_clicks=" << (int) d.size() << "\n";
  1258. if (! d.empty())
  1259. report << "roundtrip_samples=min " << d.front() << " median " << d[d.size() / 2] << " max " << d.back() << "\n"
  1260. << "roundtrip_ms=" << juce::String (1000.0 * d[d.size() / 2] / device->getCurrentSampleRate(), 2) << "\n";
  1261. }
  1262. report << "rate=" << device->getCurrentSampleRate() << "\n"
  1263. << "block=" << device->getCurrentBufferSizeSamples() << "\n"
  1264. << "output_latency=" << device->getOutputLatencyInSamples() << "\n"
  1265. << "callbacks=" << silence.calls.load() << "\n";
  1266. if (wantInput)
  1267. {
  1268. report << "input_latency=" << device->getInputLatencyInSamples() << "\n"
  1269. << "active_inputs=" << device->getActiveInputChannels().countNumberOfSetBits() << "\n"
  1270. << "callback_inputs=" << silence.inputs.load() << "\n";
  1271. for (int c = 0; c < juce::jmin (64, silence.inputs.load()); ++c)
  1272. report << " peak_in" << (c + 1) << "=" << juce::Decibels::gainToDecibels (silence.peaks[(std::size_t) c].load(), -150.0f) << " dB\n";
  1273. }
  1274. ok = silence.calls.load() > 0 && (! wantInput || silence.inputs.load() > 0);
  1275. device->close();
  1276. }
  1277. }
  1278. step (juce::String ("result=") + (ok ? "OK" : "FAILED"));
  1279. setApplicationReturnValue (ok ? 0 : 1);
  1280. quit();
  1281. return;
  1282. }
  1283. if (args.contains ("--scantest"))
  1284. {
  1285. // LYNX.exe --scantest folder report.txt: scan (in child processes) without touching the user's list
  1286. const auto i = args.indexOf ("--scantest");
  1287. lynx::PluginHost host (false);
  1288. const auto found = host.scan (juce::FileSearchPath (args[i + 1].unquoted()), {});
  1289. juce::String report;
  1290. report << "found=" << found << "\n";
  1291. for (const auto& t : host.getKnownPlugins().getTypes())
  1292. report << " " << (t.isInstrument ? "instrument: " : "effect: ") << t.name << "\n";
  1293. for (const auto& f : host.getKnownPlugins().getBlacklistedFiles())
  1294. report << " blacklisted: " << f << "\n";
  1295. juce::File (args[i + 2].unquoted()).replaceWithText (report);
  1296. setApplicationReturnValue (found > 0 ? 0 : 1);
  1297. quit();
  1298. return;
  1299. }
  1300. if (args.contains ("--wrappermiditest"))
  1301. {
  1302. // LYNX.exe --wrappermiditest plugin.dll report.txt (round 181c), with LYNX_TEST_VST2_MIDILOG set: what a
  1303. // hosted plugin receives after a wrapper MIDI option changes while it runs
  1304. const auto i = args.indexOf ("--wrappermiditest");
  1305. runWrapperMidiTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  1306. return;
  1307. }
  1308. if (args.contains ("--wrappershot"))
  1309. {
  1310. const auto i = args.indexOf ("--wrappershot");
  1311. runWrapperShot (args[i + 1].unquoted(), args[i + 2].unquoted());
  1312. return;
  1313. }
  1314. if (args.contains ("--multiouttest"))
  1315. {
  1316. const auto i = args.indexOf ("--multiouttest");
  1317. runMultiOutTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  1318. return;
  1319. }
  1320. if (args.contains ("--vstitest"))
  1321. {
  1322. // LYNX --vstitest plugin folder [project.lynx] (round 190fw, issue #162): an instrument plugin (Image-Line's
  1323. // "FL Studio VSTi") on a channel: notes in, audio out, its state through a saved project, its outputs and
  1324. // the host tempo it follows. See runVstiTest.
  1325. const auto i = args.indexOf ("--vstitest");
  1326. const auto project = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  1327. runVstiTest (args[i + 1].unquoted(), args[i + 2].unquoted(), project);
  1328. return;
  1329. }
  1330. if (args.contains ("--vst2test"))
  1331. {
  1332. const auto i = args.indexOf ("--vst2test");
  1333. runVst2Test (args[i + 1].unquoted(), args[i + 2].unquoted());
  1334. return;
  1335. }
  1336. if (args.contains ("--vst3noteidtest"))
  1337. {
  1338. const auto i = args.indexOf ("--vst3noteidtest");
  1339. runVst3NoteIdTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  1340. return;
  1341. }
  1342. if (args.contains ("--lv2scantest"))
  1343. {
  1344. runLv2ScanTest (args[args.indexOf ("--lv2scantest") + 1].unquoted());
  1345. return;
  1346. }
  1347. if (args.contains ("--wrappertest"))
  1348. {
  1349. const auto i = args.indexOf ("--wrappertest");
  1350. runWrapperTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  1351. return;
  1352. }
  1353. if (args.contains ("--plugintest"))
  1354. {
  1355. const auto i = args.indexOf ("--plugintest");
  1356. // optional 3rd argument: the plugin's name inside a shell (e.g. "CLA-2A Stereo" in a WaveShell)
  1357. const auto only = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  1358. runPluginTest (args[i + 1].unquoted(), args[i + 2].unquoted(), only);
  1359. return;
  1360. }
  1361. if (args.contains ("--crashguardtest"))
  1362. {
  1363. // LYNX --crashguardtest "LYNX Test Crash.vst3|.clap" report.txt [process|memcpy] (round 190dt,
  1364. // tools/testplugin/lynx_test_crash*.{c,cpp}): the plugin crashes in its 40th block on insert 1; LYNX must
  1365. // catch it, mark the slot, keep playing the other inserts, save the project, reload the plugin; then the
  1366. // saved project opens with the plugin crashing on its state; and LYNX's own faults are still crashes
  1367. const auto i = args.indexOf ("--crashguardtest");
  1368. runCrashGuardTest (args[i + 1].unquoted(), args[i + 2].unquoted(),
  1369. i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String ("process"));
  1370. return;
  1371. }
  1372. if (args.contains ("--claprestarttest"))
  1373. {
  1374. // LYNX.exe --claprestarttest "LYNX Test Restart.clap" report.txt (tools/testplugin/lynx_test_restart.c)
  1375. const auto i = args.indexOf ("--claprestarttest");
  1376. runClapRestartTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  1377. return;
  1378. }
  1379. if (args.contains ("--clapteardowntest"))
  1380. {
  1381. // LYNX.exe --clapteardowntest "LYNX Test Restart.clap" report.txt (round 190az, engine/ClapTeardownTest.cpp)
  1382. const auto i = args.indexOf ("--clapteardowntest");
  1383. lynx::runClapTeardownTest (args[i + 1].unquoted(), args[i + 2].unquoted(), [this] (int code) {
  1384. setApplicationReturnValue (code);
  1385. quit();
  1386. });
  1387. return;
  1388. }
  1389. if (args.contains ("--mpetest"))
  1390. {
  1391. // LYNX.exe --mpetest "LYNX Test MPE.clap" report.txt (tools/testplugin/lynx_test_mpe.c, issue #108)
  1392. const auto i = args.indexOf ("--mpetest");
  1393. runMpeTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  1394. return;
  1395. }
  1396. if (args.contains ("--mpeplaytest190hy"))
  1397. {
  1398. // LYNX --mpeplaytest190hy plugin.(clap|vst3) report.txt (round 190hy, issue #108): a song note with a pitch
  1399. // curve played by a hosted plugin with MPE on, through the whole song path (scheduler, renderer, the wrapper's
  1400. // MPE / CLAP note expressions), rendered offline; the pitch heard is measured (report.txt, report.wav)
  1401. const auto i = args.indexOf ("--mpeplaytest190hy");
  1402. runMpePlayTest190hy (args[i + 1].unquoted(), args[i + 2].unquoted());
  1403. return;
  1404. }
  1405. if (args.contains ("--editortest"))
  1406. {
  1407. // LYNX.exe --editortest plugin.vst3 report.txt ["name"]: opens the plugin's own editor in a window for a few
  1408. // seconds, then closes it (a plugin whose UI crashes the host ends the process before the report says OK)
  1409. const auto i = args.indexOf ("--editortest");
  1410. const auto only = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  1411. runEditorTest (args[i + 1].unquoted(), args[i + 2].unquoted(), only);
  1412. return;
  1413. }
  1414. if (args.contains ("--editorcrashtest"))
  1415. {
  1416. // LYNX.exe --editorcrashtest "LYNX Test Crash.clap" report.txt (issue #32, round 174a; Windows): the test
  1417. // plugin's editor faults in its own window procedure (LYNX_TEST_CRASH=editor). LYNX must catch it, close
  1418. // that editor, record the trace and keep running its message loop.
  1419. const auto i = args.indexOf ("--editorcrashtest");
  1420. runEditorCrashTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  1421. return;
  1422. }
  1423. if (args.contains ("--reloadtest"))
  1424. {
  1425. // LYNX --reloadtest plugin report.txt [shots folder] [--wait-kill]: round 190ao (reload a crashed plugin).
  1426. // Hosts the plugin in a separate process (a channel for an instrument, insert 1 for an effect) in an offline
  1427. // engine, crashes its process (--wait-kill: writes <report>.pid and waits for the process to be killed
  1428. // from outside), checks that nothing reloads by itself, reloads it on request and checks the new process,
  1429. // the state captured last, the untouched song and undo history; twice. With a shots folder: PNGs of the
  1430. // plugin window's crash notice and of the prompt.
  1431. const auto i = args.indexOf ("--reloadtest");
  1432. runReloadTest (args[i + 1].unquoted(), args[i + 2].unquoted(),
  1433. i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String(), args.contains ("--wait-kill"));
  1434. return;
  1435. }
  1436. if (args.contains ("--pluginoptionstest"))
  1437. {
  1438. // LYNX --pluginoptionstest plugin report.txt [shots folder]: round 190ao. Hosts the plugin inside LYNX (a
  1439. // channel for an instrument, insert 1 for an effect) in an offline engine, opens its window and checks
  1440. // LYNX's own plugin-window options: Pin on top (set, kept above another window, saved with the plugin,
  1441. // back when the window opens again). With a shots folder: PNGs of each state. The window is on screen.
  1442. const auto i = args.indexOf ("--pluginoptionstest");
  1443. runPluginOptionsTest (args[i + 1].unquoted(), args[i + 2].unquoted(),
  1444. i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String());
  1445. return;
  1446. }
  1447. if (args.contains ("--plugwintest"))
  1448. {
  1449. // LYNX --plugwintest plugin report.txt ["name"] [seconds]: round 162d. Puts the plugin in a channel (an
  1450. // instrument) or on insert 1 (an effect) of an offline engine, opens its plugin window (wrapper header,
  1451. // presets), checks a preset round trip, keeps the window `seconds` on screen (default 15: time for xdotool /
  1452. // screenshots), then removes the plugin from the song and reports whether its window closed by itself.
  1453. const auto i = args.indexOf ("--plugwintest");
  1454. const auto only = i + 3 < args.size() && ! args[i + 3].startsWith ("--") && ! args[i + 3].containsOnly ("0123456789") ? args[i + 3].unquoted() : juce::String();
  1455. auto seconds = 15;
  1456. for (int k = i + 3; k < juce::jmin (args.size(), i + 5); ++k)
  1457. if (args[k].containsOnly ("0123456789"))
  1458. seconds = args[k].getIntValue();
  1459. runPlugWinTest (args[i + 1].unquoted(), args[i + 2].unquoted(), only, seconds);
  1460. return;
  1461. }
  1462. if (args.contains ("--fittest"))
  1463. {
  1464. // LYNX.exe --fittest report.txt [percent]: round 163 — at that UI zoom (default 150) a window taller than
  1465. // the screen and a big resizable window that grows with a zoom change keep their title bar and close
  1466. // button on the screen. The windows show for about two seconds.
  1467. const auto i = args.indexOf ("--fittest");
  1468. runFitTest (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].getIntValue() : 150);
  1469. return;
  1470. }
  1471. if (args.contains ("--windowtest"))
  1472. {
  1473. // LYNX.exe --windowtest report.txt: opens the Quick-add palette, the Audio editor, a plugin-like window and a name dialog
  1474. // over the main window and checks that each one stays in front, owned by the main window, with the
  1475. // keyboard focus (issue #4). The windows appear on screen for a few seconds.
  1476. runWindowTest (args[args.indexOf ("--windowtest") + 1].unquoted());
  1477. return;
  1478. }
  1479. if (args.contains ("--minimizeclicktest"))
  1480. {
  1481. // LYNX --minimizeclicktest report.txt (issue #188, round 190ir): a tool window over the main window is
  1482. // minimised (through the window manager), the main window comes to the front, and a click where the tool
  1483. // window was must reach the main window's component. Run it under a window manager (openbox on a private
  1484. // Xvfb); exit code 0 = OK.
  1485. runMinimizeClickTest (args[args.indexOf ("--minimizeclicktest") + 1].unquoted());
  1486. return;
  1487. }
  1488. if (args.contains ("--focustest"))
  1489. {
  1490. // LYNX --focustest report.txt (issue #161): the main window with the Playlist and the Piano roll (native
  1491. // child windows with docking on). For each: LYNX goes to the background (the main window loses the focus),
  1492. // the user comes back with a click in the panel, then presses Space: playback must start. Also: a text
  1493. // field's focus comes back with the window, and inside the active window the click's answer is unchanged.
  1494. // Shows a window (takes the foreground on Windows: GUI lock); exit code 0 = OK.
  1495. runFocusTest (args[args.indexOf ("--focustest") + 1].unquoted());
  1496. return;
  1497. }
  1498. if (args.contains ("--simplekeytest"))
  1499. {
  1500. // LYNX --simplekeytest report.txt (round 190fc, 0.1.27 RC H2): the main window in the Simple layout; after a
  1501. // demo opened from Welcome › Start from and after clicks in the dock, its tabs, the Lyrics button, a track
  1502. // header and the grid, Space must start playback (a text field clicked into keeps its typing keys). Shows a
  1503. // window (takes the foreground on Windows: GUI lock); exit code 0 = OK.
  1504. runSimpleKeyTest (args[args.indexOf ("--simplekeytest") + 1].unquoted());
  1505. return;
  1506. }
  1507. if (args.contains ("--pluginstyle")) // round 126: force one style for this run (glow, neon, hardware, vivid; auto = per plugin)
  1508. {
  1509. const auto i = args.indexOf ("--pluginstyle");
  1510. if (i + 1 < args.size())
  1511. {
  1512. const auto name = args[i + 1].unquoted();
  1513. lynx::skin::setForcedStyle (name.equalsIgnoreCase ("auto") ? -1 : (int) lynx::skin::styleFromName (name));
  1514. }
  1515. }
  1516. if (args.contains ("--gfxprobe"))
  1517. {
  1518. // LYNX.exe --gfxprobe report.txt (round 170c, issue #11): renderer checks on this platform's native images —
  1519. // text drawn with a gradient fill (a word with a space in it) and an empty path filled with a gradient must
  1520. // stay inside their shapes. JUCE 8.0.4's CoreGraphics renderer (macOS) clipped to an empty glyph or path as
  1521. // "no clip" and flooded the whole component (Facet EQ's blank pink window).
  1522. const auto i = args.indexOf ("--gfxprobe");
  1523. juce::File (args[i + 1].unquoted()).replaceWithText (lynx::skin::rendererProbeReport());
  1524. quit();
  1525. return;
  1526. }
  1527. if (args.contains ("--steppertest"))
  1528. {
  1529. // LYNX.exe --steppertest <report.txt>: round 170c (#14) — every value stepper of every generated effect editor
  1530. // driven by synthetic input (arrows, click on the value, drag, wheel, trackpad); ends with result=OK / FAIL
  1531. const auto i = args.indexOf ("--steppertest");
  1532. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1533. juce::String report;
  1534. int fails = 0, count = 0, skips = 0;
  1535. {
  1536. lynx::AudioEngine offline (false);
  1537. auto kinds = lynx::plugui::flLayoutKinds();
  1538. for (const auto own : lynx::plugui::ownLayoutKinds())
  1539. kinds.push_back (own);
  1540. // FL's Default preset when the installation has one (the state-backed controls need FL's state)
  1541. const auto roots = lynx::findFlStudioRoots();
  1542. const auto presets = juce::File (juce::String::fromUTF8 (roots.data.c_str())).getChildFile ("Patches/Plugin presets/Effects");
  1543. for (const auto kind : kinds)
  1544. {
  1545. auto fx = lynx::makeEffectSlot (kind);
  1546. for (const auto& plugin : lynx::flPluginsForEffect (kind))
  1547. {
  1548. juce::MemoryBlock data;
  1549. const auto file = presets.getChildFile (juce::String::fromUTF8 (plugin.c_str())).getChildFile ("Default.fst");
  1550. if (file.existsAsFile() && file.loadFileAsData (data))
  1551. {
  1552. const auto* bytes = static_cast<const std::uint8_t*> (data.getData());
  1553. 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)
  1554. fx = *loaded;
  1555. }
  1556. break;
  1557. }
  1558. lynx::Song song;
  1559. song.mixer.resize (2);
  1560. song.mixer[0].name = "Master";
  1561. song.mixer[1].name = "Insert 1";
  1562. song.mixer[1].effects.push_back (fx);
  1563. offline.setSong (std::move (song));
  1564. offline.dispatchPendingMessages();
  1565. const auto lines = lynx::stepperSelfTest (offline, 1, 0, (int) lynx::plugui::layoutFor (kind).pages.size());
  1566. for (const auto& line : juce::StringArray::fromLines (lines))
  1567. if (line.isNotEmpty())
  1568. {
  1569. ++count;
  1570. fails += line.contains (": FAIL") ? 1 : 0;
  1571. skips += line.contains (": SKIP") ? 1 : 0;
  1572. }
  1573. report << lines;
  1574. juce::PopupMenu::dismissAllActiveMenus();
  1575. offline.dispatchPendingMessages();
  1576. }
  1577. }
  1578. report << "steppers=" << count << " failures=" << fails << " skipped=" << skips << "\nresult=" << (fails == 0 && count > 0 ? "OK" : "FAIL") << "\n";
  1579. juce::File (args[i + 1].unquoted()).replaceWithText (report);
  1580. quit();
  1581. return;
  1582. }
  1583. if (args.contains ("--design190inshot"))
  1584. {
  1585. // LYNX --design190inshot prefix [project.flp]: round 190in off screen (no desktop window, no audio device) —
  1586. // the channel window as it shows docked (FL's ▸, two-tone title, presets in the title bar, the 46 px strip
  1587. // with icon tabs, LED, knobs, RANGE / TRACK badges) on each tab, the floating strip, and FL's ▸ menu
  1588. const auto i = args.indexOf ("--design190inshot");
  1589. runDesign190inShot (args[i + 1].unquoted(), i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String());
  1590. quit();
  1591. return;
  1592. }
  1593. if (args.contains ("--plugui"))
  1594. {
  1595. // LYNX.exe --plugui <folder>: the native effect editors at FL's size (one PNG per editor and page), each
  1596. // loaded with the FL plugin's Default preset when the FL installation has one
  1597. const auto i = args.indexOf ("--plugui");
  1598. runPluginEditorSnapshots (args[i + 1].unquoted());
  1599. return;
  1600. }
  1601. if (args.contains ("--parityshot"))
  1602. {
  1603. // LYNX.exe --parityshot <out.png> <effect name> [<params file>]: one built-in effect's editor with the given
  1604. // parameters ("index value" lines, tools/fxrender --dump), its displays fed by the demo song — the LYNX side
  1605. // of the third-party parity pictures (round tp172b)
  1606. const auto i = args.indexOf ("--parityshot");
  1607. runParityShot (args[i + 1].unquoted(), args[i + 2].unquoted(), i + 3 < args.size() ? args[i + 3].unquoted() : juce::String());
  1608. if (parityShotFailed)
  1609. setApplicationReturnValue (2);
  1610. if (parityShow == nullptr)
  1611. quit();
  1612. return;
  1613. }
  1614. if (args.contains ("--design168rshot"))
  1615. {
  1616. // LYNX.exe --design168rshot <folder>: round 168r's editors (FL effects that had a generated page and LYNX's own
  1617. // simple built-ins) at 100 % and 200 %, with their default settings and, when they have one, the first
  1618. // preset of LYNX's own bank. "--design168rshot <folder> generated": the generated pages they had before
  1619. const auto i = args.indexOf ("--design168rshot");
  1620. if (i + 2 < args.size() && args[i + 2] == "generated")
  1621. lynx::plugui::showGeneratedLayoutsOnly (true);
  1622. runDesign168rShots (args[i + 1].unquoted());
  1623. quit();
  1624. return;
  1625. }
  1626. if (args.contains ("--eq166fshot"))
  1627. {
  1628. // LYNX.exe --eq166fshot <folder>: round 166f's pictures (issue #16) — Parametric EQ 2's spectrum and heatmap
  1629. // (flat, a +12 dB band, a -12 dB band, Top position) and Facet EQ's comparative EQ (listening to the target,
  1630. // its spectrum over the source's), each fed by the demo song rendered offline
  1631. const auto i = args.indexOf ("--eq166fshot");
  1632. runEq166fShots (args[i + 1].unquoted());
  1633. quit();
  1634. return;
  1635. }
  1636. if (args.contains ("--editorcpu"))
  1637. {
  1638. // LYNX.exe --editorcpu report.txt: opens built-in plugin editors one at a time in a small window (no audio
  1639. // device: a silent, idle editor) and writes the process CPU each costs while idle and while its display
  1640. // animates (demo signal) — round 122's check that an idle editor burns no CPU
  1641. const auto i = args.indexOf ("--editorcpu");
  1642. runEditorCpu (args[i + 1].unquoted());
  1643. return;
  1644. }
  1645. if (args.contains ("--precomputeshot"))
  1646. {
  1647. // LYNX.exe --precomputeshot project.(flp|lynx) <prefix>: round 167h — <prefix>-precompute.png (channel 1's
  1648. // Precomputed effects panel) and <prefix>-project.png (Options › Project with "Fast declick for cut groups")
  1649. const auto i = args.indexOf ("--precomputeshot");
  1650. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1651. lynx::AudioEngine shotEngine (false);
  1652. const juce::File input (args[i + 1].unquoted());
  1653. const auto prefix = args[i + 2].unquoted();
  1654. juce::String error;
  1655. bool ok = false;
  1656. if (input.hasFileExtension ("flp"))
  1657. ok = shotEngine.importFlpFile (input, error);
  1658. else if (auto song = lynx::ProjectFile::load (input, error))
  1659. shotEngine.setSong (std::move (*song)), ok = true;
  1660. shotEngine.dispatchPendingMessages();
  1661. auto shoot = [&] (std::unique_ptr<juce::Component> c, const juce::String& name) {
  1662. if (c == nullptr)
  1663. return false;
  1664. if (c->getWidth() <= 0)
  1665. c->setSize (520, 600);
  1666. savePng (lynx::shot::snapshot (*c), prefix + name);
  1667. return true;
  1668. };
  1669. ok = ok && shoot (lynx::makeChannelPrecomputePanel (shotEngine, 0), "-precompute.png");
  1670. ok = ok && shoot (lynx::makeSettingsPanel (shotEngine, lynx::SettingsPage::project), "-project.png");
  1671. setApplicationReturnValue (ok ? 0 : 1);
  1672. quit();
  1673. return;
  1674. }
  1675. if (args.contains ("--pluginthumbs"))
  1676. {
  1677. // LYNX.exe --pluginthumbs <folder> [key,key...]: the Plugin picker's pictures of LYNX's own plugins (round 171c,
  1678. // ui/PluginThumbs.h), each editor drawn off-screen and kept as <folder>/<name>.png; the picker starts this in
  1679. // the background when pictures are missing. One line per plugin on stdout.
  1680. const auto i = args.indexOf ("--pluginthumbs");
  1681. lynx::crashguard::quietCrashReports();
  1682. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1683. juce::StringArray only;
  1684. if (i + 2 < args.size() && ! args[i + 2].startsWith ("--"))
  1685. only.addTokens (args[i + 2].unquoted(), ",", "");
  1686. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  1687. // round 190bi: with --shot-scale / LYNX_SHOT_SCALE each plugin's whole editor at that scale, not the picker's
  1688. // small thumbnail (never for the picker's own cache folder, whatever the environment says)
  1689. const juce::File folder (args[i + 1].unquoted());
  1690. const auto full = lynx::shot::given() && folder != lynx::pluginthumbs::nativeFolder() ? lynx::shot::scale() : 0.0f;
  1691. const auto drawn = lynx::pluginthumbs::renderNative (folder, only, [] (const juce::String& line) {
  1692. std::printf ("%s\n", line.toRawUTF8());
  1693. std::fflush (stdout);
  1694. }, full);
  1695. std::printf ("drawn %d in %.0f ms\n", drawn, juce::Time::getMillisecondCounterHiRes() - t0);
  1696. setApplicationReturnValue (0);
  1697. quit();
  1698. return;
  1699. }
  1700. if (args.contains ("--jsonroundtrip"))
  1701. {
  1702. // LYNX.exe --jsonroundtrip <folder>: round 183c's finding — a project saved, loaded and saved again: both texts
  1703. // (a.json, b.json) and the first lines that differ (diff.txt) for the default song, with and without a Patcher
  1704. const auto i = args.indexOf ("--jsonroundtrip");
  1705. const juce::File out (args[i + 1].unquoted());
  1706. out.createDirectory();
  1707. juce::String report;
  1708. auto check = [&] (const lynx::Song& song, const juce::String& name) {
  1709. const auto a = lynx::ProjectFile::toJson (song);
  1710. juce::String error;
  1711. const auto back = lynx::ProjectFile::fromJson (a, error);
  1712. const auto b = back ? lynx::ProjectFile::toJson (*back) : juce::String ("(not loaded: " + error + ")");
  1713. out.getChildFile (name + "-a.json").replaceWithText (a);
  1714. out.getChildFile (name + "-b.json").replaceWithText (b);
  1715. juce::StringArray la, lb;
  1716. la.addLines (a);
  1717. lb.addLines (b);
  1718. report << name << ": " << (a == b ? "stable" : "DIFFERS") << " (" << la.size() << " / " << lb.size() << " lines)\n";
  1719. int shown = 0;
  1720. for (int k = 0; k < juce::jmax (la.size(), lb.size()) && shown < 12; ++k)
  1721. if (la[k] != lb[k])
  1722. {
  1723. report << " line " << (k + 1) << "\n a: " << la[k].trim().substring (0, 200) << "\n b: " << lb[k].trim().substring (0, 200) << "\n";
  1724. ++shown;
  1725. }
  1726. };
  1727. auto song = lynx::Song::makeDefault();
  1728. check (song, "default");
  1729. song.mixer.resize (3);
  1730. song.mixer[1].effects = { lynx::makeEffectSlot (lynx::EffectKind::patcher) };
  1731. check (song, "patcher");
  1732. song.mixer[1].effects = { lynx::rack::makeRackSlot (lynx::RackDoc::Kind::audioEffect) };
  1733. check (song, "rack");
  1734. out.getChildFile ("diff.txt").replaceWithText (report);
  1735. setApplicationReturnValue (0);
  1736. quit();
  1737. return;
  1738. }
  1739. if (args.contains ("--rackshot"))
  1740. {
  1741. // LYNX.exe --rackshot <folder>: round 183c's Rack view drawn off-screen (no window), for the LYNX | Live pairs:
  1742. // rack-deviceview.png (an Audio Effect Rack laid out as in Live's reference shot), rack-mapmode.png (Map mode
  1743. // with the mapping list), rack-instrument.png (an Instrument Rack with its key zones)
  1744. const auto i = args.indexOf ("--rackshot");
  1745. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1746. const auto set = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  1747. setApplicationReturnValue (runRackShots (juce::File (args[i + 1].unquoted()), set) ? 0 : 1);
  1748. quit();
  1749. return;
  1750. }
  1751. if (args.contains ("--artshot"))
  1752. {
  1753. // LYNX.exe --artshot <folder> [before|after] [name,name...]: every editor with art of its own (round 170j/170k: the
  1754. // Themed style; or only the named ones, e.g. "sakura,facet-eq") drawn off-screen at 100 % and 200 % as
  1755. // <folder>/<plugin>-<before|after>-<scale>.png. "before" draws each in the style it had before the Themed style
  1756. const auto i = args.indexOf ("--artshot");
  1757. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1758. const auto mode = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String ("after");
  1759. if (i + 3 < args.size() && ! args[i + 3].startsWith ("--")) // [name,name...]: only these arts
  1760. artOnly().addTokens (args[i + 3].unquoted(), ",", "");
  1761. setApplicationReturnValue (runArtShots (juce::File (args[i + 1].unquoted()), mode == "before") ? 0 : 1);
  1762. quit();
  1763. return;
  1764. }
  1765. if (args.contains ("--artgui"))
  1766. {
  1767. // LYNX.exe --artgui <folder> [before|after|still] [name,name...]: the same editors in REAL windows on the desktop, one at a
  1768. // time (always on top, no focus taken), each held while an outside script screenshots it (it writes
  1769. // <folder>/<plugin>.ready with the window's bounds and waits up to 10 s for <folder>/<plugin>.done), then the
  1770. // process CPU it costs over 6 s is written to <folder>/cpu-<mode>.txt. "still": Themed with the motion off
  1771. const auto i = args.indexOf ("--artgui");
  1772. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1773. const auto mode = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String ("after");
  1774. if (i + 3 < args.size() && ! args[i + 3].startsWith ("--")) // [name,name...]: only these arts
  1775. artOnly().addTokens (args[i + 3].unquoted(), ",", "");
  1776. runArtGui (juce::File (args[i + 1].unquoted()), mode);
  1777. return;
  1778. }
  1779. if (args.contains ("--instrumentshot"))
  1780. {
  1781. // LYNX.exe --instrumentshot <folder> <engine,engine...|banks> [lynx|fl]: round 168n — the channel window of
  1782. // each engine (its Plugin tab) at 100 %, 150 % and 200 %, as <folder>/<engine>-<source>-<scale>.png. Source
  1783. // "lynx" starts from the engine's LYNX bank (what a PC without FL gets), "fl" from FL's Default preset.
  1784. const auto i = args.indexOf ("--instrumentshot");
  1785. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1786. const auto source = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String ("lynx");
  1787. setApplicationReturnValue (runInstrumentShots (juce::File (args[i + 1].unquoted()), args[i + 2].unquoted(), source) ? 0 : 1);
  1788. quit();
  1789. return;
  1790. }
  1791. if (args.contains ("--flextrashot"))
  1792. {
  1793. // LYNX.exe --flextrashot <folder>: pictures of the editors of round 165g (Big Clock, Tuner, HTML NoteBook, Mute 2, Scratcher, Transmitter) + round 167n Transporter
  1794. const auto i = args.indexOf ("--flextrashot");
  1795. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1796. lynx::AudioEngine shotEngine (false);
  1797. const auto ok = lynx::runFlExtraShots (shotEngine, juce::File (args[i + 1].unquoted()));
  1798. setApplicationReturnValue (ok ? 0 : 1);
  1799. quit();
  1800. return;
  1801. }
  1802. if (args.contains ("--visualtest"))
  1803. {
  1804. // LYNX.exe --visualtest <folder> [project.flp]: the visual plugins (round 164c) — the audio path's CPU, every
  1805. // Wave Candy mode and Visualizer scene drawn from a test signal (PNG + the editor's CPU each), and the video
  1806. // export of a project (default: FL's first ZGameEditor demo) with ffmpeg and as images. Writes report.txt.
  1807. const auto i = args.indexOf ("--visualtest");
  1808. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1809. const auto project = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? juce::File (args[i + 2].unquoted()) : juce::File();
  1810. lynx::runVisualTest (juce::File (args[i + 1].unquoted()), project, [this] (bool ok) {
  1811. setApplicationReturnValue (ok ? 0 : 1);
  1812. quit();
  1813. });
  1814. return;
  1815. }
  1816. if (args.contains ("--menu-entry"))
  1817. {
  1818. // LYNX.AppImage --menu-entry on|off: puts the AppImage in the applications menu (and .lynx files on it) or
  1819. // takes it out again, without opening a window; the same as the switch in Options › General (round 161)
  1820. const auto i = args.indexOf ("--menu-entry");
  1821. const auto on = args[i + 1].unquoted() != "off";
  1822. const auto ok = lynx::runningAsAppImage() && lynx::setAppImageMenuEntry (on);
  1823. std::fprintf (ok ? stdout : stderr, "%s\n", ok ? (on ? "LYNX SHARE added to the applications menu" : "LYNX SHARE removed from the applications menu")
  1824. : "only the LYNX SHARE AppImage on Linux can do this");
  1825. setApplicationReturnValue (ok ? 0 : 1);
  1826. quit();
  1827. return;
  1828. }
  1829. if (args.contains ("--send-test-report"))
  1830. {
  1831. // LYNX.exe --send-test-report out.txt [--dry]: builds a crash report marked "test" from the newest crash /
  1832. // hang file and this computer's facts, writes its JSON to out.txt.json and (without --dry) sends it to
  1833. // lynx-share.com (LYNX_CRASH_ENDPOINT overrides); out.txt gets "id=…" and "result=OK" or the error (round 159)
  1834. const auto i = args.indexOf ("--send-test-report");
  1835. const juce::File out (args[i + 1].unquoted());
  1836. lynx::crashreporter::Session session;
  1837. session.version = getApplicationVersion();
  1838. for (const auto* pattern : { "crash *.txt", "hang *.txt" })
  1839. {
  1840. auto files = lynx::platform::settingsFile ("autosave").findChildFiles (juce::File::findFiles, false, pattern);
  1841. lynx::filesort::byTime (files, lynx::filesort::By::modificationTime, true);
  1842. if (! files.isEmpty())
  1843. (juce::String (pattern).startsWith ("crash") ? session.crashFile : session.hangFile) = files[0];
  1844. }
  1845. session.steps = { "00:00:01 test report (LYNX.exe --send-test-report)", "00:00:02 opening project " + out.getFileName() };
  1846. auto input = lynx::crashreporter::makeInput (session, session.crashFile.existsAsFile() ? "crash" : "manual", nullptr);
  1847. input.test = true;
  1848. const auto json = lynx::crashreporter::buildJson (input, false);
  1849. out.withFileExtension (out.getFileExtension() + ".json").replaceWithText (json);
  1850. const auto error = args.contains ("--dry") ? juce::String() : lynx::crashreporter::sendNow (json);
  1851. out.replaceWithText ("id=" + juce::String::fromUTF8 (input.id.c_str()) + "\nendpoint=" + lynx::crashreporter::endpoint() + "\nbytes="
  1852. + juce::String (json.getNumBytesAsUTF8()) + "\nresult=" + (error.isEmpty() ? juce::String ("OK") : error) + "\n");
  1853. setApplicationReturnValue (error.isEmpty() ? 0 : 1);
  1854. quit();
  1855. return;
  1856. }
  1857. if (args.contains ("--symbolize"))
  1858. {
  1859. // LYNX.exe --symbolize "crash … .txt" out.txt: names the LYNX.exe+offset frames of a user's crash / hang file
  1860. // (needs this build's LYNX.pdb next to LYNX.exe — the release's "LYNX-symbols" CI artifact; round 157a)
  1861. const auto i = args.indexOf ("--symbolize");
  1862. const auto text = juce::File (args[i + 1].unquoted()).loadFileAsString();
  1863. juce::File (args[i + 2].unquoted()).replaceWithText (juce::String::fromUTF8 (lynx::crashguard::symbolizeOwnFrames (text.toStdString()).c_str()));
  1864. quit();
  1865. return;
  1866. }
  1867. if (args.contains ("--opentest"))
  1868. {
  1869. // LYNX.exe --opentest report.txt [--visible]: every built-in effect and instrument window opened as the mixer /
  1870. // Channel rack open them, with default, extreme, random and old-project states; a watchdog fails the test on
  1871. // a hang (round 157a: opening the Parametric EQ froze LYNX). Windows stay off-screen without --visible.
  1872. const auto i = args.indexOf ("--opentest");
  1873. runOpenTest (args[i + 1].unquoted(), args.contains ("--visible"), [this] (bool ok) {
  1874. setApplicationReturnValue (ok ? 0 : 1);
  1875. quit();
  1876. });
  1877. return;
  1878. }
  1879. if (args.contains ("--fxfuzz"))
  1880. {
  1881. // LYNX.exe --fxfuzz report.txt [rounds] [--drags]: every built-in effect in its editor, parameters swept (and
  1882. // dragged with the mouse), audio rendered at several rates; a crash ends the process (round 111)
  1883. const auto i = args.indexOf ("--fxfuzz");
  1884. const auto rounds = args.size() > i + 2 ? juce::jmax (1, args[i + 2].getIntValue()) : 6;
  1885. // --drags: also mouse drags over the editors (their menus may flash on screen: not for the selftest)
  1886. const auto ok = runEffectFuzz (rounds, args[i + 1].unquoted(), args.contains ("--drags"));
  1887. setApplicationReturnValue (ok ? 0 : 1);
  1888. quit();
  1889. return;
  1890. }
  1891. if (args.contains ("--controllershot"))
  1892. {
  1893. // LYNX.exe --controllershot prefix: the built-in controllers' editors (round 133) as PNGs
  1894. const auto i = args.indexOf ("--controllershot");
  1895. runControllerShot (args[i + 1].unquoted());
  1896. quit();
  1897. return;
  1898. }
  1899. if (args.contains ("--edisonshot"))
  1900. {
  1901. // LYNX.exe --edisonshot prefix [audio.wav]: the audio editor's Edison tool windows (round 165l) and the
  1902. // editor before / after some of them, as PNGs (a synthetic drum loop without a file)
  1903. const auto i = args.indexOf ("--edisonshot");
  1904. runEdisonShot (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String());
  1905. quit();
  1906. return;
  1907. }
  1908. if (args.contains ("--edisonslottest"))
  1909. {
  1910. // LYNX.exe --edisonslottest folder [project.flp]: round 190cd — the audio editor as a mixer-slot plugin through
  1911. // the engine and the project file (report.txt: one "name=ok|FAIL" per check), its window as slot-*.png, and
  1912. // the Edison slots of an FL project (what was read of each)
  1913. const auto i = args.indexOf ("--edisonslottest");
  1914. const auto ok = runEdisonSlotTest (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String());
  1915. setApplicationReturnValue (ok ? 0 : 1);
  1916. quit();
  1917. return;
  1918. }
  1919. if (args.contains ("--danceshot"))
  1920. {
  1921. // LYNX.exe --danceshot prefix: LYNX Dance (round 165e) — every move as a contact sheet, the channel's editor,
  1922. // and a demo project with two dance channels (for --snapshot)
  1923. const auto i = args.indexOf ("--danceshot");
  1924. runDanceShot (args[i + 1].unquoted());
  1925. quit();
  1926. return;
  1927. }
  1928. if (args.contains ("--videoshot") && args.indexOf ("--videoshot") + 2 < args.size())
  1929. {
  1930. // LYNX.exe --videoshot prefix video: the Video Player's editor (round 165g) at a few song positions, with
  1931. // the user's ffmpeg, as PNGs + report.txt (frames decoded, the sound track)
  1932. const auto i = args.indexOf ("--videoshot");
  1933. runVideoShot (args[i + 1].unquoted(), args[i + 2].unquoted());
  1934. return;
  1935. }
  1936. if (args.contains ("--videotrackshot") && args.indexOf ("--videotrackshot") + 2 < args.size())
  1937. {
  1938. // LYNX.exe --videotrackshot prefix video [video2]: round 174d — the Playlist with video tracks (filmstrips,
  1939. // timecode row) and the video window at a few song positions, as PNGs + report.txt (the decoder, the
  1940. // frame shown for each wanted time: frame accuracy, frames dropped)
  1941. const auto i = args.indexOf ("--videotrackshot");
  1942. runVideoTrackShot (args[i + 1].unquoted(), args[i + 2].unquoted(), i + 3 < args.size() ? args[i + 3].unquoted() : juce::String());
  1943. return;
  1944. }
  1945. if (args.contains ("--vfxshot"))
  1946. {
  1947. // LYNX.exe --vfxshot prefix: the VFX note effects' editors (round 164b), on channels and in a Patcher, as PNGs
  1948. const auto i = args.indexOf ("--vfxshot");
  1949. runVfxShot (args[i + 1].unquoted());
  1950. quit();
  1951. return;
  1952. }
  1953. if (args.contains ("--patchershot"))
  1954. {
  1955. // LYNX.exe --patchershot prefix [project]: every Patcher's editor (round 141) as PNGs (a demo one without a project)
  1956. const auto i = args.indexOf ("--patchershot");
  1957. runPatcherShot (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String());
  1958. quit();
  1959. return;
  1960. }
  1961. if (args.contains ("--audioxshot"))
  1962. {
  1963. // LYNX.exe --audioxshot prefix (round 190aq): the pre-fader send, the "Low latency while recording" mark on a
  1964. // bypassed slot and the Browser's "Preview in time", drawn off-screen
  1965. runAudioXShot (args[args.indexOf ("--audioxshot") + 1].unquoted());
  1966. quit();
  1967. return;
  1968. }
  1969. if (args.contains ("--comp177shot"))
  1970. {
  1971. // LYNX.exe --comp177shot prefix project (round 177c): a project of loop takes in the maximised
  1972. // Playlist as it opened; every group after "Comp these takes", with a swipe on the first; the track and record menus
  1973. const auto i = args.indexOf ("--comp177shot");
  1974. runComp177Shot (args[i + 1].unquoted(), args[i + 2].unquoted());
  1975. quit();
  1976. return;
  1977. }
  1978. if (args.contains ("--evpaneshot"))
  1979. {
  1980. // LYNX --evpaneshot prefix [project] (round 190fz): the Piano roll's event editor divider driven with the mouse
  1981. // handlers (drag, right-click = alternate size and back, middle-click = default, a drag into the snap zone),
  1982. // a picture of each state and prefix-report.txt with the heights and the remembered settings file
  1983. const auto i = args.indexOf ("--evpaneshot");
  1984. setApplicationReturnValue (runEvPaneShot (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String()) ? 0 : 1);
  1985. quit();
  1986. return;
  1987. }
  1988. if (args.contains ("--feat166shot"))
  1989. {
  1990. // LYNX.exe --feat166shot prefix [project]: round 166d (issue #14) — the Piano Roll with a scale, folded to
  1991. // it, with one ghost channel, the ghost channels menu, and the Mixer filled to 500 inserts (its start and
  1992. // its end, and the time a full repaint takes)
  1993. const auto i = args.indexOf ("--feat166shot");
  1994. runFeat166Shot (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String());
  1995. quit();
  1996. return;
  1997. }
  1998. if (args.contains ("--pickerdropshot"))
  1999. {
  2000. // LYNX --pickerdropshot prefix: round 190hm (issue #177) — Picker panel entries dropped on the Playlist as FL
  2001. // places them (plain drop: one track per entry at the snapped time; Shift: one after another), off-screen,
  2002. // with <prefix>-checks.txt (OK / FAIL per placement)
  2003. setApplicationReturnValue (runPickerDropShot (args[args.indexOf ("--pickerdropshot") + 1].unquoted()) ? 0 : 1);
  2004. quit();
  2005. return;
  2006. }
  2007. if (args.contains ("--trackmodeshot"))
  2008. {
  2009. // LYNX --trackmodeshot prefix: rollup 190cv (UI gate of PR #151) — Playlist track header › Track mode › Audio
  2010. // track, off-screen, in three states of FL's live check 190cu (q1-01 fresh, q1-02 one insert linked
  2011. // elsewhere and one renamed, q1-07 the full state), plus a report that compares each list with FL's
  2012. setApplicationReturnValue (runTrackModeShot (args[args.indexOf ("--trackmodeshot") + 1].unquoted()) ? 0 : 1);
  2013. quit();
  2014. return;
  2015. }
  2016. if (args.contains ("--curveshot"))
  2017. {
  2018. // LYNX.exe --curveshot prefix: round 190bw — an automation clip with one segment per FL curve mode in the
  2019. // point editor and in the Playlist, and FL's point menu, off-screen
  2020. runCurveShot (args[args.indexOf ("--curveshot") + 1].unquoted());
  2021. quit();
  2022. return;
  2023. }
  2024. if (args.contains ("--remoteshot"))
  2025. {
  2026. // LYNX.exe --remoteshot prefix: Online Sessions P5-A1 (round 190ai) — the host's "Share plugins with guests"
  2027. // list and a guest's parameter editor of a plugin the host plays, off-screen with sample data
  2028. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  2029. lynx::liveui::saveRemoteShots (args[args.indexOf ("--remoteshot") + 1].unquoted());
  2030. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  2031. quit();
  2032. return;
  2033. }
  2034. if (args.contains ("--settingsshot") && ! args.contains ("--rtstress")) // (--rtstress has its own --settingsshot file.png option, round 161)
  2035. {
  2036. // LYNX.exe --settingsshot prefix: round 190bx — every Settings page off-screen at the window's size, in a
  2037. // small window (390 x 390) and, for the long pages, whole (see runSettingsShot)
  2038. runSettingsShot (args[args.indexOf ("--settingsshot") + 1].unquoted());
  2039. quit();
  2040. return;
  2041. }
  2042. if (args.contains ("--perfshot"))
  2043. {
  2044. // LYNX.exe --perfshot prefix project: the Playlist in Performance mode with a few clips launched and waiting,
  2045. // then the project patcherized (every insert's effects, the first channels) saved as prefix-patcherized.lynx
  2046. // for --patchershot (round 165m)
  2047. const auto i = args.indexOf ("--perfshot");
  2048. runPerfShot (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String());
  2049. quit();
  2050. return;
  2051. }
  2052. if (args.contains ("--freezetest"))
  2053. {
  2054. // LYNX.exe --freezetest prefix [project]: round 190ay's Freeze end to end, off-screen (see runFreezeTest)
  2055. const auto i = args.indexOf ("--freezetest");
  2056. const auto project = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  2057. // a word after the project: "keep" = freeze, save prefix-frozen.lynx and stop (the audio stays);
  2058. // "measure" = only load and render the project, for the memory and time of a process of its own
  2059. const auto mode = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  2060. setApplicationReturnValue (runFreezeTest (args[i + 1].unquoted(), project, mode) ? 0 : 1);
  2061. quit();
  2062. return;
  2063. }
  2064. if (args.contains ("--trackfreezetest"))
  2065. {
  2066. // LYNX --trackfreezetest prefix: round 190ff's Freeze Track, Flatten / Bounce Track in Place, Bounce to New
  2067. // Track and Consolidate end to end in the Clip-launch workflow, off-screen (see runTrackFreezeTest)
  2068. const auto i = args.indexOf ("--trackfreezetest");
  2069. setApplicationReturnValue (runTrackFreezeTest (args[i + 1].unquoted()) ? 0 : 1);
  2070. quit();
  2071. return;
  2072. }
  2073. if (args.contains ("--details190ihshot"))
  2074. {
  2075. // LYNX --details190ihshot prefix: round 190ih's live states off screen (no window, no audio device) — Gross
  2076. // Beat's locator and slots from its real engine, the rack's activity light, Play / Pause, the Record blink,
  2077. // the "Note on" hint, the save reminder, the Simple dock's input level, the Envelope Controller's key line
  2078. const auto i = args.indexOf ("--details190ihshot");
  2079. runDetails190ihShot (args[i + 1].unquoted());
  2080. quit();
  2081. return;
  2082. }
  2083. if (args.contains ("--paintbench"))
  2084. {
  2085. // LYNX --paintbench project.(flp|lynx|als) report.txt (round 190ge): each main view drawn off screen, whole, many
  2086. // times (the message thread's CPU per frame), with the playhead mid-song; no window, no audio device
  2087. const auto i = args.indexOf ("--paintbench");
  2088. runPaintBench (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()));
  2089. quit();
  2090. return;
  2091. }
  2092. if (args.contains ("--design190igshot"))
  2093. {
  2094. // LYNX --design190igshot prefix project.flp: round 190ig off-screen (design190ia slice 3) — the Pattern layout's
  2095. // Playlist with FL's clip and header look: the song at FL's default zoom (26 px tracks, 15.6 px a bar, bar 21),
  2096. // at FL's "zoom 17" (50 px tracks, 39.75 px a bar), and playing (the activity column), as FL's reference shots
  2097. const auto i = args.indexOf ("--design190igshot");
  2098. runDesign190igShot (args[i + 1].unquoted(), args[i + 2].unquoted());
  2099. quit();
  2100. return;
  2101. }
  2102. if (args.contains ("--gridshot"))
  2103. {
  2104. // LYNX.exe --gridshot prefix [project]: the Clip-launch workflow's layout off-screen, with a grid of sample
  2105. // clips, some playing and waiting, at the size of LYNX_SNAPSHOT_SIZE (round 181a); with a project (.lynx,
  2106. // .flp, .als), that project's grid instead (round 181c: a Live set's Session view as LYNX imports it)
  2107. const auto i = args.indexOf ("--gridshot");
  2108. const auto project = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  2109. runGridShot (args[i + 1].unquoted(), project);
  2110. quit();
  2111. return;
  2112. }
  2113. if (args.contains ("--tour190dvshot"))
  2114. {
  2115. // LYNX.exe --tour190dvshot prefix: round 190dv off-screen — the Simple workflow's Welcome screen, every step of
  2116. // the first-song tour done with its "Do it for me" (a loop dropped for the loop step), the end card, Back /
  2117. // Next / close, the Help menu, the chooser's tour button, Start from with the three demo songs, a demo
  2118. // opened in Simple — and a text report of the checks (incl. resources/demos/*.lynx = the generated songs)
  2119. const auto i = args.indexOf ("--tour190dvshot");
  2120. runTour190dvShot (args[i + 1].unquoted());
  2121. quit();
  2122. return;
  2123. }
  2124. if (args.contains ("--donateshot"))
  2125. {
  2126. // LYNX --donateshot prefix: round 190fq off-screen (no window) — Help › Support LYNX SHARE... in the three
  2127. // layouts, the Support window, the About window's Support button, the start-up support note in the main
  2128. // window, and the note's rules end to end on its saved state (run it with LYNX_PROFILE_DIR: it writes
  2129. // support-note.txt there, and puts the old one back at the end); report prefix-report.txt, exit 0 = OK
  2130. const auto i = args.indexOf ("--donateshot");
  2131. setApplicationReturnValue (runDonateShot (args[i + 1].unquoted()) ? 0 : 1);
  2132. quit();
  2133. return;
  2134. }
  2135. if (args.contains ("--simpleclosetest"))
  2136. {
  2137. // LYNX --simpleclosetest <report.txt>: round 190fc off-screen (no window) — the main window in the Simple
  2138. // layout with Welcome, the tour, Start from, a demo, the dock's tabs, Finish and Lyrics open, then closed as at
  2139. // shutdown (the 0.1.27 RC crashed on every such close); exit code 0 = OK
  2140. const auto i = args.indexOf ("--simpleclosetest");
  2141. setApplicationReturnValue (runSimpleCloseTest (args[i + 1].unquoted()) ? 0 : 1);
  2142. quit();
  2143. return;
  2144. }
  2145. if (args.contains ("--patterns190ea"))
  2146. {
  2147. // LYNX --patterns190ea <report.txt>: round 190ea off-screen (no window) — a song with no pattern at all
  2148. // reaching the engine in every layout (the Simple dock's Editor tab, the Piano roll panel of the Pattern
  2149. // layout, the Clip-launch layout), the last pattern deleted, all patterns cleared by an edit, undo / redo,
  2150. // a live session's remote song and an out-of-range current pattern; each must leave one pattern and not crash
  2151. const auto i = args.indexOf ("--patterns190ea");
  2152. setApplicationReturnValue (runPatterns190ea (args[i + 1].unquoted()) ? 0 : 1);
  2153. quit();
  2154. return;
  2155. }
  2156. if (args.contains ("--reabl190foshot"))
  2157. {
  2158. // LYNX --reabl190foshot prefix: round 190fo off-screen — the Simple Sampler track's 16 pads in the dock, its
  2159. // menus and kits, the typing keys, the .lynx round trip, a folder of stems and MIDI files — and a report
  2160. const auto i = args.indexOf ("--reabl190foshot");
  2161. runReabl190foShot (args[i + 1].unquoted());
  2162. quit();
  2163. return;
  2164. }
  2165. if (args.contains ("--simple190dsshot"))
  2166. {
  2167. // LYNX.exe --simple190dsshot prefix: round 190ds off-screen, at 1x and 2x — loops dropped in the Simple
  2168. // workflow following the project key (the dock's switch, the clip menu), the docked Piano roll in the Editor
  2169. // tab, the keyboard's modes Keys / Scale keys / Chord pad with the scale selector — and a text report
  2170. const auto i = args.indexOf ("--simple190dsshot");
  2171. runSimple190dsShot (args[i + 1].unquoted());
  2172. quit();
  2173. return;
  2174. }
  2175. if (args.contains ("--simple190dgshot"))
  2176. {
  2177. // LYNX.exe --simple190dgshot prefix: round 190dg's additions to the Simple dock off-screen, at 1x and 2x —
  2178. // the Effects tab with all eight one-knob cards and each card alone, a chain preset with Blend, the
  2179. // favourites in the Preset menu, the sound picker (a search, My plugins with a made-up plugin list) — and a
  2180. // text report of the checks
  2181. const auto i = args.indexOf ("--simple190dgshot");
  2182. runSimple190dgShot (args[i + 1].unquoted());
  2183. quit();
  2184. return;
  2185. }
  2186. if (args.contains ("--simplefxshot"))
  2187. {
  2188. // LYNX.exe --simplefxshot prefix: round 190bu's track dock of the Simple workflow off-screen, at 1x and 2x —
  2189. // the Instrument tab (LYNX sounds, My SoundFonts), the Effects tab (empty, a preset, its menus), and a text
  2190. // report: the dock's edits, a user preset saved and loaded, the same slots in the Pattern workflow's Mixer
  2191. const auto i = args.indexOf ("--simplefxshot");
  2192. runSimpleFxShot (args[i + 1].unquoted());
  2193. quit();
  2194. return;
  2195. }
  2196. if (args.contains ("--simpleshot"))
  2197. {
  2198. // LYNX.exe --simpleshot prefix: round 184a's Simple workflow off-screen — View › Layout style with each style
  2199. // chosen, Settings › General (Pattern, then Simple selected) with its style list, the window in Pattern, then
  2200. // Simple, then Pattern again, and how many Simple workflow objects existed before and after (0 before)
  2201. const auto i = args.indexOf ("--simpleshot");
  2202. runSimpleShot (args[i + 1].unquoted());
  2203. quit();
  2204. return;
  2205. }
  2206. // --versionsshot <prefix> (round 190ap): the Versions panel, File's new items, a project opened without its
  2207. // third-party plugins (window, list, File menu) and the Export window's additions, offscreen
  2208. if (args.contains ("--versionsshot"))
  2209. {
  2210. runVersionsShot (args[args.indexOf ("--versionsshot") + 1].unquoted());
  2211. quit();
  2212. return;
  2213. }
  2214. // --linkshot <prefix> (round 190bt): FL's Remote control settings / Global link settings windows, the control
  2215. // menu with "Link to controller...", the formula presets and controller menus and the Multilink items,
  2216. // offscreen; prefix-checks.txt holds the round's checks of the engine, the project file and the settings
  2217. if (args.contains ("--linkshot"))
  2218. {
  2219. setApplicationReturnValue (runLinkShot (args[args.indexOf ("--linkshot") + 1].unquoted()) ? 0 : 1);
  2220. quit();
  2221. return;
  2222. }
  2223. // --flctlshot <prefix> (round 190df): FL's multilink menu (on / off), the plugin menu's A/B and "Link all
  2224. // parameters...", the sampler's File row with its Sample history, and the Envelope / instrument page of a sampler
  2225. // running FL's voice with its envelope presets, offscreen; prefix-checks.txt holds the checks
  2226. if (args.contains ("--flctlshot"))
  2227. {
  2228. setApplicationReturnValue (runFlCtlShot (args[args.indexOf ("--flctlshot") + 1].unquoted()) ? 0 : 1);
  2229. quit();
  2230. return;
  2231. }
  2232. // --samplerpageshot <prefix> (round 190dh): FL's Sampler page offscreen (shots and checks in prefix-checks.txt)
  2233. if (args.contains ("--samplerpageshot"))
  2234. {
  2235. setApplicationReturnValue (runSamplerPageShot (args[args.indexOf ("--samplerpageshot") + 1].unquoted()) ? 0 : 1);
  2236. quit();
  2237. return;
  2238. }
  2239. // --flplshot <prefix> (round 190dx): the audio clip menu (Preview, Automate › Panning / Volume), the Playlist's "+"
  2240. // and its menu, Track mode › Instrument track, the Channel rack's "Assign to new instrument track", Tools › One-click
  2241. // audio recording and Mixer › Disk recording › Latency compensation, offscreen; prefix-checks.txt holds the checks
  2242. // --hdrshot190ft <prefix> (round 190ft, issues #163 / #164): FL's track-header selection and resize rules driven
  2243. // with synthetic mouse events on the Playlist headers and the mixer strips, offscreen; prefix-checks.txt
  2244. if (args.contains ("--hdrshot190ft"))
  2245. {
  2246. setApplicationReturnValue (runHdrShot190ft (args[args.indexOf ("--hdrshot190ft") + 1].unquoted()) ? 0 : 1);
  2247. quit();
  2248. return;
  2249. }
  2250. // --userfixshot190ib <prefix> (round 190ib): issue #182's type-to-jump in a real popup menu (the Playlist's Edit menu
  2251. // of the issue's screenshot, typed into), #183's Piano roll item, #181's Ctrl+, through the main window's keys;
  2252. // prefix-checks.txt
  2253. if (args.contains ("--userfixshot190ib"))
  2254. {
  2255. setApplicationReturnValue (runUserFixShot190ib (args[args.indexOf ("--userfixshot190ib") + 1].unquoted()) ? 0 : 1);
  2256. quit();
  2257. return;
  2258. }
  2259. // --issuesshot190ht <prefix> (round 190ht): issue #127's other tools on Pattern Blocks (Mute, Select + group move,
  2260. // Slice, Zoom) and issue #154's insert effects list on linked headers, driven with synthetic mouse events,
  2261. // offscreen; prefix-checks.txt and pictures
  2262. if (args.contains ("--issuesshot190ht"))
  2263. {
  2264. setApplicationReturnValue (runIssuesShot190ht (args[args.indexOf ("--issuesshot190ht") + 1].unquoted()) ? 0 : 1);
  2265. quit();
  2266. return;
  2267. }
  2268. // --trackautoshot190gz <prefix> (round 190gz, issue #170): LYNX's "Link Playlist tracks to mixer tracks" — the
  2269. // switch, the linked headers' M / S / volume / pan driven with synthetic mouse events, row sizes, undo and the
  2270. // .lynx round trip, offscreen; prefix-checks.txt
  2271. if (args.contains ("--trackautoshot190gz"))
  2272. {
  2273. setApplicationReturnValue (runTrackAutoShot190gz (args[args.indexOf ("--trackautoshot190gz") + 1].unquoted()) ? 0 : 1);
  2274. quit();
  2275. return;
  2276. }
  2277. if (args.contains ("--flplshot"))
  2278. {
  2279. setApplicationReturnValue (runFlPlShot (args[args.indexOf ("--flplshot") + 1].unquoted()) ? 0 : 1);
  2280. quit();
  2281. return;
  2282. }
  2283. // --genpresetshot <prefix> (round 190fs): the channel window's preset box with the user's own presets (Save
  2284. // preset..., Your presets, Delete preset, Show the presets folder) for Fruity DX10, 3x Osc and LYNX's synth, the
  2285. // name box, a load (one undo step) and the Browser's new channel, offscreen; prefix-checks.txt holds the checks
  2286. if (args.contains ("--genpresetshot"))
  2287. {
  2288. setApplicationReturnValue (runGenPresetShot (args[args.indexOf ("--genpresetshot") + 1].unquoted()) ? 0 : 1);
  2289. quit();
  2290. return;
  2291. }
  2292. // --flfixshot <prefix> (round 190ey): what the live FL session 190ew found different (the Sampler page, the
  2293. // Multilink menu, the Playlist, issue #152's question), offscreen; prefix-checks.txt holds the checks
  2294. if (args.contains ("--flfixshot"))
  2295. {
  2296. setApplicationReturnValue (runFlFixShot (args[args.indexOf ("--flfixshot") + 1].unquoted()) ? 0 : 1);
  2297. quit();
  2298. return;
  2299. }
  2300. // --flclipshot <prefix> (round 190dz): FL's audio clip menu layout (two columns, FL's sections, LYNX's own items at
  2301. // the end) and the channel's Misc › Levels adjustment, offscreen; prefix-checks.txt holds the checks
  2302. if (args.contains ("--flclipshot"))
  2303. {
  2304. setApplicationReturnValue (runFlClipShot (args[args.indexOf ("--flclipshot") + 1].unquoted()) ? 0 : 1);
  2305. quit();
  2306. return;
  2307. }
  2308. if (args.contains ("--warpshot"))
  2309. {
  2310. // LYNX.exe --warpshot prefix: round 190cg's pictures (warp commands in the audio editor, the Clip page's
  2311. // Audio panel, the arrangement with the loop switched off, a folded track, signature changes), off-screen
  2312. const auto i = args.indexOf ("--warpshot");
  2313. runWarpShot (args[i + 1].unquoted());
  2314. quit();
  2315. return;
  2316. }
  2317. // --bandlabshot <prefix> (round 190ch): Lyrics / Notes, Reference match, Start from and Clean voice, offscreen
  2318. if (args.contains ("--bandlabshot"))
  2319. {
  2320. runBandlabShot (args[args.indexOf ("--bandlabshot") + 1].unquoted());
  2321. quit();
  2322. return;
  2323. }
  2324. if (args.contains ("--mpeshot190hy"))
  2325. {
  2326. // LYNX --mpeshot190hy prefix: round 190hy (issue #108, MPE stage 2) off-screen: the Piano roll's MPE lanes (pitch
  2327. // bend, slide, pressure) over notes with curves in Pattern workflow, then the Clip-launch layout's Clip page with
  2328. // its Notes and MPE tabs. Writes prefix-checks.txt.
  2329. runMpeShot190hy (args[args.indexOf ("--mpeshot190hy") + 1].unquoted());
  2330. quit();
  2331. return;
  2332. }
  2333. if (args.contains ("--detailshot"))
  2334. {
  2335. // LYNX.exe --detailshot prefix: the Clip-launch workflow's detail view off-screen (round 183a): a track's chain
  2336. // (instrument, effects, one off, one folded), its clip page, and Pattern workflow before / after, at
  2337. // LYNX_SNAPSHOT_SIZE. Writes prefix-counts.txt with what the chain shows.
  2338. const auto i = args.indexOf ("--detailshot");
  2339. runDetailShot (args[i + 1].unquoted());
  2340. quit();
  2341. return;
  2342. }
  2343. if (args.contains ("--liverackshot190hr"))
  2344. {
  2345. // LYNX.exe --liverackshot190hr prefix: round 190hr off-screen, in the Ableton-style layout: the Device View's
  2346. // instrument menu with Group / Ungroup, an instrument grouped into an Instrument Rack and back, a rack's Save
  2347. // Preset button and drop area (a device dropped in, an instrument refused), Live's own .adg presets opened
  2348. // with their chains, and a saved .adg read back. Writes prefix-checks.txt.
  2349. runLiveRackShot190hr (args[args.indexOf ("--liverackshot190hr") + 1].unquoted());
  2350. quit();
  2351. return;
  2352. }
  2353. if (args.contains ("--liveshot190ce"))
  2354. {
  2355. // LYNX.exe --liveshot190ce prefix: round 190ce off-screen, in the Ableton-style layout: the Device View's cards
  2356. // with their hot-swap and save buttons, a device's menu, hot-swap on (the Browser's bar, the lit button), a
  2357. // swap and its undo, a duplicate, and the Browser's collections (STARRED tab, the Collections menu, a search
  2358. // by a collection's name). Writes prefix-checks.txt.
  2359. runLiveShot190ce (args[args.indexOf ("--liveshot190ce") + 1].unquoted());
  2360. quit();
  2361. return;
  2362. }
  2363. if (args.contains ("--missingsearchshot190eo"))
  2364. {
  2365. // LYNX --missingsearchshot190eo prefix folder...: round 190eo (integration of issue #159's fix) off-screen: the
  2366. // Missing files window's Samples page while a real search of the folders runs (matches streamed in, Stop
  2367. // shown, Apply usable). Writes prefix-searching.png and prefix-checks.txt; the search is let go at the end.
  2368. const auto i = args.indexOf ("--missingsearchshot190eo");
  2369. const auto prefix = args[i + 1].unquoted();
  2370. juce::StringArray folders;
  2371. for (int k = i + 2; k < args.size(); ++k)
  2372. folders.add (args[k].unquoted());
  2373. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  2374. std::shared_ptr<juce::Component> panel = lynx::makeMissingFilesPanelSearching (lynx::missingFilesSnapshotInfo(), folders);
  2375. juce::Timer::callAfterDelay (700, [this, panel, prefix] {
  2376. juce::String status;
  2377. bool stopShown = false, applyEnabled = false;
  2378. const auto searching = lynx::missingFilesSearchState (*panel, status, stopShown, applyEnabled);
  2379. auto image = lynx::shot::paint (*panel, lynx::theme::panel);
  2380. const auto file = juce::File (prefix + "-searching.png");
  2381. file.deleteFile();
  2382. if (auto out = file.createOutputStream())
  2383. juce::PNGImageFormat().writeImageToStream (image, *out);
  2384. juce::String checks;
  2385. auto check = [&checks] (const char* name, bool ok, const juce::String& detail) {
  2386. checks << name << "=" << (ok ? "OK" : "FAIL") << " " << detail << "\n";
  2387. };
  2388. check ("still_searching_at_the_shot", searching, {});
  2389. check ("status_shows_the_walk", status.contains (lynx::tr ("Searching {0}... {1} files looked at").upToFirstOccurrenceOf ("{0}", false, false)), status);
  2390. check ("stop_shown", stopShown, {});
  2391. check ("apply_usable_during_the_search", applyEnabled, {});
  2392. lynx::stopMissingFilesSearch (*panel);
  2393. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  2394. quit();
  2395. });
  2396. return;
  2397. }
  2398. // --grooveshot190fm <prefix> (round 190fm): a Playlist pattern clip's menu with its Groove items (the chooser, Commit,
  2399. // Extract) and the "Classic swing" folder, and a Groove Pool holding classic swing grooves, offscreen;
  2400. // prefix-checks.txt holds the checks (also the .lynx round trip of a Playlist clip's groove)
  2401. if (args.contains ("--grooveshot190fm"))
  2402. {
  2403. setApplicationReturnValue (runGrooveShot190fm (args[args.indexOf ("--grooveshot190fm") + 1].unquoted()) ? 0 : 1);
  2404. quit();
  2405. return;
  2406. }
  2407. if (args.contains ("--mtshot190fm"))
  2408. {
  2409. // LYNX --mtshot190fm prefix: round 190fm off-screen: the MIDI Tools panel's Generate tab with each generator
  2410. // (prefix-generate-rhythm.png … -euclidean.png), the five side by side as Live's picture shows them
  2411. // (prefix-generate-panels.png; Live's: ableton190o/shots/live-04-generate-panels.png), then each generator
  2412. // written into a one-bar pattern and undone again: prefix-checks.txt.
  2413. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  2414. runMtShot190fm (args[args.indexOf ("--mtshot190fm") + 1].unquoted());
  2415. quit();
  2416. return;
  2417. }
  2418. if (args.contains ("--drumshot190ec"))
  2419. {
  2420. // LYNX.exe --drumshot190ec prefix: round 190ec off-screen: a demo Drum Rack's pad view (default and scrolled), its
  2421. // chain list with I-O, sends and return chains, a new empty Drum Rack and the Piano roll's pad names. Writes
  2422. // prefix-checks.txt (hit tests: C1 bottom-left, overview scroll, a pad dragged onto another swaps them).
  2423. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  2424. lynx::drumshot::run (args[args.indexOf ("--drumshot190ec") + 1].unquoted());
  2425. quit();
  2426. return;
  2427. }
  2428. if (args.contains ("--linkshot190gl"))
  2429. {
  2430. // LYNX --linkshot190gl prefix (round 190gl): Ableton Link off-screen with a second Link peer in this process —
  2431. // the toolbar in FL's Pattern layout (hidden by default, then shown, off and on) and in the Clip-launch layout
  2432. // ("1 Link", the position display's progress bar, Play waiting), Settings › Ableton Link, the toggle's
  2433. // drop-down and the Options menu. Writes prefix-checks.txt.
  2434. runLinkShot190gl (args[args.indexOf ("--linkshot190gl") + 1].unquoted());
  2435. quit();
  2436. return;
  2437. }
  2438. if (args.contains ("--communityshot190hp"))
  2439. {
  2440. // LYNX --communityshot190hp prefix (round 190hp): global MIDI mappings, Mix snapshots and Split at silence
  2441. // off-screen; writes prefix-checks.txt
  2442. runCommunityShot190hp (args[args.indexOf ("--communityshot190hp") + 1].unquoted());
  2443. quit();
  2444. return;
  2445. }
  2446. if (args.contains ("--mapshot190ef"))
  2447. {
  2448. // LYNX.exe --mapshot190ef prefix: round 190ef's map modes off-screen, in the Clip-launch workflow: MIDI Map Mode
  2449. // (the overlay over the grid, the Session mixer, the Device View and the transport; the Mapping Browser with
  2450. // Min / Max), Key Map Mode, the row menu, the title bar's Draw / Key / MIDI switches, Ctrl+M / Ctrl+K and the
  2451. // Pattern layout keeping Ctrl+M. Writes prefix-checks.txt.
  2452. runMapShot190ef (args[args.indexOf ("--mapshot190ef") + 1].unquoted());
  2453. quit();
  2454. return;
  2455. }
  2456. if (args.contains ("--sceneshot190ef"))
  2457. {
  2458. // LYNX.exe --sceneshot190ef prefix: round 190ef's scene work off-screen, in the Clip-launch workflow: the scene
  2459. // column with its tempo / time signature fields, the scene menu, a scene field's menu, the column title's menu
  2460. // (Rename, colours), a duplicated scene and a captured scene. Writes prefix-checks.txt.
  2461. runSceneShot190ef (args[args.indexOf ("--sceneshot190ef") + 1].unquoted());
  2462. quit();
  2463. return;
  2464. }
  2465. if (args.contains ("--drawshot190ef"))
  2466. {
  2467. // LYNX.exe --drawshot190ef prefix: round 190ef off-screen, in the Clip-launch workflow: Draw Mode in an
  2468. // automation lane, steps at the grid width and an Alt (no grid) freehand stroke drawn through the Playlist's
  2469. // own mouse handlers, and the Options menu with "Draw Mode". Writes prefix-checks.txt.
  2470. runDrawShot190ef (args[args.indexOf ("--drawshot190ef") + 1].unquoted());
  2471. quit();
  2472. return;
  2473. }
  2474. if (args.contains ("--clipenvshot190gi"))
  2475. {
  2476. // LYNX.exe --clipenvshot190gi prefix: round 190gi off-screen: audio clip envelopes on the Playlist (volume and
  2477. // pan lanes, edited through the Playlist's own mouse handlers), the clip menu's LYNX extras (Clip envelope ›,
  2478. // Auto-warp, Quantize audio, run from the menu), warp flags added on the flag strip and moved with Alt + drag,
  2479. // and the Clip-launch Clip View's Envelopes tab (Clip › Gain, Mixer › Track Panning). Writes prefix-checks.txt.
  2480. runClipEnvShot190gi (args[args.indexOf ("--clipenvshot190gi") + 1].unquoted());
  2481. quit();
  2482. return;
  2483. }
  2484. if (args.contains ("--livefactsshot190gx"))
  2485. {
  2486. // LYNX.exe --livefactsshot190gx prefix: round 190gx off-screen: the Clip page's Audio panel in Live's 190gu
  2487. // layout (Beats: Preserve label + chooser, the loop-mode icon chooser beside the Transient Envelope box;
  2488. // Tones / Texture: Grain Size [+ Flux]; Complex [Pro]), the Envelopes tab with a Clip Gain staircase on Live's
  2489. // axis, choosers at the bottom left, and an unwarped clip without the Envelopes tab. Writes prefix-checks.txt.
  2490. runLiveFactsShot190gx (args[args.indexOf ("--livefactsshot190gx") + 1].unquoted());
  2491. quit();
  2492. return;
  2493. }
  2494. if (args.contains ("--dvshot190hr"))
  2495. {
  2496. // LYNX.exe --dvshot190hr prefix: round 190hr off-screen, the Clip-launch Clip View: a MIDI clip whose Start
  2497. // marker sits inside its loop, with its own scale and a follow action (Launch panel controls), the docked
  2498. // editor's grid value and menu, Ctrl+1 / Ctrl+3 / Ctrl+U on it, the Quantize Settings panel, and an audio clip
  2499. // transposed past ±12. Writes prefix-checks.txt.
  2500. runDvShot190hr (args[args.indexOf ("--dvshot190hr") + 1].unquoted());
  2501. quit();
  2502. return;
  2503. }
  2504. if (args.contains ("--warpshot190fm"))
  2505. {
  2506. // LYNX.exe --warpshot190fm prefix: round 190fm off-screen: the Clip page's Audio panel of a grid audio clip in
  2507. // Beats (Preserve, Transient Loop Mode, Envelope), Tones and Texture (Grain Size), Complex (none), and the clip
  2508. // made unique by a mode change while another clip shares its channel (O16). Writes prefix-checks.txt.
  2509. runWarpShot190fm (args[args.indexOf ("--warpshot190fm") + 1].unquoted());
  2510. quit();
  2511. return;
  2512. }
  2513. if (args.contains ("--liveshot190dr"))
  2514. {
  2515. // LYNX.exe --liveshot190dr prefix: round 190dr off-screen, in the Clip-launch workflow: the Session mixer
  2516. // under the clip grid (default sections, Track Options, Volume only, hidden, its View menu), the Clip page's
  2517. // Sample panel of an audio clip (Warp on / off, the Set buttons while it plays, the sample's title) and a
  2518. // device dragged from one track's Device View to another track. Writes prefix-checks.txt.
  2519. runLiveShot190dr (args[args.indexOf ("--liveshot190dr") + 1].unquoted());
  2520. quit();
  2521. return;
  2522. }
  2523. if (args.contains ("--design190igs4shot"))
  2524. {
  2525. // LYNX.exe --design190igs4shot prefix [set.als]: round 190ig slice 4 off-screen, in the Clip-launch layout with the
  2526. // set imported there (Live's colours, CL-6): the Session grid in Live's look idle, then the launch states —
  2527. // playing, a launch waiting (both blink phases), a stop waiting, recording, the status pie at 25 / 50 / 75 % —
  2528. // and the same with Animations off, then round 181a's look (the option); prefix-checks.txt
  2529. const auto i = args.indexOf ("--design190igs4shot");
  2530. const auto project = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  2531. runDesign190igS4Shot (args[i + 1].unquoted(), project);
  2532. quit();
  2533. return;
  2534. }
  2535. if (args.contains ("--typeaheadtest"))
  2536. {
  2537. // LYNX.exe --typeaheadtest out.txt: issue #64 — a real popup menu (headings, a submenu) driven by key presses
  2538. // through its window's peer, as the OS delivers them; writes what got the highlight and what was picked
  2539. const auto i = args.indexOf ("--typeaheadtest");
  2540. runTypeAheadTest (juce::File (args[i + 1].unquoted()));
  2541. return;
  2542. }
  2543. if (args.contains ("--choosertest"))
  2544. {
  2545. // LYNX --choosertest out.txt file: issue #72 — opens LYNX's file chooser as the UI does (makeFileChooser +
  2546. // launchChooser) and reports which dialog came up and what reached the callback. A built-in dialog is shot
  2547. // (out.txt.png), `file` typed into it and confirmed; a native one (zenity / kdialog) is left to answer.
  2548. const auto i = args.indexOf ("--choosertest");
  2549. runChooserTest (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()));
  2550. return;
  2551. }
  2552. if (args.contains ("--stabilityshot"))
  2553. {
  2554. // LYNX --stabilityshot <folder> (round 190gg): offscreen PNGs of the crash prompt, the plugin window's crash
  2555. // notice, the Plugin manager's "Separate process" column and the monitor's dropout line (no window opens)
  2556. const auto i = args.indexOf ("--stabilityshot");
  2557. runStabilityShot (args[i + 1].unquoted());
  2558. return;
  2559. }
  2560. if (args.contains ("--snapshot"))
  2561. {
  2562. const auto i = args.indexOf ("--snapshot");
  2563. runSnapshot (args[i + 1].unquoted(), args[i + 2].unquoted());
  2564. return;
  2565. }
  2566. if (args.contains ("--stemsplit"))
  2567. {
  2568. // LYNX.exe --stemsplit input.wav folder: the stem separation of the clip menu, without the window
  2569. const auto i = args.indexOf ("--stemsplit");
  2570. lynx::AudioEngine loader (false);
  2571. const auto error = lynx::extractStemsToFolder (loader, juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()));
  2572. juce::File (args[i + 2].unquoted()).getSiblingFile ("stemsplit.txt").replaceWithText (error.isEmpty() ? "result=OK\n" : "result=FAIL " + error + "\n");
  2573. setApplicationReturnValue (error.isEmpty() ? 0 : 1);
  2574. quit();
  2575. return;
  2576. }
  2577. if (args.contains ("--audio2midi"))
  2578. {
  2579. // LYNX.exe --audio2midi input.wav melody|harmony|drums notes.csv: the clip menu's Convert to MIDI, without the
  2580. // window (round a2m189b's measurements)
  2581. const auto i = args.indexOf ("--audio2midi");
  2582. const auto mode = args[i + 2] == "drums" ? lynx::a2m::Mode::drums : args[i + 2] == "harmony" ? lynx::a2m::Mode::harmony : lynx::a2m::Mode::melody;
  2583. lynx::AudioEngine loader (false);
  2584. const juce::File csv (args[i + 3].unquoted());
  2585. const auto error = lynx::convertFileToMidiCsv (loader, juce::File (args[i + 1].unquoted()), mode, csv);
  2586. csv.getSiblingFile ("audio2midi.txt").replaceWithText (error.isEmpty() ? "result=OK\n" : "result=FAIL " + error + "\n");
  2587. setApplicationReturnValue (error.isEmpty() ? 0 : 1);
  2588. quit();
  2589. return;
  2590. }
  2591. if (args.contains ("--stems") || args.contains ("--stemexport"))
  2592. {
  2593. // LYNX.exe --stems project.(flp|als|lynx) base.wav [--separate]: one WAV per insert that has sound (like
  2594. // "Export stems"), in one render of the song (round 190gj; --separate: one render per insert, as before).
  2595. // LYNX.exe --stemexport project base.ext options.txt [--separate]: what the Export window writes with these
  2596. // options (exportopts::toText lines: stems, sections, the full mix, formats...), the same code.
  2597. // Both write <base>.txt: the files with their peaks, the renders, the wall and CPU time.
  2598. const auto full = args.contains ("--stemexport");
  2599. const auto i = args.indexOf (full ? "--stemexport" : "--stems");
  2600. const auto separate = args.contains ("--separate");
  2601. juce::String error, report;
  2602. int written = 0;
  2603. {
  2604. lynx::AudioEngine loader (false);
  2605. const juce::File input (args[i + 1].unquoted()), base (args[i + 2].unquoted());
  2606. // an .flp or a Live set (.als) opens through the import, as File › Open does (round 182b)
  2607. auto ok = input.hasFileExtension ("flp;als") ? loader.importFlpFile (input, error) : false;
  2608. if (! input.hasFileExtension ("flp;als"))
  2609. if (auto song = lynx::ProjectFile::load (input, error))
  2610. {
  2611. loader.setSong (std::move (*song));
  2612. ok = true;
  2613. }
  2614. const auto& song = loader.getSong();
  2615. lynx::StemPlan plan;
  2616. if (full && ok)
  2617. plan = lynx::planStemExport (song, lynx::exportopts::fromText (juce::File (args[i + 3].unquoted()).loadFileAsString().toStdString()), base);
  2618. else if (ok)
  2619. {
  2620. // every insert a channel goes to, as "<base> - <insert>.wav", 24-bit, 6 s of tail at most
  2621. lynx::ExportSettings settings;
  2622. plan.sets.push_back ({ song, settings.toOptions() });
  2623. for (int t = 1; t < (int) song.mixer.size(); ++t)
  2624. if (std::any_of (song.channels.begin(), song.channels.end(), [t] (const lynx::ChannelDef& c) { return c.mixerTrack == t; }))
  2625. plan.items.push_back ({ juce::String (t), base.getSiblingFile (base.getFileNameWithoutExtension() + " - " + juce::String (t) + ".wav"), 0, t,
  2626. lynx::makeBounceSong (song, t), settings.toOptions() });
  2627. }
  2628. const auto wallStart = juce::Time::getMillisecondCounterHiRes();
  2629. const auto cpuStart = std::clock();
  2630. lynx::StemRunStats stats;
  2631. std::vector<juce::String> lines (plan.items.size());
  2632. auto previous = wallStart; // (one render per file: the time since the file before is its render's)
  2633. written = lynx::runStemExport (
  2634. plan, [] (std::function<void()> f) { f(); }, {}, {}, {},
  2635. [&] (std::size_t k, bool done, float peak) {
  2636. const auto now = juce::Time::getMillisecondCounterHiRes();
  2637. if (done)
  2638. lines[k] = plan.items[k].file.getFileName() + " peak=" + juce::String (peak) + " ms=" + juce::String (now - previous, 0) + "\n";
  2639. previous = now;
  2640. },
  2641. separate, full, &stats);
  2642. const auto wallMs = juce::Time::getMillisecondCounterHiRes() - wallStart;
  2643. const auto cpuMs = 1000.0 * (double) (std::clock() - cpuStart) / (double) CLOCKS_PER_SEC;
  2644. for (const auto& line : lines)
  2645. report << line;
  2646. report << "renders=" << (stats.passes + stats.alone) << " shared=" << stats.passes << " inshared=" << stats.inPass
  2647. << " alone=" << stats.alone << "\n";
  2648. for (const auto& why : stats.why)
  2649. report << "alone: " << why << "\n";
  2650. report << "wall_ms=" << juce::String (wallMs, 0) << " cpu_ms=" << juce::String (cpuMs, 0) << " make_ms=" << juce::String (stats.makeMs, 0)
  2651. << " render_ms=" << juce::String (stats.renderMs, 0) << "\n";
  2652. }
  2653. report << "stems=" << written << "\n";
  2654. juce::File (args[i + 2].unquoted() + ".txt").replaceWithText (report);
  2655. setApplicationReturnValue (written > 0 ? 0 : 1);
  2656. quit();
  2657. return;
  2658. }
  2659. // --export-als <in.lynx|.flp|.als> <folder> [--live11] [--reference] [--scan]: "<folder>/<name> Project/<name>.als" (round 175a)
  2660. if (args.contains ("--export-als"))
  2661. {
  2662. const auto i = args.indexOf ("--export-als");
  2663. runAlsExport (args[i + 1].unquoted(), args[i + 2].unquoted(), args.contains ("--live11"), args.contains ("--reference"));
  2664. return;
  2665. }
  2666. // --gamepadshot <prefix> (round 184a, S16): the game controller's hints overlay and the MIDI settings page with
  2667. // the option on, offscreen, plus the poller fed fake pad states ("<prefix>-gamepad.txt")
  2668. if (args.contains ("--gamepadshot"))
  2669. {
  2670. runGamepadShot (args[args.indexOf ("--gamepadshot") + 1].unquoted());
  2671. return;
  2672. }
  2673. // --export-bundle <in.lynx|.flp|.als> <folder> [--zip] [--no-mixdown] [--shot <prefix>] (round 184a, S9): File ›
  2674. // Export › "For other apps..." without the window; the report goes to "<folder>/export-bundle.txt"
  2675. if (args.contains ("--export-bundle"))
  2676. {
  2677. const auto i = args.indexOf ("--export-bundle");
  2678. runBundleExport (args[i + 1].unquoted(), args[i + 2].unquoted(), args.contains ("--zip"), ! args.contains ("--no-mixdown"),
  2679. args.contains ("--shot") ? args[args.indexOf ("--shot") + 1].unquoted() : juce::String());
  2680. return;
  2681. }
  2682. if (args.contains ("--export-flp"))
  2683. {
  2684. const auto i = args.indexOf ("--export-flp");
  2685. runFlExport (args[i + 1].unquoted(), args[i + 2].unquoted(), args.contains ("--substitute"));
  2686. return;
  2687. }
  2688. if (args.contains ("--export"))
  2689. {
  2690. const auto i = args.indexOf ("--export");
  2691. const auto insert = args.contains ("--insert") ? args[args.indexOf ("--insert") + 1].getIntValue() : 0;
  2692. runExport (args[i + 1].unquoted(), args[i + 2].unquoted(), args.contains ("--pattern"), insert);
  2693. return;
  2694. }
  2695. if (args.contains ("--tempomarkershot"))
  2696. {
  2697. // LYNX --tempomarkershot <prefix> <project.lynx> (round 190hq): the Playlist of the project with its tempo
  2698. // markers on the ruler (-playlist.png) and the "Save a copy for an older LYNX" window for each release
  2699. // (-savecopy-<release>.png); no window, nothing saved
  2700. const auto i = args.indexOf ("--tempomarkershot");
  2701. const auto prefix = args[i + 1].unquoted();
  2702. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  2703. lynx::AudioEngine shotEngine (false);
  2704. juce::String error;
  2705. auto ok = false;
  2706. if (auto song = lynx::ProjectFile::load (juce::File (args[i + 2].unquoted()), error))
  2707. shotEngine.setSong (std::move (*song)), ok = true;
  2708. if (ok)
  2709. {
  2710. {
  2711. lynx::PlaylistComponent playlist (shotEngine);
  2712. playlist.setBounds (0, 0, 1400, 420);
  2713. playlist.setVisible (true);
  2714. playlist.setViewForSnapshot (70.0, 0, 0);
  2715. shotEngine.dispatchPendingMessages();
  2716. saveSnapshot (playlist, prefix + "-playlist.png");
  2717. }
  2718. auto list = std::make_shared<juce::TextEditor>();
  2719. std::unique_ptr<juce::AlertWindow> w (lynx::MainComponent::buildSaveCopyWindow (lynx::ProjectFile::toJson (shotEngine.getSong()), list));
  2720. const auto releases = lynx::olderlynx::releases();
  2721. for (int k = 0; k < releases.size(); ++k)
  2722. {
  2723. w->getComboBoxComponent ("release")->setSelectedItemIndex (k, juce::sendNotificationSync);
  2724. saveSnapshot (*w, prefix + "-savecopy-" + releases[k] + ".png");
  2725. }
  2726. }
  2727. setApplicationReturnValue (ok ? 0 : 1);
  2728. quit();
  2729. return;
  2730. }
  2731. if (args.contains ("--savecopyfor"))
  2732. {
  2733. // LYNX --savecopyfor <in.lynx> <release> <out.lynx> (round 190hq, B20): File › "Save a copy for an older
  2734. // LYNX..." without the window; what the copy loses goes to <out.lynx>.txt (English), then result=OK
  2735. const auto i = args.indexOf ("--savecopyfor");
  2736. const juce::File input (args[i + 1].unquoted()), output (args[i + 3].unquoted());
  2737. const auto release = args[i + 2].unquoted();
  2738. juce::String report, error;
  2739. auto ok = false;
  2740. if (const auto song = lynx::ProjectFile::load (input, error))
  2741. {
  2742. const auto copy = lynx::olderlynx::forRelease (*song, release);
  2743. for (const auto& l : copy.lost)
  2744. report << (l.sound ? "sound: " : "view: ") << juce::String::fromUTF8 (l.text).replace ("{0}", l.detail) << "\n";
  2745. ok = copy.ok && output.replaceWithText (copy.json, false, false, nullptr);
  2746. if (! copy.ok)
  2747. error = copy.error;
  2748. }
  2749. report << "result=" << (ok ? juce::String ("OK") : "ERROR " + error) << "\n";
  2750. juce::File (output.getFullPathName() + ".txt").replaceWithText (report);
  2751. setApplicationReturnValue (ok ? 0 : 1);
  2752. quit();
  2753. return;
  2754. }
  2755. if (args.contains ("--render"))
  2756. {
  2757. const auto i = args.indexOf ("--render");
  2758. runRender (args[i + 1].unquoted(), args[i + 2].unquoted(), args[i + 3].getDoubleValue());
  2759. return;
  2760. }
  2761. // session breadcrumb: a fail-fast (no crash handler runs) still leaves the last steps behind (round 111)
  2762. uncleanLastStep = collectUncleanSessions();
  2763. sessionsFolder().createDirectory();
  2764. lynx::crashguard::beginSession (
  2765. sessionsFolder().getChildFile ("session-" + juce::String (lynx::crashguard::processId()) + ".txt").getFullPathName().toStdString(),
  2766. ("LYNX session\nversion=" + getApplicationVersion() + "\npid=" + juce::String (lynx::crashguard::processId())
  2767. + "\nstart=" + juce::String ((juce::int64) lynx::crashguard::processStartTime())
  2768. + "\nstarted=" + juce::Time::getCurrentTime().toISO8601 (true) + "\n").toStdString());
  2769. startHangWatch();
  2770. // LYNX_PROFILE_MAIN=<file> (round 174f): the message thread sampled every millisecond, 5-second windows
  2771. if (const auto profile = juce::SystemStats::getEnvironmentVariable ("LYNX_PROFILE_MAIN", {}); profile.isNotEmpty())
  2772. lynx::crashguard::startMainProfiler (profile.toStdString());
  2773. startupTrace.mark ("initialise (normal start)");
  2774. // (round 190hd, Windows) how long before the trace's 0 the process was made: the loader (the exe, its DLLs,
  2775. // relocations) and the static initialisers that ran before this file's
  2776. if (const auto created = lynx::crashguard::processStartTime(); created != 0)
  2777. {
  2778. const auto t0 = (std::uint64_t) std::chrono::duration_cast<std::chrono::microseconds> (startupTrace.t0System.time_since_epoch()).count() * 10u
  2779. + 116444736000000000ull; // (FILETIME: 100 ns since 1601)
  2780. if (t0 > created)
  2781. startupTrace.mark ((" (the process was made " + juce::String ((double) (t0 - created) / 10000.0, 1)
  2782. + " ms before this trace's 0: the loader, the DLLs, the first static initialisers)").toRawUTF8());
  2783. }
  2784. prepareGraphicsDevice();
  2785. if (startupTrace.on)
  2786. lynx::startupMark = startupMarkHook;
  2787. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  2788. lynx::themeui::loadSaved(); // the user's theme (Options › Theme, round 162d)
  2789. startupOptions = lynx::StartupOptions::load();
  2790. lynx::registerFileTypes();
  2791. startupTrace.mark ("options + file types");
  2792. // Double-clicking a .lynx/.flp opens LYNX with the file as an argument; a path typed in a terminal may be relative
  2793. // (D#92, round 180a: it was ignored, leaving the blank project with no message). A missing file gets "Could not open".
  2794. if (args.size() > 0 && lynx::safety::isFileArgument (args[0].unquoted().toStdString()))
  2795. fileToOpen = juce::File::getCurrentWorkingDirectory().getChildFile (args[0].unquoted());
  2796. // LYNX --no-plugins project.lynx (round 190ap): File › "Open without third-party plugins..." from the command
  2797. // line, for a project a plugin keeps from opening — no hosted plugin is created, each keeps its settings
  2798. if (const auto i = args.indexOf ("--no-plugins"); i >= 0)
  2799. {
  2800. if (i + 1 < args.size() && lynx::safety::isFileArgument (args[i + 1].unquoted().toStdString()))
  2801. fileToOpen = juce::File::getCurrentWorkingDirectory().getChildFile (args[i + 1].unquoted());
  2802. startWithoutPlugins = fileToOpen.hasFileExtension ("lynx");
  2803. }
  2804. // LYNX_TEST_MODE=1 LYNX --open-event-test <ms> <file>: the file arrives the way macOS's Finder delivers it (a Linux
  2805. // or Windows run can exercise that path): 0 ms = at once, before the window exists
  2806. if (lynx::platform::testMode() && args[0] == "--open-event-test" && args.size() > 2)
  2807. {
  2808. const auto file = args[2].unquoted().quoted();
  2809. if (args[1].getIntValue() == 0)
  2810. anotherInstanceStarted (file);
  2811. else
  2812. juce::Timer::callAfterDelay (args[1].getIntValue(), [this, file] { anotherInstanceStarted (file); });
  2813. }
  2814. // LYNX --opentime project.(flp|lynx)|- report.txt [idle seconds] (round 165i): the normal start-up (splash, audio
  2815. // device, window) opens the project, waits until it is loaded and LYNX has gone quiet, measures the idle CPU and
  2816. // memory, writes the times and quits normally (a benchmark that killed LYNX left "closed unexpectedly" behind)
  2817. if (args.contains ("--opentime"))
  2818. {
  2819. const auto i = args.indexOf ("--opentime");
  2820. const auto project = args[i + 1].unquoted();
  2821. fileToOpen = project != "-" && juce::File::isAbsolutePath (project) ? juce::File (project) : juce::File();
  2822. openTimeReport = juce::File (args[i + 2].unquoted());
  2823. if (args.size() > i + 3 && ! args[i + 3].startsWith ("--"))
  2824. openTimeIdleSeconds = juce::jlimit (1, 120, args[i + 3].getIntValue());
  2825. }
  2826. // round 190go: the ASIO device of the last session is made and opened from now on, while the splash and the
  2827. // window come up (see below)
  2828. lynx::AudioEngine::prewarmAudioDevice();
  2829. // round 190go: the built-in start-up sound is made while the splash and the window come up (pure maths)
  2830. if (startupOptions.sound && lynx::themeui::current().startupSound.empty())
  2831. startupSampleJob = std::async (std::launch::async, [] { return lynx::makeStartupSample(); });
  2832. // Round 190go (start-up faster than FL Studio): the main window is built first, with the engine ready but no
  2833. // audio device open; the device opens after it. An ASIO device of the last session was made and opened ahead,
  2834. // on a worker, while the window was built (AudioEngine::prewarmAudioDevice; the driver itself only ever runs on
  2835. // JUCE's ASIO thread, as COM wants). Play pressed before the device is open starts with it.
  2836. if (! startupOptions.splash)
  2837. {
  2838. startEngine();
  2839. createMainWindow();
  2840. mainWindow->reveal();
  2841. startupTrace.mark ("window revealed");
  2842. // the device (and the start-up sound) once the window's first frame is on screen
  2843. mainWindow->whenPainted ([this] {
  2844. openAudioDevice();
  2845. openMidiDevices();
  2846. startAfterWindow (false);
  2847. });
  2848. return;
  2849. }
  2850. // the splash first; the main window is built behind its card (still: the logo has not started to drop; building
  2851. // it during the drop would stop the animation, both run on the message thread), then the audio device opens
  2852. // (the start-up sound needs it), and the drop starts with its sound. The window shows the moment the logo has
  2853. // landed (round 190go, A4: before, the window was built only after the drop: the drop, then ~0.6 s of build).
  2854. // Round 190hd (Windows): the card draws on a thread of its own, so the main window is built DURING the drop
  2855. // (startOnItsOwnThread below).
  2856. splash = lynx::makeStartupSplash();
  2857. startupTrace.mark ("splash made");
  2858. splash->showOnDesktop();
  2859. startupTrace.mark ("splash on the desktop");
  2860. if (splash->drawsOnItsOwnThread())
  2861. {
  2862. startWithThreadedSplash();
  2863. return;
  2864. }
  2865. // the rest once the card's first frame is on the screen (round 190go: before, a fixed 40 ms), at the latest
  2866. // after 40 ms
  2867. const auto goOn = [this, started = std::make_shared<bool> (false)] {
  2868. if (std::exchange (*started, true) || splash == nullptr) // (once; or quit meanwhile)
  2869. return;
  2870. startEngine();
  2871. if (splash == nullptr) // quit meanwhile
  2872. return;
  2873. createMainWindow();
  2874. if (splash == nullptr || mainWindow == nullptr)
  2875. return;
  2876. if (startupOptions.sound)
  2877. openAudioDevice (false); // (else after the splash: nothing waits for it)
  2878. // one turn of the message loop before the drop: what fell due while the window was built (JUCE's timers,
  2879. // the window's own async work) runs now, on the still card, not in the drop's first frames
  2880. juce::MessageManager::callAsync ([this] { startDrop(); });
  2881. };
  2882. splash->onFirstFrame = goOn;
  2883. juce::Timer::callAfterDelay (40, goOn);
  2884. }
  2885. // Round 190hd (start-up faster than FL Studio, Windows): the card draws on a thread of its own (ui/Splash.cpp), so
  2886. // nothing the message thread does stops the drop. The card shows at once (no Direct2D device is made for it); the
  2887. // engine starts and the audio device opens behind the still card (an ASIO device of the last session was made and
  2888. // opened ahead on its own thread meanwhile), the drop starts with its sound, and the main window is built while
  2889. // 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
  2890. // fades the moment the logo has landed. The card stays for the drop only (the JUCE card's
  2891. // 2.1 s from the process start was there to keep a fast start from flashing; the drop alone is 1.05 s).
  2892. void startWithThreadedSplash()
  2893. {
  2894. splash->onFirstFrame = [this] {
  2895. if (splash != nullptr && startupTrace.on)
  2896. startupTrace.mark ((" splash: first frame on the screen at "
  2897. + juce::String (std::chrono::duration<double, std::milli> (splash->getFirstFrameTime() - startupTrace.t0).count(), 1) + " ms (its own thread)")
  2898. .toRawUTF8());
  2899. };
  2900. juce::MessageManager::callAsync ([this] {
  2901. if (splash == nullptr) // (quit meanwhile)
  2902. return;
  2903. startEngine();
  2904. if (splash == nullptr)
  2905. return;
  2906. if (startupOptions.sound)
  2907. openAudioDevice (false); // (else after the splash: nothing waits for it)
  2908. startDrop();
  2909. // the main window while the logo drops (one more message, so the drop's start is not held by it)
  2910. juce::MessageManager::callAsync ([this] {
  2911. if (splash == nullptr || mainWindow != nullptr || engine == nullptr)
  2912. return;
  2913. createMainWindow();
  2914. // shown as soon as it is built, behind the card: the logo goes on dropping above it and the card fades at
  2915. // the landing as before (LYNX_REVEAL_AT_LANDING=1: the window shows at the landing, as in round 190go)
  2916. if (mainWindow != nullptr && splash != nullptr
  2917. && juce::SystemStats::getEnvironmentVariable ("LYNX_REVEAL_AT_LANDING", {}) != "1")
  2918. {
  2919. mainWindow->reveal();
  2920. windowRevealed = true;
  2921. startupTrace.mark ("window revealed (behind the card, while the logo drops)");
  2922. splash->raise();
  2923. }
  2924. });
  2925. });
  2926. }
  2927. // the logo's drop and the start-up sound together; the window shows the moment the logo has landed
  2928. void startDrop()
  2929. {
  2930. const auto ownThread = splash != nullptr && splash->drawsOnItsOwnThread(); // (the window is built during the drop)
  2931. if (splash == nullptr || (mainWindow == nullptr && ! ownThread) || engine == nullptr)
  2932. return;
  2933. if (startupOptions.sound)
  2934. playStartupSound();
  2935. splash->setStatus (lynx::tr ("Loading the workspace..."));
  2936. splash->startClock();
  2937. // the minimum counts from the process start (the window and the audio device took part of it already); a card
  2938. // on its own thread stays for the drop (round 190hd)
  2939. splashDuration = ownThread ? landingSeconds : lynx::SplashScreen::remainingDuration (startupTrace.seconds());
  2940. splash->setBarDuration (splashDuration);
  2941. splash->whenLanded (splashDuration, [this] {
  2942. if (splash == nullptr || mainWindow == nullptr)
  2943. return;
  2944. if (startupTrace.on)
  2945. startupTrace.mark (("splash: the drop in " + juce::String (splash->getDropFrames()) + " frames, longest gap "
  2946. + juce::String (splash->getLongestDropGapMs(), 1) + " ms"
  2947. + (splash->getLongestDropGapAt() >= 0.0 ? " (at " + juce::String (splash->getLongestDropGapAt(), 3) + " s of its clock; the frame before: "
  2948. + splash->getLongestDropGapDetail() + ")"
  2949. : juce::String()))
  2950. .toRawUTF8());
  2951. if (! std::exchange (windowRevealed, true))
  2952. {
  2953. mainWindow->reveal();
  2954. startupTrace.mark ("window revealed (after the splash)");
  2955. }
  2956. splash->raise();
  2957. const auto deviceOpen = ! engine->isAudioDeviceOpenPending();
  2958. splash->finish ([this, deviceOpen] {
  2959. splash = nullptr;
  2960. // without the start-up sound the device opens now, once the card has faded (the window is up)
  2961. if (! deviceOpen)
  2962. openAudioDevice();
  2963. openMidiDevices();
  2964. if (! deviceOpen)
  2965. startAfterWindow (true);
  2966. });
  2967. if (deviceOpen)
  2968. mainWindow->whenPainted ([this] { startAfterWindow (true); });
  2969. });
  2970. }
  2971. // what follows the window's first frame (the audio device is open): the notice of an unclean end, the start-up
  2972. // project, the probes and the update check; on a first run (with the splash) the setup wizard
  2973. void startAfterWindow (bool offerSetupWizard)
  2974. {
  2975. if (std::exchange (startedAfterWindow, true) || mainWindow == nullptr)
  2976. return;
  2977. // (round 190go) each step after the window is a timed line of the start-up trace
  2978. showUncleanNotice();
  2979. startupTrace.mark ("after the window: unclean-session notice");
  2980. openStartupFile();
  2981. startupTrace.mark ("startup file opened");
  2982. startOpenTimeProbe();
  2983. startUpdateCheck();
  2984. startSupportNote(); // (round 190fq)
  2985. startupTrace.mark ("after the window: probes, update check scheduled");
  2986. juce::MessageManager::callAsync ([] { startupTrace.mark ("first message loop turn"); });
  2987. markSettled(); // (round 190gd)
  2988. // first run: language, audio, plugin folders (FL Studio's included) and a background scan
  2989. if (! offerSetupWizard)
  2990. return;
  2991. if (! lynx::setupWizardDone() && lynx::platform::testMode())
  2992. lynx::platform::testModeLog ("setup wizard");
  2993. else if (! lynx::setupWizardDone())
  2994. {
  2995. mainWindow->showSetupWizard();
  2996. startupTrace.mark ("after the window: setup wizard shown");
  2997. }
  2998. }
  2999. // round 190fq: the start-up support note (ui/SupportLynx.h) counts this start and, from the 10th on, may show its
  3000. // card once at a quiet moment. Only here, on the normal start path (the command-line modes returned earlier); test
  3001. // mode and CI machines neither count nor show it.
  3002. void startSupportNote()
  3003. {
  3004. if (mainWindow == nullptr)
  3005. return;
  3006. const auto env = [] (const char* name) { return juce::SystemStats::getEnvironmentVariable (name, {}).toStdString(); };
  3007. const auto quiet = lynx::supportnote::quietEnvironment (lynx::platform::testMode(), env ("CI"), env ("GITHUB_ACTIONS"), env ("LYNX_NO_SUPPORT_NOTE"));
  3008. if (quiet && lynx::platform::testMode())
  3009. lynx::platform::testModeLog ("support note: not counted (test mode)");
  3010. mainWindow->getContent().startSupportNote (quiet);
  3011. }
  3012. // the start-up trace's last lines: what the first seconds after the window add (lazy work, caches, the first paints)
  3013. static void markSettled()
  3014. {
  3015. if (! startupTrace.on)
  3016. return;
  3017. juce::Timer::callAfterDelay (5000, [] { startupTrace.mark ("5 s after the window"); startupTrace.write(); });
  3018. juce::Timer::callAfterDelay (15000, [] { startupTrace.mark ("15 s after the window"); startupTrace.write(); });
  3019. }
  3020. // Round 190hd (Windows): the Direct3D 11 + Direct2D device (~0.35 s: the graphics driver loads) is made once, on a
  3021. // worker, while the splash card, the engine and the audio device come up, and kept until LYNX closes: a 1 x 1
  3022. // Direct2D image holds JUCE's shared DirectX object (its devices), so the main window finds them made and nothing
  3023. // makes them again (before, every holder going away -- the splash's logo, a temporary one -- could mean a new device
  3024. // at its next use). Other systems: nothing to do.
  3025. void prepareGraphicsDevice()
  3026. {
  3027. #if JUCE_WINDOWS
  3028. if (juce::SystemStats::getEnvironmentVariable ("LYNX_GPU_PREWARM", {}) == "0")
  3029. return;
  3030. graphicsDeviceJob = std::async (std::launch::async, [] {
  3031. const auto from = std::chrono::steady_clock::now();
  3032. juce::Image holder (juce::Image::ARGB, 1, 1, false); // (NativeImageType: Direct2D, the shared device)
  3033. return std::make_pair (holder, std::chrono::duration<double, std::milli> (std::chrono::steady_clock::now() - from).count());
  3034. });
  3035. #endif
  3036. }
  3037. void markGraphicsDevice()
  3038. {
  3039. if (! graphicsDeviceJob.valid() || ! startupTrace.on || std::exchange (graphicsDeviceMarked, true))
  3040. return;
  3041. const auto ready = graphicsDeviceJob.wait_for (std::chrono::seconds (0)) == std::future_status::ready;
  3042. startupTrace.mark (ready ? (" graphics device made on a worker in " + juce::String (graphicsDeviceJob.get().second, 1) + " ms").toRawUTF8()
  3043. : " graphics device: still being made on its worker");
  3044. }
  3045. void startEngine()
  3046. {
  3047. startupTrace.mark ("before the audio engine");
  3048. lynx::BrowserComponent::allowIndexerProcess = true; // (round 190hd: the normal window only)
  3049. // (round 190go) ready to play, no device open yet: see openAudioDevice
  3050. engine = std::make_unique<lynx::AudioEngine> (true, -1, true, true);
  3051. lynx::videoview::install (*engine); // (Fruity Video Player channels: their sound tracks)
  3052. startupTrace.mark ("audio engine (no device yet)");
  3053. crashEngine = engine.get();
  3054. lynx::crashreporter::watchAudioDevice (engine->getDeviceManager()); // (the session file names the device: crash reports)
  3055. // a project given on the command line: its slow plugin modules (a Waves shell) start now, on their own
  3056. // thread, while the splash and the main window come up (round 121)
  3057. if (fileToOpen.hasFileExtension ("flp"))
  3058. if (juce::MemoryBlock data; fileToOpen.loadFileAsData (data))
  3059. try
  3060. {
  3061. engine->getPluginHost().startModulesFor (lynx::flpForeignPlugins (flp::parseProject ({ static_cast<const std::uint8_t*> (data.getData()), data.getSize() })));
  3062. startupTrace.mark ("plugin modules started ahead");
  3063. }
  3064. catch (const flp::Error&)
  3065. {
  3066. }
  3067. }
  3068. // The audio device of the last session, then (withSound) the start-up sound on it (once; message thread)
  3069. void openAudioDevice (bool withSound = true)
  3070. {
  3071. if (engine == nullptr || ! engine->isAudioDeviceOpenPending())
  3072. return;
  3073. engine->openAudioDevice();
  3074. if (const auto prewarmed = lynx::asioPrewarmReport(); prewarmed.isNotEmpty() && startupTrace.on)
  3075. startupTrace.mark ((" " + prewarmed).toRawUTF8());
  3076. startupTrace.mark ("audio device opened");
  3077. addDriverFileDeviceType();
  3078. if (withSound)
  3079. playStartupSound();
  3080. }
  3081. void playStartupSound()
  3082. {
  3083. if (startupOptions.sound && ! std::exchange (startupSoundPlayed, true) && engine != nullptr)
  3084. {
  3085. // Options › Theme › Startup sound (issue #12): the user's file, else (or when it can't be read) LYNX's own
  3086. std::shared_ptr<const lynx::SampleData> sound;
  3087. if (const auto& own = lynx::themeui::current().startupSound; ! own.empty() && juce::File (juce::String::fromUTF8 (own.c_str())).existsAsFile())
  3088. sound = engine->getSampleLibrary().load (juce::String::fromUTF8 (own.c_str()));
  3089. if (sound == nullptr && startupSampleJob.valid())
  3090. sound = startupSampleJob.get();
  3091. engine->previewSample (sound != nullptr ? sound : lynx::makeStartupSample());
  3092. }
  3093. startupTrace.mark ("startup sound");
  3094. }
  3095. void openMidiDevices()
  3096. {
  3097. if (engine != nullptr)
  3098. engine->openMidiDevices(); // (its own line in the start-up trace: "engine: MIDI inputs")
  3099. }
  3100. void createMainWindow()
  3101. {
  3102. mainWindow = std::make_unique<MainWindow> ("LYNX SHARE", *engine); // the brand; getApplicationName() stays "LYNX" (an id: instance lock, X11 WM_CLASS, ALSA client)
  3103. lynx::setMainWindowForOwnership (mainWindow.get());
  3104. lynx::applyRenderingChoice (*mainWindow); // (GPU rendering off: GDI; round 157a)
  3105. lynx::startRenderingWatch();
  3106. startupTrace.mark ("main window built");
  3107. lynx::remoteui::install ([this] (bool enabled) {
  3108. remoteControl = nullptr;
  3109. if (enabled)
  3110. remoteControl = lynx::RemoteControl::create (*engine, true, [this] {
  3111. const auto title = mainWindow != nullptr ? mainWindow->getName() : juce::String ("Untitled");
  3112. const auto separator = title.indexOf (" - ");
  3113. return separator >= 0 ? title.substring (separator + 3) : title;
  3114. }, [this] {
  3115. const auto file = mainWindow != nullptr ? mainWindow->getContent().getCurrentProjectFile() : juce::File();
  3116. return file == juce::File() ? juce::String() : file.getFullPathName();
  3117. });
  3118. lynx::remoteui::setRuntimeStatus (remoteControl != nullptr && remoteControl->active());
  3119. });
  3120. markGraphicsDevice();
  3121. }
  3122. // the previous run ended without closing (see collectUncleanSessions): say so once, with its last step — and, as
  3123. // Settings › General › "Crash reports" says (round 159), ask whether to send a report, send it unasked, or not
  3124. void showUncleanNotice()
  3125. {
  3126. if (lynx::platform::testMode()) // LYNX_TEST_MODE: no prompt, no report sent (written to test-mode.log)
  3127. {
  3128. if (uncleanLastStep.isNotEmpty())
  3129. lynx::platform::testModeLog ("\"closed unexpectedly\" notice (last step: " + uncleanLastStep + ")");
  3130. return;
  3131. }
  3132. if (uncleanLastStep.isEmpty())
  3133. {
  3134. lynx::crashreporter::retryPending(); // (reports an earlier run could not send: once more)
  3135. return;
  3136. }
  3137. auto message = lynx::tr ("The last session ended without closing normally. Last step: {0}. Backup copies of your project are in "
  3138. "LYNX SHARE's autosave folder; details in crash-history.log.",
  3139. { uncleanLastStep });
  3140. uncleanLastStep.clear();
  3141. const auto cause = uncleanCause();
  3142. // round 157a: a plugin's editor was opening — it crashed (often in the graphics driver, inside the plugin's own
  3143. // OpenGL window): offer to keep that plugin in its own process, where a crash takes only the plugin down
  3144. juce::String separatePlugin;
  3145. if (cause.editorPlugin.isNotEmpty() && ! lynx::pluginSandboxEnabled() && ! lynx::pluginAlwaysSeparate (cause.editorPlugin))
  3146. separatePlugin = cause.editorPlugin;
  3147. // LYNX's own drawing crashed in the graphics driver (Direct2D / Direct3D): draw with the CPU from now on
  3148. else if (cause.gpuDriver && lynx::gpuRenderingEnabled())
  3149. {
  3150. lynx::setGpuRenderingEnabled (false);
  3151. message << "\n\n"
  3152. << lynx::tr ("The crash was in the graphics driver ({0}). LYNX SHARE now draws its windows without the GPU; you can turn GPU "
  3153. "rendering back on in Options > General settings (after a driver update, for example).",
  3154. { cause.driverModule });
  3155. }
  3156. // round 165e: the Visualizer's GPU view was drawing when the session ended (a driver crash, a hang, the machine
  3157. // going down): the Visualizer draws with the 2D renderer from now on (its GPU button turns it back on)
  3158. for (int i = uncleanSteps.size(); --i >= 0;)
  3159. {
  3160. if (uncleanSteps[i].contains (lynx::visualgl::stopNote))
  3161. break;
  3162. if (uncleanSteps[i].contains (lynx::visualgl::startNote))
  3163. {
  3164. if (lynx::visualgl::enabled())
  3165. {
  3166. lynx::visualgl::setEnabled (false);
  3167. message << "\n\n"
  3168. << lynx::tr ("The Visualizer was drawing with the GPU (OpenGL) when it happened. It now draws without the GPU; its GPU "
  3169. "button turns it back on.");
  3170. }
  3171. break;
  3172. }
  3173. }
  3174. const auto session = lynx::crashreporter::parseSession (uncleanSessionText);
  3175. auto* devices = engine != nullptr ? &engine->getDeviceManager() : nullptr;
  3176. const auto action = lynx::crashreport::actionFor (lynx::crashreporter::consent());
  3177. lynx::crashreporter::retryPending();
  3178. if (action == lynx::crashreport::Action::askUser)
  3179. {
  3180. if (separatePlugin.isNotEmpty())
  3181. message << "\n\n"
  3182. << lynx::tr ("It happened while the window of {0} was opening{1}.",
  3183. { separatePlugin, cause.gpuDriver ? lynx::tr (" (in the graphics driver, {0})", { cause.driverModule }) : juce::String() });
  3184. lynx::crashreporter::showStartupDialog (session, message, separatePlugin, [separatePlugin] { lynx::setPluginAlwaysSeparate (separatePlugin, true); },
  3185. devices);
  3186. return;
  3187. }
  3188. if (action == lynx::crashreport::Action::sendSilently)
  3189. {
  3190. const auto input = lynx::crashreporter::makeInput (session, session.kind(), devices);
  3191. lynx::crashreporter::send (lynx::crashreporter::buildJson (input, false), juce::String::fromUTF8 (input.id.c_str()));
  3192. message << "\n\n" << lynx::tr ("A crash report is being sent to help fix it (Options > General settings > Crash reports).");
  3193. }
  3194. if (separatePlugin.isNotEmpty())
  3195. {
  3196. juce::AlertWindow::showOkCancelBox (
  3197. juce::MessageBoxIconType::WarningIcon, lynx::tr ("LYNX SHARE closed unexpectedly"),
  3198. message + "\n\n"
  3199. + lynx::tr ("It happened while the window of {0} was opening{1}. Run {0} in a separate process from now on? If it "
  3200. "crashes again, only the plugin stops and LYNX SHARE keeps running (Plugin wrapper menu: \"Always run in a "
  3201. "separate process\").",
  3202. { separatePlugin, cause.gpuDriver ? lynx::tr (" (in the graphics driver, {0})", { cause.driverModule }) : juce::String() }),
  3203. lynx::tr ("Run separately"), lynx::tr ("No"), nullptr,
  3204. juce::ModalCallbackFunction::create ([separatePlugin] (int result) {
  3205. if (result != 0)
  3206. lynx::setPluginAlwaysSeparate (separatePlugin, true);
  3207. }));
  3208. return;
  3209. }
  3210. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, lynx::tr ("LYNX SHARE closed unexpectedly"), message);
  3211. }
  3212. // --opentime: after the start-up file was handed to the window
  3213. void startOpenTimeProbe()
  3214. {
  3215. if (openTimeReport == juce::File())
  3216. return;
  3217. struct Probe final : juce::Timer
  3218. {
  3219. LynxApplication& app;
  3220. juce::File report, project;
  3221. int idleSeconds;
  3222. int phase = 0; // 0 loading, 1 settling, 2 idle measurement
  3223. double revealedS = 0.0, loadedS = -1.0, settledS = -1.0, cpuAtLoaded = 0.0;
  3224. double lastCpu = 0.0, lastT = 0.0, quietSince = -1.0, idleCpu0 = 0.0, idleT0 = 0.0;
  3225. Probe (LynxApplication& a, juce::File r, juce::File p, int idle)
  3226. : app (a), report (std::move (r)), project (std::move (p)), idleSeconds (idle)
  3227. {
  3228. revealedS = startupTrace.seconds();
  3229. startTimer (250);
  3230. }
  3231. bool loaded() const
  3232. {
  3233. if (project == juce::File())
  3234. return true;
  3235. return app.mainWindow != nullptr
  3236. && app.mainWindow->getName().containsIgnoreCase (project.getFileNameWithoutExtension());
  3237. }
  3238. void finish (const juce::String& result)
  3239. {
  3240. stopTimer();
  3241. const auto now = startupTrace.seconds();
  3242. const auto cpu = lynx::processCpuSeconds();
  3243. juce::String text;
  3244. text << "project=" << (project == juce::File() ? juce::String ("-") : project.getFullPathName()) << "\n"
  3245. << "window_s=" << juce::String (revealedS, 3) << "\n"
  3246. << "loaded_s=" << juce::String (loadedS, 3) << "\n"
  3247. << "settled_s=" << juce::String (settledS, 3) << "\n"
  3248. << "cpu_at_loaded_s=" << juce::String (cpuAtLoaded, 3) << "\n"
  3249. << "idle_s=" << juce::String (now - idleT0, 2) << "\n"
  3250. << "idle_cpu_pct=" << juce::String (phase == 2 && now > idleT0 ? 100.0 * (cpu - idleCpu0) / (now - idleT0) : -1.0, 1) << "\n"
  3251. << "working_set_mb=" << juce::String ((double) lynx::toolbar::PerformanceMeter::processMemoryBytes() / 1048576.0, 0) << "\n"
  3252. << "cpu_total_s=" << juce::String (cpu, 3) << "\n"
  3253. << "result=" << result << "\n";
  3254. report.replaceWithText (text);
  3255. app.setApplicationReturnValue (result == "OK" ? 0 : 1);
  3256. app.quit();
  3257. }
  3258. void timerCallback() override
  3259. {
  3260. const auto now = startupTrace.seconds();
  3261. const auto cpu = lynx::processCpuSeconds();
  3262. if (phase == 0)
  3263. {
  3264. if (loaded())
  3265. {
  3266. loadedS = now;
  3267. cpuAtLoaded = cpu;
  3268. phase = 1;
  3269. lastCpu = cpu;
  3270. lastT = now;
  3271. }
  3272. else if (now - revealedS > 240.0)
  3273. finish ("TIMEOUT loading");
  3274. return;
  3275. }
  3276. if (phase == 1)
  3277. {
  3278. // quiet = under 10 % of one core for 1.5 s (the harness's rule), at most 30 s after loading
  3279. const auto use = now > lastT ? 100.0 * (cpu - lastCpu) / (now - lastT) : 0.0;
  3280. lastCpu = cpu;
  3281. lastT = now;
  3282. if (use < 10.0)
  3283. {
  3284. if (quietSince < 0.0)
  3285. quietSince = now - 0.25;
  3286. if (now - quietSince >= 1.5)
  3287. settledS = quietSince;
  3288. }
  3289. else
  3290. quietSince = -1.0;
  3291. if (settledS >= 0.0 || now - loadedS > 30.0)
  3292. {
  3293. phase = 2;
  3294. idleCpu0 = cpu;
  3295. idleT0 = now;
  3296. }
  3297. return;
  3298. }
  3299. if (now - idleT0 >= (double) idleSeconds)
  3300. finish ("OK");
  3301. }
  3302. };
  3303. perf = std::make_unique<Probe> (*this, openTimeReport, fileToOpen, openTimeIdleSeconds);
  3304. }
  3305. // round 166b: the update check of a normal start (never in --opentime and the other command-line modes), a few
  3306. // seconds after the window is up so it never competes with the start-up; and the result of an update just installed
  3307. void startUpdateCheck()
  3308. {
  3309. if (openTimeReport != juce::File())
  3310. return;
  3311. lynx::updater::afterStart();
  3312. juce::Timer::callAfterDelay (3000, [] { lynx::updater::startAutomaticCheck(); });
  3313. }
  3314. void openStartupFile()
  3315. {
  3316. startupFileHandled = true;
  3317. if (fileToOpen != juce::File() && mainWindow != nullptr)
  3318. {
  3319. if (std::exchange (startWithoutPlugins, false)) // --no-plugins (round 190ap)
  3320. mainWindow->getContent().openNextWithoutPlugins (true);
  3321. mainWindow->openFile (fileToOpen);
  3322. mainWindow->getContent().openNextWithoutPlugins (false); // (a file that did not open leaves nothing behind)
  3323. }
  3324. else if (mainWindow != nullptr && openTimeReport == juce::File())
  3325. mainWindow->getContent().openStartupProject(); // issue #123 (FL's Startup project)
  3326. }
  3327. void shutdown() override
  3328. {
  3329. parityShow.reset(); // (LYNX_PARITYSHOT_SHOW's window, before the engine it shows)
  3330. if (relaunched || updateHelper)
  3331. return; // the copy that ran owns the session (its crash notes stay for the next start)
  3332. lynx::crashguard::note ("closing");
  3333. lynx::shutdownPluginSandboxWorker();
  3334. splash = nullptr;
  3335. lynx::shutdownStemExtraction(); // (a separation in flight stops before its window and the engine go)
  3336. lynx::shutdownAudioToMidi(); // (the same for a conversion to MIDI)
  3337. if (mainWindow != nullptr && mainWindow->isVisible())
  3338. mainWindow->saveState();
  3339. lynx::remoteui::shutdown();
  3340. remoteControl = nullptr; // cancels queued control work before its engine and UI go
  3341. mainWindow = nullptr; // the UI goes before the engine
  3342. graphicsDeviceJob = {}; // (round 190hd: the graphics device's holder, after every window)
  3343. lynx::updater::shutdown(); // (a check or download in flight stops)
  3344. crashEngine = nullptr;
  3345. engine = nullptr;
  3346. // separate-process plugins end on threads of their own (issue #159): a moment for them, never the 10 s a dead
  3347. // child's pipe can take
  3348. lynx::finishSandboxTeardowns (2000);
  3349. // CLAP plugins whose instance another thread deleted while this one was busy: deactivated and destroyed now
  3350. lynx::ClapPluginFormat::finishPendingTeardowns();
  3351. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  3352. heartbeat.stopTimer();
  3353. lynx::crashreporter::shutdown(); // (an upload in flight gets a moment, never long)
  3354. lynx::crashguard::stopHangWatch();
  3355. lynx::crashguard::stopMainProfiler();
  3356. lynx::crashguard::endSession(); // a clean exit: no breadcrumb left behind
  3357. // everything is saved and closed: a process that loaded third-party plugins ends here, before the DLLs' own
  3358. // teardown runs (some crash in it at exit, round 111)
  3359. if (sandboxChild || lynx::PluginHost::pluginsWereLoaded())
  3360. lynx::crashguard::exitNow (getApplicationReturnValue());
  3361. }
  3362. void systemRequestedQuit() override
  3363. {
  3364. if (mainWindow != nullptr)
  3365. mainWindow->confirmDiscard ([] { juce::JUCEApplication::quit(); });
  3366. else
  3367. quit();
  3368. }
  3369. private:
  3370. // round 157a: a frozen UI (Windows' "not responding") writes the message thread's stack to autosave\hang <time>.txt
  3371. // and a session step, so a freeze can be told apart from a crash and located. The timer is the heartbeat.
  3372. struct Heartbeat final : juce::Timer
  3373. {
  3374. void timerCallback() override { lynx::crashguard::heartbeat(); }
  3375. } heartbeat;
  3376. void startHangWatch()
  3377. {
  3378. const auto folder = lynx::platform::settingsFile ("autosave");
  3379. folder.createDirectory();
  3380. // keep the newest hang files only
  3381. auto old = folder.findChildFiles (juce::File::findFiles, false, "hang *.txt");
  3382. lynx::filesort::byTime (old, lynx::filesort::By::modificationTime, true);
  3383. for (int i = 20; i < old.size(); ++i)
  3384. old.getReference (i).deleteFile();
  3385. lynx::crashguard::startHangWatch (folder.getFullPathName().replaceCharacter ('\\', '/').toStdString());
  3386. heartbeat.startTimerHz (5);
  3387. }
  3388. bool sandboxChild = false;
  3389. bool relaunched = false; // relaunchFromAsciiPath ran LYNX from its short path: this process only waited
  3390. bool updateHelper = false; // --apply-update (round 166b)
  3391. juce::String uncleanLastStep; // last step of a previous run that ended without closing
  3392. // LYNX_PROFILE_DIR=<folder> LYNX --lv2scantest report.txt (Linux, issue #85): the LV2 scan's promise, with real child
  3393. // processes. A new PluginHost per step, as every start of LYNX has. The LV2 folders of the machine are read too.
  3394. void runLv2ScanTest (const juce::String& reportPath)
  3395. {
  3396. juce::String report;
  3397. auto ok = lynx::platform::profileOverride() != juce::File();
  3398. #if JUCE_LINUX
  3399. const auto folder = lynx::platform::profileOverride().getChildFile ("lv2-test");
  3400. const juce::FileSearchPath paths (folder.getFullPathName());
  3401. const auto check = [&] (const juce::String& name, bool passed) {
  3402. report << name << "=" << (passed ? "ok" : "FAILED") << "\n";
  3403. ok = ok && passed;
  3404. };
  3405. const auto install = [&] (const juce::String& name) {
  3406. const auto bundle = folder.getChildFile (name + ".lv2");
  3407. bundle.createDirectory();
  3408. bundle.getChildFile ("manifest.ttl").replaceWithText ("@prefix lv2: <http://lv2plug.in/ns/lv2core#> .\n@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n"
  3409. "<urn:lynx-test:" + name + "> a lv2:Plugin ; lv2:binary <" + name + ".so> ; rdfs:seeAlso <plugin.ttl> .\n");
  3410. bundle.getChildFile ("plugin.ttl").replaceWithText ("@prefix doap: <http://usefulinc.com/ns/doap#> .\n<urn:lynx-test:" + name + "> doap:name \"" + name + "\" .\n");
  3411. };
  3412. auto date = juce::Time::getCurrentTime();
  3413. const auto touch = [&] { // the next date, whatever the file system's date resolution
  3414. date += juce::RelativeTime::seconds (2.0);
  3415. folder.getChildFile ("a.lv2/plugin.ttl").setLastModificationTime (date);
  3416. };
  3417. const auto listed = [] (lynx::PluginHost& host, const juce::String& name) {
  3418. for (const auto& d : host.getKnownPlugins().getTypes())
  3419. if (d.fileOrIdentifier == "urn:lynx-test:" + name)
  3420. return true;
  3421. return false;
  3422. };
  3423. const auto step = [&] (const juce::String& name, int children, const std::function<void (lynx::PluginHost&)>& prepare = {}) {
  3424. lynx::PluginHost host (true);
  3425. if (prepare)
  3426. prepare (host);
  3427. host.scan (paths, {});
  3428. check (name, host.scanChildrenStarted() == children && listed (host, "a"));
  3429. };
  3430. install ("a");
  3431. step ("first_scan_one_child", 1);
  3432. step ("nothing_changed_no_child", 0);
  3433. touch();
  3434. step ("ttl_updated", 1);
  3435. install ("b");
  3436. step ("bundle_installed", 1);
  3437. step ("forget_file", 1, [] (lynx::PluginHost& host) { host.forgetFile ("urn:lynx-test:a"); });
  3438. step ("forget_all", 1, [] (lynx::PluginHost& host) { host.forgetAll(); });
  3439. lynx::platform::settingsFile ("plugins.xml").deleteFile();
  3440. step ("list_lost", 1);
  3441. step ("nothing_changed_again", 0);
  3442. // cancelled while the child works: stopped at once, and nothing is taken for done
  3443. touch();
  3444. setenv ("LYNX_TEST_CRASH", "lv2-batch-hang", 1);
  3445. {
  3446. lynx::PluginHost host (true);
  3447. const auto started = juce::Time::getMillisecondCounter();
  3448. host.scan (paths, [] (float, const juce::String&) { return false; });
  3449. check ("cancel_stops_the_child", host.scanChildrenStarted() == 1 && juce::Time::getMillisecondCounter() - started < 20000);
  3450. }
  3451. unsetenv ("LYNX_TEST_CRASH");
  3452. step ("described_after_cancel", 1);
  3453. // the child dies: plugin by plugin takes over (stopped after two of them: a machine may have hundreds)
  3454. touch();
  3455. setenv ("LYNX_TEST_CRASH", "lv2-batch", 1);
  3456. {
  3457. lynx::PluginHost host (true);
  3458. host.scan (paths, [&host] (float, const juce::String&) { return host.scanChildrenStarted() < 3; });
  3459. check ("crash_falls_back_plugin_by_plugin", host.scanChildrenStarted() == 3);
  3460. auto blamed = false;
  3461. for (const auto& file : host.getKnownPlugins().getBlacklistedFiles())
  3462. blamed = blamed || file.startsWith ("lv2-folders:");
  3463. check ("crash_blacklists_nothing", ! blamed);
  3464. }
  3465. unsetenv ("LYNX_TEST_CRASH");
  3466. step ("described_after_crash", 1);
  3467. // round 190fw: past the first limit, a child that still works is waited for (FL Studio's own VST plugin boots
  3468. // the FL engine), one that sits still is killed as before, and a busy one only up to the cap. Limits are
  3469. // shortened for the test: 2 s first limit, 2 s without work, 8 s cap (real: 30 s, 30 s, 5 min).
  3470. setenv ("LYNX_TEST_SCAN_MS", "2000,2000,8000", 1);
  3471. const auto timed = [&] (const char* fault, const std::function<bool (lynx::PluginHost&)>& progress) {
  3472. touch();
  3473. setenv ("LYNX_TEST_CRASH", fault, 1);
  3474. lynx::PluginHost host (true);
  3475. const auto started = juce::Time::getMillisecondCounter();
  3476. host.scan (paths, [&] (float, const juce::String&) { return ! progress || progress (host); });
  3477. unsetenv ("LYNX_TEST_CRASH");
  3478. const auto took = (int) (juce::Time::getMillisecondCounter() - started);
  3479. report << " " << fault << ": " << took << " ms, children " << host.scanChildrenStarted() << "\n";
  3480. return std::make_pair (took, host.scanChildrenStarted());
  3481. };
  3482. // (after a failed batch, one plugin-by-plugin child and no more: it describes quickly)
  3483. const auto stopAfterBatch = [] (lynx::PluginHost& host) { return host.scanChildrenStarted() < 2; };
  3484. {
  3485. const auto [took, children] = timed ("lv2-batch-busy:5000", {});
  3486. check ("busy_child_is_waited_for", children == 1 && took >= 4500);
  3487. }
  3488. {
  3489. const auto [took, children] = timed ("lv2-batch-hang", stopAfterBatch);
  3490. check ("idle_child_ends_near_the_first_limit", children == 2 && took >= 1900 && took < 9000);
  3491. }
  3492. {
  3493. const auto [took, children] = timed ("lv2-batch-busy:60000", stopAfterBatch);
  3494. check ("busy_child_ends_at_the_cap", children == 2 && took >= 7500 && took < 20000);
  3495. }
  3496. unsetenv ("LYNX_TEST_SCAN_MS");
  3497. step ("described_after_slow_children", 1);
  3498. #endif
  3499. juce::File (reportPath).replaceWithText (report + "result=" + (ok ? "OK" : "FAILED") + "\n");
  3500. setApplicationReturnValue (ok ? 0 : 1);
  3501. quit();
  3502. }
  3503. // LYNX.exe --selftest report.txt: renders 2 s without a sound card and writes the result.
  3504. // Exit code 0 = audio came out, 1 = silence.
  3505. // --selftest (round 190ci): two more copies of LYNX end by a fault on purpose (--faulttest), one on a normal stack
  3506. // (the top-level filter) and one on a stack Windows cannot walk (the first-chance hook); each must leave
  3507. // "crash <time>.txt" with the access violation in the folder it is given.
  3508. // Round 190dt (Linux / macOS): a plain fault, and LYNX's own fault inside a guarded plugin call (in its code, and in
  3509. // the C library called from its code), must each leave the crash file with the signal: the plugin guard passes
  3510. // LYNX's own faults on to the crash handler instead of swallowing them ("swallowed.txt" = it did).
  3511. // Round 190gj (P9): the inserts' stems from one render are the files each stem's own render writes, byte for byte
  3512. // (a short song with a bus, a send return, delay compensation, a channel on the Master, an automated insert and a
  3513. // side-chained insert), streamed (24-bit WAV with the full mix) and buffered (normalised float).
  3514. static juce::String stemsSinglePassSelfTest()
  3515. {
  3516. auto s = lynx::Song::makeDefault();
  3517. s.mixer = lynx::Song::defaultMixer (7);
  3518. for (std::size_t c = 0; c < s.channels.size(); ++c)
  3519. s.channels[c].mixerTrack = (int) c + 1;
  3520. auto onMaster = s.channels[2];
  3521. onMaster.mixerTrack = 0;
  3522. onMaster.pan = -0.4f;
  3523. s.channels.push_back (onMaster);
  3524. for (int step : { 1, 5, 9, 13 })
  3525. s.patterns[0].toggleStep ((int) s.channels.size() - 1, step);
  3526. for (int step : { 4, 12 })
  3527. s.patterns[0].toggleStep (3, step); // the snare
  3528. for (int k = 0; k < 4; ++k) // the synth under the kick (its compressor listens to it)
  3529. s.patterns[0].notes.push_back ({ (std::int64_t) k * lynx::ppq, lynx::ppq - 60, 4, 57 + 3 * k, 0.9f });
  3530. s.patterns[0].sortNotes();
  3531. s.mixer[0].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::limiter));
  3532. s.mixer[1].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::compressor));
  3533. s.mixer[2].toMaster = false;
  3534. s.mixer[2].sends = { lynx::MixerSend { 6, 1.0f } };
  3535. s.mixer[3].sends = { lynx::MixerSend { 7, 0.5f } };
  3536. s.mixer[3].latencyMs = 3.0f;
  3537. s.mixer[4].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::delay));
  3538. s.mixer[4].latencyMs = 5.0f;
  3539. s.mixer[4].sends = { lynx::MixerSend { 6, 0.7f } };
  3540. s.mixer[4].masterLevel = 0.8f;
  3541. auto keyed = lynx::makeEffectSlot (lynx::EffectKind::compressor);
  3542. keyed.params[0] = 0.5f; // (−30 dB: the kick's hits pull the synth down)
  3543. keyed.sidechain = 1;
  3544. s.mixer[5].effects.push_back (keyed);
  3545. s.mixer[6].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::distortion));
  3546. s.mixer[7].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::reverb));
  3547. lynx::Automation a;
  3548. a.target = { lynx::AutomationTargetKind::mixerPan, 3 };
  3549. a.points = { { 0, 0.2f, 0.0f }, { 8 * lynx::ppq, 0.9f, 0.0f } };
  3550. s.automations.push_back (a);
  3551. s.playlist.clear();
  3552. for (int bar = 0; bar < 2; ++bar)
  3553. s.playlist.push_back ({ 0, 0, bar * 4 * lynx::ppq, 4 * lynx::ppq, 0 });
  3554. lynx::Clip automationClip;
  3555. automationClip.kind = lynx::ClipKind::automation;
  3556. automationClip.automation = 0;
  3557. automationClip.length = 8 * lynx::ppq;
  3558. automationClip.track = 1;
  3559. s.playlist.push_back (automationClip);
  3560. s.mode = lynx::PlayMode::song;
  3561. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-stems190gj-" + juce::String (juce::Time::currentTimeMillis()));
  3562. juce::String problems;
  3563. auto run = [&] (lynx::exportopts::Options o, const juce::String& name) {
  3564. o.stems = lynx::exportopts::Stems::mixerTracks;
  3565. o.maxTailSeconds = 3.0;
  3566. const auto alone = dir.getChildFile ("alone"), shared = dir.getChildFile ("shared");
  3567. alone.createDirectory();
  3568. shared.createDirectory();
  3569. const auto ext = juce::String (lynx::exportopts::extension (o.format));
  3570. const auto planAlone = lynx::planStemExport (s, o, alone.getChildFile (name + ext));
  3571. const auto planShared = lynx::planStemExport (s, o, shared.getChildFile (name + ext));
  3572. auto now = [] (std::function<void()> f) { f(); };
  3573. lynx::StemRunStats stats;
  3574. const auto a = lynx::runStemExport (planAlone, now, {}, {}, {}, {}, true);
  3575. const auto b = lynx::runStemExport (planShared, now, {}, {}, {}, {}, false, true, &stats);
  3576. if (a != (int) planAlone.items.size() || b != a)
  3577. problems << name << ": " << a << " / " << b << " files; ";
  3578. // (every insert from the one render, insert 5 with its side-chain too: it stays ducked as in the mix)
  3579. if (stats.passes != 1 || stats.inPass < 6)
  3580. problems << name << ": renders " << stats.passes << " shared, " << stats.inPass << " in it, " << stats.alone << " alone; ";
  3581. for (std::size_t k = 0; k < planShared.items.size() && k < planAlone.items.size(); ++k)
  3582. {
  3583. juce::MemoryBlock x, y;
  3584. planAlone.items[k].file.loadFileAsData (x);
  3585. planShared.items[k].file.loadFileAsData (y);
  3586. if (x.getSize() == 0 || x != y)
  3587. problems << name << ": " << planShared.items[k].file.getFileName() << " differs; ";
  3588. }
  3589. };
  3590. lynx::exportopts::Options streamed;
  3591. streamed.wavBits = 24;
  3592. streamed.stemsIncludeMaster = true;
  3593. run (streamed, "streamed");
  3594. lynx::exportopts::Options buffered;
  3595. buffered.wavBits = 32;
  3596. buffered.normalize = true;
  3597. run (buffered, "buffered");
  3598. dir.deleteRecursively();
  3599. return problems.isEmpty() ? juce::String ("OK") : "ERROR " + problems;
  3600. }
  3601. static juce::String faultReportSelfTest()
  3602. {
  3603. #if (JUCE_WINDOWS && (defined (_M_X64) || defined (__x86_64__))) \
  3604. || ((JUCE_LINUX || JUCE_MAC) && (defined (__x86_64__) || defined (__aarch64__)))
  3605. const auto exe = juce::File::getSpecialLocation (juce::File::currentExecutableFile);
  3606. const auto root = juce::File::getSpecialLocation (juce::File::tempDirectory)
  3607. .getChildFile ("lynx-faulttest-" + juce::String::toHexString (juce::Random::getSystemRandom().nextInt64()));
  3608. juce::StringArray problems;
  3609. #if JUCE_WINDOWS
  3610. const char* const kinds[] = { "plain", "unwalkable" };
  3611. #else
  3612. const char* const kinds[] = { "plain", "guarded", "guarded-libc", "thread", "thread-libc" };
  3613. #endif
  3614. for (const auto* kind : kinds)
  3615. {
  3616. const auto folder = root.getChildFile (kind);
  3617. folder.createDirectory();
  3618. juce::ChildProcess child;
  3619. const auto started = child.start (juce::StringArray { exe.getFullPathName(), "--faulttest", kind, folder.getFullPathName() }, 0);
  3620. if (! started || ! child.waitForProcessToFinish (60000))
  3621. {
  3622. child.kill();
  3623. problems.add (juce::String (kind) + ": " + (started ? "did not end" : "did not start"));
  3624. continue;
  3625. }
  3626. juce::String text;
  3627. for (const auto& file : folder.findChildFiles (juce::File::findFiles, false, "crash *.txt"))
  3628. text = file.loadFileAsString();
  3629. #if JUCE_WINDOWS
  3630. const auto found = text.contains ("0xc0000005");
  3631. #else
  3632. const auto found = text.contains ("segmentation fault") || text.contains ("bus error");
  3633. #endif
  3634. if (folder.getChildFile ("swallowed.txt").existsAsFile())
  3635. problems.add (juce::String (kind) + ": LYNX's own fault was caught as a plugin's ("
  3636. + folder.getChildFile ("swallowed.txt").loadFileAsString() + ")");
  3637. else if (! found)
  3638. problems.add (juce::String (kind) + ": " + (text.isEmpty() ? "no crash file" : "a crash file without the fault")
  3639. + " (exit code 0x" + juce::String::toHexString ((juce::int64) child.getExitCode()) + ")");
  3640. }
  3641. root.deleteRecursively();
  3642. return problems.isEmpty() ? juce::String ("OK") : "ERROR " + problems.joinIntoString ("; ");
  3643. #else
  3644. return "SKIPPED (Windows x64, Linux / macOS x86-64 / ARM64 only)";
  3645. #endif
  3646. }
  3647. void runSelfTest (const juce::String& reportPath, const juce::String& demoProjectPath)
  3648. {
  3649. lynx::AudioEngine offline (false);
  3650. const auto peak = offline.renderOffline (2.0, 48000.0);
  3651. const auto audioOk = peak > 0.01f && peak < 10.0f;
  3652. // project format round trip, with accents in the name
  3653. auto original = lynx::Song::makeDefault();
  3654. original.channels[0].name = "Bumbo ação";
  3655. original.playlist.push_back ({ 0, 2, 3840, 1920, 960 });
  3656. original.mode = lynx::PlayMode::song;
  3657. original.mixer[3].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::delay));
  3658. original.mixer[3].effects[0].params[1] = 0.25f;
  3659. lynx::Automation automation;
  3660. automation.name = "Pan";
  3661. automation.target = { lynx::AutomationTargetKind::effectParam, 3, 0, 1 };
  3662. automation.points = { { 0, 0.25f, 0.5f }, { 3840, 1.0f, 0.0f } };
  3663. original.automations.push_back (automation);
  3664. lynx::Clip automationClip;
  3665. automationClip.kind = lynx::ClipKind::automation;
  3666. automationClip.automation = 0;
  3667. automationClip.track = 4;
  3668. automationClip.length = 3840;
  3669. original.playlist.push_back (automationClip);
  3670. original.loopStart = 960;
  3671. original.loopEnd = 7680;
  3672. original.playlistTracks.resize (3);
  3673. original.playlistTracks[2].colour = 0xFF2A6FDB; // a track colour (round 90)
  3674. { // the clip grid (round 181a)
  3675. lynx::launcher::setClip (original, 1, 2, { 0, 0, 0, 1920, 0 });
  3676. auto& slot = *lynx::launcher::settingsAt (*original.clipGrid, 1, 2);
  3677. slot.name = "Clip ação";
  3678. slot.mode = lynx::LaunchMode::toggle;
  3679. slot.quant = lynx::LaunchQuant::eighthTriplet;
  3680. slot.legato = true;
  3681. slot.loop = false;
  3682. original.clipGrid->scenes[0].name = "Intro";
  3683. original.clipGrid->globalQuant = lynx::LaunchQuant::bars2;
  3684. }
  3685. std::uint32_t savedGroove = 0;
  3686. { // round 190bv: the groove pool, a groove on the slot's clip, and that clip copied and the copy moved
  3687. lynx::Groove g;
  3688. g.name = "Balanço";
  3689. g.base = lynx::GrooveBase::eighth;
  3690. g.quantize = 0.25f;
  3691. g.timing = 0.8f;
  3692. g.random = 0.1f;
  3693. g.velocity = -0.5f;
  3694. g.length = 1920;
  3695. g.points = { { 0, 1.0f }, { 560, 0.5f } };
  3696. savedGroove = lynx::groove::add (original.grooves, g);
  3697. original.grooves.amount = 1.2f;
  3698. lynx::groove::setClipGroove (original, 1, 2, savedGroove);
  3699. lynx::session::moveClip (original, 1, 2, 0, 1, true);
  3700. lynx::session::moveClip (original, 0, 1, 2, 0, false);
  3701. original.playlist[0].groove = savedGroove; // round 190fm: a Playlist pattern clip's groove
  3702. }
  3703. original.playlistTracks[2].grouped = true; // track groups and rack filter groups (round 104)
  3704. original.playlistTracks[1].collapsed = true;
  3705. original.channelGroups = { "Drums", "Keys" };
  3706. original.channels[1].group = 1;
  3707. original.channels[1].cutOthersOnly = original.channels[1].cutAtNoteEnd = true; // FL Studio Mobile's cut rule (round 190fe)
  3708. juce::String error;
  3709. if (demoProjectPath.isNotEmpty()) // sample project for checking the UI with --snapshot
  3710. lynx::ProjectFile::save (original, juce::File (demoProjectPath), error);
  3711. const auto reloaded = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (original), error);
  3712. // round 190bw: FL's curve modes of automation points come back from a project, tension whole; a bent point
  3713. // without a mode (a project saved before the modes: [tick, value, tension]) keeps LYNX's older law
  3714. const auto curveModesOk = [&original] {
  3715. auto song = original;
  3716. auto& a = song.automations[0];
  3717. a.points = { { 0, 0.25f, 0.5f, (std::uint8_t) lynx::flcurve::stairs },
  3718. { 960, 1.0f, -0.123456f, (std::uint8_t) lynx::flcurve::smooth },
  3719. { 1920, 0.5f, 0.0f, (std::uint8_t) lynx::flcurve::hold },
  3720. { 2400, 0.75f, 0.7f, lynx::AutomationPoint::legacyCurve },
  3721. { 2880, 0.3f, 0.0f, 0 },
  3722. { 3840, 0.6f, 0.0f, 0 } };
  3723. a.lfo.on = true;
  3724. a.lfo.amp = { { 0, 1.0f, -0.25f, (std::uint8_t) lynx::flcurve::pulse }, { 960, 0.5f, 0.0f, 0 } };
  3725. juce::String e;
  3726. const auto text = lynx::ProjectFile::toJson (song);
  3727. const auto back = lynx::ProjectFile::fromJson (text, e);
  3728. return back && back->automations.size() == 1 && back->automations[0].points == a.points && back->automations[0].lfo.amp == a.lfo.amp
  3729. && back->automations[0].valueAt (700.0) == a.valueAt (700.0) && back->automations[0].valueAt (2600.0) == a.valueAt (2600.0);
  3730. }();
  3731. const auto projectOk = curveModesOk && reloaded && reloaded->channels.size() == original.channels.size()
  3732. && reloaded->channels[0].name == original.channels[0].name
  3733. && reloaded->patterns[0].notes.size() == original.patterns[0].notes.size()
  3734. && reloaded->patterns[0].notes[3].start == original.patterns[0].notes[3].start
  3735. && reloaded->mode == lynx::PlayMode::song && reloaded->playlist.size() == 2
  3736. && reloaded->clipGrid.has_value() && reloaded->clipGrid->globalQuant == lynx::LaunchQuant::bars2
  3737. && reloaded->clipGrid->scenes.size() == 3 && reloaded->clipGrid->scenes[0].name == "Intro"
  3738. && lynx::launcher::clipAt (*reloaded->clipGrid, 1, 2) != nullptr
  3739. && [&reloaded] {
  3740. auto grid = *reloaded->clipGrid;
  3741. const auto* slot = lynx::launcher::settingsAt (grid, 1, 2);
  3742. return slot != nullptr && slot->name == "Clip ação" && slot->mode == lynx::LaunchMode::toggle
  3743. && slot->quant == lynx::LaunchQuant::eighthTriplet && slot->legato && ! slot->loop;
  3744. }()
  3745. && [&reloaded, &original, savedGroove] { // round 190bv
  3746. auto grid = *reloaded->clipGrid;
  3747. const auto* kept = lynx::launcher::settingsAt (grid, 1, 2);
  3748. const auto* moved = lynx::launcher::settingsAt (grid, 2, 0);
  3749. const auto* clip = lynx::launcher::clipAt (grid, 2, 0);
  3750. return reloaded->grooves == original.grooves && reloaded->grooves.grooves.size() == 1
  3751. && reloaded->grooves.amount == 1.2f && reloaded->grooves.grooves[0].name == "Balanço"
  3752. && reloaded->grooves.grooves[0].points.size() == 2 && savedGroove != 0
  3753. && kept != nullptr && kept->groove == savedGroove
  3754. && lynx::launcher::clipAt (grid, 0, 1) == nullptr
  3755. && clip != nullptr && clip->pattern == 0 && clip->length == 1920
  3756. && moved != nullptr && moved->groove == savedGroove && moved->name == "Clip ação"
  3757. && moved->mode == lynx::LaunchMode::toggle && moved->legato && ! moved->loop
  3758. && reloaded->playlist[0].groove == savedGroove && reloaded->playlist[1].groove == 0; // (190fm)
  3759. }()
  3760. && reloaded->playlist[1].kind == lynx::ClipKind::automation && reloaded->playlist[1].automation == 0
  3761. && reloaded->automations.size() == 1 && reloaded->automations[0].target == automation.target
  3762. && reloaded->automations[0].points.size() == 2 && reloaded->automations[0].points[0].tension == 0.5f
  3763. && reloaded->automations[0].points[1].tick == 3840
  3764. && reloaded->loopStart == 960 && reloaded->loopEnd == 7680
  3765. && reloaded->playlistTracks.size() == 3 && reloaded->playlistTracks[2].colour == 0xFF2A6FDB
  3766. && reloaded->playlistTracks[1].colour == 0
  3767. && reloaded->playlistTracks[2].grouped && reloaded->playlistTracks[1].collapsed && ! reloaded->playlistTracks[1].grouped
  3768. && reloaded->channelGroups == original.channelGroups && reloaded->channels[1].group == 1 && reloaded->channels[0].group == -1
  3769. && reloaded->channels[1].cutOthersOnly && reloaded->channels[1].cutAtNoteEnd && ! reloaded->channels[0].cutOthersOnly
  3770. && ! reloaded->channels[0].cutAtNoteEnd
  3771. && reloaded->playlist[0].offset == 960 && reloaded->playlist[0].track == 2
  3772. && reloaded->mixer[3].effects.size() == 1
  3773. && reloaded->mixer[3].effects[0].kind == lynx::EffectKind::delay
  3774. && reloaded->mixer[3].effects[0].params[1] == 0.25f;
  3775. // round trip of the newer features: synth/sampler with modulation, EQs, utility, markers
  3776. auto rich = lynx::Song::makeDefault();
  3777. auto& synth = rich.channels[4].synth;
  3778. synth.osc[1] = { lynx::Waveform::square, -1, 7.0f, 0.4f, 5, -0.25f };
  3779. synth.filterType = 2;
  3780. synth.mono = true;
  3781. synth.portaBeats = 0.125f;
  3782. synth.am = true;
  3783. synth.filterEnv = { 3.0f, 0.01f, 0.02f, 0.3f, 0.25f, 0.4f };
  3784. synth.lfo[lynx::lfoPitch] = { 0.5f, 0.25f, true, 1, 0.1f, 0.2f };
  3785. auto& sampler = rich.channels[0].sampler;
  3786. sampler.cutoff = 1200.0f;
  3787. sampler.resonance = 0.3f;
  3788. sampler.filterType = 1;
  3789. sampler.pitchEnv = { -12.0f, 0.0f, 0.0f, 0.05f, 0.0f, 0.1f };
  3790. sampler.lfo[lynx::lfoVolume] = { 0.5f, 0.5f, false, 2, 0.0f, 0.0f };
  3791. rich.mixer[2].eq.gainDb = { 3.0f, -2.5f, 1.0f };
  3792. rich.mixer[2].eq.hz[1] = 2200.0f;
  3793. auto peqSlot = lynx::makeEffectSlot (lynx::EffectKind::parametricEq);
  3794. peqSlot.params[(std::size_t) lynx::peq::param (2, 2)] = lynx::peq::gainValue (6.0);
  3795. peqSlot.params[(std::size_t) (lynx::peq::slopeParam + 0)] = lynx::peq::slopeValue (3);
  3796. rich.mixer[2].effects.push_back (peqSlot);
  3797. auto utilitySlot = lynx::makeEffectSlot (lynx::EffectKind::utility);
  3798. utilitySlot.params[1] = 0.2f;
  3799. rich.mixer[2].effects.push_back (utilitySlot);
  3800. auto vocodexSlot = lynx::makeEffectSlot (lynx::EffectKind::vocodex); // FL's raw state travels as base64
  3801. for (int i = 0; i < 300; ++i)
  3802. vocodexSlot.state.push_back ((std::uint8_t) (i * 37));
  3803. vocodexSlot.sidechain = 1;
  3804. vocodexSlot.sidechain2 = 2;
  3805. rich.mixer[3].effects.push_back (vocodexSlot);
  3806. rich.addMarker ({ 3840, "Refrão", 0, 4 });
  3807. rich.addMarker ({ 7680, {}, 7, 8 });
  3808. const auto richBack = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (rich), error);
  3809. auto paramsClose = [] (const lynx::EffectParams& a, const lynx::EffectParams& b) {
  3810. for (std::size_t i = 0; i < a.size(); ++i)
  3811. if (std::abs (a[i] - b[i]) > 1.0e-3f)
  3812. return false;
  3813. return true;
  3814. };
  3815. // round 190bu: a one-knob effect, the chain's Blend and its preset name travel in the project; a project without
  3816. // them reads as before (no goal, Blend 100 %) and writes none of the new keys
  3817. bool fx190buOk = false;
  3818. {
  3819. auto song = lynx::Song::makeDefault();
  3820. const auto plainJson = lynx::ProjectFile::toJson (song);
  3821. const auto* preset = lynx::chains::find ("Whisper Air");
  3822. if (preset != nullptr && song.mixer.size() > 2)
  3823. {
  3824. lynx::chains::apply (song, 1, *preset);
  3825. song.mixer[2].effects.push_back (lynx::goals::make (lynx::goals::room, 0.62f));
  3826. song.mixer[2].effects.push_back (lynx::goals::make (lynx::goals::bass, 0.3f));
  3827. song.mixer[2].chainBlend = 0.4f;
  3828. const auto json = lynx::ProjectFile::toJson (song);
  3829. const auto back = lynx::ProjectFile::fromJson (json, error);
  3830. const auto plainBack = lynx::ProjectFile::fromJson (plainJson, error);
  3831. auto same = back && back->mixer.size() == song.mixer.size();
  3832. for (std::size_t t = 1; same && t <= 2; ++t)
  3833. {
  3834. const auto& a = song.mixer[t];
  3835. const auto& b = back->mixer[t];
  3836. same = a.effects.size() == b.effects.size() && std::abs (a.chainBlend - b.chainBlend) < 1.0e-6f && a.chainPreset == b.chainPreset;
  3837. for (std::size_t i = 0; same && i < a.effects.size(); ++i)
  3838. same = a.effects[i].kind == b.effects[i].kind && a.effects[i].goal == b.effects[i].goal
  3839. && std::abs (a.effects[i].goalAmount - b.effects[i].goalAmount) < 1.0e-6f && a.effects[i].row == b.effects[i].row
  3840. && lynx::goals::active (b.effects[i]) == lynx::goals::active (a.effects[i]);
  3841. }
  3842. fx190buOk = same && lynx::chains::unchanged (*back, 1) && back->mixer[2].chainPreset.empty()
  3843. && ! plainJson.contains ("\"goal\"") && ! plainJson.contains ("chainBlend") && ! plainJson.contains ("chainPreset")
  3844. && json.contains ("\"goalAmount\"") && plainBack && plainBack->mixer[1].chainBlend == 1.0f
  3845. && lynx::ProjectFile::toJson (*back) == json;
  3846. // a user's chain preset file: the slots, Blend and name come back; the strip's level is not part of it
  3847. song.mixer[2].volume = 0.31f;
  3848. const auto file = lynx::ProjectFile::mixerTrackStateToJson (lynx::chains::stateOf (song.mixer[2], "Mine"));
  3849. const auto state = lynx::ProjectFile::mixerTrackStateFromJson (file, error);
  3850. fx190buOk = fx190buOk && state && state->effects.size() == 2 && state->effects[0].goal == lynx::goals::room
  3851. && lynx::goals::active (state->effects[1]) && std::abs (state->chainBlend - 0.4f) < 1.0e-6f && state->chainPreset == "Mine"
  3852. && state->volume == lynx::MixerTrack().volume;
  3853. }
  3854. }
  3855. const auto richOk = fx190buOk && richBack && richBack->channels[4].synth == synth && richBack->channels[0].sampler == sampler
  3856. && richBack->mixer[2].eq == rich.mixer[2].eq && richBack->mixer[2].effects.size() == 2
  3857. && richBack->mixer[2].effects[0].kind == lynx::EffectKind::parametricEq
  3858. && paramsClose (richBack->mixer[2].effects[0].params, peqSlot.params)
  3859. && richBack->mixer[2].effects[1].kind == lynx::EffectKind::utility
  3860. && paramsClose (richBack->mixer[2].effects[1].params, utilitySlot.params)
  3861. && richBack->mixer[3].effects.size() == 1 && richBack->mixer[3].effects[0].kind == lynx::EffectKind::vocodex
  3862. && richBack->mixer[3].effects[0].state == vocodexSlot.state && richBack->mixer[3].effects[0].sidechain2 == 2
  3863. && richBack->markers() == rich.markers();
  3864. // issue #96's per-plugin option: saved only when on; old projects (no field) read as off
  3865. bool hostKeysOk = false;
  3866. {
  3867. auto song = lynx::Song::makeDefault();
  3868. lynx::ChannelDef plugin;
  3869. plugin.instrument = lynx::InstrumentKind::plugin;
  3870. plugin.plugin.id = "x";
  3871. song.channels.push_back (plugin);
  3872. const auto channel = song.channels.size() - 1;
  3873. const auto off = lynx::ProjectFile::toJson (song);
  3874. song.channels[channel].plugin.allowHostKeys = true;
  3875. song.channels[channel].plugin.hostKeysFirst = true;
  3876. song.channels[channel].plugin.pinned = true; // (round 190ao: Pin on top)
  3877. song.channels[channel].plugin.velocityMode = lynx::prefs::pluginVelocityFixed; // (round 190ao: the plugin's own velocity)
  3878. song.channels[channel].plugin.fixedVelocity = 64;
  3879. const auto on = lynx::ProjectFile::toJson (song);
  3880. const auto offBack = lynx::ProjectFile::fromJson (off, error);
  3881. const auto onBack = lynx::ProjectFile::fromJson (on, error);
  3882. hostKeysOk = ! off.contains ("allowHostKeys") && on.contains ("allowHostKeys") && offBack && onBack
  3883. && ! offBack->channels[channel].plugin.allowHostKeys && onBack->channels[channel].plugin.allowHostKeys
  3884. && ! off.contains ("hostKeysFirst") && ! offBack->channels[channel].plugin.hostKeysFirst && onBack->channels[channel].plugin.hostKeysFirst
  3885. && ! off.contains ("pinnedOnTop") && ! offBack->channels[channel].plugin.pinned && onBack->channels[channel].plugin.pinned
  3886. && ! off.contains ("velocityMode") && ! off.contains ("fixedVelocity") && offBack->channels[channel].plugin.velocityMode == 0
  3887. && offBack->channels[channel].plugin.fixedVelocity == lynx::prefs::defaultFixedVelocity
  3888. && onBack->channels[channel].plugin.velocityMode == lynx::prefs::pluginVelocityFixed && onBack->channels[channel].plugin.fixedVelocity == 64;
  3889. }
  3890. // round 190ad: a new project has FL's plugin levels and keeps them through a save; a project saved before
  3891. // (no "pluginLevels") reads as LYNX's own law, and stays so when it opens
  3892. bool pluginLevelsOk = false;
  3893. {
  3894. const auto fresh = lynx::makeNewProject();
  3895. const auto saved = lynx::ProjectFile::toJson (fresh);
  3896. const auto back = lynx::ProjectFile::fromJson (saved, error);
  3897. auto old = lynx::Song::makeDefault(); // (what every earlier version made)
  3898. const auto oldSaved = lynx::ProjectFile::toJson (old);
  3899. const auto oldBack = lynx::ProjectFile::fromJson (oldSaved, error);
  3900. const auto stripped = lynx::ProjectFile::fromJson (saved.replace ("\"pluginLevels\"", "\"pluginLevelsGone\""), error);
  3901. pluginLevelsOk = fresh.flPluginLevels && saved.contains ("\"pluginLevels\"") && back && back->flPluginLevels
  3902. && ! old.flPluginLevels && ! oldSaved.contains ("pluginLevels") && oldBack && ! oldBack->flPluginLevels
  3903. && stripped && ! stripped->flPluginLevels;
  3904. }
  3905. // hardware output targets (REA round 156): saved only when set; old projects (no field) keep the defaults
  3906. bool hwOutOk = false;
  3907. {
  3908. auto song = lynx::Song::makeDefault();
  3909. const auto plain = lynx::ProjectFile::toJson (song);
  3910. song.mixer[0].outputChannel = lynx::outputNone;
  3911. song.mixer[1].outputChannel = 2;
  3912. song.mixer[1].outputMode = lynx::OutputMode::monoRight;
  3913. song.mixer[2].outputChannel = 6;
  3914. song.mixer[3].outputChannel = 4;
  3915. song.mixer[3].outputMode = lynx::OutputMode::monoSum;
  3916. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  3917. const auto plainBack = lynx::ProjectFile::fromJson (plain, error);
  3918. hwOutOk = back && back->mixer[0].outputChannel == lynx::outputNone && back->mixer[1].outputChannel == 2
  3919. && back->mixer[1].outputMode == lynx::OutputMode::monoRight && back->mixer[2].outputChannel == 6
  3920. && back->mixer[2].outputMode == lynx::OutputMode::stereo && back->mixer[3].outputMode == lynx::OutputMode::monoSum
  3921. && back->mixer[4].outputChannel == lynx::outputDefault && ! plain.contains ("\"output\"") && plainBack
  3922. && plainBack->mixer[0].outputChannel == lynx::outputDefault && plainBack->mixer[1].outputChannel == lynx::outputDefault;
  3923. }
  3924. // round 168j: FL's icons (channel / mixer track / playlist track), PDC Automatic / Compensate automations, Time
  3925. // settings, scale highlighting and data folder — saved only when set, old projects load with FL's defaults
  3926. bool flp168jOk = false;
  3927. {
  3928. auto song = lynx::Song::makeDefault();
  3929. const auto plain = lynx::ProjectFile::toJson (song);
  3930. song.channels[0].icon = 75;
  3931. song.mixer[2].icon = 71;
  3932. song.playlistTracks.resize (3);
  3933. song.playlistTracks[2].icon = 30;
  3934. song.autoPdc = false;
  3935. song.compensateAutomations = false;
  3936. song.timeSignatureMode = true;
  3937. song.scaleHighlight = { 10, 5 };
  3938. song.dataFolder = "D:\\Projects\\data";
  3939. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  3940. const auto plainBack = lynx::ProjectFile::fromJson (plain, error);
  3941. flp168jOk = back && back->channels[0].icon == 75 && back->mixer[2].icon == 71 && back->playlistTracks.size() >= 3
  3942. && back->playlistTracks[2].icon == 30 && ! back->autoPdc && ! back->compensateAutomations && back->timeSignatureMode
  3943. && back->scaleHighlight == song.scaleHighlight && back->dataFolder == song.dataFolder && plainBack && plainBack->autoPdc
  3944. && plainBack->compensateAutomations && ! plainBack->timeSignatureMode && plainBack->scaleHighlight == lynx::Song::ScaleHighlight {}
  3945. && plainBack->dataFolder.empty() && plainBack->channels[0].icon == 0 && ! plain.contains ("\"icon\"")
  3946. && ! plain.contains ("autoPdc") && ! plain.contains ("scaleHighlight");
  3947. }
  3948. // round 180d: clip fades take FL's S curve; a project saved before that keeps its straight fades, also after another
  3949. // save, and a clip made in it takes the S curve. FL's fade tensions and stretch mode and PITCH survive a save.
  3950. // issue #122: playlist tracks linked to inserts (audio) and channels (instrument) survive save, load and save
  3951. // again byte for byte (they were read before the mixer and fell back to Unassigned)
  3952. bool trackModes122Ok = false;
  3953. {
  3954. auto song = lynx::Song::makeDefault();
  3955. song.playlistTracks.resize (6);
  3956. song.playlistTracks[1].mode = lynx::PlaylistTrackMode::audio;
  3957. song.playlistTracks[1].mixerTrack = 3;
  3958. song.playlistTracks[4].mode = lynx::PlaylistTrackMode::audio;
  3959. song.playlistTracks[4].mixerTrack = (int) song.mixer.size() - 1;
  3960. song.playlistTracks[5].mode = lynx::PlaylistTrackMode::instrument;
  3961. song.playlistTracks[5].channel = 1;
  3962. song.playlistTracks[5].mixerTrack = 2;
  3963. const auto json = lynx::ProjectFile::toJson (song, false);
  3964. const auto loaded = lynx::ProjectFile::fromJson (json, error);
  3965. const auto again = loaded ? lynx::ProjectFile::toJson (*loaded, false) : juce::String();
  3966. trackModes122Ok = loaded && json.contains ("playlistTrackModes") && again == json && loaded->playlistTracks.size() >= 6
  3967. && loaded->playlistTracks[1].mode == lynx::PlaylistTrackMode::audio && loaded->playlistTracks[1].mixerTrack == 3
  3968. && loaded->playlistTracks[4].mode == lynx::PlaylistTrackMode::audio
  3969. && loaded->playlistTracks[4].mixerTrack == (int) song.mixer.size() - 1
  3970. && loaded->playlistTracks[5].mode == lynx::PlaylistTrackMode::instrument && loaded->playlistTracks[5].channel == 1;
  3971. }
  3972. bool clipFades180dOk = false;
  3973. {
  3974. auto song = lynx::Song::makeDefault();
  3975. lynx::Clip faded;
  3976. faded.kind = lynx::ClipKind::audio;
  3977. faded.channel = 0;
  3978. faded.length = lynx::ppq * 8;
  3979. faded.fadeIn = lynx::ppq;
  3980. faded.fadeOutTension = -812.933f;
  3981. faded.fadeOut = lynx::ppq * 2;
  3982. lynx::Clip plainClip = faded;
  3983. plainClip.fadeIn = plainClip.fadeOut = 0;
  3984. plainClip.fadeOutTension = 0.0f;
  3985. plainClip.start = lynx::ppq * 16;
  3986. song.playlist = { faded, plainClip };
  3987. song.channels[0].sampler.flStretchMode = 5;
  3988. song.channels[0].sampler.flStretchPitch = 247;
  3989. const auto json = lynx::ProjectFile::toJson (song);
  3990. const auto current = lynx::ProjectFile::fromJson (json, error);
  3991. const auto oldJson = json.replace ("\"clipFadesPerClip\"", "\"clipFadesOther\"");
  3992. auto old = lynx::ProjectFile::fromJson (oldJson, error);
  3993. auto resaved = old;
  3994. if (resaved)
  3995. {
  3996. auto added = faded;
  3997. added.start = lynx::ppq * 32;
  3998. added.linearFades = 0;
  3999. resaved->playlist.push_back (added);
  4000. resaved = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (*resaved), error);
  4001. }
  4002. clipFades180dOk = current && old && resaved && json.contains ("clipFadesPerClip") && ! oldJson.contains ("clipFadesPerClip")
  4003. && current->playlist.size() == 2 && ! current->playlist[0].linearFades
  4004. && current->playlist[0].fadeOutTension == -812.933f && ! current->playlist[1].linearFades
  4005. && current->channels[0].sampler.flStretchMode == 5 && current->channels[0].sampler.flStretchPitch == 247
  4006. && old->playlist.size() == 2 && old->playlist[0].linearFades && ! old->playlist[1].linearFades
  4007. && resaved->playlist.size() == 3 && resaved->playlist[0].linearFades && ! resaved->playlist[1].linearFades
  4008. && ! resaved->playlist[2].linearFades && resaved->playlist[0].fadeOutTension == -812.933f;
  4009. }
  4010. // FL's legacy Pattern Blocks (round 170f): the option and every arrangement's blocks are saved; a project without
  4011. // them has neither in its file and loads with the option off
  4012. bool blocksOk = false;
  4013. {
  4014. auto song = lynx::Song::makeDefault();
  4015. const auto plain = lynx::ProjectFile::toJson (song);
  4016. song.patternBlocksOn = true;
  4017. lynx::patternblocks::place (song, 0, 0);
  4018. lynx::patternblocks::place (song, 0, 4 * 4 * lynx::ppq);
  4019. lynx::patternblocks::setMuted (song, 1, true); // (round 190ht, issue #127: a muted block keeps its mute)
  4020. song.addArrangement ("Second");
  4021. lynx::patternblocks::place (song, 0, 2 * 4 * lynx::ppq);
  4022. song.selectArrangement (0);
  4023. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  4024. const auto plainBack = lynx::ProjectFile::fromJson (plain, error);
  4025. blocksOk = back && back->patternBlocksOn && back->blocks == song.blocks && song.blocks.size() == 2 && back->blocks[1].muted
  4026. && back->arrangements.size() == 2 && back->arrangements[1].blocks == song.arrangements[1].blocks
  4027. && song.arrangements[1].blocks.size() == 1 && back->songLength() == song.songLength() && plainBack
  4028. && ! plainBack->patternBlocksOn && plainBack->blocks.empty() && ! plain.contains ("blocks")
  4029. && ! plain.contains ("patternBlocks");
  4030. }
  4031. // FL's pattern clip takeover (issue #158): saved when on; a project saved before it (no key) loads with it off and
  4032. // keeps playing every overlapping clip of a pattern in full; new projects have it on
  4033. bool takeoverOk = false;
  4034. {
  4035. auto song = lynx::Song::makeDefault();
  4036. const auto plain = lynx::ProjectFile::toJson (song);
  4037. song.patternClipTakeover = true;
  4038. const auto json = lynx::ProjectFile::toJson (song);
  4039. const auto back = lynx::ProjectFile::fromJson (json, error);
  4040. const auto plainBack = lynx::ProjectFile::fromJson (plain, error);
  4041. takeoverOk = back && back->patternClipTakeover && json.contains ("patternClipTakeover") && plainBack
  4042. && ! plainBack->patternClipTakeover && ! plain.contains ("patternClipTakeover")
  4043. && lynx::makeNewProject().patternClipTakeover;
  4044. }
  4045. // comping (round 177c): a comp's equal-power crossfades (Clip::fadeCurve) and the crossfade length are saved; a
  4046. // project without them has neither in its file
  4047. bool compOk = false;
  4048. {
  4049. auto song = lynx::Song::makeDefault();
  4050. const auto plain = lynx::ProjectFile::toJson (song);
  4051. lynx::ChannelDef take;
  4052. take.instrument = lynx::InstrumentKind::audioClip;
  4053. take.samplePath = "take.wav";
  4054. song.channels.push_back (take);
  4055. lynx::Clip a;
  4056. a.kind = lynx::ClipKind::audio;
  4057. a.channel = (int) song.channels.size() - 1;
  4058. a.length = lynx::ppq;
  4059. a.fadeOut = 20;
  4060. a.fadeCurve = 2;
  4061. auto b = a;
  4062. b.start = lynx::ppq - 20;
  4063. b.fadeOut = 0;
  4064. b.fadeIn = 20;
  4065. b.fadeCurve = 1;
  4066. // round 180d's FL fade fields (indices 17..20) and the comp curve (index 21) on one clip, all kept
  4067. auto c = a;
  4068. c.start = 4 * lynx::ppq;
  4069. c.fadeIn = 30;
  4070. c.fadeInTension = -0.75f;
  4071. c.fadeOutTension = 0.5f;
  4072. c.linearFades = 2;
  4073. c.flFadeFlags = 0x1234u;
  4074. c.fadeCurve = 3;
  4075. song.playlist = { a, b, c };
  4076. song.compCrossfadeMs = 12.5f;
  4077. song.playlistTracks.resize (2);
  4078. song.playlistTracks[0].compTrack = true;
  4079. song.playlistTracks[1].grouped = true;
  4080. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  4081. const auto plainBack = lynx::ProjectFile::fromJson (plain, error);
  4082. const auto* both = back && back->playlist.size() == 3 ? &back->playlist[2] : nullptr;
  4083. compOk = back && back->playlist.size() == 3 && back->playlist[0].fadeCurve == 2 && back->playlist[1].fadeCurve == 1
  4084. && both != nullptr && both->fadeCurve == 3 && both->fadeInTension == -0.75f && both->fadeOutTension == 0.5f
  4085. && both->linearFades == 2 && both->flFadeFlags == 0x1234u && both->fadeIn == 30
  4086. && back->playlist[1].fadeIn == 20 && back->compCrossfadeMs == 12.5f && back->playlistTracks[0].compTrack && ! back->playlistTracks[1].compTrack && plainBack
  4087. && plainBack->compCrossfadeMs == lynx::Song::defaultCompCrossfadeMs && ! plain.contains ("compCrossfadeMs") && ! plain.contains ("playlistCompTracks");
  4088. }
  4089. // Misc › Mono / Porta / Slide on every generator (round 168l): kept in the file; a project saved before (an
  4090. // imported engine's flags in its synth settings) gets them back, a Max polyphony of 1 is not Mono
  4091. bool polyOk = false;
  4092. {
  4093. auto song = lynx::Song::makeDefault();
  4094. lynx::ChannelDef osc;
  4095. osc.instrument = lynx::InstrumentKind::threeosc;
  4096. osc.misc.mono = osc.misc.porta = true;
  4097. osc.misc.portaBeats = 0.25f;
  4098. song.channels.push_back (osc);
  4099. auto old = osc;
  4100. old.misc = {};
  4101. old.synth.mono = old.synth.porta = true;
  4102. old.synth.portaBeats = 0.5f;
  4103. song.channels.push_back (old);
  4104. old.maxPolyphony = 1;
  4105. song.channels.push_back (old);
  4106. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  4107. const auto n = song.channels.size();
  4108. polyOk = back && back->channels.size() == n && back->channels[n - 3].misc.mono && back->channels[n - 3].misc.porta
  4109. && std::abs (back->channels[n - 3].misc.portaBeats - 0.25f) < 1e-6f && back->channels[n - 2].misc.mono
  4110. && back->channels[n - 2].misc.porta && std::abs (back->channels[n - 2].misc.portaBeats - 0.5f) < 1e-6f
  4111. && ! back->channels[n - 1].misc.mono && back->channels[n - 1].maxPolyphony == 1
  4112. && ! back->channels[4].misc.mono; // (the LYNX Synth keeps its own flags)
  4113. }
  4114. // FL's track latency (REA round 165f-mixer): manual ms, bypass mode and master compensation saved only when set
  4115. bool latencyOk = false;
  4116. {
  4117. auto song = lynx::Song::makeDefault();
  4118. const auto plain = lynx::ProjectFile::toJson (song);
  4119. song.mixer[1].latencyMs = -20.0f;
  4120. song.mixer[2].latencyMs = 12.5f;
  4121. song.mixer[2].latencyBypass = lynx::LatencyBypass::always;
  4122. song.mixer[3].latencyBypass = lynx::LatencyBypass::whenRecordingOrStopped;
  4123. song.mixer[3].compensateMasterLatency = false;
  4124. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  4125. latencyOk = back && back->mixer[1].latencyMs == -20.0f && back->mixer[2].latencyMs == 12.5f
  4126. && back->mixer[2].latencyBypass == lynx::LatencyBypass::always
  4127. && back->mixer[3].latencyBypass == lynx::LatencyBypass::whenRecordingOrStopped && ! back->mixer[3].compensateMasterLatency
  4128. && back->mixer[4].latencyMs == 0.0f && back->mixer[4].compensateMasterLatency
  4129. && ! plain.contains ("latencyMs") && ! plain.contains ("latencyBypass") && ! plain.contains ("compensateMaster");
  4130. }
  4131. // LYNX's pre-fader sends (round 190aq): saved only when one is used, in a list of its own ("preSends") that a
  4132. // version from before ignores (its sends then play post-fader, as FL's)
  4133. bool preSendOk = false;
  4134. {
  4135. auto song = lynx::Song::makeDefault();
  4136. song.setRoute (1, 3, true, 0.5f);
  4137. song.setRoute (1, 4, true);
  4138. song.setRoute (2, 3, true);
  4139. const auto plain = lynx::ProjectFile::toJson (song);
  4140. song.setSendPre (1, 3, true);
  4141. const auto json = lynx::ProjectFile::toJson (song);
  4142. const auto back = lynx::ProjectFile::fromJson (json, error);
  4143. preSendOk = back && back->sendPre (1, 3) && ! back->sendPre (1, 4) && ! back->sendPre (2, 3)
  4144. && std::abs (back->routeLevel (1, 3) - 0.5f) < 1.0e-4f && back->mixer[1].sends == song.mixer[1].sends
  4145. && ! plain.contains ("preSends") && json.contains ("preSends")
  4146. && json.replace ("\"preSends\"", "\"preSendsOld\"") != json;
  4147. // the same file without the list (what an older version reads): the sends are there, post-fader
  4148. if (const auto old = lynx::ProjectFile::fromJson (json.replace ("\"preSends\"", "\"unknownToOldVersions\""), error))
  4149. preSendOk = preSendOk && old->routes (1, 3) && ! old->sendPre (1, 3) && old->mixer[1].sends.size() == 2;
  4150. else
  4151. preSendOk = false;
  4152. }
  4153. // LYNX's "Low latency while recording" (round 190aq): a latency-adding effect on a monitored insert's path is
  4154. // bypassed in the engine only — PDC drops, the slot is marked, the song and the saved project stay as they are —
  4155. // and it is back when the option goes off
  4156. bool lowLatencyOk = false;
  4157. {
  4158. lynx::AudioEngine live (false);
  4159. live.editSong ([] (lynx::Song& s) {
  4160. s.mixer[1].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::limiter)); // 1.5 ms look-ahead
  4161. s.mixer[1].inputChannel = 0;
  4162. s.mixer[1].monitor = lynx::InputMonitor::on;
  4163. });
  4164. const auto before = live.getLatencySamples();
  4165. const auto saved = lynx::ProjectFile::toJson (live.getSong());
  4166. const auto idle = live.lowLatencyBypassedCount() == 0; // the option is off: nothing is bypassed
  4167. auto o = live.getRecordOptions();
  4168. o.lowLatencyRecording = true;
  4169. live.setRecordOptions (o);
  4170. const auto during = live.getLatencySamples();
  4171. const auto marked = live.isSlotLowLatencyBypassed (1, 0) && live.lowLatencyBypassedLatency (1, 0) > 0 && live.lowLatencyBypassedCount() >= 1;
  4172. const auto untouched = live.getSong().mixer[1].effects[0].enabled && lynx::ProjectFile::toJson (live.getSong()) == saved;
  4173. // monitoring leaves "On" (nothing armed): the effect returns
  4174. live.editSong ([] (lynx::Song& s) { s.mixer[1].monitor = lynx::InputMonitor::whenArmed; });
  4175. const auto released = live.getLatencySamples() == before && ! live.isSlotLowLatencyBypassed (1, 0);
  4176. live.editSong ([] (lynx::Song& s) { s.mixer[1].monitor = lynx::InputMonitor::on; });
  4177. const auto again = live.getLatencySamples() == during && live.isSlotLowLatencyBypassed (1, 0);
  4178. o.lowLatencyRecording = false;
  4179. live.setRecordOptions (o);
  4180. lowLatencyOk = before > 0 && idle && during < before && marked && untouched && released && again
  4181. && live.getLatencySamples() == before && live.lowLatencyBypassedCount() == 0;
  4182. }
  4183. // The Browser's "Preview in time" (round 190aq): a loop whose name gives its tempo is stretched to the project's
  4184. // and starts on the beat; a one-shot plays as it always did; off, nothing changes
  4185. bool previewInTimeOk = false;
  4186. double previewPrepareMs = 0.0;
  4187. {
  4188. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest-preview");
  4189. dir.deleteRecursively();
  4190. dir.createDirectory();
  4191. auto writeWav = [&dir] (const juce::String& name, int frames, bool loop) {
  4192. const auto wav = dir.getChildFile (name);
  4193. juce::WavAudioFormat format;
  4194. juce::AudioBuffer<float> audio (1, frames);
  4195. for (int i = 0; i < frames; ++i) // a click on every beat of 120 BPM over a tone, or a decaying hit
  4196. audio.setSample (0, i, loop ? (i % 24000 < 400 ? 0.8f : 0.0f) + 0.1f * std::sin (0.02f * (float) i)
  4197. : 0.6f * std::exp (-(float) i / 2000.0f) * std::sin (0.05f * (float) i));
  4198. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  4199. if (auto* w = format.createWriterFor (out.get(), 48000.0, 1, 16, {}, 0))
  4200. {
  4201. out.release();
  4202. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  4203. writer->writeFromAudioSampleBuffer (audio, 0, frames);
  4204. }
  4205. return wav;
  4206. };
  4207. const auto loop = writeWav ("selftest loop 120 bpm.wav", 96000, true); // 4 beats at 120 BPM
  4208. const auto hit = writeWav ("selftest hit.wav", 14400, false); // 0.3 s
  4209. lynx::AudioEngine player (false);
  4210. const auto projectBpm = player.getTransport().bpm.load();
  4211. // off (FL's preview): nothing is prepared, the file plays as it is
  4212. player.previewFile (loop);
  4213. const auto offOk = ! player.getPreviewTiming().pending && ! player.getPreviewTiming().inTime;
  4214. player.setPreviewInTime (true);
  4215. player.previewFile (hit); // a one-shot: as it always played, at once
  4216. const auto hitOk = ! player.getPreviewTiming().pending && ! player.getPreviewTiming().inTime;
  4217. player.previewFile (loop);
  4218. const auto queued = player.getPreviewTiming().pending || std::abs (projectBpm - 120.0) < 0.2;
  4219. player.finishPreviewJobs();
  4220. const auto timing = player.getPreviewTiming();
  4221. previewPrepareMs = player.getLastPreviewPrepareMs();
  4222. const auto wanted = lynx::previewtempo::stretchRatio (120.0, projectBpm);
  4223. const auto stretchedOk = timing.inTime && ! timing.pending && timing.source == lynx::previewtempo::Source::name
  4224. && std::abs (timing.fileBpm - 120.0) < 1.0e-9 && std::abs (timing.ratio - wanted) < 1.0e-12
  4225. && std::abs ((double) timing.frames - 96000.0 * wanted) < 96000.0 * 0.01;
  4226. // the second click on the same file has its stretch ready
  4227. player.previewFile (loop);
  4228. const auto cachedOk = ! player.getPreviewTiming().pending && player.getPreviewTiming().inTime && player.getPreviewTiming().frames == timing.frames;
  4229. player.previewFile ({});
  4230. const auto stoppedOk = ! player.getPreviewTiming().inTime && player.getPreviewInTimeProgress() < 0.0;
  4231. // the start: on the next heard beat while the transport plays (sample exact), at once when it is stopped
  4232. auto firstSample = [] (bool playing, double startTick, int latency) {
  4233. lynx::Transport transport;
  4234. transport.sampleRate.store (48000.0);
  4235. transport.bpm.store (120.0); // 0.04 ticks per sample
  4236. transport.playing.store (playing);
  4237. transport.positionTicks.store (startTick);
  4238. lynx::PreviewPlayer p;
  4239. p.prepareToPlay (48000.0, 512);
  4240. p.setTransport (&transport);
  4241. p.setSyncLatency (latency);
  4242. auto dc = std::make_shared<lynx::SampleData>();
  4243. dc->sampleRate = 48000.0;
  4244. dc->left.assign (48000, 0.5f);
  4245. p.playBrowser (dc, 1.0f, true);
  4246. juce::AudioBuffer<float> block (2, 512);
  4247. juce::MidiBuffer midi;
  4248. for (int done = 0; done < 48000; done += 512)
  4249. {
  4250. p.processBlock (block, midi);
  4251. for (int i = 0; i < 512; ++i)
  4252. if (block.getSample (0, i) != 0.0f)
  4253. return done + i;
  4254. if (playing)
  4255. transport.positionTicks.store (transport.positionTicks.load() + 512 * transport.ticksPerSample());
  4256. }
  4257. return -1;
  4258. };
  4259. const auto beatOk = firstSample (true, 480.0, 0) == 12000 // half a beat to go: 480 ticks / 0.04
  4260. && firstSample (true, 480.0, 100) == 12100 // the song is heard 100 samples late (PDC)
  4261. && firstSample (true, 960.0, 0) == 0 // on a beat: now
  4262. && firstSample (false, 480.0, 0) == 0; // stopped: a free start
  4263. previewInTimeOk = loop.existsAsFile() && hit.existsAsFile() && offOk && hitOk && queued && stretchedOk && cachedOk && stoppedOk && beatOk;
  4264. dir.deleteRecursively();
  4265. }
  4266. // LYNX substitutes (round 98): a missing plugin's slot plays a built-in equivalent and the project keeps the
  4267. // original reference byte for byte (.flp record and LYNX plugin state)
  4268. bool substituteOk = false;
  4269. {
  4270. auto song = lynx::Song::makeDefault();
  4271. lynx::ForeignPlugin vv; // an .flp VST3 record (ValhallaVintageVerb's class ID), opaque state
  4272. vv.format = lynx::ForeignPlugin::Format::vst3;
  4273. const std::uint8_t cid[] = { 0x76, 0x54, 0x53, 0x56, 0x65, 0x65, 0x76, 0x33, 0x61, 0x6c, 0x68, 0x61, 0x6c, 0x6c, 0x61, 0x76 };
  4274. std::copy (std::begin (cid), std::end (cid), vv.classId.begin());
  4275. vv.hasClassId = true;
  4276. vv.name = "ValhallaVintageVerb";
  4277. vv.path = "C:\\x\\ValhallaVintageVerb.vst3";
  4278. for (int i = 0; i < 777; ++i)
  4279. vv.state.push_back ((std::uint8_t) (i * 13 + 1));
  4280. lynx::EffectSlot fromFlp;
  4281. fromFlp.kind = lynx::EffectKind::plugin;
  4282. fromFlp.plugin.foreign = vv;
  4283. lynx::EffectSlot fromLynx; // a LYNX reference whose plugin isn't installed here
  4284. fromLynx.kind = lynx::EffectKind::plugin;
  4285. fromLynx.plugin.id = "VST3-FabFilter Pro-Q 3-1a2b3c4d-5e6f7a8b";
  4286. fromLynx.plugin.name = "FabFilter Pro-Q 3";
  4287. fromLynx.plugin.state = "AAECAwQFBgcICQ==";
  4288. const auto flpRef = fromFlp.plugin, lynxRef = fromLynx.plugin;
  4289. song.mixer[1].effects = { fromFlp, fromLynx };
  4290. const auto substitutesOn = lynx::pluginSubstitutesEnabled();
  4291. const auto changed = offline.getPluginHost().applySubstitutes (song);
  4292. auto& fx = song.mixer[1].effects;
  4293. // only the LYNX reference is substituted here (an .flp record is the import's job); do the .flp one directly
  4294. const auto flpSubstituted = lynx::substituteEffectSlot (fx[0], lynx::pluginIdentity (vv));
  4295. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  4296. substituteOk = flpSubstituted && fx[0].kind == lynx::EffectKind::epochVerb
  4297. && (! substitutesOn || (changed == 1 && fx[1].kind == lynx::EffectKind::facetEq && fx[1].substituteFor == lynxRef))
  4298. && back && back->mixer[1].effects.size() == 2 && back->mixer[1].effects[0].kind == lynx::EffectKind::epochVerb
  4299. && back->mixer[1].effects[0].substituteFor == flpRef && back->mixer[1].effects[0].substituteFor.foreign.state == vv.state
  4300. && back->mixer[1].effects[1].kind == fx[1].kind && back->mixer[1].effects[1].substituteFor == fx[1].substituteFor;
  4301. }
  4302. // undo/redo
  4303. offline.editSong ([] (lynx::Song& s) { s.bpm = 99.0; });
  4304. offline.editSong ([] (lynx::Song& s) { s.bpm = 101.0; });
  4305. offline.undo();
  4306. const auto afterUndo = offline.getSong().bpm;
  4307. offline.redo();
  4308. const auto undoOk = afterUndo == 99.0 && offline.getSong().bpm == 101.0 && offline.canUndo() && ! offline.canRedo()
  4309. && offline.isModified();
  4310. // Remote-owned steps still behave as ordinary native history when no RemoteControl instance is enabled.
  4311. // Only API undo/redo refuse device drift; remote reads, staging and publication never hold the audio-device callback lock.
  4312. const auto remoteHistoryResult = []() -> juce::String {
  4313. int checks = 0;
  4314. const auto require = [&] (bool condition, const char* message) {
  4315. ++checks;
  4316. if (! condition) throw std::runtime_error (message);
  4317. };
  4318. try
  4319. {
  4320. for (const auto session : { false, true })
  4321. {
  4322. lynx::AudioEngine history (false);
  4323. lynx::Song initial;
  4324. initial.channels.resize (1);
  4325. initial.channels[0].instrument = lynx::InstrumentKind::synth;
  4326. initial.mixer = lynx::Song::defaultMixer (1);
  4327. initial.bpm = 120.0;
  4328. history.setSong (std::move (initial));
  4329. history.setSessionHistory (session);
  4330. const auto editTempo = [&] (double bpm) {
  4331. require (history.editSongRemoteTransaction ([&] (lynx::Song& s) { s.bpm = bpm; }), "remote tempo edit was not committed");
  4332. };
  4333. const auto refused = [&] (const std::function<void()>& operation) {
  4334. const auto position = history.getHistoryPosition();
  4335. const auto before = lynx::ProjectFile::toJsonExact (history.getSong());
  4336. bool changed = false;
  4337. try { operation(); }
  4338. catch (const lynx::RemoteError& e) { changed = e.code == "changed" && ! e.uncertain; }
  4339. require (changed, "API history did not refuse untracked device changes");
  4340. require (history.getHistoryPosition() == position && lynx::ProjectFile::toJsonExact (history.getSong()) == before,
  4341. "refused API history changed the project or history position");
  4342. };
  4343. const auto withoutDeviceLock = [&] (const std::function<void()>& operation) {
  4344. juce::WaitableEvent locked, release;
  4345. bool timedOut = false;
  4346. std::thread callback ([&] {
  4347. const juce::ScopedLock lock (history.getDeviceManager().getAudioCallbackLock());
  4348. locked.signal();
  4349. timedOut = ! release.wait (3000);
  4350. });
  4351. const auto acquired = locked.wait (3000);
  4352. std::exception_ptr failure;
  4353. try { if (acquired) operation(); }
  4354. catch (...) { failure = std::current_exception(); }
  4355. release.signal();
  4356. callback.join();
  4357. // Check before rethrowing: an expected rejection must not conceal waiting for this lock.
  4358. require (acquired && ! timedOut, "remote read, edit or history publication waited for the audio-device callback lock");
  4359. if (failure) std::rethrow_exception (failure);
  4360. };
  4361. const auto baseline = lynx::ProjectFile::toJsonExact (history.getSong());
  4362. const auto baselineStamp = history.getSongStamp();
  4363. const auto baselinePosition = history.getHistoryPosition();
  4364. const auto unchanged = [&] {
  4365. return history.getSongStamp() == baselineStamp && history.getHistoryPosition() == baselinePosition
  4366. && lynx::ProjectFile::toJsonExact (history.getSong()) == baseline;
  4367. };
  4368. withoutDeviceLock ([&] {
  4369. require (lynx::ProjectFile::toJsonExact (history.snapshotForRemoteControl()) == baseline,
  4370. "remote snapshot changed the project");
  4371. require (history.remoteDeviceStateHash().isNotEmpty(), "remote snapshot did not hash device state");
  4372. });
  4373. require (unchanged(), "remote reads changed the project, revision or history");
  4374. bool staged = false;
  4375. withoutDeviceLock ([&] {
  4376. require (! history.editSongRemoteTransaction ([&] (lynx::Song&) { staged = true; }),
  4377. "remote no-op committed a history step");
  4378. });
  4379. require (staged && unchanged(), "remote no-op did not stage cleanly without changing history");
  4380. bool rejected = false;
  4381. try {
  4382. withoutDeviceLock ([&] {
  4383. history.editSongRemoteTransaction ([] (lynx::Song& next) {
  4384. next.bpm = 999.0;
  4385. throw lynx::RemoteError ("invalid", "selftest stage rejection");
  4386. });
  4387. });
  4388. }
  4389. catch (const lynx::RemoteError& e) { rejected = e.code == "invalid" && ! e.uncertain; }
  4390. require (rejected && unchanged(), "rejected staging changed the project, revision or history");
  4391. for (const auto cancelAfterStage : { false, true })
  4392. {
  4393. int calls = 0;
  4394. staged = false;
  4395. bool cancelledEdit = false;
  4396. try {
  4397. withoutDeviceLock ([&] {
  4398. history.editSongRemoteTransaction ([&] (lynx::Song& next) { staged = true; next.bpm = 999.0; },
  4399. [&] { return ++calls >= (cancelAfterStage ? 2 : 1); });
  4400. });
  4401. }
  4402. catch (const lynx::RemoteError& e) { cancelledEdit = e.code == "failed" && ! e.uncertain; }
  4403. require (cancelledEdit && staged == cancelAfterStage && unchanged(),
  4404. "cancelled edit changed the project, revision or history");
  4405. }
  4406. withoutDeviceLock ([&] { editTempo (130.0); });
  4407. require (history.getSong().bpm == 130.0 && history.getHistoryPosition() == baselinePosition + 1
  4408. && history.getSongStamp() > baselineStamp, "remote commit did not publish one history step");
  4409. history.editSong ([] (lynx::Song& s) { s.channels[0].volume = 0.23f; }, false);
  4410. refused ([&] { history.undoRemoteControl(); });
  4411. withoutDeviceLock ([&] { history.undo(); });
  4412. require (history.getHistoryPosition() == 0 && history.getSong().bpm == 120.0 && history.getRemoteHistoryError().isEmpty(),
  4413. "native undo refused device drift while remote control was disabled");
  4414. history.editSong ([] (lynx::Song& s) { s.channels[0].name = "Untracked change"; }, false);
  4415. refused ([&] { history.redoRemoteControl(); });
  4416. withoutDeviceLock ([&] { history.redo(); });
  4417. require (history.getHistoryPosition() == 1 && history.getSong().bpm == 130.0 && history.getRemoteHistoryError().isEmpty(),
  4418. "native redo refused device drift while remote control was disabled");
  4419. withoutDeviceLock ([&] { editTempo (140.0); });
  4420. history.editSong ([] (lynx::Song& s) { s.channels[0].volume = 0.42f; }, false);
  4421. withoutDeviceLock ([&] { history.jumpToHistory (0); });
  4422. require (history.getHistoryPosition() == 0 && history.getSong().bpm == 120.0, "native history jump stopped at a remote step");
  4423. withoutDeviceLock ([&] { history.jumpToHistory (2); });
  4424. require (history.getHistoryPosition() == 2 && history.getSong().bpm == 140.0, "native redo jump stopped at a remote step");
  4425. withoutDeviceLock ([&] { history.undoRemoteControl(); });
  4426. require (history.getHistoryPosition() == 1 && history.getSong().bpm == 130.0, "API undo failed with an unchanged device fence");
  4427. withoutDeviceLock ([&] { history.redoRemoteControl(); });
  4428. require (history.getHistoryPosition() == 2 && history.getSong().bpm == 140.0, "API redo failed with an unchanged device fence");
  4429. int cancelledChecks = 0;
  4430. bool cancelled = false;
  4431. try { history.undoRemoteControl ([&] { return ++cancelledChecks >= 2; }); }
  4432. catch (const lynx::RemoteError& e) { cancelled = e.code == "failed" && ! e.uncertain; }
  4433. require (cancelled && history.getHistoryPosition() == 2 && history.getSong().bpm == 140.0,
  4434. "cancelled API history moved a step");
  4435. withoutDeviceLock ([&] { history.undo(); });
  4436. require (history.getHistoryPosition() == 1 && history.getSong().bpm == 130.0 && history.getRemoteHistoryError().isEmpty(),
  4437. "API cancellation leaked into native history");
  4438. }
  4439. return "OK (" + juce::String (checks) + " checks)";
  4440. }
  4441. catch (const std::exception& e) { return "ERROR " + juce::String::fromUTF8 (e.what()); }
  4442. }();
  4443. // Hosted state access and processing share a per-instance lock, including fixed blocks and deferred resets.
  4444. const auto hostedStateLockResult = []() -> juce::String {
  4445. struct Probe final : juce::AudioPluginInstance
  4446. {
  4447. struct Parameter final : juce::HostedAudioProcessorParameter
  4448. {
  4449. explicit Parameter (Probe& p) : owner (p) {}
  4450. float getValue() const override { owner.access (owner.parameterReads); return value.load(); }
  4451. void setValue (float v) override { owner.access (owner.parameterWrites); value.store (v); }
  4452. float getDefaultValue() const override { return 0.0f; }
  4453. juce::String getName (int) const override { return "Value"; }
  4454. juce::String getLabel() const override { return {}; }
  4455. juce::String getParameterID() const override { return "value"; }
  4456. float getValueForText (const juce::String& text) const override { return text.getFloatValue(); }
  4457. Probe& owner;
  4458. std::atomic<float> value { 0.0f };
  4459. };
  4460. Probe() : AudioPluginInstance (BusesProperties().withInput ("Input", juce::AudioChannelSet::stereo(), true)
  4461. .withOutput ("Output", juce::AudioChannelSet::stereo(), true))
  4462. {
  4463. addHostedParameter (std::make_unique<Parameter> (*this));
  4464. }
  4465. const juce::String getName() const override { return "State lock probe"; }
  4466. void fillInPluginDescription (juce::PluginDescription& d) const override { d.name = getName(); }
  4467. void prepareToPlay (double, int) override {}
  4468. void releaseResources() override {}
  4469. void processBlock (juce::AudioBuffer<float>& audio, juce::MidiBuffer&) override { access (blocks); audio.clear(); }
  4470. void reset() override { access (resets, std::this_thread::get_id() == ui); } // (on the UI thread: the export reset)
  4471. double getTailLengthSeconds() const override { return 0.0; }
  4472. bool acceptsMidi() const override { return true; }
  4473. bool producesMidi() const override { return false; }
  4474. bool hasEditor() const override { return false; }
  4475. juce::AudioProcessorEditor* createEditor() override { return nullptr; }
  4476. int getNumPrograms() override { return 1; }
  4477. int getCurrentProgram() override { return 0; }
  4478. void setCurrentProgram (int) override {}
  4479. const juce::String getProgramName (int) override { return {}; }
  4480. void changeProgramName (int, const juce::String&) override {}
  4481. void getStateInformation (juce::MemoryBlock& state) override { access (captures); state.replaceAll ("state", 5); }
  4482. void setStateInformation (const void*, int) override { access (restores, true); }
  4483. // Round 190ha: only a restore and the export reset are exclusive with the audio side. A capture and the
  4484. // UI's parameter changes run beside processing, as on JUCE's own hosts (UI-thread calls never overlap
  4485. // each other here: they run in turn).
  4486. void access (std::atomic<int>& calls, bool exclusive = false)
  4487. {
  4488. ++calls;
  4489. if (exclusive)
  4490. {
  4491. ++exclusiveActive;
  4492. if (active.fetch_add (1) != 0) overlap = true;
  4493. }
  4494. else
  4495. {
  4496. ++active;
  4497. if (exclusiveActive.load() != 0) overlap = true;
  4498. }
  4499. juce::Thread::sleep (1); // widen the concurrent vendor-call window without using real plugins
  4500. --active;
  4501. if (exclusive) --exclusiveActive;
  4502. }
  4503. const std::thread::id ui = std::this_thread::get_id();
  4504. std::atomic<int> active { 0 }, exclusiveActive { 0 }, blocks { 0 }, resets { 0 }, captures { 0 }, restores { 0 };
  4505. std::atomic<int> parameterReads { 0 }, parameterWrites { 0 };
  4506. std::atomic<bool> overlap { false };
  4507. };
  4508. int checks = 0;
  4509. const auto require = [&] (bool condition, const char* message) {
  4510. ++checks;
  4511. if (! condition) throw std::runtime_error (message);
  4512. };
  4513. const auto exercise = [&] (auto& adapter, Probe& probe, const auto& render, const auto& reset) {
  4514. const auto saved = adapter.captureState();
  4515. require (saved.has_value(), "mock hosted state could not be captured");
  4516. juce::WaitableEvent start (true);
  4517. std::thread audio ([&] {
  4518. start.wait();
  4519. for (int i = 0; i < 32; ++i)
  4520. {
  4521. adapter.setParameter (0, i % 2 == 0 ? 0.25f : 0.75f);
  4522. (void) adapter.parameterValue (0);
  4523. reset();
  4524. render();
  4525. }
  4526. });
  4527. const juce::ScopeGuard joinAudio { [&] { if (audio.joinable()) audio.join(); } };
  4528. start.signal();
  4529. bool stateOk = true;
  4530. for (int i = 0; i < 32; ++i)
  4531. {
  4532. stateOk = adapter.captureState().has_value() && stateOk;
  4533. stateOk = adapter.restoreState (*saved) && stateOk;
  4534. adapter.setParameterFromUi (0, i % 2 == 0 ? 0.1f : 0.9f);
  4535. if (i % 8 == 0) adapter.resetForExport();
  4536. }
  4537. audio.join();
  4538. // Contended audio callbacks may all have bypassed while state was held.
  4539. // Exercise a successful callback after release before checking coverage.
  4540. adapter.setParameter (0, 0.5f);
  4541. (void) adapter.parameterValue (0);
  4542. reset();
  4543. render();
  4544. require (stateOk && probe.blocks > 0 && probe.resets > 0 && probe.captures > 0 && probe.restores > 0,
  4545. "mock did not exercise processing, resets and hosted state access");
  4546. require (probe.parameterReads > 0 && probe.parameterWrites > 0,
  4547. "mock did not exercise concurrent hosted parameter access");
  4548. require (! probe.overlap, "hosted processing/reset/parameters overlapped a state restore or the export reset");
  4549. require (! adapter.hasCrashed(), "mock hosted adapter crashed");
  4550. };
  4551. try
  4552. {
  4553. for (const auto fixed : { 0, 64 })
  4554. {
  4555. std::array<float, 128> left {}, right {};
  4556. auto instrument = std::make_unique<Probe>();
  4557. auto* instrumentProbe = instrument.get();
  4558. lynx::PluginInstrument voice (std::move (instrument), 128, fixed);
  4559. exercise (voice, *instrumentProbe, [&] { voice.render (left.data(), right.data(), 128, 1.0f, 1.0f); }, [&] { voice.panic(); });
  4560. auto effect = std::make_unique<Probe>();
  4561. auto* effectProbe = effect.get();
  4562. lynx::PluginEffect fx (std::move (effect), 128, fixed);
  4563. exercise (fx, *effectProbe, [&] { fx.process (left.data(), right.data(), 128, {}, 120.0); }, [&] { fx.transportReset(); });
  4564. }
  4565. return "OK (" + juce::String (checks) + " checks)";
  4566. }
  4567. catch (const std::exception& e) { return "ERROR " + juce::String::fromUTF8 (e.what()); }
  4568. }();
  4569. const auto hostedStateContentionResult = lynx::pluginStateContentionSelfTest();
  4570. // recording from the PC keyboard: a one-beat note lands in the pattern, in a single undo step
  4571. // (Blend on: this checks that the take joins the pattern's notes; a new install starts with Blend off)
  4572. const auto notesBefore = offline.getSong().patterns[0].notes.size();
  4573. {
  4574. auto o = offline.getRecordOptions();
  4575. o.mode = lynx::RecordMode::overdub;
  4576. offline.setRecordOptions (o);
  4577. }
  4578. offline.setRecording (true);
  4579. offline.play();
  4580. offline.getTransport().positionTicks.store (960.0);
  4581. offline.sendLiveNote (2, 72, 0.9f, true, true);
  4582. offline.getTransport().positionTicks.store (1920.0);
  4583. offline.sendLiveNote (2, 72, 0.0f, false, true);
  4584. offline.setRecording (false);
  4585. offline.stop();
  4586. const auto& recorded = offline.getSong().patterns[0].notes;
  4587. const auto recordOk = recorded.size() == notesBefore + 1
  4588. && std::any_of (recorded.begin(), recorded.end(), [] (const lynx::Note& n) {
  4589. return n.key == 72 && n.channel == 2 && n.length == 960 && n.start >= 960 && n.start < 3840;
  4590. });
  4591. offline.undo();
  4592. const auto recordUndoOk = offline.getSong().patterns[0].notes.size() == notesBefore;
  4593. // FL's Tools › Cancel recording (round 187a): the pass's notes go, an edit made before it stays, recording turns
  4594. // off and playback goes on; nothing to redo
  4595. bool cancelRecordOk = false;
  4596. {
  4597. offline.editSong ([] (lynx::Song& s) { s.bpm = 123.0; });
  4598. const auto notesThen = offline.getSong().patterns[0].notes.size();
  4599. offline.setRecording (true);
  4600. offline.play();
  4601. offline.getTransport().positionTicks.store (960.0);
  4602. offline.sendLiveNote (2, 74, 0.9f, true, true);
  4603. offline.getTransport().positionTicks.store (1920.0);
  4604. offline.sendLiveNote (2, 74, 0.0f, false, true);
  4605. offline.sendLiveNote (2, 76, 0.9f, true, true); // (still held when the pass is cancelled)
  4606. const auto cancelled = offline.cancelRecording();
  4607. cancelRecordOk = cancelled && ! offline.isRecording() && offline.getTransport().playing.load()
  4608. && offline.getSong().patterns[0].notes.size() == notesThen && offline.getSong().bpm == 123.0 && ! offline.canRedo()
  4609. && ! offline.cancelRecording(); // (not recording: nothing to cancel)
  4610. offline.sendLiveNote (2, 76, 0.0f, false, false);
  4611. offline.stop();
  4612. }
  4613. // MIDI: exporting the pattern and importing it back gives the same notes
  4614. bool midiOk = false;
  4615. {
  4616. auto source = lynx::Song::makeDefault();
  4617. source.patterns[0].notes.push_back ({ 1000, 480, 4, 67, 0.5f });
  4618. source.patterns[0].sortNotes();
  4619. const auto midiFile = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest.mid");
  4620. juce::String midiError;
  4621. const auto saved = lynx::MidiFileIo::savePattern (source, 0, midiFile, midiError);
  4622. const auto song = saved ? lynx::MidiFileIo::loadSong (midiFile, midiError) : std::nullopt;
  4623. midiFile.deleteFile();
  4624. if (song && song->patterns.size() == 1 && song->patterns[0].notes.size() == source.patterns[0].notes.size()
  4625. && std::abs (song->bpm - source.bpm) < 0.01)
  4626. {
  4627. midiOk = true;
  4628. const auto& a = source.patterns[0].notes;
  4629. const auto& b = song->patterns[0].notes;
  4630. for (std::size_t i = 0; i < a.size(); ++i)
  4631. midiOk = midiOk && a[i].start == b[i].start && a[i].key == b[i].key && a[i].length == b[i].length;
  4632. }
  4633. }
  4634. // project package (REA round 118): a project with a sample exported as .zip, extracted and opened again,
  4635. // finds its sample inside the extracted folder
  4636. bool packageOk = false;
  4637. {
  4638. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest-package");
  4639. dir.deleteRecursively();
  4640. dir.getChildFile ("src").createDirectory();
  4641. const auto wav = dir.getChildFile ("src/hit.wav");
  4642. {
  4643. juce::WavAudioFormat format;
  4644. juce::AudioBuffer<float> hit (1, 480);
  4645. for (int i = 0; i < 480; ++i)
  4646. hit.setSample (0, i, 0.5f * std::sin (0.1f * (float) i));
  4647. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  4648. if (auto* w = format.createWriterFor (out.get(), 48000.0, 1, 16, {}, 0))
  4649. {
  4650. out.release();
  4651. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  4652. writer->writeFromAudioSampleBuffer (hit, 0, 480);
  4653. }
  4654. }
  4655. auto source = lynx::Song::makeDefault();
  4656. lynx::ChannelDef c;
  4657. c.name = "Hit";
  4658. c.instrument = lynx::InstrumentKind::sampler;
  4659. c.samplePath = wav.getFullPathName().toStdString();
  4660. source.channels.push_back (c);
  4661. lynx::ProjectPackage::Result packed;
  4662. juce::String packageError;
  4663. const auto zip = dir.getChildFile ("Beat.zip");
  4664. if (wav.existsAsFile() && lynx::ProjectPackage::exportZip (source, "Beat", zip, packed, packageError) && packed.files == 1)
  4665. {
  4666. const auto project = lynx::ProjectPackage::extractZip (zip, dir.getChildFile ("out"), packageError);
  4667. const auto song = project.existsAsFile() ? lynx::ProjectFile::load (project, packageError) : std::nullopt;
  4668. if (song && ! song->channels.empty())
  4669. {
  4670. const juce::File back (juce::String::fromUTF8 (song->channels.back().samplePath.c_str()));
  4671. packageOk = back.existsAsFile() && back.isAChildOf (project.getParentDirectory()) && back.getSize() == wav.getSize();
  4672. }
  4673. }
  4674. dir.deleteRecursively();
  4675. }
  4676. // D#92, round 180a: a non-ASCII folder and a dotted name save and load back; an unwritable place says so, and a
  4677. // relative path resolves as the start-up argument does
  4678. bool projectSaveOk = false;
  4679. {
  4680. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest-save180a");
  4681. dir.deleteRecursively();
  4682. const auto folder = dir.getChildFile (juce::String::fromUTF8 ("M\xc3\xbasica nova"));
  4683. folder.createDirectory();
  4684. const auto named = lynx::ProjectFile::withProjectExtension (folder.getChildFile (juce::String::fromUTF8 ("Can\xc3\xa7\xc3\xa3o.v2")));
  4685. auto song = lynx::Song::makeDefault();
  4686. lynx::Note note;
  4687. note.length = 240;
  4688. note.key = 64;
  4689. song.patterns[0].notes.push_back (note);
  4690. juce::String error, blockedError;
  4691. const auto again = lynx::ProjectFile::save (song, named, error) ? lynx::ProjectFile::load (named, error) : std::nullopt;
  4692. const auto blocker = dir.getChildFile ("a file");
  4693. blocker.replaceWithText ("x");
  4694. const auto cwd = juce::File::getCurrentWorkingDirectory();
  4695. folder.setAsCurrentWorkingDirectory();
  4696. const auto relative = juce::File::getCurrentWorkingDirectory().getChildFile (named.getFileName());
  4697. cwd.setAsCurrentWorkingDirectory();
  4698. projectSaveOk = named.getFileName().endsWith (".v2.lynx") && again && again->patterns[0].notes.size() == song.patterns[0].notes.size()
  4699. && relative == named && ! lynx::ProjectFile::save (song, blocker.getChildFile ("x.lynx"), blockedError)
  4700. && blockedError.isNotEmpty() && lynx::ProjectFile::withProjectExtension (named) == named;
  4701. dir.deleteRecursively();
  4702. }
  4703. // Online Sessions (round 168a): a project sent as a .lynxpack (one sample used twice is stored once, the uids
  4704. // survive), a stand-in rendered through an ExportJob, the guest's part sent back and merged by the host
  4705. juce::String sessionResult = "ERROR";
  4706. {
  4707. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest-session");
  4708. dir.deleteRecursively();
  4709. dir.getChildFile ("src").createDirectory();
  4710. const auto wav = dir.getChildFile ("src/hit.wav");
  4711. {
  4712. juce::WavAudioFormat format;
  4713. juce::AudioBuffer<float> hit (1, 4800);
  4714. for (int i = 0; i < 4800; ++i)
  4715. hit.setSample (0, i, 0.5f * std::sin (0.05f * (float) i) * (1.0f - (float) i / 4800.0f));
  4716. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  4717. if (auto* w = format.createWriterFor (out.get(), 48000.0, 1, 16, {}, 0))
  4718. {
  4719. out.release();
  4720. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  4721. writer->writeFromAudioSampleBuffer (hit, 0, 4800);
  4722. }
  4723. }
  4724. auto host = lynx::Song::makeDefault();
  4725. host.mode = lynx::PlayMode::song;
  4726. const auto copyOfWav = dir.getChildFile ("src/hit copy.wav"); // the same bytes under another name: stored once
  4727. wav.copyFileTo (copyOfWav);
  4728. for (const auto& [name, file] : { std::pair<const char*, juce::File> { "Hit", wav }, { "Hit 2", copyOfWav } })
  4729. {
  4730. lynx::ChannelDef c;
  4731. c.name = name;
  4732. c.instrument = lynx::InstrumentKind::sampler;
  4733. c.samplePath = file.getFullPathName().toStdString();
  4734. host.channels.push_back (c);
  4735. }
  4736. const auto hitChannel = (int) host.channels.size() - 2;
  4737. lynx::Note hitNote;
  4738. hitNote.channel = hitChannel;
  4739. hitNote.length = 480;
  4740. host.patterns[0].notes.push_back (hitNote);
  4741. host.playlist.push_back ({ 0, 0, 0, host.patterns[0].effectiveLength (host.meter()), 0 });
  4742. lynx::uids::normalize (host);
  4743. const auto* guest = lynx::parts::invite (host, "Host", "Ana", 0xFF3D9BE9, false);
  4744. juce::String e;
  4745. std::vector<lynx::sessionpack::Rendered> rendered;
  4746. // (a sampler stands in for a plugin channel here: render() renders whatever it is given)
  4747. const std::vector<lynx::sessionpack::RenderItem> items { { false, hitChannel, false, "Hit", "Test" } };
  4748. const auto renderedOk = guest != nullptr && lynx::sessionpack::render (host, items, 44100.0, dir.getChildFile ("stems"), "Host", rendered, {}, e)
  4749. && rendered.size() == 1 && rendered[0].standIns.size() == 2
  4750. && juce::File (juce::String::fromUTF8 (rendered[0].standIns[0].path.c_str())).getSize() > 1000;
  4751. if (renderedOk)
  4752. lynx::sessionpack::apply (host, rendered);
  4753. lynx::sessionpack::Manifest m;
  4754. m.projectName = "Selftest";
  4755. m.from = *host.session.find (lynx::session::hostTag);
  4756. m.to = *host.session.find (2);
  4757. lynx::sessionpack::WriteResult written;
  4758. const auto pack = dir.getChildFile (juce::String ("Selftest") + lynx::sessionpack::extension);
  4759. const auto packOk = renderedOk && lynx::sessionpack::write (lynx::parts::guestCopy (host, 2), m, offline.getPluginHost(), pack, written, e)
  4760. && written.media == 3 && written.duplicates == 1; // the sample once (used twice), the stand-in pair
  4761. auto opened = packOk ? lynx::sessionpack::open (pack, dir.getChildFile ("received"), e) : std::nullopt;
  4762. bool openOk = false, mergeOk = false;
  4763. if (opened && opened->corrupt.isEmpty())
  4764. {
  4765. const auto& g = opened->song;
  4766. const juce::File sample (juce::String::fromUTF8 (g.channels[(std::size_t) hitChannel].samplePath.c_str()));
  4767. openOk = g.session.me == 2 && g.projectId == host.projectId && g.channels[(std::size_t) hitChannel].uid == host.channels[(std::size_t) hitChannel].uid
  4768. && sample.existsAsFile() && sample.isAChildOf (opened->folder) && g.channels[(std::size_t) hitChannel].standIns.size() == 2
  4769. && juce::File (juce::String::fromUTF8 (g.channels[(std::size_t) hitChannel].standIns[1].path.c_str())).existsAsFile();
  4770. // the guest adds a channel and a pattern of his own, sends his part back
  4771. auto copy = g;
  4772. lynx::ChannelDef mine;
  4773. mine.name = "Ana's hit";
  4774. mine.instrument = lynx::InstrumentKind::sampler;
  4775. mine.samplePath = sample.getFullPathName().toStdString();
  4776. copy.channels.push_back (mine);
  4777. lynx::Pattern p;
  4778. p.name = "Ana";
  4779. lynx::Note note;
  4780. note.channel = (int) copy.channels.size() - 1;
  4781. note.length = 240;
  4782. note.key = 64;
  4783. p.notes.push_back (note);
  4784. copy.patterns.push_back (p);
  4785. lynx::uids::normalize (copy);
  4786. // its uids survive a save and a load
  4787. const auto saved = dir.getChildFile ("guest.lynx");
  4788. auto reloaded = lynx::ProjectFile::save (copy, saved, e) ? lynx::ProjectFile::load (saved, e) : std::nullopt;
  4789. lynx::sessionpack::Manifest back;
  4790. back.part = true;
  4791. back.from = *copy.session.self();
  4792. const auto partFile = dir.getChildFile (juce::String ("Ana part") + lynx::sessionpack::extension);
  4793. lynx::sessionpack::WriteResult partWritten;
  4794. auto part = reloaded && reloaded->channels.back().uid == copy.channels.back().uid && lynx::uids::tagOf (reloaded->channels.back().uid) == 2
  4795. ? lynx::sessionpack::write (lynx::parts::extract (*reloaded, 2), back, offline.getPluginHost(), partFile, partWritten, e)
  4796. : false;
  4797. auto partOpened = part ? lynx::sessionpack::open (partFile, dir.getChildFile ("parts"), e) : std::nullopt;
  4798. if (partOpened && partOpened->manifest.part && lynx::sessionpack::adoptMedia (partOpened->song, dir.getChildFile ("Session media/Ana"), e))
  4799. {
  4800. const auto report = lynx::parts::merge (host, partOpened->song, 2);
  4801. const auto& added = host.channels.back();
  4802. mergeOk = report.ok && report.channels >= 1 && added.name == "Ana's hit" && lynx::uids::tagOf (added.uid) == 2
  4803. && juce::File (juce::String::fromUTF8 (added.samplePath.c_str())).isAChildOf (dir.getChildFile ("Session media/Ana"))
  4804. && host.channels[(std::size_t) hitChannel].name == "Hit";
  4805. }
  4806. }
  4807. // a crafted package whose project points at a file elsewhere on this computer: opening it must not
  4808. // reach that file, or merging would copy it into the project and the next package would send it on
  4809. if (mergeOk)
  4810. {
  4811. const auto secret = dir.getChildFile ("secret.wav");
  4812. wav.copyFileTo (secret);
  4813. auto evil = lynx::Song::makeDefault();
  4814. lynx::ChannelDef c;
  4815. c.instrument = lynx::InstrumentKind::sampler;
  4816. c.samplePath = secret.getFullPathName().toStdString();
  4817. evil.channels.push_back (c);
  4818. lynx::ChannelDef keys; // (FL Keys' zones are read by the engine but are not in the media list)
  4819. keys.instrument = lynx::InstrumentKind::flkeys;
  4820. keys.zones.push_back ({});
  4821. keys.zones.back().path = c.samplePath;
  4822. evil.channels.push_back (keys);
  4823. lynx::ChannelDef patch; // (a Patcher's nodes are not in the media list either)
  4824. patch.instrument = lynx::InstrumentKind::patcher;
  4825. patch.patcher.nodes.resize (2);
  4826. patch.patcher.nodes[0].generator = true;
  4827. patch.patcher.nodes[0].channel = c;
  4828. patch.patcher.nodes[1].effect.samplePath = c.samplePath;
  4829. evil.channels.push_back (patch);
  4830. evil.mixer[1].recordTo = dir.getChildFile ("overwritten.wav").getFullPathName().toStdString();
  4831. const auto evilProject = dir.getChildFile ("evil.lynx");
  4832. lynx::sessionpack::Manifest em;
  4833. em.part = true;
  4834. juce::ZipFile::Builder b;
  4835. const auto json = lynx::sessionpack::manifestToJson (em);
  4836. b.addEntry (new juce::MemoryInputStream (json.toRawUTF8(), json.getNumBytesAsUTF8(), true), 0, "manifest.json", {});
  4837. const auto evilPack = dir.getChildFile (juce::String ("Evil") + lynx::sessionpack::extension);
  4838. bool zipped = false;
  4839. if (lynx::ProjectFile::save (evil, evilProject, e))
  4840. {
  4841. b.addFile (evilProject, 0, "project.lynx");
  4842. juce::FileOutputStream out (evilPack);
  4843. zipped = out.openedOk() && b.writeToStream (out, nullptr);
  4844. }
  4845. auto evilOpened = zipped ? lynx::sessionpack::open (evilPack, dir.getChildFile ("evil"), e) : std::nullopt;
  4846. const auto media = dir.getChildFile ("Session media/Evil");
  4847. mergeOk = evilOpened && lynx::sessionpack::adoptMedia (evilOpened->song, media, e)
  4848. && std::none_of (evilOpened->song.channels.begin(), evilOpened->song.channels.end(), [&] (const lynx::ChannelDef& ch) {
  4849. return juce::File (juce::String::fromUTF8 (ch.samplePath.c_str())) == secret
  4850. || std::any_of (ch.zones.begin(), ch.zones.end(), [&] (const lynx::SampleZone& z) { return juce::File (juce::String::fromUTF8 (z.path.c_str())) == secret; });
  4851. })
  4852. && evilOpened->song.channels.back().patcher.nodes.size() == 2
  4853. && juce::File (juce::String::fromUTF8 (evilOpened->song.channels.back().patcher.nodes[0].channel.samplePath.c_str())) != secret
  4854. && juce::File (juce::String::fromUTF8 (evilOpened->song.channels.back().patcher.nodes[1].effect.samplePath.c_str())) != secret
  4855. && evilOpened->song.mixer[1].recordTo.empty()
  4856. && media.findChildFiles (juce::File::findFiles, true).isEmpty();
  4857. if (! mergeOk && e.isEmpty())
  4858. e = "a received package reached a file outside it";
  4859. }
  4860. // ... nor through its own folder: "..", Windows' dotted names (". ." climbs like ".." there), and a manifest
  4861. // media entry outside the package (it must not even be read: "/dev/zero" would never end)
  4862. if (mergeOk)
  4863. {
  4864. const auto secret = dir.getChildFile ("secret.wav");
  4865. const auto folder = dir.getChildFile ("evil2").getChildFile ("Evil2"); // (where open() will unpack it)
  4866. const auto climb = folder.getFullPathName() + "/media/../../../secret.wav";
  4867. const auto dotted = folder.getFullPathName() + "/. ./.. ./secret.wav";
  4868. auto evil = lynx::Song::makeDefault();
  4869. for (const auto& path : { climb, dotted })
  4870. {
  4871. lynx::ChannelDef c;
  4872. c.instrument = lynx::InstrumentKind::sampler;
  4873. c.samplePath = path.toStdString();
  4874. evil.channels.push_back (c);
  4875. }
  4876. juce::MemoryBlock secretBytes;
  4877. secret.loadFileAsData (secretBytes);
  4878. lynx::sessionpack::Manifest em;
  4879. em.part = true;
  4880. em.media.push_back ({ "sha256-" + juce::String (lynx::sha256Hex ((const std::uint8_t*) secretBytes.getData(), secretBytes.getSize())),
  4881. "secret.wav", (juce::int64) secretBytes.getSize(), "../../secret.wav" });
  4882. const auto evilProject = dir.getChildFile ("evil2.lynx");
  4883. juce::ZipFile::Builder b;
  4884. const auto json = lynx::sessionpack::manifestToJson (em);
  4885. b.addEntry (new juce::MemoryInputStream (json.toRawUTF8(), json.getNumBytesAsUTF8(), true), 0, "manifest.json", {});
  4886. const auto evilPack = dir.getChildFile (juce::String ("Evil2") + lynx::sessionpack::extension);
  4887. bool zipped = false;
  4888. if (lynx::ProjectFile::save (evil, evilProject, e))
  4889. {
  4890. b.addFile (evilProject, 0, "project.lynx");
  4891. juce::FileOutputStream out (evilPack);
  4892. zipped = out.openedOk() && b.writeToStream (out, nullptr);
  4893. }
  4894. auto evilOpened = zipped ? lynx::sessionpack::open (evilPack, dir.getChildFile ("evil2"), e) : std::nullopt;
  4895. const auto media = dir.getChildFile ("Session media/Evil2");
  4896. mergeOk = evilOpened && evilOpened->folder == folder && evilOpened->corrupt.contains ("secret.wav")
  4897. && lynx::sessionpack::adoptMedia (evilOpened->song, media, e) && evilOpened->song.channels.size() >= 2
  4898. && std::none_of (evilOpened->song.channels.begin(), evilOpened->song.channels.end(), [&] (const lynx::ChannelDef& ch) {
  4899. const auto p = juce::String::fromUTF8 (ch.samplePath.c_str());
  4900. return p == climb || p == dotted || (juce::File::isAbsolutePath (p) && juce::File (p) == secret);
  4901. })
  4902. && media.findChildFiles (juce::File::findFiles, true).isEmpty();
  4903. if (! mergeOk && e.isEmpty())
  4904. e = "a received package climbed out of its folder";
  4905. }
  4906. if (! packOk && e.isEmpty())
  4907. e = "media " + juce::String (written.media) + ", duplicates " + juce::String (written.duplicates) + ", missing "
  4908. + written.missing.joinIntoString (";");
  4909. sessionResult = mergeOk ? juce::String ("OK")
  4910. : "ERROR (" + juce::String (renderedOk ? packOk ? openOk ? "merge" : "open" : "pack" : "render") + (e.isEmpty() ? "" : ": " + e) + ")";
  4911. dir.deleteRecursively();
  4912. }
  4913. // WavPack: a .wv from the FL packs (if installed) opens through the sample loader
  4914. juce::String wavpack = "NO_FL";
  4915. {
  4916. const auto roots = lynx::findFlStudioRoots();
  4917. const auto packs = juce::File (juce::String::fromUTF8 (roots.data.c_str())).getChildFile ("Patches/Packs");
  4918. const auto found = packs.isDirectory() ? packs.findChildFiles (juce::File::findFiles, true, "*.wv") : juce::Array<juce::File> {};
  4919. if (! found.isEmpty())
  4920. {
  4921. lynx::SampleLibrary library;
  4922. const auto sample = library.load (found.getFirst().getFullPathName());
  4923. float peakWv = 0.0f;
  4924. if (sample != nullptr)
  4925. for (std::size_t i = 0; i < sample->frames(); ++i)
  4926. peakWv = std::max (peakWv, std::abs (sample->leftData()[i]));
  4927. wavpack = sample != nullptr && sample->frames() > 0 && peakWv > 1e-4f ? "OK" : "ERROR";
  4928. }
  4929. }
  4930. // every built-in effect's editor and engine with extreme settings (round 111): a crash or NaN output fails here
  4931. const auto effectsOk = runEffectFuzz (4, {}); // (no mouse drags: nothing may open on screen)
  4932. // FL's Patcher (round 141): a mixer slot and a generator channel with their graphs survive save / load, and the
  4933. // generator one plays through the rack
  4934. bool patcherOk = false;
  4935. {
  4936. auto song = lynx::Song::makeDefault();
  4937. song.mixer.resize (4);
  4938. auto slot = lynx::makeEffectSlot (lynx::EffectKind::patcher);
  4939. lynx::PatchNode reverb, gain;
  4940. reverb.effect = lynx::makeEffectSlot (lynx::EffectKind::utility); // (exact defaults: params are saved to 4 decimals)
  4941. reverb.label = "Room";
  4942. reverb.x = 120.5f;
  4943. reverb.y = 40.0f;
  4944. gain.effect = lynx::makeEffectSlot (lynx::EffectKind::utility);
  4945. gain.effect.enabled = false;
  4946. slot.patcher.nodes = { reverb, gain };
  4947. lynx::PatchWire a, b, c, control;
  4948. a.to = 0;
  4949. b.from = 0, b.to = 1, b.gain = 0.5f;
  4950. c.from = 1;
  4951. control.kind = lynx::PatchWire::Kind::control, control.from = 0, control.to = 1, control.toPort = 0, control.curve = { 0.0f, 0.25f, 1.0f };
  4952. slot.patcher.wires = { a, b, c, control };
  4953. slot.patcher.outputTracks = { 3 };
  4954. song.mixer[1].effects = { slot };
  4955. lynx::ChannelDef ch;
  4956. ch.name = "Patched";
  4957. ch.instrument = lynx::InstrumentKind::patcher;
  4958. lynx::PatchNode synth;
  4959. synth.generator = true;
  4960. synth.channel.instrument = lynx::InstrumentKind::synth;
  4961. synth.channel.name = "Synth";
  4962. ch.patcher.nodes = { synth };
  4963. lynx::PatchWire notes, out;
  4964. notes.kind = lynx::PatchWire::Kind::midi, notes.to = 0;
  4965. out.from = 0;
  4966. ch.patcher.wires = { notes, out };
  4967. // round 162: the I/O nodes' MIDI pins and a MIDI Out node between them
  4968. lynx::PatchNode midiOutNode;
  4969. midiOutNode.generator = true;
  4970. midiOutNode.channel.instrument = lynx::InstrumentKind::midiOut;
  4971. lynx::midictl::writeMidiOut (midiOutNode.channel.pluginState, { 4, 0, 0, -1, -1 });
  4972. ch.patcher.nodes.push_back (midiOutNode);
  4973. lynx::PatchWire portIn, portOut;
  4974. portIn.kind = portOut.kind = lynx::PatchWire::Kind::midi;
  4975. portIn.fromPort = lynx::patchMidiPortPin (7), portIn.to = 1;
  4976. portOut.from = 1, portOut.to = lynx::patchToHost, portOut.toPort = 9;
  4977. ch.patcher.wires.push_back (portIn);
  4978. ch.patcher.wires.push_back (portOut);
  4979. ch.patcher.fromMidiPorts = { 2, 7 };
  4980. ch.patcher.toMidiPorts = { 9, 11 };
  4981. ch.patcher.fromNotesHidden = true;
  4982. song.channels.push_back (ch);
  4983. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  4984. patcherOk = back && back->mixer.size() >= 2 && back->mixer[1].effects.size() == 1
  4985. && back->mixer[1].effects[0].kind == lynx::EffectKind::patcher && back->mixer[1].effects[0].patcher == slot.patcher
  4986. && back->channels.back().instrument == lynx::InstrumentKind::patcher && back->channels.back().patcher.nodes.size() == 2
  4987. && back->channels.back().patcher.fromMidiPorts == ch.patcher.fromMidiPorts
  4988. && back->channels.back().patcher.toMidiPorts == ch.patcher.toMidiPorts && back->channels.back().patcher.fromNotesHidden
  4989. && back->channels.back().patcher.nodes[1].channel.pluginState == midiOutNode.channel.pluginState
  4990. && back->channels.back().patcher.nodes[0].generator
  4991. && back->channels.back().patcher.nodes[0].channel.instrument == lynx::InstrumentKind::synth
  4992. && back->channels.back().patcher.wires == ch.patcher.wires;
  4993. }
  4994. // Round 183c, Racks: (1) a plain Patcher's stored JSON loads and saves back byte for byte and never holds a
  4995. // "rack" key (FL's Patcher is untouched); (2) an Audio Effect Rack slot and an Instrument Rack channel survive save /
  4996. // load with their chains, zones, macros, mappings, variations and compiled cables
  4997. juce::String rackResult = "OK";
  4998. {
  4999. lynx::MixerTrack plain;
  5000. plain.name = "Plain Patcher";
  5001. auto fx = lynx::makeEffectSlot (lynx::EffectKind::patcher);
  5002. lynx::PatchNode a, b;
  5003. a.effect = lynx::makeEffectSlot (lynx::EffectKind::utility);
  5004. a.label = "A";
  5005. a.x = 120.5f;
  5006. b.effect = lynx::makeEffectSlot (lynx::EffectKind::utility);
  5007. b.effect.enabled = false;
  5008. fx.patcher.nodes = { a, b };
  5009. lynx::PatchWire w1, w2, w3, wc;
  5010. w1.to = 0;
  5011. w2.from = 0, w2.to = 1, w2.gain = 0.5f;
  5012. w3.from = 1;
  5013. wc.kind = lynx::PatchWire::Kind::control, wc.from = 0, wc.to = 1, wc.toPort = 0, wc.curve = { 0.0f, 0.25f, 1.0f };
  5014. fx.patcher.wires = { w1, w2, w3, wc };
  5015. lynx::SurfaceControl knob;
  5016. knob.name = "Drive";
  5017. knob.value = 0.25f;
  5018. fx.patcher.surface = { knob };
  5019. lynx::PatchParam pp;
  5020. pp.node = 0, pp.param = 1, pp.name = "Balance";
  5021. fx.patcher.published = { pp };
  5022. plain.effects = { fx };
  5023. const auto first = juce::JSON::toString (lynx::ProjectFile::mixerTrackToVar (plain), true);
  5024. const auto again = juce::JSON::toString (lynx::ProjectFile::mixerTrackToVar (lynx::ProjectFile::mixerTrackFromVar (juce::JSON::parse (first))), true);
  5025. if (first != again || first.contains ("\"rack\"") || first.contains ("rackMixer"))
  5026. rackResult = "ERROR plain Patcher changed";
  5027. auto song = lynx::Song::makeDefault();
  5028. song.mixer.resize (3);
  5029. auto rackSlot = lynx::rack::makeRackSlot (lynx::RackDoc::Kind::audioEffect);
  5030. auto& doc = rackSlot.patcher;
  5031. lynx::PatchNode u;
  5032. u.effect = lynx::makeEffectSlot (lynx::EffectKind::utility);
  5033. const auto n0 = lynx::rack::addDevice (doc, 0, u);
  5034. lynx::rack::addChain (doc, "Wet");
  5035. lynx::rack::addDevice (doc, 1, u);
  5036. doc.rack[0].chains[1].select = { 10, 90, 30, 70 };
  5037. lynx::rack::setChainPan (doc, 1, -0.5f);
  5038. lynx::RackMapping m;
  5039. m.node = n0, m.param = 0, m.min = 0.2f, m.max = 0.9f;
  5040. lynx::rack::map (doc, 0, m);
  5041. lynx::RackMapping v;
  5042. v.target = lynx::RackMapping::Target::chainVolume, v.chain = 1, v.min = 0.0f, v.max = lynx::rack::unityVolume;
  5043. lynx::rack::map (doc, 1, v);
  5044. lynx::rack::setMacro (doc, 0, 64.0f);
  5045. lynx::rack::storeVariation (doc);
  5046. lynx::rack::setMacro (doc, 0, 100.0f);
  5047. lynx::rack::storeVariation (doc);
  5048. doc.rack[0].morphOn = true, doc.rack[0].morphA = 0, doc.rack[0].morphB = 1;
  5049. lynx::rack::setMorph (doc, 0.5f);
  5050. lynx::rack::compile (doc);
  5051. song.mixer[1].effects = { rackSlot };
  5052. lynx::ChannelDef inst;
  5053. inst.name = "Instrument Rack";
  5054. inst.instrument = lynx::InstrumentKind::patcher;
  5055. inst.patcher = lynx::rack::makeRack (lynx::RackDoc::Kind::instrument);
  5056. lynx::PatchNode synth;
  5057. synth.generator = true;
  5058. synth.channel.instrument = lynx::InstrumentKind::synth;
  5059. synth.channel.name = "Synth";
  5060. lynx::rack::addDevice (inst.patcher, 0, synth);
  5061. inst.patcher.rack[0].chains[0].velocity = { 1, 127, 64, 127 };
  5062. lynx::rack::compile (inst.patcher);
  5063. song.channels.push_back (inst);
  5064. const auto json = lynx::ProjectFile::toJson (song);
  5065. const auto back = lynx::ProjectFile::fromJson (json, error);
  5066. // (the devices' parameters are stored to 4 decimals: the documents are compared as stored, the rack exactly)
  5067. const auto loaded = back && back->mixer.size() >= 2 && back->mixer[1].effects.size() == 1;
  5068. const auto& got = loaded ? back->mixer[1].effects[0].patcher : doc;
  5069. if (! loaded)
  5070. rackResult = "ERROR rack slot not loaded";
  5071. else if (got.rack != doc.rack)
  5072. rackResult = "ERROR rack model";
  5073. else if (got.wires != doc.wires)
  5074. rackResult = "ERROR rack cables";
  5075. else if (got.nodes.size() != doc.nodes.size())
  5076. rackResult = "ERROR rack devices";
  5077. else if (back->channels.back().patcher.rack != inst.patcher.rack || back->channels.back().patcher.wires != inst.patcher.wires
  5078. || back->channels.back().patcher.zones != inst.patcher.zones || back->channels.back().patcher.nodes.size() != inst.patcher.nodes.size())
  5079. rackResult = "ERROR instrument rack";
  5080. // the slot's insert as stored, once more: the same text (the stored form is stable)
  5081. else if (const auto once = juce::JSON::toString (lynx::ProjectFile::mixerTrackToVar (back->mixer[1]), true);
  5082. once != juce::JSON::toString (lynx::ProjectFile::mixerTrackToVar (lynx::ProjectFile::mixerTrackFromVar (juce::JSON::parse (once))), true))
  5083. rackResult = "ERROR rack stored form not stable";
  5084. }
  5085. // Round 190ec, Drum Rack: pads (Receive / Play / Choke / Audio To / sends), return chains and the views survive save /
  5086. // load with their compiled zones and cables
  5087. if (rackResult == "OK")
  5088. {
  5089. lynx::Song song;
  5090. song.mixer.resize (2);
  5091. lynx::ChannelDef ch;
  5092. ch.name = "Drums";
  5093. ch.instrument = lynx::InstrumentKind::patcher;
  5094. ch.patcher = lynx::rack::makeDrumRack();
  5095. lynx::PatchNode synth;
  5096. synth.generator = true;
  5097. synth.channel.instrument = lynx::InstrumentKind::synth;
  5098. const auto kick = lynx::rack::addPad (ch.patcher, 36, "Kick", synth);
  5099. const auto hat = lynx::rack::addPad (ch.patcher, 42, "Hat", synth);
  5100. lynx::rack::addPad (ch.patcher, -1, "Every note");
  5101. lynx::rack::addReturn (ch.patcher, "A Verb");
  5102. lynx::rack::setPlay (ch.patcher, kick, 64);
  5103. lynx::rack::setChoke (ch.patcher, hat, 2);
  5104. lynx::rack::setSend (ch.patcher, hat, 0, 0.25f, false);
  5105. lynx::rack::setAudioTo (ch.patcher, kick, 0);
  5106. lynx::rack::rackOf (ch.patcher)->showIO = true;
  5107. lynx::rack::rackOf (ch.patcher)->padScroll = 17;
  5108. song.channels.push_back (ch);
  5109. juce::String error;
  5110. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  5111. const auto& got = back && ! back->channels.empty() ? back->channels.back().patcher : lynx::PatcherDoc {};
  5112. if (! back || ! lynx::rack::isDrumRack (got))
  5113. rackResult = "ERROR drum rack not loaded";
  5114. else if (got.rack != ch.patcher.rack)
  5115. rackResult = "ERROR drum rack model";
  5116. else if (got.zones != ch.patcher.zones || got.wires != ch.patcher.wires)
  5117. rackResult = "ERROR drum rack cables";
  5118. }
  5119. // FL engines in a native project (round 142, issue #5): every engine this PC can make survives save / load and
  5120. // the instruments play through the rack
  5121. juce::String nativesResult = "OK";
  5122. int nativesMade = 0, nativesSilent = 0;
  5123. {
  5124. auto song = lynx::Song::makeDefault();
  5125. song.channels.clear();
  5126. song.patterns[0].notes.clear();
  5127. song.mixer.resize (3);
  5128. const auto& fl = lynx::flStudioAccess();
  5129. for (const auto& e : lynx::natives::instrumentEngines())
  5130. if (lynx::natives::available (e, fl))
  5131. if (auto c = lynx::natives::makeChannel (e.kind, fl))
  5132. {
  5133. c->mixerTrack = 1;
  5134. song.channels.push_back (*c);
  5135. }
  5136. for (const auto& e : lynx::natives::effectEngines())
  5137. if (auto fx = lynx::natives::makeSlot (e.kind, fl))
  5138. song.mixer[2].effects.push_back (*fx);
  5139. nativesMade = (int) (song.channels.size() + song.mixer[2].effects.size());
  5140. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  5141. auto same = back && back->channels.size() == song.channels.size() && back->mixer.size() >= 3
  5142. && back->mixer[2].effects.size() == song.mixer[2].effects.size();
  5143. for (std::size_t i = 0; same && i < song.channels.size(); ++i)
  5144. {
  5145. const auto& a = song.channels[i];
  5146. const auto& b = back->channels[i];
  5147. same = a.instrument == b.instrument && a.pluginState == b.pluginState && a.samplePath == b.samplePath && a.zones.size() == b.zones.size()
  5148. && a.modelParams.size() == b.modelParams.size();
  5149. if (! same)
  5150. nativesResult = "ERROR channel " + juce::String::fromUTF8 (a.name.c_str());
  5151. }
  5152. for (std::size_t i = 0; same && i < song.mixer[2].effects.size(); ++i)
  5153. {
  5154. const auto& a = song.mixer[2].effects[i];
  5155. const auto& b = back->mixer[2].effects[i];
  5156. same = a.kind == b.kind && a.state == b.state;
  5157. for (std::size_t p = 0; same && p < a.params.size(); ++p)
  5158. same = std::abs (a.params[p] - b.params[p]) < 1.0e-3f;
  5159. if (! same)
  5160. nativesResult = juce::String ("ERROR effect ") + lynx::effectInfo (a.kind).name;
  5161. }
  5162. if (! back)
  5163. nativesResult = "ERROR " + error;
  5164. // each instrument plays a note alone. The Granulizer and Wave Traveller play the channel's sample, and a new
  5165. // one has none (a PC without FL Studio, macOS / Linux: FL's presets are not there either), so they get a
  5166. // generated one: a second of a 220 Hz tone (round 167m, PR #19: Wave Traveller was "SILENT 1" on macOS)
  5167. const auto toneWav = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest-natives.wav");
  5168. {
  5169. juce::WavAudioFormat format;
  5170. juce::AudioBuffer<float> tone (1, 48000);
  5171. for (int i = 0; i < 48000; ++i)
  5172. tone.setSample (0, i, 0.5f * std::sin (juce::MathConstants<float>::twoPi * 220.0f * (float) i / 48000.0f));
  5173. toneWav.deleteFile();
  5174. std::unique_ptr<juce::OutputStream> out (toneWav.createOutputStream().release());
  5175. if (auto* w = format.createWriterFor (out.get(), 48000.0, 1, 16, {}, 0))
  5176. {
  5177. out.release();
  5178. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  5179. writer->writeFromAudioSampleBuffer (tone, 0, 48000);
  5180. }
  5181. }
  5182. juce::StringArray silentNames;
  5183. for (std::size_t i = 0; same && i < song.channels.size(); ++i)
  5184. {
  5185. auto one = song;
  5186. one.channels = { song.channels[i] };
  5187. one.channels[0].mixerTrack = 1;
  5188. const auto kind = song.channels[i].instrument;
  5189. // A new Fruity Slicer has no sample and no slices, and FL's is silent then too (round 180c), so it is
  5190. // not one of the engines that must sound here (Linux / macOS CI: "SILENT 1 [Fruity Slicer]", 0.1.25)
  5191. if (kind == lynx::InstrumentKind::fruityslicer && one.channels[0].samplePath.empty())
  5192. continue;
  5193. if (kind == lynx::InstrumentKind::slicex && one.channels[0].samplePath.empty()) // (the same: no sample on its decks yet)
  5194. continue;
  5195. if (kind == lynx::InstrumentKind::directwave && one.channels[0].zones.empty()) // (FL's new DirectWave: no zones yet, round 190hz)
  5196. continue;
  5197. if ((kind == lynx::InstrumentKind::granulizer || kind == lynx::InstrumentKind::wavetraveller) && one.channels[0].samplePath.empty())
  5198. one.channels[0].samplePath = toneWav.getFullPathName().toStdString();
  5199. one.mixer[2].effects.clear();
  5200. // Drumaxx plays pad 1's key: FL's default kit has a pad at 48, LYNX's own bank kits (a PC without FL,
  5201. // macOS / Linux; round 168p) start at 36 (round 169d: "SILENT 1 [Drumaxx]" on the Linux / macOS CI)
  5202. auto key = 60;
  5203. if (kind == lynx::InstrumentKind::drumaxx)
  5204. {
  5205. const auto padKey = lynx::drumaxxParam (one.channels[0].pluginState, 4);
  5206. key = std::isfinite (padKey) && padKey >= 0.0f && padKey <= 127.0f ? (int) padKey : 48;
  5207. }
  5208. // FPC plays its pads' keys; a kit without a sample (FL's "Empty" kit: no FL Studio on this PC) is silent
  5209. // in FL too (round 190q)
  5210. if (kind == lynx::InstrumentKind::fpc)
  5211. {
  5212. const auto pads = lynx::fpcChannelPads (one.channels[0]);
  5213. if (pads.empty())
  5214. continue;
  5215. key = pads.front().key;
  5216. }
  5217. one.patterns[0].notes = { { 0, 1920, 0, key, 0.8f } };
  5218. lynx::AudioEngine player (false);
  5219. player.setSong (std::move (one));
  5220. player.dispatchPendingMessages();
  5221. if (! (player.renderOffline (1.0, 48000.0) > 1.0e-4f))
  5222. {
  5223. ++nativesSilent;
  5224. silentNames.add (juce::String::fromUTF8 (song.channels[i].name.c_str()));
  5225. }
  5226. }
  5227. toneWav.deleteFile();
  5228. if (nativesSilent > 0 && nativesResult == "OK")
  5229. nativesResult = "SILENT " + juce::String (nativesSilent) + " [" + silentNames.joinIntoString (", ") + "]";
  5230. }
  5231. const auto nativesOk = nativesResult == "OK";
  5232. // The metronome as FL 2026 plays it (round 165z-a2): FL's five sounds from its install, the downbeat at
  5233. // 0.9404 × the Tick two semitones up, into the Master ("---") by default; insert 2 as its track plays it through
  5234. // insert 2 (muted: silent); never in an export
  5235. juce::String metronomeResult = "OK";
  5236. int metronomeFlSounds = 0;
  5237. float metronomeMaster = 0.0f;
  5238. {
  5239. const auto& flData = lynx::flStudioAccess().roots.data;
  5240. const auto sounds = lynx::Metronome::loadSounds (flData.empty() ? juce::File() : lynx::platform::localFile (flData));
  5241. for (const auto& s : sounds)
  5242. metronomeFlSounds += s.fromFl ? 1 : 0;
  5243. auto renderClick = [] (int track, bool muteInsert, bool include) {
  5244. auto song = lynx::Song::makeDefault();
  5245. song.channels.clear();
  5246. song.playlist.clear();
  5247. for (auto& p : song.patterns)
  5248. p.notes.clear();
  5249. song.mixer[0].effects.clear(); // (the default Master limiter)
  5250. song.mixer[2].muted = muteInsert;
  5251. lynx::AudioEngine player (false);
  5252. player.setSong (std::move (song));
  5253. player.dispatchPendingMessages();
  5254. auto& t = player.getTransport();
  5255. t.metronome = true;
  5256. t.metronomeSound = 1; // Tick
  5257. t.metronomeTrack = track;
  5258. lynx::AudioEngine::RenderOptions o;
  5259. o.seconds = 0.25;
  5260. o.sampleRate = 44100.0;
  5261. o.pluginWarmUp = false;
  5262. o.includeMetronome = include;
  5263. return player.renderOffline (o);
  5264. };
  5265. metronomeMaster = renderClick (0, false, true);
  5266. const auto insert = renderClick (2, false, true);
  5267. const auto muted = renderClick (2, true, true);
  5268. const auto exported = renderClick (0, false, false);
  5269. // FL's Tick peaks at 1.0: its downbeat at most 0.9404 (the interpolation may land between peaks)
  5270. const auto expectHigh = metronomeFlSounds == lynx::metronome::soundCount ? lynx::metronome::downbeatGain + 1.0e-3f : 1.0f;
  5271. if (! (metronomeMaster > 0.5f && metronomeMaster < expectHigh))
  5272. metronomeResult = "ERROR master " + juce::String (metronomeMaster, 4);
  5273. else if (std::abs (insert - metronomeMaster) > 2.0e-3f)
  5274. metronomeResult = "ERROR insert " + juce::String (insert, 4);
  5275. else if (muted > 1.0e-4f)
  5276. metronomeResult = "ERROR muted insert " + juce::String (muted, 4);
  5277. else if (exported > 1.0e-4f)
  5278. metronomeResult = "ERROR in export " + juce::String (exported, 4);
  5279. }
  5280. const auto metronomeOk = metronomeResult == "OK";
  5281. // Settings › Audio "Driver settings…" with a fake driver panel (issue #13's crash, the panel's buffer kept)
  5282. const auto driverPanel = lynx::AudioEngine::driverPanelSelfTest();
  5283. // issue #134 (round 190c): the output device, its rate and its buffer changed under a playing project, on
  5284. // stand-in devices (a short run; --devicechangetest plays every instrument and effect)
  5285. const auto deviceChange = lynx::AudioEngine::deviceChangeSelfTest (10, false);
  5286. // round 190gh: export parity (B7) and MIDI device hot-plug (B8)
  5287. const auto exportParity = lynx::AudioEngine::exportParitySelfTest();
  5288. const auto midiHotplug = lynx::AudioEngine::midiHotplugSelfTest();
  5289. // Online Sessions P2 (round 169b): live sessions without a network (the JSON round trip of every entity, replicas
  5290. // through it, the invite code's keys)
  5291. const auto liveResult = lynx::livetest::selfTest (&rich);
  5292. // issue #67: every built-in effect's parameters, named and hidden (the Parametric EQ's FL law, processing, band
  5293. // mask...), at odd values, through a project save and reload: the same floats back
  5294. juce::String effectParamsResult = "OK";
  5295. {
  5296. auto song = lynx::Song::makeDefault();
  5297. song.mixer.resize (1);
  5298. for (int k = 0; k <= (int) lynx::lastEffectKind; ++k)
  5299. {
  5300. const auto kind = (lynx::EffectKind) k;
  5301. if (kind == lynx::EffectKind::plugin || kind == lynx::EffectKind::parallel)
  5302. continue;
  5303. auto fx = lynx::makeEffectSlot (kind);
  5304. for (std::size_t i = 0; i < fx.params.size(); ++i)
  5305. {
  5306. auto v = (float) ((double) ((i * 7919 + (std::size_t) k * 104729) % 65521) / 65521.0);
  5307. fx.params[i] = v == fx.params[i] ? 1.0f - v : v;
  5308. }
  5309. if (kind == lynx::EffectKind::fruitySend) // ("Send to" is written over the insert span)
  5310. fx.params[3] = 0.0f;
  5311. song.mixer.emplace_back();
  5312. song.mixer.back().name = "Insert " + std::to_string (song.mixer.size() - 1);
  5313. song.mixer.back().effects.push_back (fx);
  5314. }
  5315. // round 171b's Patcher round trip (coordinator): the Frequency Splitter, Fruity Delay 3 and Peak Controller
  5316. // nodes came back different (their FL defaults, e.g. the LFO speed 32750 / 65336, lost to 4 decimals)
  5317. {
  5318. auto patch = lynx::makeEffectSlot (lynx::EffectKind::patcher);
  5319. for (const auto kind : { lynx::EffectKind::frequencySplitter, lynx::EffectKind::fruityDelay3, lynx::EffectKind::peakController,
  5320. lynx::EffectKind::reverb, lynx::EffectKind::hardwareInsert })
  5321. {
  5322. lynx::PatchNode node;
  5323. node.effect = lynx::natives::newEffect (kind, lynx::flStudioAccess()).value_or (lynx::makeEffectSlot (kind));
  5324. if (kind == lynx::EffectKind::peakController)
  5325. node.effect.params[7] = 32750.0f / 65336.0f;
  5326. node.x = 200.0f, node.y = 60.0f * (float) patch.patcher.nodes.size();
  5327. patch.patcher.nodes.push_back (node);
  5328. }
  5329. song.mixer.emplace_back();
  5330. song.mixer.back().name = "Patcher";
  5331. song.mixer.back().effects.push_back (patch);
  5332. }
  5333. juce::String why;
  5334. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
  5335. if (back && back->mixer.size() == song.mixer.size())
  5336. {
  5337. const auto& a = song.mixer.back().effects[0].patcher.nodes;
  5338. const auto& b = back->mixer.back().effects[0].patcher.nodes;
  5339. for (std::size_t n = 0; n < a.size(); ++n)
  5340. if (n >= b.size() || ! (a[n].effect == b[n].effect))
  5341. effectParamsResult = juce::String ("ERROR Patcher node ") + lynx::effectInfo (a[n].effect.kind).name;
  5342. }
  5343. if (! back || back->mixer.size() != song.mixer.size())
  5344. effectParamsResult = "ERROR load " + why;
  5345. else
  5346. for (std::size_t t = 1; t + 1 < song.mixer.size() && effectParamsResult == "OK"; ++t)
  5347. if (back->mixer[t].effects.size() != 1 || back->mixer[t].effects[0].params != song.mixer[t].effects[0].params)
  5348. {
  5349. effectParamsResult = juce::String ("ERROR ") + lynx::effectInfo (song.mixer[t].effects[0].kind).name;
  5350. break;
  5351. }
  5352. }
  5353. // round 170j: the Themed plugin style (its resolution with and without art; every art draws)
  5354. const auto artResult = lynx::skin::artSelfTest();
  5355. // round 177b: a plugin's sidechain bus gets the slot's sidechain (one-click sidechain)
  5356. const auto sidechainResult = lynx::pluginSidechainSelfTest();
  5357. // round 190ap: the Versions panel's list of files, and its labels on disk beside them
  5358. const auto versionsResult = lynx::versionsSelfTest();
  5359. // round 190ap: a project opened with its plugins off creates none of them and saves their settings unchanged
  5360. const auto pluginsOffResult = lynx::pluginsOffSelfTest();
  5361. const auto missingFilesResult = lynx::missingFilesSelfTest(); // issue #165
  5362. // round 190cj: a dancer's own native window stays where the stage put it (it drifted off the screen: JUCE
  5363. // moved a transparent child window by the main window's client offset on every repaint)
  5364. juce::String danceWindowDetail;
  5365. const auto danceWindowResult = lynx::danceWindowSelfTest (&danceWindowDetail);
  5366. // issue #161: a click in a panel (a native child window that takes no focus on a click) of an inactive main
  5367. // window activates it (back from another app, Space played nothing until the Browser was clicked)
  5368. const auto clickActivationResult = lynx::nativechild::clickActivationSelfTest();
  5369. // round 177b: automation lanes come back from a project (track, automation, height, folded)
  5370. juce::String lanesResult = "OK";
  5371. {
  5372. auto song = lynx::Song::makeDefault();
  5373. const auto lane = lynx::autolanes::addLane (song, 3, { lynx::AutomationTargetKind::mixerVolume, 1, 0, 0 }, "Vol", 0.4f);
  5374. song.playlistTracks[3].lanes[0].height = 72;
  5375. song.playlistTracks[3].lanesFolded = true;
  5376. // (the same round's clip LFO and modulators ride along)
  5377. auto& lfo = song.automations[(std::size_t) lane].lfo;
  5378. lfo.on = true;
  5379. lfo.level = -40;
  5380. lfo.speed = 30000;
  5381. lfo.flags = 1 | 4;
  5382. lfo.phase = 123456789u;
  5383. lfo.amp = { { 0, 0.5f, 0.0f }, { 960, 1.0f, 0.0f } };
  5384. lynx::Modulator mod;
  5385. mod.name = "LFO 1";
  5386. mod.shape = lynx::ModShape::square;
  5387. mod.sync = false;
  5388. mod.hz = 2.5;
  5389. mod.routes = { { { lynx::AutomationTargetKind::mixerPan, 1, 0, 0 }, -0.5f } };
  5390. song.modulators.push_back (mod);
  5391. juce::String why;
  5392. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
  5393. if (! back || back->playlistTracks.size() < 4 || ! (back->playlistTracks[3].lanes == song.playlistTracks[3].lanes)
  5394. || ! back->playlistTracks[3].lanesFolded || back->automations.size() != song.automations.size()
  5395. || ! (back->automations[(std::size_t) lane].points == song.automations[(std::size_t) lane].points)
  5396. || ! (back->automations[(std::size_t) lane].lfo == lfo) || ! (back->modulators == song.modulators))
  5397. lanesResult = "ERROR " + why;
  5398. }
  5399. // round 190cg: the loop switch, folded tracks and the tempo lane's range come back from a project; a project
  5400. // without them loads as before (loop on, nothing folded, the whole range)
  5401. juce::String arrange190cgResult = "OK";
  5402. {
  5403. auto song = lynx::Song::makeDefault();
  5404. juce::String why;
  5405. const auto plain = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
  5406. song.loopStart = 960;
  5407. song.loopEnd = 4800;
  5408. song.loopOff = true;
  5409. song.tempoViewLow = 80.0;
  5410. song.tempoViewHigh = 160.0;
  5411. song.playlistTracks.resize (std::max<std::size_t> (song.playlistTracks.size(), 6));
  5412. song.playlistTracks[2].folded = song.playlistTracks[5].folded = true;
  5413. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
  5414. if (! plain || plain->loopOff || plain->tempoViewLow != 0.0 || plain->tempoViewHigh != 0.0
  5415. || std::any_of (plain->playlistTracks.begin(), plain->playlistTracks.end(), [] (const lynx::PlaylistTrack& t) { return t.folded; }))
  5416. arrange190cgResult = "ERROR defaults " + why;
  5417. else if (! back || ! back->loopOff || back->loopStart != 960 || back->loopEnd != 4800 || back->loopPlays() || back->tempoViewLow != 80.0
  5418. || back->tempoViewHigh != 160.0 || back->playlistTracks.size() < 6 || ! back->playlistTracks[2].folded
  5419. || ! back->playlistTracks[5].folded || back->playlistTracks[3].folded)
  5420. arrange190cgResult = "ERROR round trip " + why;
  5421. }
  5422. // round 190gz (issue #170): "Link Playlist tracks to mixer tracks" comes back from a project with its links; a
  5423. // project without it loads with it off (FL's tracks)
  5424. juce::String trackauto190gzResult = "OK";
  5425. {
  5426. auto song = lynx::Song::makeDefault();
  5427. juce::String why;
  5428. const auto plain = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
  5429. lynx::Clip clip;
  5430. clip.kind = lynx::ClipKind::pattern;
  5431. clip.pattern = 0; // (the default pattern: Kick, Clap and Hat; a second one plays Kick alone)
  5432. song.playlist.push_back (clip);
  5433. auto& kick = song.patterns.emplace_back();
  5434. kick.name = "Kick";
  5435. kick.toggleStep (0, 0);
  5436. clip.pattern = (int) song.patterns.size() - 1;
  5437. clip.track = 1;
  5438. song.playlist.push_back (clip);
  5439. lynx::autolink::setOn (song, true);
  5440. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
  5441. if (! plain || plain->linkTracksToMixer)
  5442. trackauto190gzResult = "ERROR defaults " + why;
  5443. // (round 190ib: Track 1 holds Kick, Clap and Hat, so they all go through insert 1 and Track 1 is its audio
  5444. // track; Track 2 only repeats Kick and stays unassigned)
  5445. // (a .lynx keeps the tracks up to the last one that differs from a plain track: Track 2 may not be written)
  5446. else if (! back || ! back->linkTracksToMixer || back->playlistTracks.empty() || back->playlistTracks[0].mode != lynx::PlaylistTrackMode::audio
  5447. || back->playlistTracks[0].mixerTrack != 1
  5448. || (back->playlistTracks.size() > 1 && back->playlistTracks[1].mode != lynx::PlaylistTrackMode::unassigned)
  5449. || back->channels[1].mixerTrack != 1 || back->channels[2].mixerTrack != 1)
  5450. {
  5451. trackauto190gzResult = "ERROR round trip " + why;
  5452. if (back && ! back->playlistTracks.empty() && back->channels.size() >= 3)
  5453. trackauto190gzResult << " tracks " << (int) back->playlistTracks.size() << " mode " << (int) back->playlistTracks[0].mode << " insert "
  5454. << back->playlistTracks[0].mixerTrack << " routes " << back->channels[0].mixerTrack << " "
  5455. << back->channels[1].mixerTrack << " " << back->channels[2].mixerTrack;
  5456. }
  5457. }
  5458. // round 190fm: the MIDI Tools generators' settings come back from a project; a project without them loads with
  5459. // Live's defaults (and saves none)
  5460. juce::String midigen190fmResult = "OK";
  5461. {
  5462. auto song = lynx::Song::makeDefault();
  5463. juce::String why;
  5464. const auto plainJson = lynx::ProjectFile::toJson (song);
  5465. const auto plain = lynx::ProjectFile::fromJson (plainJson, why);
  5466. song.midiGenerate.tool = lynx::midigen::Settings::stacks;
  5467. song.midiGenerate.rhythmOptions.pattern = 3;
  5468. song.midiGenerate.seedOptions.voices = 2;
  5469. song.midiGenerate.shapeOptions.levels[4] = 0.25f;
  5470. song.midiGenerate.shapeOptions.preset = lynx::midigen::ShapeOptions::custom;
  5471. song.midiGenerate.stacksOptions.sequence.push_back ({ 4, 3, 67, 1, 1, 0.5f, 2.0f });
  5472. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
  5473. if (! plain || ! plain->midiGenerate.isDefault() || plainJson.contains ("midiGenerate"))
  5474. midigen190fmResult = "ERROR defaults " + why;
  5475. else if (! back || ! (back->midiGenerate == song.midiGenerate))
  5476. midigen190fmResult = "ERROR round trip " + why;
  5477. }
  5478. // round 190gi: audio clip envelopes come back from a project (an entry two clips share stays shared, an unused one
  5479. // is not written, the lane shown, FL's curve modes); a project without them writes neither "clipEnvelopes" nor a
  5480. // clip field 25 (older projects save byte-identical)
  5481. juce::String clipenv190giResult = "OK";
  5482. {
  5483. auto song = lynx::Song::makeDefault();
  5484. lynx::ChannelDef channel;
  5485. channel.instrument = lynx::InstrumentKind::audioClip;
  5486. channel.samplePath = "clipenv190gi.wav";
  5487. song.channels.push_back (channel);
  5488. lynx::Clip clip;
  5489. clip.kind = lynx::ClipKind::audio;
  5490. clip.channel = (int) song.channels.size() - 1;
  5491. clip.length = lynx::ppq * 4;
  5492. song.playlist.push_back (clip);
  5493. juce::String why;
  5494. const auto plainJson = lynx::ProjectFile::toJson (song);
  5495. lynx::ClipEnvelope e;
  5496. e.volume = { { 0, 1.0f, 0.0f, 0 }, { lynx::ppq * 4, 0.25f, 0.3f, 1 } };
  5497. e.pan = { { 0, 0.5f, 0.0f, 0 }, { lynx::ppq * 2, 0.0f, 0.0f, 0 } };
  5498. e.shown = lynx::clipenv::panLane;
  5499. song.clipEnvelopes.emplace_back(); // (no clip uses it: not written)
  5500. song.clipEnvelopes.push_back (e);
  5501. song.playlist.back().envelope = 1;
  5502. auto twin = song.playlist.back();
  5503. twin.start = lynx::ppq * 8;
  5504. song.playlist.push_back (twin);
  5505. const auto json = lynx::ProjectFile::toJson (song);
  5506. const auto back = lynx::ProjectFile::fromJson (json, why);
  5507. if (plainJson.contains ("clipEnvelopes") || ! json.contains ("clipEnvelopes"))
  5508. clipenv190giResult = "ERROR written " + why;
  5509. else if (! back || back->clipEnvelopes.size() != 1 || ! (back->clipEnvelopes[0] == e))
  5510. clipenv190giResult = "ERROR table " + why;
  5511. else
  5512. {
  5513. int withEnvelope = 0;
  5514. for (const auto& c : back->playlist)
  5515. withEnvelope += c.kind == lynx::ClipKind::audio && c.envelope == 0 ? 1 : 0;
  5516. if (withEnvelope != 2)
  5517. clipenv190giResult = "ERROR clips " + why;
  5518. }
  5519. }
  5520. // round 190gx: Beats' law in the .lynx — a new project's channels are Measured; a project saved before the law
  5521. // (no "beatsLaw190gx" mark, or a nine-number warpModes list) loads Classic; a Classic channel stays Classic
  5522. juce::String beatslaw190gxResult = "OK";
  5523. {
  5524. auto song = lynx::Song::makeDefault();
  5525. lynx::ChannelDef channel;
  5526. channel.instrument = lynx::InstrumentKind::audioClip;
  5527. channel.samplePath = "beatslaw190gx.wav";
  5528. channel.sampler.keepPitch = true;
  5529. channel.sampler.stretchMethod = lynx::StretchMethod::beats;
  5530. song.channels.push_back (channel);
  5531. const auto index = song.channels.size() - 1;
  5532. juce::String why;
  5533. const auto json = lynx::ProjectFile::toJson (song);
  5534. const auto lawOf = [&] (const juce::String& text) {
  5535. const auto back = lynx::ProjectFile::fromJson (text, why);
  5536. return back && back->channels.size() > index ? (int) back->channels[index].sampler.warpModes.beatsLaw : -1;
  5537. };
  5538. auto oldVar = juce::JSON::parse (json); // (the mark removed: a project saved before 190gx)
  5539. if (auto* o = oldVar.getDynamicObject())
  5540. o->removeProperty ("beatsLaw190gx");
  5541. const auto old = juce::JSON::toString (oldVar);
  5542. auto classic = song;
  5543. classic.channels[index].sampler.warpModes.beatsLaw = lynx::WarpModeSettings::beatsLawClassic;
  5544. auto nine = song;
  5545. nine.channels[index].sampler.warpModes.beatsLoop = 0; // (a 190fm project with a changed setting: nine numbers)
  5546. // (the list with its tenth number, the law, removed: what a 190fm build wrote)
  5547. auto nineVar = juce::JSON::parse (lynx::ProjectFile::toJson (nine));
  5548. bool trimmed = false;
  5549. if (auto* channels = nineVar.getProperty ("channels", {}).getArray(); channels != nullptr && (int) index < channels->size())
  5550. if (auto* modes = (*channels)[(int) index].getProperty ("samplerSettings", {}).getProperty ("warpModes", {}).getArray(); modes != nullptr && modes->size() == 10)
  5551. {
  5552. modes->removeLast();
  5553. trimmed = true;
  5554. }
  5555. const auto nineJson = juce::JSON::toString (nineVar);
  5556. if (! json.contains ("beatsLaw190gx") || old.contains ("beatsLaw190gx"))
  5557. beatslaw190gxResult = "ERROR mark";
  5558. else if (lawOf (json) != lynx::WarpModeSettings::beatsLawMeasured)
  5559. beatslaw190gxResult = "ERROR new " + why;
  5560. else if (lawOf (old) != lynx::WarpModeSettings::beatsLawClassic)
  5561. beatslaw190gxResult = "ERROR old " + why;
  5562. else if (lawOf (lynx::ProjectFile::toJson (classic)) != lynx::WarpModeSettings::beatsLawClassic)
  5563. beatslaw190gxResult = "ERROR classic kept " + why;
  5564. else if (! trimmed || lawOf (nineJson) != lynx::WarpModeSettings::beatsLawClassic)
  5565. beatslaw190gxResult = "ERROR nine-number list";
  5566. }
  5567. // round 190he (issue #152): a channel window's Scaling is saved with the channel; the default (125 %) writes
  5568. // nothing, so older projects and untouched channels read as before
  5569. juce::String editorScale190heResult = "OK";
  5570. {
  5571. auto song = lynx::Song::makeDefault();
  5572. song.channels[0].editorScale = 100;
  5573. song.channels[1].editorScale = 0;
  5574. juce::String why;
  5575. const auto json = lynx::ProjectFile::toJson (song);
  5576. const auto back = lynx::ProjectFile::fromJson (json, why);
  5577. auto outOfRange = juce::JSON::parse (json);
  5578. if (auto* chans = outOfRange.getProperty ("channels", {}).getArray(); chans != nullptr && ! chans->isEmpty())
  5579. if (auto* o = (*chans)[0].getDynamicObject())
  5580. o->setProperty ("editorScale", 9000);
  5581. const auto clamped = lynx::ProjectFile::fromJson (juce::JSON::toString (outOfRange), why);
  5582. if (! back || back->channels[0].editorScale != 100 || back->channels[1].editorScale != 0)
  5583. editorScale190heResult = "ERROR round trip " + why;
  5584. else if (json.indexOf ("editorScale") != json.lastIndexOf ("editorScale"))
  5585. editorScale190heResult = "ERROR written for a default channel";
  5586. else if (! clamped || clamped->channels[0].editorScale != lynx::editorscale::maxPercent)
  5587. editorScale190heResult = "ERROR not clamped";
  5588. }
  5589. // round 190he (coordinator's gate): a project saved before 190he (no "sfModBase190he") keeps the old 0.5 centre of
  5590. // a Modulation route on a Soundfont knob; a new song, saved and opened again, centres on the knob
  5591. juce::String sfModBase190heResult = "OK";
  5592. {
  5593. auto song = lynx::Song::makeDefault();
  5594. juce::String why;
  5595. const auto json = lynx::ProjectFile::toJson (song);
  5596. auto oldVar = juce::JSON::parse (json);
  5597. if (auto* o = oldVar.getDynamicObject())
  5598. o->removeProperty ("sfModBase190he");
  5599. const auto back = lynx::ProjectFile::fromJson (json, why);
  5600. const auto old = lynx::ProjectFile::fromJson (juce::JSON::toString (oldVar), why);
  5601. auto resaved = old ? lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (*old), why) : std::optional<lynx::Song> {};
  5602. if (! json.contains ("sfModBase190he") || ! back || ! back->soundfontModBaseReal)
  5603. sfModBase190heResult = "ERROR new song " + why;
  5604. else if (! old || old->soundfontModBaseReal)
  5605. sfModBase190heResult = "ERROR old project " + why;
  5606. else if (! resaved || resaved->soundfontModBaseReal)
  5607. sfModBase190heResult = "ERROR old project saved again";
  5608. }
  5609. // round 190hq: tempo markers (B11) and the fader / route PDC switch (B13) in the .lynx, and the copy for an older
  5610. // LYNX (B20): an effect 0.1.27 does not know keeps its slot (as a switched-off Utility) and loses its automation,
  5611. // the later slots and their automation stay; the copy for 0.1.28 turns the markers into a plain tempo clip
  5612. juce::String community190hqResult = "OK";
  5613. {
  5614. auto song = lynx::Song::makeDefault();
  5615. song.mode = lynx::PlayMode::song;
  5616. lynx::tempomarkers::add (song, 4 * lynx::ppq, 90.0);
  5617. lynx::tempomarkers::add (song, 8 * lynx::ppq, 140.0, true);
  5618. song.mixer[1].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::anvilBus));
  5619. song.mixer[1].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::delay));
  5620. for (const auto slot : { 0, 1 })
  5621. {
  5622. lynx::Automation a;
  5623. a.name = slot == 0 ? "Anvil" : "Delay";
  5624. a.target = { lynx::AutomationTargetKind::effectParam, 1, slot, 1 };
  5625. a.points = { { 0, 0.2f }, { 1920, 0.8f } };
  5626. song.automations.push_back (a);
  5627. }
  5628. juce::String why;
  5629. const auto json = lynx::ProjectFile::toJson (song);
  5630. const auto back = lynx::ProjectFile::fromJson (json, why);
  5631. auto unmarked = juce::JSON::parse (json);
  5632. if (auto* o = unmarked.getDynamicObject())
  5633. o->removeProperty ("mixerLevelPdc190hq");
  5634. const auto old = lynx::ProjectFile::fromJson (juce::JSON::toString (unmarked), why);
  5635. const auto marks = back ? lynx::tempomarkers::list (*back) : std::vector<lynx::tempomarkers::Mark> {};
  5636. const auto for127 = lynx::olderlynx::forRelease (song, "0.1.27");
  5637. const auto for128 = lynx::olderlynx::forRelease (song, "0.1.28");
  5638. const auto copy127 = for127.ok ? lynx::ProjectFile::fromJson (for127.json, why) : std::optional<lynx::Song> {};
  5639. const auto copy128 = for128.ok ? lynx::ProjectFile::fromJson (for128.json, why) : std::optional<lynx::Song> {};
  5640. const auto anvilLost = std::any_of (for127.lost.begin(), for127.lost.end(), [] (const lynx::olderlynx::Loss& l) {
  5641. return juce::String (l.text).startsWith ("Anvil Bus");
  5642. });
  5643. auto targetOf = [] (const std::optional<lynx::Song>& s, const char* name) {
  5644. if (s)
  5645. for (const auto& a : s->automations)
  5646. if (a.name == name)
  5647. return a.target;
  5648. return lynx::AutomationTarget {};
  5649. };
  5650. if (! back || ! back->compensateMixerLevels || ! old || old->compensateMixerLevels)
  5651. community190hqResult = "ERROR mixer level PDC mark " + why;
  5652. else if (marks.size() != 2 || marks[0].tick != 4 * lynx::ppq || std::abs (marks[1].bpm - 140.0) > 0.01 || ! marks[1].glide || marks[0].glide
  5653. || std::abs (back->tempoAt (5.0 * lynx::ppq) - 102.5) > 0.5) // (90 at bar 2, ramping into the gliding 140 at bar 3)
  5654. community190hqResult = "ERROR tempo markers round trip";
  5655. else if (! copy127 || for127.json.contains ("anvilBus") || copy127->mixer[1].effects.size() != 2
  5656. || copy127->mixer[1].effects[0].kind != lynx::EffectKind::utility || copy127->mixer[1].effects[0].enabled
  5657. || copy127->mixer[1].effects[1].kind != lynx::EffectKind::delay || ! anvilLost)
  5658. community190hqResult = "ERROR copy for 0.1.27: slots " + why;
  5659. else if (targetOf (copy127, "Anvil").kind != lynx::AutomationTargetKind::none
  5660. || ! (targetOf (copy127, "Delay") == lynx::AutomationTarget { lynx::AutomationTargetKind::effectParam, 1, 1, 1 }))
  5661. community190hqResult = "ERROR copy for 0.1.27: automation";
  5662. else if (! juce::JSON::parse (for127.json)["savedBy"].toString().equalsIgnoreCase ("0.1.27") || for127.json.contains ("tempoMarkers")
  5663. || for127.json.contains ("mixerLevelPdc190hq") || for127.json.contains ("beatsLaw190gx"))
  5664. community190hqResult = "ERROR copy for 0.1.27: fields";
  5665. else if (! copy128 || for128.json.contains ("tempoMarkers") || ! for128.json.contains ("anvilBus") || lynx::tempomarkers::automationIndex (*copy128) >= 0
  5666. || std::abs (copy128->tempoAt (5.0 * lynx::ppq) - 102.5) > 0.5 || std::abs (copy128->tempoAt (12.0 * lynx::ppq) - 140.0) > 0.01)
  5667. community190hqResult = "ERROR copy for 0.1.28";
  5668. else if (lynx::olderlynx::forRelease (song, "0.1.9").ok)
  5669. community190hqResult = "ERROR unknown release accepted";
  5670. }
  5671. // rollup 0.1.30 (round 190il): the copy for 0.1.28 knows what the other 0.1.30 rounds save: a Tetra channel becomes
  5672. // an empty Sampler, MPE note curves, muted Pattern Blocks, clips transposed past ±12, clip slots' Start markers and
  5673. // scales, Voice Shift's revision 1, Ridge's Pink EQ, Hush's Allround timing (round 190iy), automation colours and mix snapshots are reported and taken
  5674. // out; a DirectWave state's 36-byte sample format record is completed (0.1.28 skipped it, and the loop with it)
  5675. juce::String rollup030Result = "OK";
  5676. {
  5677. auto song = lynx::Song::makeDefault();
  5678. lynx::ChannelDef tetra;
  5679. tetra.name = "FM";
  5680. tetra.instrument = lynx::InstrumentKind::tetra;
  5681. tetra.modelParams = { 0.5f, 0.25f };
  5682. song.channels.push_back (tetra);
  5683. lynx::ChannelDef wave;
  5684. wave.name = "Piano";
  5685. wave.instrument = lynx::InstrumentKind::directwave;
  5686. {
  5687. auto doc = lynx::dw::freshDoc();
  5688. lynx::dw::Node zone;
  5689. zone.id = 3;
  5690. zone.container = true;
  5691. lynx::dw::Node format;
  5692. format.id = 0x1F7;
  5693. format.body.assign (36, 0);
  5694. format.body[20] = 2; // loop mode
  5695. format.body[24] = 44; // loop A
  5696. format.body[28] = 200; // loop B
  5697. zone.kids.push_back (format);
  5698. for (auto& n : doc.top)
  5699. if (n.id == 1 && n.container)
  5700. {
  5701. n.kids.push_back (zone);
  5702. break;
  5703. }
  5704. wave.pluginState = lynx::dw::writeDoc (doc);
  5705. }
  5706. song.channels.push_back (wave);
  5707. lynx::Note curved;
  5708. curved.key = 60;
  5709. curved.length = lynx::ppq;
  5710. lynx::NoteCurves curves;
  5711. curves.lane (lynx::NoteCurveLane::pitch) = { { 0.0f, 0.0f }, { 96.0f, 200.0f } };
  5712. curved.curves = curves;
  5713. song.patterns[0].notes.push_back (curved);
  5714. song.patternBlocksOn = true;
  5715. lynx::patternblocks::place (song, 0, 0);
  5716. lynx::patternblocks::place (song, 0, 4 * lynx::ppq);
  5717. lynx::patternblocks::setMuted (song, 1, true);
  5718. lynx::Clip up;
  5719. up.track = 1;
  5720. up.length = 4 * lynx::ppq;
  5721. up.pitch = 24.0f;
  5722. song.playlist.push_back (up);
  5723. lynx::Clip slotClip;
  5724. slotClip.length = 4 * lynx::ppq;
  5725. if (const auto id = lynx::launcher::setClip (song, 0, 0, slotClip); id >= 0)
  5726. {
  5727. song.clipGrid->slots[(std::size_t) id].startMarker = lynx::ppq;
  5728. song.clipGrid->slots[(std::size_t) id].ownScale = true;
  5729. }
  5730. song.mixer[1].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::voiceShift)); // (a new one: revision 1)
  5731. auto ridgeSlot = lynx::makeEffectSlot (lynx::EffectKind::ridgeStrip);
  5732. ridgeSlot.params[(std::size_t) lynx::mixsuite::ridge::k4Pink] = 1.0f;
  5733. song.mixer[2].effects.push_back (ridgeSlot);
  5734. auto hushSlot = lynx::makeEffectSlot (lynx::EffectKind::hushDeEsser); // (a new one: the measured timing, round 190iq)
  5735. hushSlot.params[(std::size_t) lynx::mixsuite::hush::allround] = 1.0f;
  5736. song.mixer[3].effects.push_back (hushSlot);
  5737. lynx::Automation coloured;
  5738. coloured.name = "Cutoff";
  5739. coloured.colour = 0xFFC03030u;
  5740. coloured.points = { { 0, 0.2f }, { 1920, 0.8f } };
  5741. song.automations.push_back (coloured);
  5742. lynx::mixsnap::take (song);
  5743. const auto copy = lynx::olderlynx::forRelease (song, "0.1.28");
  5744. juce::String why;
  5745. const auto back = copy.ok ? lynx::ProjectFile::fromJson (copy.json, why) : std::optional<lynx::Song> {};
  5746. const auto said = [&copy] (const char* start) {
  5747. return std::any_of (copy.lost.begin(), copy.lost.end(), [start] (const lynx::olderlynx::Loss& l) { return juce::String (l.text).startsWith (start); });
  5748. };
  5749. const auto parsed = juce::JSON::parse (copy.json);
  5750. const auto* channels = parsed["channels"].getArray();
  5751. bool fmEmpty = false, notesCut = true, waveDone = false;
  5752. if (channels != nullptr)
  5753. for (const auto& c : *channels)
  5754. {
  5755. if (c["name"].toString() == "FM")
  5756. fmEmpty = c["instrument"].toString() == "sampler" && ! c.hasProperty ("modelParams");
  5757. if (c["name"].toString() == "Piano")
  5758. {
  5759. juce::MemoryOutputStream bytes;
  5760. if (juce::Base64::convertFromBase64 (bytes, c["pluginState"].toString()))
  5761. {
  5762. const auto* b = static_cast<const std::uint8_t*> (bytes.getData());
  5763. if (const auto st = lynx::dw::parseState (std::vector<std::uint8_t> (b, b + bytes.getDataSize())))
  5764. for (const auto& prog : st->programs)
  5765. for (const auto& z : prog.zones)
  5766. waveDone = waveDone || (z.loopMode == 2 && z.loopA == 44 && z.loopB == 200 && z.bits == 32);
  5767. if (const auto doc = lynx::dw::readDoc (std::vector<std::uint8_t> (b, b + bytes.getDataSize())))
  5768. for (const auto& n : doc->top)
  5769. for (const auto& z : n.kids)
  5770. for (const auto& r : z.kids)
  5771. if (r.id == 0x1F7)
  5772. waveDone = waveDone && r.body.size() == 40;
  5773. }
  5774. }
  5775. }
  5776. if (const auto* patterns = parsed["patterns"].getArray())
  5777. for (const auto& pt : *patterns)
  5778. if (const auto* notes = pt["notes"].getArray())
  5779. for (const auto& n : *notes)
  5780. notesCut = notesCut && n.size() <= 19;
  5781. if (! copy.ok || ! back)
  5782. rollup030Result = "ERROR copy " + why;
  5783. else if (! fmEmpty || ! said ("Tetra is not in this release"))
  5784. rollup030Result = "ERROR Tetra channel";
  5785. else if (! waveDone)
  5786. rollup030Result = "ERROR DirectWave short record";
  5787. else if (! notesCut || ! said ("{0} note(s) lose their MPE curves"))
  5788. rollup030Result = "ERROR note curves";
  5789. else if (back->blocks.size() != 1 || back->blocks[0].start != 0 || ! said ("{0} muted Pattern Block(s)"))
  5790. rollup030Result = "ERROR muted blocks";
  5791. else if (std::none_of (back->playlist.begin(), back->playlist.end(), [] (const lynx::Clip& c) { return c.pitch == 12.0f; })
  5792. || ! said ("{0} clip(s) transposed"))
  5793. rollup030Result = "ERROR clip pitch";
  5794. else if (copy.json.contains ("startMarker") || copy.json.contains ("clipScale") || ! said ("{0} clip slot(s) launch") || ! said ("Clip scales"))
  5795. rollup030Result = "ERROR clip slots";
  5796. else if (! said ("Voice Shift's Measured law") || ! said ("Ridge Strip's 4K Pink EQ") || ! said ("Hush De-esser's Allround mode")
  5797. || parsed["mixer"][1]["effects"][0]["params"].size() > lynx::voiceshift::revision
  5798. || parsed["mixer"][3]["effects"][0]["params"].size() > lynx::mixsuite::hush::timing)
  5799. rollup030Result = "ERROR effects";
  5800. else if (copy.json.contains ("mixSnapshots") || ! said ("Mix snapshots") || ! said ("Automation clip colours")
  5801. || std::any_of (back->automations.begin(), back->automations.end(), [] (const lynx::Automation& a) { return a.colour != 0; }))
  5802. rollup030Result = "ERROR view items";
  5803. else if (const auto plain = lynx::olderlynx::forRelease (lynx::Song::makeDefault(), "0.1.28");
  5804. ! plain.ok || std::any_of (plain.lost.begin(), plain.lost.end(), [] (const lynx::olderlynx::Loss& l) {
  5805. const auto t = juce::String (l.text);
  5806. return t.startsWith ("Tetra") || t.contains ("MPE") || t.contains ("Pattern Block") || t.contains ("Voice Shift")
  5807. || t.contains ("Ridge") || t.contains ("Hush") || t.startsWith ("Automation clip colours") || t.startsWith ("Mix snapshots");
  5808. }))
  5809. rollup030Result = "ERROR a plain project reports a loss it does not have";
  5810. }
  5811. // round 190dr: the Session mixer's sections come back from a project (a project without them: Live's defaults);
  5812. // a device dragged to another track and a Warp switch are one undo step each in a real engine
  5813. juce::String livescr190drResult = "OK";
  5814. {
  5815. auto song = lynx::Song::makeDefault();
  5816. lynx::launcher::ensureGrid (song);
  5817. juce::String why;
  5818. const auto plain = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
  5819. song.clipGrid->mixerView.io = false;
  5820. song.clipGrid->mixerView.trackOptions = true;
  5821. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
  5822. if (! plain || ! plain->clipGrid || ! (plain->clipGrid->mixerView == lynx::SessionMixerView {}))
  5823. livescr190drResult = "ERROR view defaults " + why;
  5824. else if (! back || ! back->clipGrid || back->clipGrid->mixerView.io || ! back->clipGrid->mixerView.trackOptions || ! back->clipGrid->mixerView.shown)
  5825. livescr190drResult = "ERROR view round trip " + why;
  5826. lynx::AudioEngine e (false);
  5827. e.editSong ([] (lynx::Song& s) {
  5828. if (s.mixer.size() < 4)
  5829. s.mixer.resize (4);
  5830. s.mixer[2].effects.clear();
  5831. s.mixer[3].effects.clear();
  5832. for (auto kind : { lynx::EffectKind::eq, lynx::EffectKind::compressor })
  5833. {
  5834. lynx::EffectSlot fx;
  5835. fx.kind = kind;
  5836. s.mixer[2].effects.push_back (fx);
  5837. }
  5838. lynx::Automation a;
  5839. a.target = { lynx::AutomationTargetKind::effectMix, 2, 1, 0 };
  5840. s.automations.push_back (a);
  5841. }, false);
  5842. const auto id = e.getSong().mixer[2].effects[1].instance.id;
  5843. const auto automations = e.getSong().automations.size();
  5844. e.editSongStructural ([] (lynx::Song& s) { lynx::detailchain::moveEffectToInsert (s, 2, 1, 3, false); });
  5845. const auto& moved = e.getSong();
  5846. if (livescr190drResult == "OK"
  5847. && (moved.mixer[2].effects.size() != 1 || moved.mixer[3].effects.size() != 1 || moved.mixer[3].effects[0].instance.id != id
  5848. || moved.automations.size() != automations || moved.automations.back().target.index != 3 || moved.automations.back().target.slot != 0))
  5849. livescr190drResult = "ERROR device move";
  5850. e.undo();
  5851. const auto& undone = e.getSong();
  5852. if (livescr190drResult == "OK"
  5853. && (undone.mixer[2].effects.size() != 2 || undone.mixer[3].effects.size() != 0 || undone.mixer[2].effects[1].instance.id != id
  5854. || undone.automations.back().target.index != 2 || undone.automations.back().target.slot != 1))
  5855. livescr190drResult = "ERROR device move undo";
  5856. e.editSong ([] (lynx::Song& s) {
  5857. s.channels.resize (std::max<std::size_t> (s.channels.size(), 1));
  5858. s.channels[0].sampler.stretchBeats = 16.0f;
  5859. lynx::Clip c;
  5860. c.kind = lynx::ClipKind::audio;
  5861. c.channel = 0;
  5862. c.offset = 4 * lynx::ppq;
  5863. c.length = 8 * lynx::ppq;
  5864. lynx::launcher::setClip (s, 0, 0, c);
  5865. }, false);
  5866. e.editSong ([] (lynx::Song& s) { lynx::clipsample::setWarp (s, 0, false, 4.0); });
  5867. const auto* off = e.getSong().clipGrid ? lynx::launcher::clipAt (*e.getSong().clipGrid, 0, 0) : nullptr;
  5868. 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)))
  5869. livescr190drResult = "ERROR warp off";
  5870. e.undo();
  5871. const auto* on = e.getSong().clipGrid ? lynx::launcher::clipAt (*e.getSong().clipGrid, 0, 0) : nullptr;
  5872. if (livescr190drResult == "OK" && (e.getSong().channels[0].sampler.stretchBeats != 16.0f || on == nullptr || on->length != 8 * lynx::ppq))
  5873. livescr190drResult = "ERROR warp undo";
  5874. }
  5875. // round 190ef: the map modes' storage (.lynx round trip of key / MIDI mappings and a link's Min / Max; an older
  5876. // reader keeps the plain link), and in a real engine: a link's range, MIDI Map Mode catching the control instead
  5877. // of moving anything, a slot's MIDI mapping firing on its press and release
  5878. juce::String livewf190efResult = "OK";
  5879. {
  5880. using namespace lynx::remotemap;
  5881. auto song = lynx::Song::makeDefault();
  5882. lynx::launcher::ensureGrid (song);
  5883. const lynx::AutomationTarget vol { lynx::AutomationTargetKind::mixerVolume, 1, 0, 0 };
  5884. assignMidi (song, Target::parameter (vol), { 0, 20, -1 });
  5885. assignMidi (song, Target::slot (0, 0), { 0, lynx::linkNoteBase + 36, 2 });
  5886. assignKey (song, Target::sceneLaunch (0), 'S');
  5887. assignKey (song, Target::parameter ({ lynx::AutomationTargetKind::tempo, 0, 0, 0 }), 'T');
  5888. setRange (song, rows (song, Mode::midi)[0], 0.25f, 0.75f);
  5889. setRange (song, rows (song, Mode::key)[1], 0.9f, 0.1f);
  5890. juce::String why;
  5891. const auto json = lynx::ProjectFile::toJson (song);
  5892. const auto back = lynx::ProjectFile::fromJson (json, why);
  5893. if (! back || back->remoteMappings != song.remoteMappings || back->midiLinks != song.midiLinks)
  5894. livewf190efResult = "ERROR round trip " + why;
  5895. auto parsed = juce::JSON::parse (json);
  5896. if (auto* o = parsed.getDynamicObject())
  5897. {
  5898. o->removeProperty ("remoteMappings");
  5899. o->removeProperty ("midiLinkSettings");
  5900. }
  5901. const auto older = lynx::ProjectFile::fromJson (juce::JSON::toString (parsed), why);
  5902. if (livewf190efResult == "OK" && (! older || ! older->remoteMappings.empty() || older->midiLinks.size() != 1 || older->midiLinks[0].max != 1.0f))
  5903. livewf190efResult = "ERROR older reader";
  5904. const auto plain = lynx::ProjectFile::toJson (lynx::Song::makeDefault());
  5905. if (livewf190efResult == "OK" && plain.contains ("remoteMappings"))
  5906. livewf190efResult = "ERROR written without mappings";
  5907. lynx::AudioEngine e (false);
  5908. e.editSong ([vol] (lynx::Song& s) {
  5909. if (s.mixer.size() < 3)
  5910. s.mixer.resize (3);
  5911. lynx::MidiLink l { 20, 0, vol };
  5912. l.min = 0.25f;
  5913. l.max = 0.75f;
  5914. s.midiLinks = { l };
  5915. lynx::launcher::ensureGrid (s);
  5916. assignMidi (s, Target::slot (0, 0), { 0, 21, -1 });
  5917. });
  5918. e.injectControllerForTest (20, 0, 127);
  5919. const auto top = e.currentTargetValue (vol);
  5920. e.injectControllerForTest (20, 0, 0);
  5921. const auto bottom = e.currentTargetValue (vol);
  5922. if (livewf190efResult == "OK" && (std::abs (top - 0.75f) > 0.01f || std::abs (bottom - 0.25f) > 0.01f))
  5923. livewf190efResult = "ERROR range " + juce::String (bottom) + " " + juce::String (top);
  5924. std::vector<Fire> fired;
  5925. e.onRemoteFire = [&fired] (const Fire& f) { fired.push_back (f); };
  5926. e.injectControllerForTest (21, 0, 127);
  5927. e.injectControllerForTest (21, 0, 127); // (still down: no new press)
  5928. e.injectControllerForTest (21, 0, 0);
  5929. if (livewf190efResult == "OK"
  5930. && (fired.size() != 2 || fired[0].edge != Edge::press || fired[1].edge != Edge::release || ! (fired[0].target == Target::slot (0, 0))))
  5931. livewf190efResult = "ERROR slot fire " + juce::String ((int) fired.size());
  5932. e.setMapMode (Mode::midi);
  5933. fired.clear();
  5934. e.injectControllerForTest (20, 0, 127);
  5935. e.injectControllerForTest (21, 0, 127);
  5936. const auto caught = e.takeMapCapture();
  5937. if (livewf190efResult == "OK" && (std::abs (e.currentTargetValue (vol) - 0.25f) > 0.01f || ! fired.empty()))
  5938. livewf190efResult = "ERROR mappings acted in MIDI Map Mode";
  5939. else if (livewf190efResult == "OK" && (! caught || caught->number != 21 || caught->channel != 0 || e.takeMapCapture().has_value()))
  5940. livewf190efResult = "ERROR map capture";
  5941. e.setMapMode (Mode::off);
  5942. e.onRemoteFire = nullptr;
  5943. }
  5944. // round 190em: a scene's time signature denominator (.lynx round trip; an older file without it reads n/4; a
  5945. // 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
  5946. // armed track, the selected scene's slot, the tempo from a phrase played while stopped (8 notes at 148 BPM), the
  5947. // new clip launched and the transport started
  5948. juce::String livewf190emResult = "OK";
  5949. {
  5950. auto song = lynx::Song::makeDefault();
  5951. auto& grid = lynx::launcher::ensureGrid (song);
  5952. grid.scenes.resize (3);
  5953. lynx::session::setSceneSignature (song, 1, 6, 8);
  5954. lynx::session::setSceneTempo (song, 1, 100.0);
  5955. juce::String why;
  5956. const auto json = lynx::ProjectFile::toJson (song);
  5957. const auto back = lynx::ProjectFile::fromJson (json, why);
  5958. if (! back || ! back->clipGrid || back->clipGrid->scenes != song.clipGrid->scenes || back->clipGrid->scenes[1].beatUnit != 8)
  5959. livewf190emResult = "ERROR round trip " + why;
  5960. {
  5961. // a captured clip's blank label (ClipGridSlot::blankName) survives the round trip
  5962. auto withClip = song;
  5963. lynx::Clip c;
  5964. c.pattern = 0;
  5965. c.length = 4 * lynx::ppq;
  5966. if (withClip.patterns.empty())
  5967. withClip.patterns.emplace_back();
  5968. const auto slot = lynx::launcher::setClip (withClip, 0, 0, c);
  5969. if (slot >= 0)
  5970. withClip.clipGrid->slots[(std::size_t) slot].blankName = true;
  5971. const auto again = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (withClip), why);
  5972. const auto* keptClip = again && again->clipGrid ? lynx::launcher::clipAt (*again->clipGrid, 0, 0) : nullptr;
  5973. const auto* kept = keptClip != nullptr ? &again->clipGrid->slots[(std::size_t) keptClip->gridSlot] : nullptr;
  5974. if (livewf190emResult == "OK" && (slot < 0 || kept == nullptr || ! kept->blankName))
  5975. livewf190emResult = "ERROR blank clip name round trip";
  5976. }
  5977. auto parsed = juce::JSON::parse (json);
  5978. if (auto* scenes = parsed.getProperty ("clipGrid", {}).getProperty ("scenes", {}).getArray(); scenes != nullptr && scenes->size() > 1)
  5979. if (auto* o = (*scenes)[1].getDynamicObject())
  5980. o->removeProperty ("beatUnit");
  5981. const auto older = lynx::ProjectFile::fromJson (juce::JSON::toString (parsed), why);
  5982. if (livewf190emResult == "OK" && (! older || ! older->clipGrid || older->clipGrid->scenes.size() < 2 || older->clipGrid->scenes[1].beatUnit != 4
  5983. || older->clipGrid->scenes[1].beatsPerBar != 6))
  5984. livewf190emResult = "ERROR older reader";
  5985. if (livewf190emResult == "OK" && lynx::ProjectFile::toJson (lynx::Song::makeDefault()).contains ("beatUnit"))
  5986. livewf190emResult = "ERROR beatUnit written by default";
  5987. // round 190fg: the song meter's denominator round-trips through .lynx; a file without it reads n/4
  5988. {
  5989. auto six = lynx::Song::makeDefault();
  5990. six.beatsPerBar = 6;
  5991. six.beatUnit = 8;
  5992. const auto text = lynx::ProjectFile::toJson (six);
  5993. juce::String why2;
  5994. const auto back = lynx::ProjectFile::fromJson (text, why2);
  5995. auto json = juce::JSON::parse (text);
  5996. if (auto* o = json.getDynamicObject())
  5997. o->removeProperty ("beatUnit");
  5998. const auto old = lynx::ProjectFile::fromJson (juce::JSON::toString (json), why2);
  5999. if (livewf190emResult == "OK" && (! back || back->beatsPerBar != 6 || back->beatUnit != 8 || ! old || old->beatsPerBar != 6 || old->beatUnit != 4))
  6000. livewf190emResult = "ERROR song meter round trip";
  6001. }
  6002. lynx::AudioEngine e (false);
  6003. e.editSong ([] (lynx::Song& s) {
  6004. s.bpm = 120.0;
  6005. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 4));
  6006. auto& g = lynx::launcher::ensureGrid (s);
  6007. g.scenes.resize (3);
  6008. lynx::session::setSceneSignature (s, 2, 6, 8);
  6009. lynx::session::setSceneTempo (s, 2, 90.0);
  6010. }, false);
  6011. e.launcherCommand ({ lynx::launcher::Command::Type::launchScene, 0, 2 });
  6012. // (round 190fg: the song takes the scene's 6 / 8 as it is: six eighths a bar, 3 quarters long)
  6013. if (livewf190emResult == "OK" && (e.getSong().beatsPerBar != 6 || e.getSong().beatUnit != 8 || e.getSong().barTicks() != 3 * lynx::ppq
  6014. || e.getSong().bpm != 90.0))
  6015. livewf190emResult = "ERROR scene launch " + juce::String (e.getSong().beatsPerBar) + "/" + juce::String (e.getSong().beatUnit) + " "
  6016. + juce::String (e.getSong().bpm);
  6017. e.stop();
  6018. e.editSong ([] (lynx::Song& s) {
  6019. s.bpm = 120.0;
  6020. s.beatsPerBar = 4;
  6021. s.beatUnit = 4;
  6022. }, false);
  6023. e.setGridTrackArmed (2, true, true);
  6024. const auto now = juce::Time::getMillisecondCounterHiRes();
  6025. const auto beat = 60000.0 / 148.0;
  6026. for (int i = 0; i < 8; ++i)
  6027. {
  6028. const auto at = now - 9.0 * beat + i * beat;
  6029. e.logPlayedNoteForTest (at, 0, 60 + (i % 4) * 2, 0.8f, true);
  6030. e.logPlayedNoteForTest (at + beat * 0.5, 0, 60 + (i % 4) * 2, 0.8f, false);
  6031. }
  6032. int placed = -1;
  6033. bool into = true;
  6034. const auto r = e.captureMidiToSlot (2, 1, placed, into);
  6035. const auto& g = *e.getSong().clipGrid;
  6036. const auto* clip = lynx::launcher::clipAt (g, 2, 1);
  6037. if (livewf190emResult == "OK" && (r.notes != 8 || placed != 1 || into || clip == nullptr || clip->length != 8 * lynx::ppq))
  6038. livewf190emResult = "ERROR capture " + juce::String (r.notes) + " " + juce::String (placed) + (clip == nullptr ? " no clip" : " " + juce::String ((int) clip->length));
  6039. else if (livewf190emResult == "OK" && std::abs (e.getSong().bpm - 148.0) > 0.5)
  6040. livewf190emResult = "ERROR tempo " + juce::String (e.getSong().bpm, 2);
  6041. else if (livewf190emResult == "OK" && ! e.getTransport().playing.load())
  6042. livewf190emResult = "ERROR the capture did not start the transport";
  6043. e.stop();
  6044. }
  6045. const auto mixerBasics = lynx::mixerbasics::run();
  6046. // issue #142: every font has a typeface, and one without does not crash (fonts get theirs through the
  6047. // look and feel, as in the app)
  6048. auto& lookBefore = juce::LookAndFeel::getDefaultLookAndFeel();
  6049. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  6050. const auto fontsResult = lynx::theme::fontSelfTest();
  6051. const auto paintCachesResult = lynx::theme::paintCacheSelfTest(); // (round 190gr)
  6052. const auto motionOverlayResult = lynx::ui::MotionOverlay::selfTest(); // (round 190ip)
  6053. // round 190bm (0.1.25 showed the Mixer and the Playlist black): their cached pictures shown on native and
  6054. // software targets against straight paints (ui/PictureCheck.h; --picturetest runs more sizes and scales)
  6055. juce::String picturesResult = "OK";
  6056. {
  6057. lynx::AudioEngine pictureEngine (false);
  6058. auto pictureFailures = 0;
  6059. juce::String lines;
  6060. {
  6061. lynx::PlaylistComponent playlist (pictureEngine);
  6062. playlist.setBounds (0, 0, 1200, 700);
  6063. playlist.setVisible (true);
  6064. lines << lynx::ui::picturecheck::run (playlist, "Playlist 1200 x 700", { 1.0f, 1.5f }, pictureFailures, {});
  6065. }
  6066. {
  6067. lynx::MixerComponent mixer (pictureEngine);
  6068. mixer.setBounds (0, 0, 1200, 500);
  6069. mixer.setVisible (true);
  6070. lines << lynx::ui::picturecheck::run (mixer, "Mixer 1200 x 500", { 1.0f, 1.5f }, pictureFailures, {});
  6071. }
  6072. if (pictureFailures > 0 || ! lines.contains (": ok"))
  6073. picturesResult = "ERROR " + lines.trim().replace ("\n", "; ");
  6074. }
  6075. // round 190ci (the 0.1.26 release candidate ended when an FPC channel was added): every built-in generator and
  6076. // effect, its editor built as the Channel Rack / mixer opens it and painted once. The report file names the
  6077. // plugin being opened, so a run that dies there says which one.
  6078. const auto editorsResult = lynx::pluginthumbs::checkEditors ([&reportPath] (const juce::String& key) {
  6079. if (reportPath.isNotEmpty())
  6080. juce::File (reportPath).replaceWithText ("(opening the editor of " + key + ")\n");
  6081. });
  6082. // round 190ci: a fault leaves a crash file, also on a stack Windows cannot walk (that FPC fault left none)
  6083. const auto faultResult = faultReportSelfTest();
  6084. const auto stemsResult = stemsSinglePassSelfTest(); // round 190gj
  6085. juce::LookAndFeel::setDefaultLookAndFeel (&lookBefore);
  6086. const auto ok = editorsResult.startsWith ("OK") && ! faultResult.startsWith ("ERROR") && stemsResult == "OK"
  6087. && 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
  6088. && sessionResult == "OK" && liveResult.startsWith ("OK")
  6089. && wavpack != "ERROR" && effectsOk && driverPanel == "OK" && deviceChange.startsWith ("OK") && exportParity.startsWith ("OK") && midiHotplug.startsWith ("OK") && metronomeOk && artResult == "OK" && effectParamsResult == "OK"
  6090. && sidechainResult == "OK" && lanesResult == "OK" && arrange190cgResult == "OK" && livescr190drResult == "OK" && livewf190efResult == "OK" && livewf190emResult == "OK" && versionsResult == "OK" && pluginsOffResult == "OK" && missingFilesResult == "OK"
  6091. && midigen190fmResult == "OK" && clipenv190giResult == "OK" && beatslaw190gxResult == "OK" && editorScale190heResult == "OK" && sfModBase190heResult == "OK" && trackauto190gzResult == "OK" && community190hqResult == "OK" && rollup030Result == "OK"
  6092. && remoteHistoryResult.startsWith ("OK") && hostedStateLockResult.startsWith ("OK")
  6093. && hostedStateContentionResult.startsWith ("OK")
  6094. && danceWindowResult == "OK" && clickActivationResult == "OK" && motionOverlayResult.startsWith ("OK");
  6095. juce::String report;
  6096. report << "connections=" << offline.getNumGraphConnections() << "\n"
  6097. << "peak=" << peak << "\n"
  6098. << "stems_single_pass=" << stemsResult << "\n"
  6099. << "project=" << (projectOk ? "OK" : "ERROR " + error) << "\n"
  6100. << "playlist_track_modes_roundtrip=" << (trackModes122Ok ? "OK" : "ERROR") << "\n"
  6101. << "project_features=" << (richOk ? "OK" : "ERROR") << "\n"
  6102. << "hardware_outputs=" << (hwOutOk ? "OK" : "ERROR") << "\n"
  6103. << "plugin_host_keys_option=" << (hostKeysOk ? "OK" : "ERROR") << "\n"
  6104. << "plugin_levels_new_project=" << (pluginLevelsOk ? "OK" : "ERROR") << "\n"
  6105. << "flp168j_fields=" << (flp168jOk ? "OK" : "ERROR") << "\n"
  6106. << "clip_fades_180d=" << (clipFades180dOk ? "OK" : "ERROR") << "\n"
  6107. << "pattern_blocks=" << (blocksOk ? "OK" : "ERROR") << "\n"
  6108. << "pattern_clip_takeover=" << (takeoverOk ? "OK" : "ERROR") << "\n"
  6109. << "comp_crossfades=" << (compOk ? "OK" : "ERROR") << "\n"
  6110. << "channel_polyphony=" << (polyOk ? "OK" : "ERROR") << "\n"
  6111. << "track_latency=" << (latencyOk ? "OK" : "ERROR") << "\n"
  6112. << "pre_fader_sends=" << (preSendOk ? "OK" : "ERROR") << "\n"
  6113. << "low_latency_recording=" << (lowLatencyOk ? "OK" : "ERROR") << "\n"
  6114. << "preview_in_time=" << (previewInTimeOk ? "OK" : "ERROR") << " (2 s loop prepared in " << juce::String (previewPrepareMs, 1) << " ms)\n"
  6115. << "plugin_substitutes=" << (substituteOk ? "OK" : "ERROR") << "\n"
  6116. << "patcher=" << (patcherOk ? "OK" : "ERROR") << "\n"
  6117. << "racks=" << rackResult << "\n"
  6118. << "native_engines=" << nativesResult << " (" << nativesMade << " made)\n"
  6119. << "undo=" << (undoOk ? "OK" : "ERROR") << "\n"
  6120. << "mixer_basics=" << mixerBasics << "\n"
  6121. << "remote_history=" << remoteHistoryResult << "\n"
  6122. << "hosted_state_lock=" << hostedStateLockResult << "\n"
  6123. << "hosted_state_contention=" << hostedStateContentionResult << "\n"
  6124. << "fonts=" << fontsResult << "\n"
  6125. << "paint_caches=" << paintCachesResult << "\n"
  6126. << "motion_overlay=" << motionOverlayResult << "\n"
  6127. << "cached_pictures=" << picturesResult << "\n"
  6128. << "plugin_editors=" << editorsResult << "\n"
  6129. << "fault_report=" << faultResult << "\n"
  6130. << "recording=" << (recordOk && recordUndoOk ? "OK" : "ERROR") << "\n"
  6131. << "cancel_recording=" << (cancelRecordOk ? "OK" : "ERROR") << "\n"
  6132. << "midi=" << (midiOk ? "OK" : "ERROR") << "\n"
  6133. << "package=" << (packageOk ? "OK" : "ERROR") << "\n"
  6134. << "projectSave=" << (projectSaveOk ? "OK" : "ERROR") << "\n"
  6135. << "online_session=" << sessionResult << "\n"
  6136. << "live_session=" << liveResult << "\n"
  6137. << "wavpack=" << wavpack << "\n"
  6138. << "effects=" << (effectsOk ? "OK" : "NONFINITE") << "\n"
  6139. << "effect_params_saved=" << effectParamsResult << "\n"
  6140. << "driver_panel=" << driverPanel << "\n"
  6141. << "device_change=" << deviceChange << "\n"
  6142. << "export_parity=" << exportParity << "\n"
  6143. << "midi_hotplug=" << midiHotplug << "\n"
  6144. << "plugin_art=" << artResult << "\n"
  6145. << "plugin_sidechain=" << sidechainResult << "\n"
  6146. << "versions_panel=" << versionsResult << "\n"
  6147. << "plugins_off=" << pluginsOffResult << "\n"
  6148. << "missing_files_rows=" << missingFilesResult << "\n"
  6149. << "dance_window=" << danceWindowResult << "\n"
  6150. << "dance_window_detail=" << danceWindowDetail << "\n"
  6151. << "click_activation=" << clickActivationResult << "\n"
  6152. << "lanes_saved=" << lanesResult << "\n"
  6153. << "arrange190cg_saved=" << arrange190cgResult << "\n"
  6154. << "livescr190dr=" << livescr190drResult << "\n"
  6155. << "livewf190ef=" << livewf190efResult << "\n"
  6156. << "livewf190em=" << livewf190emResult << "\n"
  6157. << "midigen190fm_saved=" << midigen190fmResult << "\n"
  6158. << "trackauto190gz_saved=" << trackauto190gzResult << "\n"
  6159. << "clipenv190gi_saved=" << clipenv190giResult << "\n"
  6160. << "beatslaw190gx_saved=" << beatslaw190gxResult << "\n"
  6161. << "editor_scale190he_saved=" << editorScale190heResult << "\n"
  6162. << "sf_mod_base190he=" << sfModBase190heResult << "\n"
  6163. << "community190hq_saved=" << community190hqResult << "\n"
  6164. << "rollup030_copy_for_0128=" << rollup030Result << "\n"
  6165. << "metronome=" << metronomeResult << " (FL sounds " << metronomeFlSounds << "/" << lynx::metronome::soundCount
  6166. << ", downbeat peak " << juce::String (metronomeMaster, 4) << ")\n";
  6167. // issue #138 (round 190c): a short note at the very start of the Playlist against the same note at bar 2, through
  6168. // the Export window's path (its own thread while the message loop runs: the report is finished from there)
  6169. if (reportPath.isNotEmpty())
  6170. juce::File (reportPath).replaceWithText (report + "(short_export running)\n");
  6171. lynx::shortexport::run (false, 1, {}, {}, [this, report, ok, reportPath] (juce::String shortExport) {
  6172. const auto all = ok && shortExport.startsWith ("OK");
  6173. const auto text = report + "short_export=" + shortExport + "\nresult=" + (all ? "OK" : "FAILED") + "\n";
  6174. if (reportPath.isNotEmpty())
  6175. juce::File (reportPath).replaceWithText (text);
  6176. setApplicationReturnValue (all ? 0 : 1);
  6177. quit();
  6178. });
  6179. }
  6180. // Every built-in effect in its native editor: random / extreme parameters, mouse drags over the editor, the editor
  6181. // painted, audio rendered at 44.1 / 48 / 96 kHz. Returns false when an effect output NaN / inf (muted by the
  6182. // renderer's guard). The report lists each effect. Used by --fxfuzz and (a short run) by --selftest.
  6183. bool runEffectFuzz (int rounds, const juce::String& reportPath, bool drags = false)
  6184. {
  6185. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  6186. lynx::setNativeEditorDemo (true);
  6187. juce::String report;
  6188. auto allFinite = true;
  6189. {
  6190. lynx::AudioEngine offline (false);
  6191. juce::Random random (111);
  6192. const auto value = [&] { const auto r = random.nextInt (6); return r == 0 ? 0.0f : r == 1 ? 1.0f : random.nextFloat(); };
  6193. for (int k = 0; k <= (int) lynx::lastEffectKind; ++k)
  6194. {
  6195. const auto kind = (lynx::EffectKind) k;
  6196. if (! lynx::NativeEffectWindows::canOpen (kind) || kind == lynx::EffectKind::patcher) // (the Patcher's editor is a graph window)
  6197. continue;
  6198. const auto before = lynx::RackRenderer::nonFiniteEffectBlocks();
  6199. const auto& info = lynx::effectInfo (kind);
  6200. // (FL engines: a fresh instance as the menus make it, from the user's FL installation; round 142)
  6201. auto fx = lynx::natives::newEffect (kind, lynx::flStudioAccess()).value_or (lynx::makeEffectSlot (kind));
  6202. int dragged = 0; // parameter changes made by the mouse drags
  6203. for (int round = 0; round < rounds; ++round)
  6204. {
  6205. if (round > 0)
  6206. for (std::size_t p = 0; p < info.params.size(); ++p)
  6207. fx.params[p] = round == 1 ? 0.0f : round == 2 ? 1.0f : value();
  6208. auto song = lynx::Song::makeDefault(); // its demo beat feeds the effect
  6209. song.mixer.resize (2);
  6210. song.mixer[0].name = "Master";
  6211. song.mixer[1].name = "Insert 1";
  6212. song.mixer[1].effects.assign (1, fx);
  6213. for (auto& channel : song.channels)
  6214. channel.mixerTrack = 1;
  6215. offline.setSong (std::move (song));
  6216. offline.dispatchPendingMessages();
  6217. const auto pages = juce::jmax (1, (int) lynx::plugui::layoutFor (kind).pages.size());
  6218. for (int page = 0; page < pages; ++page)
  6219. {
  6220. auto editor = kind == lynx::EffectKind::facetEq ? lynx::makeFacetEqEditor (offline, 1, 0, false)
  6221. : lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, page);
  6222. if (editor == nullptr || editor->getWidth() <= 0 || editor->getHeight() <= 0)
  6223. continue;
  6224. juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
  6225. const auto paint = [&] {
  6226. juce::Graphics g (image);
  6227. editor->paintEntireComponent (g, false);
  6228. };
  6229. paint();
  6230. // drags from a grid of points, as a user moving every control (plain left button)
  6231. if (round >= 3 && drags)
  6232. {
  6233. const auto source = juce::Desktop::getInstance().getMainMouseSource();
  6234. const auto step = juce::jmax (12, juce::jmin (editor->getWidth(), editor->getHeight()) / 8);
  6235. for (int y = step / 2; y < editor->getHeight(); y += step)
  6236. for (int x = step / 2; x < editor->getWidth(); x += step)
  6237. {
  6238. auto* target = editor->getComponentAt (x, y);
  6239. if (target == nullptr)
  6240. continue;
  6241. const auto at = target->getLocalPoint (editor.get(), juce::Point<float> ((float) x, (float) y));
  6242. const auto now = juce::Time::getCurrentTime();
  6243. const auto event = [&] (juce::Point<float> p, juce::ModifierKeys mods) {
  6244. return juce::MouseEvent (source, p, mods, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, target, target, now, at, now, 1, false);
  6245. };
  6246. const auto down = juce::ModifierKeys (juce::ModifierKeys::leftButtonModifier);
  6247. const juce::Component::SafePointer<juce::Component> alive (target);
  6248. target->mouseDown (event (at, down));
  6249. const auto dy = (float) (random.nextBool() ? 400 : -400), dx = (float) (random.nextInt (401) - 200);
  6250. if (alive != nullptr)
  6251. target->mouseDrag (event (at + juce::Point<float> (dx * 0.5f, dy * 0.5f), down));
  6252. if (alive != nullptr)
  6253. target->mouseDrag (event (at + juce::Point<float> (dx, dy), down));
  6254. if (alive != nullptr)
  6255. target->mouseUp (event (at + juce::Point<float> (dx, dy), juce::ModifierKeys()));
  6256. juce::PopupMenu::dismissAllActiveMenus();
  6257. offline.dispatchPendingMessages();
  6258. }
  6259. paint();
  6260. }
  6261. }
  6262. for (const auto rate : { 44100.0, 48000.0, 96000.0 })
  6263. offline.renderOffline (0.05, rate);
  6264. if (round == 0 || round >= 3) // keep what the drags set for the next round
  6265. if (offline.getSong().mixer.size() > 1 && ! offline.getSong().mixer[1].effects.empty())
  6266. {
  6267. const auto& now = offline.getSong().mixer[1].effects[0];
  6268. for (std::size_t p = 0; p < fx.params.size(); ++p)
  6269. dragged += now.params[p] != fx.params[p] ? 1 : 0;
  6270. dragged += now.state != fx.state ? 1 : 0;
  6271. fx = now;
  6272. }
  6273. }
  6274. const auto broken = lynx::RackRenderer::nonFiniteEffectBlocks() - before;
  6275. allFinite = allFinite && broken == 0;
  6276. report << info.name << ": " << (broken == 0 ? juce::String ("OK") : "non-finite output in " + juce::String ((juce::int64) broken) + " blocks")
  6277. << " (" << dragged << " changes by mouse)\n";
  6278. if (reportPath.isNotEmpty())
  6279. juce::File (reportPath).replaceWithText (report + "(running)\n"); // what was reached, if it crashes
  6280. }
  6281. }
  6282. lynx::setNativeEditorDemo (false);
  6283. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  6284. report << "result=" << (allFinite ? "OK" : "NONFINITE") << "\n";
  6285. if (reportPath.isNotEmpty())
  6286. juce::File (reportPath).replaceWithText (report);
  6287. return allFinite;
  6288. }
  6289. // --opentest (round 157a): see the command line. Runs on the message loop (the editors' timers, animations and
  6290. // native windows are real); one step per timer tick.
  6291. void runOpenTest (const juce::String& reportPath, bool visible, std::function<void (bool)> done)
  6292. {
  6293. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  6294. struct OpenTest final : juce::Timer
  6295. {
  6296. juce::String reportPath, report;
  6297. bool visible = false, ok = true;
  6298. std::function<void (bool)> done;
  6299. std::unique_ptr<lynx::AudioEngine> engine;
  6300. std::vector<std::pair<juce::String, std::function<void()>>> steps;
  6301. std::size_t next = 0;
  6302. std::atomic<std::int64_t> lastStep { 0 };
  6303. std::atomic<bool> finished { false };
  6304. std::thread watchdog;
  6305. juce::String current;
  6306. std::mutex currentLock;
  6307. int opened = 0, painted = 0;
  6308. // LYNX_OPENTEST_TIMEOUT (seconds): longer for sanitizer builds
  6309. const std::int64_t timeoutMs = 1000 * juce::jmax (5, juce::SystemStats::getEnvironmentVariable ("LYNX_OPENTEST_TIMEOUT", "20").getIntValue());
  6310. static std::int64_t now() { return (std::int64_t) juce::Time::getMillisecondCounter(); }
  6311. void write (const juce::String& tail = {}) { juce::File (reportPath).replaceWithText (report + tail); }
  6312. ~OpenTest() override
  6313. {
  6314. finished = true;
  6315. if (watchdog.joinable())
  6316. watchdog.join();
  6317. }
  6318. void start()
  6319. {
  6320. lastStep = now();
  6321. // the UI hang watch runs during the whole test (5 s): a slow step leaves its stack next to the report
  6322. const auto folder = juce::File (reportPath).getParentDirectory().getChildFile ("opentest-hang");
  6323. folder.deleteRecursively();
  6324. folder.createDirectory();
  6325. lynx::crashguard::startHangWatch (folder.getFullPathName().replaceCharacter ('\\', '/').toStdString(), 5000);
  6326. watchdog = std::thread ([this] {
  6327. while (! finished)
  6328. {
  6329. std::this_thread::sleep_for (std::chrono::milliseconds (200));
  6330. if (now() - lastStep.load() > timeoutMs)
  6331. {
  6332. juce::String at;
  6333. {
  6334. const std::lock_guard<std::mutex> l (currentLock);
  6335. at = current;
  6336. }
  6337. juce::File (reportPath).replaceWithText (report + "HANG at " + at + " (no progress for " + juce::String (timeoutMs / 1000) + " s; stack in opentest-hang)\nresult=HANG\n");
  6338. lynx::crashguard::exitNow (3);
  6339. }
  6340. }
  6341. });
  6342. startTimer (30);
  6343. }
  6344. // every LYNX window but none of the main one (there is none here): moved off-screen, painted once into an image
  6345. void touchWindows (bool resize, bool large)
  6346. {
  6347. auto& desktop = juce::Desktop::getInstance();
  6348. for (int i = desktop.getNumComponents(); --i >= 0;)
  6349. if (auto* c = desktop.getComponent (i); c != nullptr && c->isVisible())
  6350. {
  6351. if (! visible && c->getScreenX() > -3000)
  6352. c->setTopLeftPosition (-6000, -6000);
  6353. if (resize)
  6354. if (auto* w = dynamic_cast<juce::ResizableWindow*> (c))
  6355. {
  6356. const auto b = w->getBounds();
  6357. w->setSize (large ? b.getWidth() * 2 : juce::jmax (40, b.getWidth() / 3), large ? b.getHeight() * 2 : juce::jmax (40, b.getHeight() / 3));
  6358. }
  6359. if (c->getWidth() > 0 && c->getHeight() > 0 && c->getWidth() < 8000 && c->getHeight() < 8000)
  6360. {
  6361. juce::Image image (juce::Image::ARGB, c->getWidth(), c->getHeight(), true);
  6362. juce::Graphics g (image);
  6363. c->paintEntireComponent (g, false);
  6364. ++painted;
  6365. // LYNX_OPENTEST_SHOTS=folder: each window as first painted (before the resizes), for a look
  6366. if (const auto shots = juce::SystemStats::getEnvironmentVariable ("LYNX_OPENTEST_SHOTS", {}); shots.isNotEmpty() && ! resize)
  6367. {
  6368. juce::FileOutputStream out (juce::File (shots).getChildFile (juce::String (painted).paddedLeft ('0', 4) + ".png"));
  6369. if (out.openedOk())
  6370. {
  6371. out.setPosition (0), out.truncate();
  6372. juce::PNGImageFormat().writeImageToStream (c->createComponentSnapshot (c->getLocalBounds()), out);
  6373. }
  6374. }
  6375. }
  6376. }
  6377. }
  6378. void timerCallback() override
  6379. {
  6380. if (next >= steps.size())
  6381. {
  6382. stopTimer();
  6383. lynx::NativeEffectWindows::closeAll();
  6384. lynx::closeChannelSettings();
  6385. // the UI hang watch itself: the message thread spins past the stall time; the watcher must write the stack
  6386. {
  6387. const auto before = lynx::crashguard::lastHangFile();
  6388. for (const auto until = now() + 7000; now() < until;)
  6389. lastStep = now(); // (busy: no heartbeat; the test's own watchdog stays quiet)
  6390. for (const auto until = now() + 1500; now() < until && lynx::crashguard::lastHangFile() == before;)
  6391. std::this_thread::sleep_for (std::chrono::milliseconds (20));
  6392. lynx::crashguard::stopHangWatch();
  6393. const juce::File hang (juce::String::fromUTF8 (lynx::crashguard::lastHangFile().c_str()));
  6394. const auto text = hang.loadFileAsString();
  6395. const auto frames = juce::StringArray::fromLines (text).size() - 2;
  6396. #if JUCE_WINDOWS
  6397. const auto hangOk = lynx::crashguard::lastHangFile() != before && hang.existsAsFile() && text.contains ("LYNX.exe+0x") && frames >= 3;
  6398. #else
  6399. const auto hangOk = lynx::crashguard::lastHangFile() != before && hang.existsAsFile() && frames >= 3;
  6400. #endif
  6401. report << "hang watch: " << (hangOk ? "OK" : "FAIL") << " (" << hang.getFileName() << ", " << frames << " lines"
  6402. << (before.empty() ? juce::String() : "; a step stalled > 5 s earlier: " + juce::String::fromUTF8 (before.c_str())) << ")\n";
  6403. ok = ok && hangOk;
  6404. }
  6405. report << "windows opened: " << opened << ", paints: " << painted << "\nresult=" << (ok ? "OK" : "FAIL") << "\n";
  6406. write();
  6407. finished = true;
  6408. if (done)
  6409. done (ok);
  6410. return;
  6411. }
  6412. auto& [label, fn] = steps[next++];
  6413. {
  6414. const std::lock_guard<std::mutex> l (currentLock);
  6415. current = label;
  6416. }
  6417. fn();
  6418. lastStep = now();
  6419. lynx::crashguard::heartbeat();
  6420. }
  6421. };
  6422. auto* test = new OpenTest();
  6423. test->reportPath = reportPath;
  6424. test->visible = visible;
  6425. test->engine = std::make_unique<lynx::AudioEngine> (false);
  6426. test->done = [test, done] (bool ok) {
  6427. juce::MessageManager::callAsync ([test, done, ok] {
  6428. delete test;
  6429. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  6430. done (ok);
  6431. });
  6432. };
  6433. auto& engine = *test->engine;
  6434. lynx::setNativeEditorDemo (true); // live displays animate without an audio device
  6435. const auto songWith = [] (const lynx::EffectSlot& fx) {
  6436. auto song = lynx::Song::makeDefault();
  6437. song.mixer.resize (2);
  6438. song.mixer[0].name = "Master";
  6439. song.mixer[1].name = "Insert 1";
  6440. song.mixer[1].effects.assign (1, fx);
  6441. for (auto& channel : song.channels)
  6442. channel.mixerTrack = 1;
  6443. return song;
  6444. };
  6445. // an older project's slot: its parameter list cut to `count` and read back by the project reader (the
  6446. // parameters a newer LYNX added after them take their defaults)
  6447. const auto oldState = [songWith] (const lynx::EffectSlot& fx, std::size_t count) -> std::optional<lynx::Song> {
  6448. auto json = juce::JSON::parse (lynx::ProjectFile::toJson (songWith (fx)));
  6449. if (auto* mixer = json["mixer"].getArray(); mixer != nullptr && mixer->size() > 1)
  6450. if (auto* effects = (*mixer)[1]["effects"].getArray(); effects != nullptr && ! effects->isEmpty())
  6451. if (auto* params = (*effects)[0]["params"].getArray())
  6452. params->removeRange ((int) count, params->size());
  6453. juce::String error;
  6454. return lynx::ProjectFile::fromJson (juce::JSON::toString (json), error);
  6455. };
  6456. auto& steps = test->steps;
  6457. juce::Random random (157);
  6458. for (int k = 0; k <= (int) lynx::lastEffectKind; ++k)
  6459. {
  6460. const auto kind = (lynx::EffectKind) k;
  6461. if (! lynx::NativeEffectWindows::canOpen (kind) || kind == lynx::EffectKind::patcher)
  6462. continue;
  6463. const auto& info = lynx::effectInfo (kind);
  6464. const auto base = lynx::natives::newEffect (kind, lynx::flStudioAccess()).value_or (lynx::makeEffectSlot (kind));
  6465. const auto n = info.params.size();
  6466. std::vector<std::pair<juce::String, std::function<std::optional<lynx::Song>()>>> variants;
  6467. variants.push_back ({ "default", [=] { return std::optional<lynx::Song> (songWith (base)); } });
  6468. for (const auto value : { 0.0f, 1.0f })
  6469. variants.push_back ({ value == 0.0f ? "all 0" : "all 1", [=] {
  6470. auto fx = base;
  6471. for (std::size_t p = 0; p < n; ++p) fx.params[p] = value;
  6472. return std::optional<lynx::Song> (songWith (fx));
  6473. } });
  6474. const auto seed = random.nextInt64();
  6475. variants.push_back ({ "random", [=] {
  6476. juce::Random r (seed);
  6477. auto fx = base;
  6478. for (std::size_t p = 0; p < n; ++p) fx.params[p] = r.nextFloat();
  6479. return std::optional<lynx::Song> (songWith (fx));
  6480. } });
  6481. std::vector<std::size_t> cuts { n / 2 };
  6482. 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)
  6483. if (c < n) cuts.push_back (c);
  6484. for (const auto c : cuts)
  6485. variants.push_back ({ "old project (" + juce::String ((int) c) + " of " + juce::String ((int) n) + " params)", [=] { return oldState (base, c); } });
  6486. for (const auto& [variant, makeSong] : variants)
  6487. {
  6488. const auto label = juce::String::fromUTF8 (info.name) + " / " + variant;
  6489. steps.push_back ({ label + ": open", [test, &engine, label, makeSong = makeSong] {
  6490. auto song = makeSong();
  6491. if (! song)
  6492. {
  6493. test->report << "FAIL " << label << ": project reader refused the state\n";
  6494. test->ok = false;
  6495. return;
  6496. }
  6497. engine.setSong (std::move (*song));
  6498. engine.dispatchPendingMessages();
  6499. lynx::NativeEffectWindows::open (engine, 1, 0);
  6500. ++test->opened;
  6501. test->touchWindows (false, false);
  6502. } });
  6503. steps.push_back ({ label + ": run", [test, &engine] {
  6504. for (const auto rate : { 44100.0, 48000.0, 96000.0 })
  6505. engine.renderOffline (0.03, rate);
  6506. test->touchWindows (false, false);
  6507. } });
  6508. steps.push_back ({ label + ": small", [test] { test->touchWindows (true, false); } });
  6509. steps.push_back ({ label + ": large", [test] { test->touchWindows (true, true); } });
  6510. steps.push_back ({ label + ": close", [test, label] {
  6511. lynx::NativeEffectWindows::closeAll();
  6512. test->report << label << ": OK\n";
  6513. test->write ("(running)\n");
  6514. } });
  6515. }
  6516. }
  6517. // instruments: the channel window the Channel rack opens (Patcher: its graph window, not here)
  6518. for (int k = 0; k <= (int) lynx::InstrumentKind::soundfont; ++k)
  6519. {
  6520. const auto kind = (lynx::InstrumentKind) k;
  6521. if (kind == lynx::InstrumentKind::plugin || kind == lynx::InstrumentKind::patcher)
  6522. continue;
  6523. for (const auto* variant : { "default", "old project (saved and read back)", "odd settings" })
  6524. {
  6525. if (juce::String (variant) == "odd settings" && kind != lynx::InstrumentKind::soundfont)
  6526. continue;
  6527. const auto label = "instrument " + juce::String (k) + " / " + variant;
  6528. steps.push_back ({ label + ": open", [test, &engine, kind, label, variant = juce::String (variant), old = juce::String (variant) != "default"] {
  6529. auto song = lynx::Song::makeDefault();
  6530. auto channel = lynx::natives::makeChannel (kind, lynx::flStudioAccess());
  6531. lynx::ChannelDef def;
  6532. def.instrument = kind;
  6533. def.name = "Test";
  6534. song.channels.push_back (channel ? *channel : def);
  6535. if (kind == lynx::InstrumentKind::soundfont && variant != "default")
  6536. {
  6537. // a real font when FL's is there; NaN / huge / truncated settings
  6538. const auto& roots = lynx::flStudioAccess().roots;
  6539. if (! roots.data.empty())
  6540. song.channels.back().samplePath = (juce::File (juce::String::fromUTF8 (roots.data.c_str()))
  6541. .getChildFile ("Patches/Soundfonts/STR_Ensemble.sf2"))
  6542. .getFullPathName().toStdString();
  6543. if (variant == "odd settings")
  6544. song.channels.back().modelParams = { NAN, 1.0e9f, -1.0e9f, 0.5f, 7.0f };
  6545. }
  6546. if (old)
  6547. {
  6548. juce::String error;
  6549. if (auto again = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error))
  6550. song = std::move (*again);
  6551. }
  6552. const auto index = (int) song.channels.size() - 1;
  6553. engine.setSong (std::move (song));
  6554. engine.dispatchPendingMessages();
  6555. lynx::openChannelSettings (engine, index);
  6556. ++test->opened;
  6557. test->touchWindows (false, false);
  6558. } });
  6559. steps.push_back ({ label + ": run", [test, &engine] {
  6560. engine.renderOffline (0.03, 48000.0);
  6561. test->touchWindows (false, false);
  6562. } });
  6563. steps.push_back ({ label + ": small", [test] { test->touchWindows (true, false); } });
  6564. steps.push_back ({ label + ": large", [test] { test->touchWindows (true, true); } });
  6565. steps.push_back ({ label + ": close", [test, label] {
  6566. lynx::closeChannelSettings();
  6567. test->report << label << ": OK\n";
  6568. test->write ("(running)\n");
  6569. } });
  6570. }
  6571. }
  6572. test->start();
  6573. }
  6574. void runPluginOptionsTest (const juce::String& pluginPath, const juce::String& reportPath, const juce::String& shotsPath)
  6575. {
  6576. struct Test final : juce::Timer
  6577. {
  6578. juce::String reportPath, report;
  6579. juce::File shots;
  6580. std::unique_ptr<lynx::AudioEngine> engine;
  6581. std::unique_ptr<juce::DocumentWindow> mainWindow, other; // LYNX's main window stand-in; another secondary window
  6582. bool instrument = false, ok = true;
  6583. int channelIndex = -1, phase = 0;
  6584. juce::uint32 phaseStart = 0;
  6585. juce::AudioPluginInstance* instance = nullptr;
  6586. std::function<void (bool)> done;
  6587. void step (const juce::String& line)
  6588. {
  6589. report << line << "\n";
  6590. juce::File (reportPath).replaceWithText (report);
  6591. }
  6592. void expect (const juce::String& name, bool value)
  6593. {
  6594. step (name + "=" + juce::String ((int) value));
  6595. ok = ok && value;
  6596. }
  6597. void next (int to)
  6598. {
  6599. phase = to;
  6600. phaseStart = juce::Time::getMillisecondCounter();
  6601. }
  6602. int elapsed() const { return (int) (juce::Time::getMillisecondCounter() - phaseStart); }
  6603. lynx::PluginRef* ref (lynx::Song& song) const
  6604. {
  6605. if (instrument)
  6606. return channelIndex < 0 || channelIndex >= (int) song.channels.size() ? nullptr : &song.channels[(size_t) channelIndex].plugin;
  6607. return song.mixer.size() < 2 || song.mixer[1].effects.empty() ? nullptr : &song.mixer[1].effects[0].plugin;
  6608. }
  6609. const lynx::PluginRef& refNow() const { return *ref (const_cast<lynx::Song&> (engine->getSong())); }
  6610. juce::AudioPluginInstance* find()
  6611. {
  6612. if (instrument)
  6613. {
  6614. if (auto* p = dynamic_cast<lynx::PluginInstrument*> (engine->getChannelInstrument (channelIndex).get()))
  6615. return &p->getInstance();
  6616. }
  6617. else if (auto* p = dynamic_cast<lynx::PluginEffect*> (engine->getEffect (1, 0).get()))
  6618. return &p->getInstance();
  6619. return nullptr;
  6620. }
  6621. void openWindow()
  6622. {
  6623. std::shared_ptr<void> owner = instrument ? std::shared_ptr<void> (engine->getChannelInstrument (channelIndex))
  6624. : std::shared_ptr<void> (engine->getEffect (1, 0));
  6625. lynx::PluginWindows::open (owner, *instance, instance->getName(),
  6626. { engine.get(), [this] (lynx::Song& song) { return ref (song); }, instrument, instrument ? -1 : 1,
  6627. instrument ? -1 : 0, {}, {} });
  6628. }
  6629. void shot (const char* name, bool settingsPage = false)
  6630. {
  6631. if (shots != juce::File() && instance != nullptr)
  6632. step (juce::String ("shot_") + name + "=" + juce::String ((int) lynx::PluginWindows::saveWindowShot (*instance, shots.getChildFile (juce::String (name) + ".png"), settingsPage)));
  6633. }
  6634. // the plugin window is in front of the other secondary window
  6635. bool pluginInFront()
  6636. {
  6637. auto* plug = lynx::PluginWindows::hostWindowHandle (*instance);
  6638. #if JUCE_WINDOWS
  6639. return plug != nullptr && lynx::nativechild::isAbove (plug, other->getWindowHandle());
  6640. #else
  6641. auto& desktop = juce::Desktop::getInstance();
  6642. for (int i = 0; i < desktop.getNumComponents(); ++i)
  6643. if (auto* c = desktop.getComponent (i); c->getWindowHandle() == plug)
  6644. return c->isAlwaysOnTop() || desktop.getComponent (desktop.getNumComponents() - 1) == c;
  6645. return false;
  6646. #endif
  6647. }
  6648. void timerCallback() override
  6649. {
  6650. if (phase == 0) // waiting for the engine to host the plugin
  6651. {
  6652. instance = find();
  6653. if (instance == nullptr)
  6654. {
  6655. if (elapsed() > 20000)
  6656. finish ("not hosted");
  6657. return;
  6658. }
  6659. step ("hosted=" + instance->getName() + " format=" + instance->getPluginDescription().pluginFormatName);
  6660. openWindow();
  6661. next (1);
  6662. return;
  6663. }
  6664. if (phase == 1 && elapsed() >= 800) // Pin on top: off for a new plugin
  6665. {
  6666. expect ("pin_off_by_default", ! lynx::PluginWindows::isPinnedOnTop (*instance) && ! refNow().pinned);
  6667. shot ("pin-off");
  6668. const auto history = engine->getHistoryPosition();
  6669. lynx::PluginWindows::setPinnedOnTop (*instance, true);
  6670. expect ("pin_set", lynx::PluginWindows::isPinnedOnTop (*instance) && refNow().pinned);
  6671. expect ("pin_no_undo_step_project_modified", engine->getHistoryPosition() == history && engine->isModified());
  6672. // another secondary window brought in front of it
  6673. other = std::make_unique<juce::DocumentWindow> ("Another LYNX window", juce::Colours::darkslategrey, juce::DocumentWindow::closeButton);
  6674. other->setUsingNativeTitleBar (true);
  6675. other->setBounds (mainWindow->getX() + 60, mainWindow->getY() + 60, 420, 300);
  6676. other->setVisible (true);
  6677. lynx::keepAboveMainWindow (*other);
  6678. lynx::forceForegroundForTest (*other);
  6679. other->toFront (true);
  6680. next (2);
  6681. return;
  6682. }
  6683. if (phase == 2 && elapsed() >= 1200)
  6684. {
  6685. expect ("pinned_stays_in_front_of_a_clicked_window", pluginInFront());
  6686. shot ("pin-on");
  6687. // closed and opened again: the pin comes back from the project
  6688. lynx::PluginWindows::close (*instance);
  6689. openWindow();
  6690. next (3);
  6691. return;
  6692. }
  6693. if (phase == 3 && elapsed() >= 600)
  6694. {
  6695. expect ("pin_remembered_when_reopened", lynx::PluginWindows::isPinnedOnTop (*instance));
  6696. lynx::PluginWindows::setPinnedOnTop (*instance, false);
  6697. expect ("pin_cleared", ! lynx::PluginWindows::isPinnedOnTop (*instance) && ! refNow().pinned);
  6698. other->toFront (true);
  6699. next (4);
  6700. return;
  6701. }
  6702. if (phase == 4 && elapsed() >= 1000)
  6703. {
  6704. #if JUCE_WINDOWS
  6705. expect ("unpinned_goes_behind_a_clicked_window", ! pluginInFront());
  6706. #endif
  6707. other = nullptr;
  6708. // the wrapper settings page: LYNX's Velocity row in the MIDI group (instruments), default = follow
  6709. expect ("velocity_follows_midi_settings_by_default", refNow().velocityMode == lynx::prefs::pluginVelocityFollow
  6710. && refNow().fixedVelocity == lynx::prefs::defaultFixedVelocity);
  6711. shot ("wrapper-velocity-default", true);
  6712. engine->editSong ([this] (lynx::Song& song) {
  6713. if (auto* r = ref (song))
  6714. {
  6715. r->velocityMode = lynx::prefs::pluginVelocityFixed;
  6716. r->fixedVelocity = 96;
  6717. }
  6718. });
  6719. next (5);
  6720. return;
  6721. }
  6722. if (phase == 5 && elapsed() >= 400)
  6723. {
  6724. expect ("velocity_change_keeps_the_running_plugin", find() == instance);
  6725. shot ("wrapper-velocity-fixed", true);
  6726. engine->undo();
  6727. expect ("velocity_undo", refNow().velocityMode == lynx::prefs::pluginVelocityFollow && find() == instance);
  6728. // the preset menu's "Play a note when a preset loads": off by default, a user setting
  6729. expect ("audition_off_by_default", ! lynx::pluginpresetui::auditionOnLoad());
  6730. lynx::pluginpresetui::setAuditionOnLoad (true);
  6731. expect ("audition_menu_opened", lynx::PluginWindows::showPresetMenu (*instance));
  6732. next (6);
  6733. return;
  6734. }
  6735. if (phase == 6 && elapsed() >= 500) // the menu, as drawn
  6736. {
  6737. auto found = false;
  6738. auto& desktop = juce::Desktop::getInstance();
  6739. for (int c = desktop.getNumComponents(); --c >= 0 && ! found;)
  6740. if (auto* menu = desktop.getComponent (c); dynamic_cast<juce::TopLevelWindow*> (menu) == nullptr && menu->isVisible()
  6741. && menu->getHeight() > 60 && shots != juce::File())
  6742. {
  6743. const auto image = menu->createComponentSnapshot (menu->getLocalBounds(), true, 1.0f);
  6744. juce::FileOutputStream out (shots.getChildFile ("preset-menu-audition.png"));
  6745. found = out.openedOk() && juce::PNGImageFormat().writeImageToStream (image, out);
  6746. }
  6747. step ("shot_preset-menu-audition=" + juce::String ((int) found));
  6748. juce::PopupMenu::dismissAllActiveMenus();
  6749. // a preset loaded while the song is stopped: the note waits a moment, sounds, ends
  6750. const auto asked = engine->auditionPreset (*instance);
  6751. expect ("audition_only_for_channel_instruments", asked == instrument);
  6752. expect ("audition_waits_first", ! instrument || engine->auditionState() == 1);
  6753. next (7);
  6754. return;
  6755. }
  6756. if (phase == 7 && elapsed() >= 300)
  6757. {
  6758. expect ("audition_sounds", ! instrument || engine->auditionState() == 2);
  6759. next (8);
  6760. return;
  6761. }
  6762. if (phase == 8 && elapsed() >= 700)
  6763. {
  6764. expect ("audition_ends", engine->auditionState() == 0);
  6765. engine->getTransport().playing.store (true); // the song plays: no audition
  6766. expect ("no_audition_while_playing", ! engine->auditionPreset (*instance) && engine->auditionState() == 0);
  6767. engine->getTransport().playing.store (false);
  6768. lynx::pluginpresetui::setAuditionOnLoad (false);
  6769. expect ("audition_setting_off_again", ! lynx::pluginpresetui::auditionOnLoad());
  6770. finish ({});
  6771. }
  6772. }
  6773. void finish (const juce::String& failure)
  6774. {
  6775. stopTimer();
  6776. if (failure.isNotEmpty())
  6777. step ("failed=" + failure);
  6778. ok = ok && failure.isEmpty();
  6779. step (ok ? "result=OK" : "result=FAILED");
  6780. lynx::PluginWindows::closeAll();
  6781. done (ok);
  6782. }
  6783. };
  6784. auto* test = new Test();
  6785. test->reportPath = reportPath;
  6786. if (shotsPath.isNotEmpty())
  6787. {
  6788. test->shots = juce::File (shotsPath);
  6789. test->shots.createDirectory();
  6790. }
  6791. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  6792. test->done = [this, test] (bool ok) {
  6793. setApplicationReturnValue (ok ? 0 : 1);
  6794. juce::MessageManager::callAsync ([this, test] {
  6795. lynx::setMainWindowForOwnership (nullptr);
  6796. test->other = nullptr;
  6797. test->mainWindow = nullptr;
  6798. test->engine = nullptr;
  6799. delete test;
  6800. quit();
  6801. });
  6802. };
  6803. test->engine = std::make_unique<lynx::AudioEngine> (false);
  6804. test->mainWindow = std::make_unique<juce::DocumentWindow> ("LYNX test main window", juce::Colours::darkgrey, 0);
  6805. test->mainWindow->setBounds (20, 20, 300, 200);
  6806. test->mainWindow->setVisible (true);
  6807. lynx::setMainWindowForOwnership (test->mainWindow.get());
  6808. auto& host = test->engine->getPluginHost();
  6809. test->step ("plugins_in_file=" + juce::String (host.addPluginFile (juce::File (pluginPath))));
  6810. std::optional<juce::PluginDescription> chosen;
  6811. for (const auto& type : host.getKnownPlugins().getTypes())
  6812. if (juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginPath).getFileName() || type.fileOrIdentifier == pluginPath)
  6813. {
  6814. chosen = type;
  6815. break;
  6816. }
  6817. if (! chosen)
  6818. {
  6819. test->step ("result=FAILED (no plugin)");
  6820. test->done (false);
  6821. return;
  6822. }
  6823. test->instrument = chosen->isInstrument;
  6824. lynx::PluginRef ref;
  6825. ref.id = chosen->createIdentifierString().toStdString();
  6826. ref.name = chosen->name.toStdString();
  6827. test->engine->editSong ([&] (lynx::Song& song) {
  6828. if (test->instrument)
  6829. {
  6830. lynx::ChannelDef c;
  6831. c.name = ref.name;
  6832. c.instrument = lynx::InstrumentKind::plugin;
  6833. c.plugin = ref;
  6834. test->channelIndex = (int) song.channels.size();
  6835. song.channels.push_back (c);
  6836. }
  6837. else
  6838. {
  6839. while (song.mixer.size() < 2)
  6840. song.mixer.emplace_back();
  6841. lynx::EffectSlot slot;
  6842. slot.kind = lynx::EffectKind::plugin;
  6843. slot.plugin = ref;
  6844. song.mixer[1].effects.push_back (slot);
  6845. }
  6846. });
  6847. test->engine->markSaved();
  6848. test->step ("plugin=" + chosen->name + " instrument=" + juce::String ((int) test->instrument));
  6849. test->next (0);
  6850. test->startTimerHz (20);
  6851. }
  6852. void runReloadTest (const juce::String& pluginPath, const juce::String& reportPath, const juce::String& shotsPath, bool waitKill)
  6853. {
  6854. struct Test final : juce::Timer
  6855. {
  6856. juce::String reportPath, report;
  6857. juce::File shots;
  6858. std::unique_ptr<lynx::AudioEngine> engine;
  6859. std::unique_ptr<juce::DocumentWindow> mainWindow; // stands for LYNX's main window (window ownership)
  6860. bool instrument = false, waitKill = false, ok = true;
  6861. int channelIndex = -1, phase = 0, round = 0;
  6862. juce::uint32 phaseStart = 0;
  6863. int firstPid = 0, pid = 0, historyBefore = 0;
  6864. bool modifiedBefore = false;
  6865. float captured = -1.0f;
  6866. juce::AudioPluginInstance* instance = nullptr;
  6867. std::vector<lynx::ChannelDef> channelsBefore;
  6868. std::function<void (bool)> done;
  6869. lynx::AudioEngine::HostedSlot where() const { return instrument ? lynx::AudioEngine::HostedSlot { channelIndex, -1, -1 } : lynx::AudioEngine::HostedSlot { -1, 1, 0 }; }
  6870. void step (const juce::String& line)
  6871. {
  6872. report << line << "\n";
  6873. juce::File (reportPath).replaceWithText (report);
  6874. }
  6875. void expect (const juce::String& name, bool value)
  6876. {
  6877. step (name + "=" + juce::String ((int) value));
  6878. ok = ok && value;
  6879. }
  6880. void next (int to)
  6881. {
  6882. phase = to;
  6883. phaseStart = juce::Time::getMillisecondCounter();
  6884. }
  6885. int elapsed() const { return (int) (juce::Time::getMillisecondCounter() - phaseStart); }
  6886. juce::AudioPluginInstance* find()
  6887. {
  6888. if (instrument)
  6889. {
  6890. if (auto* p = dynamic_cast<lynx::PluginInstrument*> (engine->getChannelInstrument (channelIndex).get()))
  6891. return &p->getInstance();
  6892. }
  6893. else if (auto* p = dynamic_cast<lynx::PluginEffect*> (engine->getEffect (1, 0).get()))
  6894. return &p->getInstance();
  6895. return nullptr;
  6896. }
  6897. // a few blocks through the plugin (the offline engine has no audio thread): they carry parameter changes to
  6898. // the plugin's process and its values back
  6899. void pump (int blocks)
  6900. {
  6901. std::vector<float> l (512), r (512);
  6902. lynx::EffectParams none {};
  6903. for (int b = 0; b < blocks; ++b)
  6904. {
  6905. std::fill (l.begin(), l.end(), 0.0f);
  6906. std::fill (r.begin(), r.end(), 0.0f);
  6907. if (instrument)
  6908. {
  6909. if (auto in = engine->getChannelInstrument (channelIndex))
  6910. in->render (l.data(), r.data(), 512, 1.0f, 1.0f);
  6911. }
  6912. else if (auto fx = engine->getEffect (1, 0))
  6913. fx->process (l.data(), r.data(), 512, none, 120.0);
  6914. }
  6915. }
  6916. juce::AudioProcessorParameter* firstParam()
  6917. {
  6918. if (instance != nullptr)
  6919. for (auto* candidate : instance->getParameters())
  6920. if (candidate->isAutomatable() && ! candidate->isMetaParameter() && candidate != instance->getBypassParameter())
  6921. return candidate;
  6922. return nullptr;
  6923. }
  6924. void openWindow()
  6925. {
  6926. std::shared_ptr<void> owner = instrument ? std::shared_ptr<void> (engine->getChannelInstrument (channelIndex))
  6927. : std::shared_ptr<void> (engine->getEffect (1, 0));
  6928. lynx::PluginWindows::WrapperContext context { engine.get(), [this] (lynx::Song& song) -> lynx::PluginRef* {
  6929. if (instrument)
  6930. return channelIndex < 0 || channelIndex >= (int) song.channels.size()
  6931. ? nullptr : &song.channels[(size_t) channelIndex].plugin;
  6932. return song.mixer.size() < 2 || song.mixer[1].effects.empty() ? nullptr : &song.mixer[1].effects[0].plugin;
  6933. }, instrument, instrument ? -1 : 1, instrument ? -1 : 0, {}, {} };
  6934. context.reload = [] {}; // (the test reloads by itself; with it the window shows the notice)
  6935. lynx::PluginWindows::open (owner, *instance, instance->getName(), std::move (context));
  6936. }
  6937. void shot (const char* name, bool settingsPage = false)
  6938. {
  6939. if (shots != juce::File() && instance != nullptr)
  6940. step (juce::String ("shot_") + name + "=" + juce::String ((int) lynx::PluginWindows::saveWindowShot (*instance, shots.getChildFile (juce::String (name) + ".png"), settingsPage)));
  6941. }
  6942. void timerCallback() override
  6943. {
  6944. if (phase == 0) // waiting for the engine to host the plugin
  6945. {
  6946. instance = find();
  6947. if (instance == nullptr)
  6948. {
  6949. if (elapsed() > 20000)
  6950. finish ("not hosted");
  6951. return;
  6952. }
  6953. pid = firstPid = lynx::sandboxedPluginProcessId (*instance);
  6954. step ("hosted=" + instance->getName() + " format=" + instance->getPluginDescription().pluginFormatName + " pid=" + juce::String (pid));
  6955. expect ("separate_process", lynx::isSandboxedPlugin (*instance) && pid != 0);
  6956. expect ("running", ! engine->hostedPluginDown (where()) && engine->downHostedPlugins().empty());
  6957. // a setting that is captured (what a save or a backup does), then one that is not
  6958. if (auto* param = firstParam())
  6959. {
  6960. param->setValue (param->getValue() > 0.5f ? 0.13f : 0.87f);
  6961. pump (4);
  6962. engine->capturePluginStates();
  6963. captured = param->getValue();
  6964. param->setValue (captured > 0.5f ? 0.31f : 0.69f);
  6965. pump (4);
  6966. step ("param=" + param->getName (64) + " captured=" + juce::String (captured, 4) + " then=" + juce::String (param->getValue(), 4));
  6967. }
  6968. else
  6969. {
  6970. engine->capturePluginStates();
  6971. step ("param=none");
  6972. }
  6973. channelsBefore = engine->getSong().channels;
  6974. historyBefore = engine->getHistoryPosition();
  6975. modifiedBefore = engine->isModified();
  6976. if (shots != juce::File())
  6977. openWindow();
  6978. next (1);
  6979. return;
  6980. }
  6981. if (phase == 1 && elapsed() >= 600) // the plugin's process goes
  6982. {
  6983. shot (round == 0 ? "window-running" : "window-reloaded");
  6984. if (waitKill && round == 0)
  6985. {
  6986. juce::File (reportPath + ".pid").replaceWithText (juce::String (pid));
  6987. step ("waiting_for_kill pid=" + juce::String (pid));
  6988. }
  6989. else
  6990. lynx::crashSandboxedPluginForTest (*instance);
  6991. next (2);
  6992. return;
  6993. }
  6994. if (phase == 2) // LYNX notices
  6995. {
  6996. if (! engine->hostedPluginDown (where()))
  6997. {
  6998. pump (1); // (as the audio thread would: a block that gets no answer marks it too)
  6999. if (elapsed() > (waitKill && round == 0 ? 120000 : 10000))
  7000. finish ("the plugin never went down");
  7001. return;
  7002. }
  7003. step ("down_after_ms=" + juce::String (elapsed()));
  7004. const auto down = engine->downHostedPlugins();
  7005. expect ("listed_down", down.size() == 1 && down.front() == where());
  7006. expect ("listed_by_name", engine->downHostedPlugins (nameInSong()).size() == 1 && engine->downHostedPlugins ("no such plugin").empty());
  7007. next (3);
  7008. return;
  7009. }
  7010. if (phase == 3 && elapsed() >= 1500) // nothing reloads by itself
  7011. {
  7012. expect ("still_down_without_asking", engine->hostedPluginDown (where()) && find() == instance
  7013. && lynx::sandboxedPluginProcessId (*instance) == pid);
  7014. shot (round == 0 ? "reload-notice" : "reload-notice-again");
  7015. if (shots != juce::File() && round == 0)
  7016. {
  7017. lynx::PluginWindows::close (*instance);
  7018. lynx::PluginWindows::promptReload (*engine, where(), {});
  7019. next (4);
  7020. return;
  7021. }
  7022. next (5);
  7023. return;
  7024. }
  7025. if (phase == 4 && elapsed() >= 500) // the prompt a click on the channel / slot shows
  7026. {
  7027. auto found = false;
  7028. for (int c = juce::Desktop::getInstance().getNumComponents(); --c >= 0;)
  7029. if (auto* alert = dynamic_cast<juce::AlertWindow*> (juce::Desktop::getInstance().getComponent (c)))
  7030. {
  7031. const auto image = alert->createComponentSnapshot (alert->getLocalBounds(), true, 1.0f);
  7032. juce::FileOutputStream out (shots.getChildFile ("reload-prompt.png"));
  7033. found = out.openedOk() && juce::PNGImageFormat().writeImageToStream (image, out);
  7034. alert->exitModalState (0); // Close: nothing reloads
  7035. break;
  7036. }
  7037. step ("shot_reload-prompt=" + juce::String ((int) found));
  7038. next (45);
  7039. return;
  7040. }
  7041. if (phase == 45 && elapsed() >= 300)
  7042. {
  7043. expect ("still_down_after_close", engine->hostedPluginDown (where()));
  7044. next (5);
  7045. return;
  7046. }
  7047. if (phase == 5) // Reload, as the notice's button / the prompt / the menu item do
  7048. {
  7049. auto* old = instance;
  7050. const auto running = lynx::PluginWindows::reload (*engine, { where() });
  7051. instance = find();
  7052. const auto newPid = instance != nullptr ? lynx::sandboxedPluginProcessId (*instance) : 0;
  7053. expect ("reloaded", running == 1 && instance != nullptr && ! engine->hostedPluginDown (where()) && engine->downHostedPlugins().empty());
  7054. expect ("new_process", newPid != 0 && newPid != pid);
  7055. step ("pid=" + juce::String (newPid) + " same_object=" + juce::String ((int) (instance == old)));
  7056. expect ("old_window_closed", ! lynx::PluginWindows::isOpen (*old) || instance == old);
  7057. pid = newPid;
  7058. if (instance != nullptr)
  7059. {
  7060. pump (4);
  7061. if (auto* param = firstParam(); param != nullptr && captured >= 0.0f)
  7062. {
  7063. step ("param_after_reload=" + juce::String (param->getValue(), 4));
  7064. expect ("state_captured_last", std::abs (param->getValue() - captured) < 0.02f);
  7065. }
  7066. }
  7067. expect ("song_untouched", engine->getSong().channels == channelsBefore);
  7068. expect ("no_undo_step", engine->getHistoryPosition() == historyBefore && engine->isModified() == modifiedBefore);
  7069. if (instance == nullptr)
  7070. {
  7071. finish ("no instance after the reload");
  7072. return;
  7073. }
  7074. if (shots != juce::File())
  7075. openWindow();
  7076. if (round == 0) // once more: a plugin that crashes again waits for the user again
  7077. {
  7078. round = 1;
  7079. next (1);
  7080. return;
  7081. }
  7082. next (6);
  7083. return;
  7084. }
  7085. if (phase == 6 && elapsed() >= 400) // an edit and its undo keep the reloaded plugin
  7086. {
  7087. shot ("window-reloaded-twice");
  7088. auto* before = find();
  7089. engine->editSong ([] (lynx::Song& song) { song.bpm += 1.0f; });
  7090. engine->undo();
  7091. expect ("undo_keeps_the_reloaded_plugin", find() == before && ! engine->hostedPluginDown (where()));
  7092. lynx::PluginWindows::closeAll();
  7093. finish ({});
  7094. }
  7095. }
  7096. std::string nameInSong() const
  7097. {
  7098. const auto& song = engine->getSong();
  7099. return instrument ? song.channels[(size_t) channelIndex].plugin.name : song.mixer[1].effects[0].plugin.name;
  7100. }
  7101. void finish (const juce::String& failure)
  7102. {
  7103. stopTimer();
  7104. if (failure.isNotEmpty())
  7105. step ("failed=" + failure);
  7106. ok = ok && failure.isEmpty();
  7107. step (ok ? "result=OK" : "result=FAILED");
  7108. lynx::PluginWindows::closeAll();
  7109. done (ok);
  7110. }
  7111. };
  7112. lynx::setPluginSandboxAlerts (true); // (the deaths are recorded as in the app; no box: there is no main component)
  7113. auto* test = new Test();
  7114. test->reportPath = reportPath;
  7115. test->waitKill = waitKill;
  7116. if (shotsPath.isNotEmpty())
  7117. {
  7118. test->shots = juce::File (shotsPath);
  7119. test->shots.createDirectory();
  7120. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  7121. }
  7122. juce::File (reportPath + ".pid").deleteFile();
  7123. test->done = [this, test] (bool ok) {
  7124. setApplicationReturnValue (ok ? 0 : 1);
  7125. juce::MessageManager::callAsync ([this, test] {
  7126. lynx::setMainWindowForOwnership (nullptr);
  7127. test->mainWindow = nullptr;
  7128. test->engine = nullptr;
  7129. delete test;
  7130. quit();
  7131. });
  7132. };
  7133. test->engine = std::make_unique<lynx::AudioEngine> (false);
  7134. if (shotsPath.isNotEmpty())
  7135. {
  7136. test->mainWindow = std::make_unique<juce::DocumentWindow> ("LYNX test main window", juce::Colours::darkgrey, 0);
  7137. test->mainWindow->setBounds (20, 20, 300, 200);
  7138. test->mainWindow->setVisible (true);
  7139. lynx::setMainWindowForOwnership (test->mainWindow.get());
  7140. }
  7141. auto& host = test->engine->getPluginHost();
  7142. test->step ("plugins_in_file=" + juce::String (host.addPluginFile (juce::File (pluginPath))));
  7143. std::optional<juce::PluginDescription> chosen;
  7144. for (const auto& type : host.getKnownPlugins().getTypes())
  7145. if (juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginPath).getFileName() || type.fileOrIdentifier == pluginPath)
  7146. {
  7147. chosen = type;
  7148. break;
  7149. }
  7150. if (! chosen)
  7151. {
  7152. test->step ("result=FAILED (no plugin)");
  7153. test->done (false);
  7154. return;
  7155. }
  7156. test->instrument = chosen->isInstrument;
  7157. lynx::PluginRef ref;
  7158. ref.separateProcess = true;
  7159. ref.id = chosen->createIdentifierString().toStdString();
  7160. ref.name = chosen->name.toStdString();
  7161. test->engine->editSong ([&] (lynx::Song& song) {
  7162. if (test->instrument)
  7163. {
  7164. lynx::ChannelDef c;
  7165. c.name = ref.name;
  7166. c.instrument = lynx::InstrumentKind::plugin;
  7167. c.plugin = ref;
  7168. test->channelIndex = (int) song.channels.size();
  7169. song.channels.push_back (c);
  7170. }
  7171. else
  7172. {
  7173. while (song.mixer.size() < 2)
  7174. song.mixer.emplace_back();
  7175. lynx::EffectSlot slot;
  7176. slot.kind = lynx::EffectKind::plugin;
  7177. slot.plugin = ref;
  7178. song.mixer[1].effects.push_back (slot);
  7179. }
  7180. });
  7181. test->step ("plugin=" + chosen->name + " instrument=" + juce::String ((int) test->instrument));
  7182. test->next (0);
  7183. test->startTimerHz (20);
  7184. }
  7185. void runPlugWinTest (const juce::String& pluginPath, const juce::String& reportPath, const juce::String& only, int seconds)
  7186. {
  7187. struct Test final : juce::Timer
  7188. {
  7189. juce::String reportPath, report;
  7190. std::unique_ptr<lynx::AudioEngine> engine;
  7191. bool instrument = false;
  7192. int phase = 0, ticks = 0, seconds = 15, dockStep = 0;
  7193. juce::uint32 phaseStartMs = 0; // (phase 1 counts real time: the timer's ticks ran faster than 20 Hz here)
  7194. juce::AudioPluginInstance* instance = nullptr;
  7195. juce::AudioProcessorParameter* checked = nullptr;
  7196. std::unique_ptr<juce::DocumentWindow> mainWindow; // stands for LYNX's main window (window ownership)
  7197. lynx::Workspace* workspace = nullptr; // LYNX_PLUGWIN_DOCK=1: the real main window's desktop (issue #116)
  7198. int channelIndex = -1; // an instrument: its channel (added after the song's own channels)
  7199. int stepMs = 3000; // dock mode: each state held that long (screenshots)
  7200. bool keysDone = false;
  7201. bool dockOk = true;
  7202. std::function<void (bool)> done;
  7203. // LYNX_PLUGWIN_DROP=<sample> (issue #174): a Sample browser window beside the plugin window with that file
  7204. // selected. The report gives the row's and the editor's places on screen with what LYNX sees there (for a
  7205. // real drag by xdotool / SendInput in that time), and, before the plugin is removed, whether the plugin took
  7206. // the file (its saved state names it).
  7207. juce::File dropFile;
  7208. std::unique_ptr<juce::DocumentWindow> dropWindow;
  7209. lynx::BrowserComponent* dropBrowser = nullptr;
  7210. int dropStage = 0;
  7211. juce::uint32 dropReadyMs = 0; // (the Browser may take long to list a big library: the time counts from here)
  7212. void dropTick (int elapsedMs)
  7213. {
  7214. if (dropStage == 0 && elapsedMs >= 1000)
  7215. {
  7216. lynx::externaldrag::install();
  7217. auto content = lynx::BrowserComponent::makeSampleBrowserContent (*engine, [this] (lynx::BrowserComponent& b) { dropBrowser = &b; });
  7218. dropWindow = std::make_unique<juce::DocumentWindow> ("LYNX test sample browser", juce::Colours::darkgrey, 0);
  7219. dropWindow->setContentOwned (content.release(), false);
  7220. dropWindow->setBounds (20, 240, 340, 520);
  7221. dropWindow->setVisible (true);
  7222. if (dropBrowser != nullptr)
  7223. {
  7224. dropBrowser->showFilterForSnapshot (dropFile.getParentDirectory(), lynx::browserview::ContentFilter::all);
  7225. step ("drop_locate=" + juce::String ((int) dropBrowser->locateFile (dropFile)));
  7226. }
  7227. dropStage = 1;
  7228. }
  7229. else if (dropStage == 1 && elapsedMs >= 2500)
  7230. {
  7231. using namespace lynx::externaldrag;
  7232. const auto row = dropBrowser != nullptr ? dropBrowser->selectedRowScreenBounds() : juce::Rectangle<int>();
  7233. const auto from = row.getCentre();
  7234. // (physical pixels too: SendInput / xdotool work in those)
  7235. auto physical = [] (juce::Point<int> p) {
  7236. const auto q = juce::Desktop::getInstance().getDisplays().logicalToPhysical (p);
  7237. return " phys=" + juce::String (q.x) + "," + juce::String (q.y);
  7238. };
  7239. step ("drop_source=" + juce::String (from.x) + "," + juce::String (from.y) + " place=" + placeName (placeAt (from)) + physical (from));
  7240. if (const auto pid = lynx::sandboxedPluginProcessId (*instance); pid != 0)
  7241. step ("drop_target_pid=" + juce::String (pid)); // (its window is the other process's)
  7242. else if (auto* editor = instance->getActiveEditor())
  7243. {
  7244. const auto to = editor->getScreenBounds().getCentre();
  7245. step ("drop_target=" + juce::String (to.x) + "," + juce::String (to.y) + " place=" + placeName (placeAt (to)) + physical (to));
  7246. }
  7247. const auto files = filesOf (juce::String (lynx::BrowserComponent::dragDescription) + "|" + dropFile.getFullPathName(), nullptr);
  7248. step ("drop_files=" + files.joinIntoString (";"));
  7249. dropStage = 2;
  7250. dropReadyMs = juce::Time::getMillisecondCounter();
  7251. }
  7252. }
  7253. void dropResult()
  7254. {
  7255. juce::MemoryBlock state;
  7256. instance->getStateInformation (state);
  7257. const auto name = dropFile.getFileNameWithoutExtension().toStdString();
  7258. auto holds = [&name] (const juce::MemoryBlock& block) {
  7259. const auto* bytes = static_cast<const char*> (block.getData());
  7260. return ! name.empty() && std::search (bytes, bytes + block.getSize(), name.begin(), name.end()) != bytes + block.getSize();
  7261. };
  7262. auto received = holds (state);
  7263. // (JUCE's VST3 host keeps the plugin's own state base64-encoded inside an XML of its own)
  7264. auto xml = juce::AudioProcessor::getXmlFromBinary (state.getData(), (int) state.getSize());
  7265. if (xml == nullptr)
  7266. xml = juce::parseXML (state.toString());
  7267. if (! received && xml != nullptr)
  7268. for (auto* e : xml->getChildIterator())
  7269. {
  7270. juce::MemoryBlock inner;
  7271. if (inner.fromBase64Encoding (e->getAllSubText().trim()) && holds (inner))
  7272. received = true;
  7273. }
  7274. step ("drop_received=" + juce::String ((int) received));
  7275. }
  7276. // issue #116 (with LYNX_DOCKED_PLUGINS=1 and LYNX_PLUGWIN_DOCK=1), FL's f116 sequence for every floating
  7277. // panel: the docked plugin window goes behind a clicked panel and comes back in front when clicked; a
  7278. // panel called by its key comes in front too; Detached reopens it as a window of its own, which stays above
  7279. // every panel clicked (it is owned by the main window).
  7280. const std::array<lynx::workspace::Panel, 4> dockPanels { lynx::workspace::Panel::channelRack, lynx::workspace::Panel::playlist,
  7281. lynx::workspace::Panel::pianoRoll, lynx::workspace::Panel::mixer };
  7282. const int dockSteps = 2 * 4 + 18; // (the last one reports dock_result)
  7283. int danceChannel = -1; // issue #116 slice 4: a dance channel's dancer over the docked plugin
  7284. lynx::MainComponent* ui = nullptr; // dock mode: the real main window's contents
  7285. struct ScaleSpy final : juce::ComponentPeer::ScaleFactorListener
  7286. {
  7287. int calls = 0;
  7288. double last = 0.0;
  7289. void nativeScaleFactorChanged (double s) override { ++calls; last = s; }
  7290. } scaleSpy;
  7291. juce::ComponentPeer* spiedPeer = nullptr;
  7292. void* panelHandle (lynx::workspace::Panel p) const { return workspace->getFrame (p).getWindowHandle(); }
  7293. void dockCheck (int at)
  7294. {
  7295. using lynx::workspace::Panel;
  7296. auto* main = mainWindow->getWindowHandle();
  7297. auto* plug = lynx::PluginWindows::hostWindowHandle (*instance);
  7298. auto expect = [this] (const juce::String& name, bool value) {
  7299. step (name + "=" + juce::String ((int) value));
  7300. dockOk = dockOk && value;
  7301. };
  7302. auto id = [] (Panel p) { return juce::String (lynx::workspace::panelId (p)); };
  7303. if (at == 0)
  7304. {
  7305. expect ("docked", lynx::PluginWindows::isDocked (*instance));
  7306. expect ("plugin_native_child", plug != nullptr && lynx::nativechild::parentOf (plug) == main);
  7307. for (auto p : dockPanels)
  7308. {
  7309. auto* h = panelHandle (p);
  7310. expect (id (p) + "_visible", workspace->isPanelVisible (p));
  7311. expect (id (p) + "_native_child", h != nullptr && h != main && lynx::nativechild::parentOf (h) == main);
  7312. expect ("plugin_above_" + id (p) + "_when_opened", lynx::nativechild::isAbove (plug, h));
  7313. }
  7314. expect ("browser_plain", ! workspace->isNativePanel (Panel::browser));
  7315. }
  7316. if (at < 2 * 4)
  7317. {
  7318. const auto p = dockPanels[at / 2];
  7319. if (at % 2 == 0)
  7320. {
  7321. workspace->activate (p); // a click on the panel
  7322. expect (id (p) + "_above_plugin_after_its_click", lynx::nativechild::isAbove (panelHandle (p), plug));
  7323. // the plugin stays above the panels nobody clicked
  7324. for (auto other : dockPanels)
  7325. if (other != p)
  7326. expect ("plugin_above_" + id (other) + "_after_" + id (p) + "_click", lynx::nativechild::isAbove (plug, panelHandle (other)));
  7327. }
  7328. else
  7329. {
  7330. lynx::PluginWindows::open ({}, *instance, {}); // (open again = a click on the plugin)
  7331. expect ("plugin_above_" + id (p) + "_after_plugin_click", lynx::nativechild::isAbove (plug, panelHandle (p)));
  7332. }
  7333. return;
  7334. }
  7335. if (at == 8)
  7336. {
  7337. // a layout change elsewhere (a panel resized, the Browser shown) keeps the plugin in front; a panel
  7338. // called by its key comes in front of it
  7339. workspace->hide (Panel::browser);
  7340. workspace->show (Panel::browser);
  7341. for (auto p : dockPanels)
  7342. expect ("plugin_above_" + id (p) + "_after_layout_change", lynx::nativechild::isAbove (plug, panelHandle (p)));
  7343. workspace->show (Panel::mixer);
  7344. expect ("mixer_above_plugin_after_show", lynx::nativechild::isAbove (panelHandle (Panel::mixer), plug));
  7345. }
  7346. else if (at == 9)
  7347. {
  7348. // the setup wizard (Options › Setup wizard; first start) in front of the native panels and the plugin
  7349. ui->showSetupWizard();
  7350. }
  7351. else if (at == 10)
  7352. {
  7353. auto* overlay = ui->setupOverlayForTest();
  7354. auto* h = overlay != nullptr ? overlay->getWindowHandle() : nullptr;
  7355. expect ("setup_overlay_native_child", h != nullptr && h != main && lynx::nativechild::parentOf (h) == main);
  7356. expect ("setup_overlay_above_plugin", lynx::nativechild::isAbove (h, plug));
  7357. for (auto p : dockPanels)
  7358. expect ("setup_overlay_above_" + id (p), lynx::nativechild::isAbove (h, panelHandle (p)));
  7359. workspace->activate (Panel::playlist); // (a panel brought in front by code: the overlay stays in front)
  7360. lynx::PluginWindows::open ({}, *instance, {});
  7361. expect ("setup_overlay_stays_in_front", lynx::nativechild::isAbove (h, plug) && lynx::nativechild::isAbove (h, panelHandle (Panel::playlist)));
  7362. }
  7363. else if (at == 11)
  7364. {
  7365. ui->closeSetupWizardForSnapshot();
  7366. expect ("setup_overlay_closed", ui->setupOverlayForTest() == nullptr);
  7367. // drops: JUCE's list of windows in the native stacking order once a drag starts
  7368. workspace->activate (Panel::mixer);
  7369. workspace->hide (Panel::browser);
  7370. workspace->show (Panel::browser);
  7371. lynx::matchWindowOrderToScreen();
  7372. auto children = lynx::nativechild::attachedChildren (main);
  7373. auto& desktop = juce::Desktop::getInstance();
  7374. int last = -1;
  7375. bool ordered = children.size() >= 5;
  7376. for (auto* c : children)
  7377. if (c->isVisible())
  7378. {
  7379. int at2 = -1;
  7380. for (int k = 0; k < desktop.getNumComponents(); ++k)
  7381. if (desktop.getComponent (k) == c)
  7382. at2 = k;
  7383. ordered = ordered && at2 > last;
  7384. last = at2;
  7385. }
  7386. expect ("drop_order_matches_screen", ordered);
  7387. }
  7388. else if (at == 12)
  7389. {
  7390. // the main window's scale changes (a display with another scale): every native child placed again in
  7391. // physical pixels, the docked editor's window told (JUCE tells child windows nothing by itself)
  7392. for (int i = 0; i < juce::ComponentPeer::getNumPeers(); ++i)
  7393. if (auto* peer = juce::ComponentPeer::getPeer (i); peer != nullptr && peer->getNativeHandle() == plug)
  7394. spiedPeer = peer;
  7395. if (spiedPeer != nullptr)
  7396. spiedPeer->addScaleFactorListener (&scaleSpy);
  7397. lynx::nativechild::notifyScaleListenersForTest (*mainWindow);
  7398. juce::Desktop::getInstance().setGlobalScaleFactor (1.25f); // and LYNX's own UI zoom
  7399. }
  7400. else if (at == 13)
  7401. {
  7402. bool placed = true;
  7403. for (auto* c : lynx::nativechild::attachedChildren (main))
  7404. placed = placed && (! c->isVisible() || lynx::nativechild::placedPhysically (*c));
  7405. expect ("native_children_placed_at_125", placed);
  7406. expect ("docked_editor_told_the_scale", scaleSpy.calls > 0 && spiedPeer != nullptr
  7407. && std::abs (scaleSpy.last - spiedPeer->getPlatformScaleFactor()) < 0.001);
  7408. if (spiedPeer != nullptr && juce::ComponentPeer::isValidPeer (spiedPeer))
  7409. spiedPeer->removeScaleFactorListener (&scaleSpy);
  7410. juce::Desktop::getInstance().setGlobalScaleFactor (1.0f);
  7411. lynx::PluginWindows::setDetached (*instance, true);
  7412. }
  7413. else if (at == 14)
  7414. {
  7415. expect ("detached_reopened", lynx::PluginWindows::isOpen (*instance) && ! lynx::PluginWindows::isDocked (*instance));
  7416. expect ("detached_owned_by_main", plug != nullptr && lynx::nativechild::ownerOf (plug) == main);
  7417. expect ("detached_saved", find() == instance && engineRef() != nullptr && engineRef()->detached);
  7418. for (auto p : dockPanels)
  7419. workspace->activate (p);
  7420. }
  7421. else if (at == 15)
  7422. {
  7423. // (an owned top-level window: above the main window and so above all its child windows)
  7424. expect ("detached_stays_above_clicked_panels", plug != nullptr && lynx::nativechild::ownerOf (plug) == main
  7425. && lynx::nativechild::parentOf (plug) != main && lynx::PluginWindows::isOpen (*instance));
  7426. lynx::PluginWindows::setDetached (*instance, false);
  7427. }
  7428. else if (at == 16)
  7429. {
  7430. // issue #116 slice 4: a Fruity Dance dancer standing on the docked plugin window, in front of it
  7431. auto* stage = dynamic_cast<lynx::DanceStage*> (ui->danceStageForTest());
  7432. juce::Rectangle<int> over;
  7433. for (auto* c : lynx::nativechild::attachedChildren (main))
  7434. if (c->getWindowHandle() == plug)
  7435. over = ui->getLocalArea (nullptr, c->getScreenBounds());
  7436. expect ("dance_stage", stage != nullptr && ! over.isEmpty());
  7437. lynx::dance::Settings s;
  7438. s.move = lynx::dance::held; // (a still pose: the pixels tested below stay where they are)
  7439. s.x = over.getCentreX();
  7440. s.y = over.getCentreY() + 70;
  7441. const auto state = lynx::dance::toState (s);
  7442. engine->editSongStructural ([this, state] (lynx::Song& song) {
  7443. lynx::ChannelDef c;
  7444. c.name = "Fruity Dance";
  7445. c.instrument = lynx::InstrumentKind::fruitydance;
  7446. c.pluginState = state;
  7447. danceChannel = (int) song.channels.size();
  7448. song.channels.push_back (c);
  7449. });
  7450. engine->dispatchPendingMessages();
  7451. if (stage != nullptr)
  7452. stage->update();
  7453. }
  7454. else if (at == 17)
  7455. {
  7456. auto* stage = dynamic_cast<lynx::DanceStage*> (ui->danceStageForTest());
  7457. auto* w = stage != nullptr ? stage->windowOf (danceChannel) : nullptr;
  7458. auto* h = w != nullptr ? w->getWindowHandle() : nullptr;
  7459. expect ("dancer_window_native_child", h != nullptr && h != main && lynx::nativechild::parentOf (h) == main);
  7460. expect ("dancer_window_layered", lynx::nativechild::isLayered (h));
  7461. expect ("dancer_above_plugin", lynx::nativechild::isAbove (h, plug));
  7462. for (auto p : dockPanels)
  7463. expect ("dancer_above_" + id (p), lynx::nativechild::isAbove (h, panelHandle (p)));
  7464. // panels and the plugin brought in front (clicks, keys): the dancer stays in front of them
  7465. workspace->activate (Panel::mixer);
  7466. workspace->show (Panel::pianoRoll);
  7467. lynx::PluginWindows::open ({}, *instance, {});
  7468. expect ("dancer_stays_in_front", lynx::nativechild::isAbove (h, plug) && lynx::nativechild::isAbove (h, panelHandle (Panel::mixer))
  7469. && lynx::nativechild::isAbove (h, panelHandle (Panel::pianoRoll)));
  7470. // the mouse: the dancer's body takes it, its window's transparent pixels let it through
  7471. if (w != nullptr)
  7472. {
  7473. const auto picture = w->createComponentSnapshot (w->getLocalBounds(), true, 1.0f);
  7474. const auto body = stage->bodyOf (danceChannel) - (w->getScreenPosition() - stage->getScreenPosition());
  7475. juce::Point<int> solid { -1, -1 }, clear { -1, -1 };
  7476. for (int y = body.getCentreY() - 10; y < body.getBottom() && solid.x < 0; ++y)
  7477. for (int x = body.getX(); x < body.getRight() && solid.x < 0; ++x)
  7478. if (picture.getBounds().contains (x, y) && picture.getPixelAt (x, y).getAlpha() == 255)
  7479. solid = { x, y };
  7480. for (int y = 0; y < picture.getHeight() && clear.x < 0; y += 2)
  7481. for (int x = 0; x < picture.getWidth() && clear.x < 0; x += 2)
  7482. if (picture.getPixelAt (x, y).getAlpha() == 0 && ! body.expanded (8).contains (x, y))
  7483. clear = { x, y };
  7484. step ("dancer_window=" + w->getBounds().toString() + " solid=" + solid.toString() + " clear=" + clear.toString());
  7485. auto* atSolid = lynx::nativechild::windowAt (*w, solid);
  7486. auto* atClear = lynx::nativechild::windowAt (*w, clear);
  7487. expect ("dancer_takes_its_body_clicks", solid.x >= 0 && atSolid == h);
  7488. expect ("dancer_lets_clicks_through", clear.x >= 0 && atClear != nullptr && atClear != h);
  7489. expect ("stage_leaves_the_mouse", ! stage->hitTest (stage->bodyOf (danceChannel).getCentreX(), stage->bodyOf (danceChannel).getCentreY()));
  7490. }
  7491. }
  7492. else if (at == 18)
  7493. {
  7494. // no dance channel: no dancer window (nothing drawn, no cost)
  7495. auto* stage = dynamic_cast<lynx::DanceStage*> (ui->danceStageForTest());
  7496. engine->editSongStructural ([this] (lynx::Song& song) {
  7497. if (danceChannel >= 0 && danceChannel < (int) song.channels.size())
  7498. song.channels.erase (song.channels.begin() + danceChannel);
  7499. });
  7500. engine->dispatchPendingMessages();
  7501. if (stage != nullptr)
  7502. stage->update();
  7503. expect ("dancer_window_gone", stage != nullptr && stage->windowCount() == 0);
  7504. }
  7505. else if (at == 19 || at == 20)
  7506. {
  7507. // round 190ev (issue #152, "flickering windows"): on Windows a docked panel no longer fades by its
  7508. // window's alpha (each fade switched its drawing surface twice and the panel flashed); it shows and
  7509. // hides at once, as FL's docked windows. Elsewhere round 190i's fade stays.
  7510. auto& frame = workspace->getFrame (Panel::mixer);
  7511. if (at == 19)
  7512. {
  7513. workspace->show (Panel::mixer);
  7514. expect ("mixer_above_plugin_when_shown", lynx::nativechild::isAbove (panelHandle (Panel::mixer), plug));
  7515. workspace->hide (Panel::mixer);
  7516. expect ("mixer_hides_at_once", ! frame.isVisible() && workspace->nativeFadeDirection (Panel::mixer) == 0
  7517. && frame.getAlpha() == 1.0f && ! lynx::nativechild::isLayered (frame.getWindowHandle()));
  7518. }
  7519. else
  7520. {
  7521. workspace->show (Panel::mixer);
  7522. expect ("mixer_shows_at_once", frame.isVisible() && frame.getAlpha() == 1.0f && workspace->nativeFadeDirection (Panel::mixer) == 0
  7523. && ! lynx::nativechild::isLayered (frame.getWindowHandle())
  7524. && lynx::nativechild::isAbove (panelHandle (Panel::mixer), plug));
  7525. }
  7526. }
  7527. else if (at >= 21 && at <= 23)
  7528. {
  7529. // round 190ev (issue #152, "the Channel rack almost never comes to the front"): LYNX's own editor
  7530. // windows (here a channel's settings) are docked like FL's plugin windows, so a click on the rack
  7531. // brings the rack in front of them and a click on one brings it back; a click inside a docked
  7532. // plugin's own view (a native window JUCE never hears of) brings that plugin window in front.
  7533. auto docked = [] {
  7534. auto& desktop = juce::Desktop::getInstance();
  7535. for (int i = 0; i < desktop.getNumComponents(); ++i)
  7536. if (auto* c = desktop.getComponent (i); c != nullptr && c->isVisible() && (bool) c->getProperties()["lynxDockedWindow"])
  7537. return c;
  7538. return (juce::Component*) nullptr;
  7539. };
  7540. auto* rack = panelHandle (Panel::channelRack);
  7541. if (at == 21)
  7542. {
  7543. lynx::openChannelSettings (*engine, 0);
  7544. auto* ed = docked();
  7545. auto* h = ed != nullptr ? ed->getWindowHandle() : nullptr;
  7546. expect ("editor_docked", h != nullptr && lynx::nativechild::parentOf (h) == main && lynx::nativechild::ownerOf (h) == nullptr);
  7547. expect ("editor_above_rack_when_opened", h != nullptr && lynx::nativechild::isAbove (h, rack));
  7548. workspace->activate (Panel::channelRack); // a click on the rack
  7549. expect ("rack_above_editor_after_its_click", h != nullptr && lynx::nativechild::isAbove (rack, h));
  7550. // a real click (a message to the editor's own window) on its title bar, at a point where the editor
  7551. // can be seen. Round 190fc (0.1.27 RC M1): JUCE takes a button-down only where the system says its
  7552. // window is the one under the point (HWNDComponentPeer::contains asks WindowFromPoint), so the old
  7553. // fixed point (60, 8) was dropped whenever the rack, raised just above, covered it there: the
  7554. // check read 0 while real clicks (on what can be seen) raise the editor.
  7555. if (h != nullptr && ed != nullptr)
  7556. {
  7557. juce::Point<int> at (-1, -1);
  7558. for (int x = 30; x < ed->getWidth() - 40 && at.x < 0; x += 12)
  7559. if (lynx::nativechild::windowAt (*ed, { x, 8 }) == h)
  7560. at = { x, 8 };
  7561. step (juce::String ("editor_title_visible_at=") + juce::String (at.x));
  7562. if (at.x >= 0)
  7563. {
  7564. const auto scale = ed->getPeer() != nullptr ? ed->getPeer()->getPlatformScaleFactor() * (double) ed->getDesktopScaleFactor() : 1.0;
  7565. lynx::nativechild::postClickForTest (h, (at.toDouble() * scale).roundToInt());
  7566. }
  7567. }
  7568. }
  7569. else if (at == 22)
  7570. {
  7571. auto* ed = docked();
  7572. auto* h = ed != nullptr ? ed->getWindowHandle() : nullptr;
  7573. expect ("editor_above_rack_after_its_click", h != nullptr && lynx::nativechild::isAbove (h, rack));
  7574. workspace->activate (Panel::channelRack);
  7575. expect ("rack_above_plugin_after_its_click", lynx::nativechild::isAbove (rack, plug));
  7576. auto* view = lynx::nativechild::innermostChild (plug);
  7577. step (juce::String ("plugin_view_window=") + (view != nullptr ? "1" : "0"));
  7578. if (view != nullptr) // a click in the plugin's own view, near its top-left corner
  7579. lynx::nativechild::postClickForTest (view, { 2, 2 });
  7580. }
  7581. else
  7582. {
  7583. if (lynx::nativechild::innermostChild (plug) != nullptr)
  7584. expect ("plugin_above_rack_after_click_in_its_view", lynx::nativechild::isAbove (plug, rack));
  7585. lynx::closeChannelSettings();
  7586. // FL's Tools > Macros > Switch all plugin editors to > Detached (round 190i)
  7587. lynx::PluginWindows::setAllDetached (*engine, true);
  7588. }
  7589. }
  7590. else if (at == 24)
  7591. {
  7592. expect ("macro_detached_the_open_editor", lynx::PluginWindows::isOpen (*instance) && ! lynx::PluginWindows::isDocked (*instance)
  7593. && plug != nullptr && lynx::nativechild::ownerOf (plug) == main);
  7594. expect ("macro_detached_saved", find() == instance && engineRef() != nullptr && engineRef()->detached);
  7595. lynx::PluginWindows::setAllDetached (*engine, false); // ... > Attached
  7596. }
  7597. else
  7598. {
  7599. expect ("docked_again", lynx::PluginWindows::isDocked (*instance) && engineRef() != nullptr && ! engineRef()->detached);
  7600. step (juce::String ("dock_result=") + (dockOk ? "OK" : "FAILED"));
  7601. }
  7602. }
  7603. const lynx::PluginRef* engineRef() const
  7604. {
  7605. const auto& song = engine->getSong();
  7606. if (instrument)
  7607. return channelIndex < 0 || channelIndex >= (int) song.channels.size() ? nullptr : &song.channels[(size_t) channelIndex].plugin;
  7608. return song.mixer.size() < 2 || song.mixer[1].effects.empty() ? nullptr : &song.mixer[1].effects[0].plugin;
  7609. }
  7610. void step (const juce::String& line)
  7611. {
  7612. report << line << "\n";
  7613. juce::File (reportPath).replaceWithText (report);
  7614. }
  7615. juce::AudioPluginInstance* find()
  7616. {
  7617. if (instrument)
  7618. {
  7619. if (auto* p = dynamic_cast<lynx::PluginInstrument*> (engine->getChannelInstrument (channelIndex).get()))
  7620. return &p->getInstance();
  7621. }
  7622. else if (auto* p = dynamic_cast<lynx::PluginEffect*> (engine->getEffect (1, 0).get()))
  7623. return &p->getInstance();
  7624. return nullptr;
  7625. }
  7626. void timerCallback() override
  7627. {
  7628. ++ticks;
  7629. if (phase == 0) // waiting for the engine to host the plugin
  7630. {
  7631. instance = find();
  7632. if (instance == nullptr)
  7633. {
  7634. if (ticks > 200)
  7635. {
  7636. step ("result=FAILED (not hosted)");
  7637. stopTimer();
  7638. done (false);
  7639. }
  7640. return;
  7641. }
  7642. step ("hosted=" + instance->getName() + " format=" + instance->getPluginDescription().pluginFormatName);
  7643. step ("programs=" + juce::String (instance->getNumPrograms()));
  7644. for (int p = 0; p < juce::jmin (5, instance->getNumPrograms()); ++p)
  7645. step ("program" + juce::String (p) + "=" + instance->getProgramName (p));
  7646. step ("save_formats=" + lynx::pluginpresetui::saveWildcard (*instance));
  7647. // preset round trip: save, change the first parameter, load, compare
  7648. juce::AudioProcessorParameter* param = nullptr;
  7649. for (auto* candidate : instance->getParameters())
  7650. if (candidate->isAutomatable() && ! candidate->isMetaParameter() && candidate != instance->getBypassParameter())
  7651. {
  7652. param = candidate;
  7653. break;
  7654. }
  7655. if (param != nullptr)
  7656. {
  7657. step ("param=" + param->getName (64));
  7658. checked = param;
  7659. const auto file = lynx::pluginpresetui::folderFor (instance->getName()).getChildFile ("plugwintest.lynxpreset");
  7660. juce::String error;
  7661. const auto before = param->getValue();
  7662. const auto saved = lynx::pluginpresetui::save (*instance, file, "plugwintest", error);
  7663. param->setValueNotifyingHost (before > 0.5f ? 0.1f : 0.9f);
  7664. const auto changed = param->getValue();
  7665. const auto loaded = saved && lynx::pluginpresetui::load (*instance, file, error);
  7666. step ("preset_roundtrip saved=" + juce::String ((int) saved) + " loaded=" + juce::String ((int) loaded) + " param0 before="
  7667. + juce::String (before, 4) + " changed=" + juce::String (changed, 4) + " after=" + juce::String (param->getValue(), 4)
  7668. + (error.isNotEmpty() ? " error=" + error : juce::String()));
  7669. for (const auto* ext : { "fxp", "fxb", "vstpreset" })
  7670. {
  7671. juce::String e2;
  7672. const auto f2 = file.withFileExtension (ext);
  7673. const auto ok2 = lynx::pluginpresetui::save (*instance, f2, "plugwintest", e2) && lynx::pluginpresetui::load (*instance, f2, e2);
  7674. step (juce::String ("preset_") + ext + "=" + juce::String ((int) ok2) + (e2.isNotEmpty() ? " (" + e2 + ")" : juce::String()));
  7675. f2.deleteFile();
  7676. }
  7677. step ("browser_lists=" + juce::String (lynx::pluginpresetui::userPresets (instance->getName()).size()));
  7678. }
  7679. std::shared_ptr<void> owner = instrument ? std::shared_ptr<void> (engine->getChannelInstrument (channelIndex))
  7680. : std::shared_ptr<void> (engine->getEffect (1, 0));
  7681. lynx::PluginWindows::open (owner, *instance, instance->getName(),
  7682. { engine.get(), [this] (lynx::Song& song) -> lynx::PluginRef* {
  7683. if (instrument)
  7684. return channelIndex < 0 || channelIndex >= (int) song.channels.size()
  7685. ? nullptr : &song.channels[(size_t) channelIndex].plugin;
  7686. return song.mixer.size() < 2 || song.mixer[1].effects.empty() ? nullptr : &song.mixer[1].effects[0].plugin;
  7687. }, instrument });
  7688. owner.reset();
  7689. step ("window_open=" + juce::String ((int) lynx::PluginWindows::isOpen (*instance)));
  7690. phase = 1;
  7691. ticks = 0;
  7692. phaseStartMs = juce::Time::getMillisecondCounter();
  7693. return;
  7694. }
  7695. if (phase == 1 && ticks >= 30 && ! keysDone && juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGWIN_KEYS", {}).isNotEmpty() && instance->getActiveEditor() != nullptr)
  7696. keysDone = ! lynx::pluginKeysTestTick (*instance->getActiveEditor(),
  7697. [this] (bool on) {
  7698. engine->editSong ([this, on] (lynx::Song& song) {
  7699. (instrument ? song.channels[(size_t) channelIndex].plugin : song.mixer[1].effects[0].plugin).hostKeysFirst = on;
  7700. });
  7701. },
  7702. [this] (const juce::String& line) { step (line); });
  7703. const auto elapsedMs = (int) (juce::Time::getMillisecondCounter() - phaseStartMs);
  7704. if (phase == 1 && ticks == 20 && checked != nullptr)
  7705. step ("param_after_1s=" + juce::String (checked->getValue(), 4));
  7706. // round 190in: LYNX_PLUGWIN_MENU=<png>: FL's ▸ wrapper menu of the open window (two columns for a channel)
  7707. if (const auto menuShot = juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGWIN_MENU", {}); phase == 1 && ticks == 10 && menuShot.isNotEmpty())
  7708. if (const auto menu = lynx::PluginWindows::wrapperMenuForSnapshot (*instance))
  7709. {
  7710. juce::PopupMenu left, right;
  7711. auto* to = &left;
  7712. for (juce::PopupMenu::MenuItemIterator it (*menu); it.next();)
  7713. {
  7714. to->addItem (it.getItem());
  7715. if (it.getItem().shouldBreakAfter)
  7716. to = &right;
  7717. }
  7718. juce::StringArray names { "Plugin" };
  7719. std::vector<juce::PopupMenu> menus { left };
  7720. if (right.getNumItems() > 0)
  7721. {
  7722. names.add ("Channel");
  7723. menus.push_back (right);
  7724. }
  7725. LynxApplication::saveMenus (names, menus, menuShot);
  7726. step ("wrapper_menu_items=" + juce::String (left.getNumItems()) + "+" + juce::String (right.getNumItems()));
  7727. }
  7728. // (3 s apart: time for screenshots of each state)
  7729. if (phase == 1 && workspace != nullptr && dockStep < dockSteps && elapsedMs >= (dockStep + 1) * stepMs)
  7730. dockCheck (dockStep++);
  7731. if (phase == 1 && dropFile.existsAsFile())
  7732. dropTick (elapsedMs);
  7733. // (with LYNX_PLUGWIN_DROP: `seconds` after the drop places were reported, time for the drag)
  7734. const auto dropDone = ! dropFile.existsAsFile()
  7735. || (dropStage == 2 && (int) (juce::Time::getMillisecondCounter() - dropReadyMs) >= seconds * 1000);
  7736. if (phase == 1 && elapsedMs >= seconds * 1000 && dropDone && (workspace == nullptr || dockStep >= dockSteps)) // remove the plugin from the song
  7737. {
  7738. if (dropFile.existsAsFile())
  7739. dropResult();
  7740. engine->editSong ([this] (lynx::Song& song) {
  7741. if (instrument)
  7742. {
  7743. if (channelIndex >= 0 && channelIndex < (int) song.channels.size())
  7744. song.channels.erase (song.channels.begin() + channelIndex);
  7745. }
  7746. else
  7747. song.mixer[1].effects.clear();
  7748. });
  7749. step ("removed");
  7750. phase = 2;
  7751. ticks = 0;
  7752. return;
  7753. }
  7754. if (phase == 2 && ticks >= 40)
  7755. {
  7756. const auto open = lynx::PluginWindows::isOpen (*instance);
  7757. step ("window_open_after_remove=" + juce::String ((int) open));
  7758. step (open || ! dockOk ? "result=FAILED" : "result=OK");
  7759. stopTimer();
  7760. lynx::PluginWindows::closeAll();
  7761. done (! open && dockOk);
  7762. }
  7763. }
  7764. };
  7765. // round 190in: LYNX_PLUGWIN_ZOOM=<percent>: LYNX's interface zoom for the run (the wrapper's header at 150 %)
  7766. if (const auto zoom = juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGWIN_ZOOM", {}).getIntValue(); zoom >= 50 && zoom <= 300)
  7767. juce::Desktop::getInstance().setGlobalScaleFactor ((float) zoom / 100.0f);
  7768. auto* test = new Test();
  7769. test->reportPath = reportPath;
  7770. test->seconds = seconds;
  7771. if (const auto drop = juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGWIN_DROP", {}); drop.isNotEmpty())
  7772. test->dropFile = juce::File (drop);
  7773. test->done = [this, test] (bool ok) {
  7774. setApplicationReturnValue (ok ? 0 : 1);
  7775. juce::MessageManager::callAsync ([this, test] {
  7776. lynx::setMainWindowForOwnership (nullptr);
  7777. lynx::PluginWindows::setDockWorkspace (nullptr);
  7778. test->dropWindow = nullptr; // (its Browser before the engine)
  7779. test->workspace = nullptr;
  7780. test->mainWindow = nullptr; // (dock mode: the main component with it, before the engine)
  7781. test->engine = nullptr;
  7782. delete test;
  7783. quit();
  7784. });
  7785. };
  7786. test->engine = std::make_unique<lynx::AudioEngine> (false);
  7787. test->mainWindow = std::make_unique<juce::DocumentWindow> ("LYNX test main window", juce::Colours::darkgrey, 0);
  7788. test->mainWindow->setBounds (20, 20, 300, 200);
  7789. if (juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGWIN_DOCK", {}) == "1" && lynx::nativechild::dockingEnabled())
  7790. {
  7791. // the real main window's contents (it docks plugin windows in its own desktop), so the panels are real
  7792. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  7793. auto* ui = new lynx::MainComponent (*test->engine, false);
  7794. test->mainWindow->setUsingNativeTitleBar (true);
  7795. test->mainWindow->setContentOwned (ui, false);
  7796. test->mainWindow->setBounds (20, 20, 1500, 900);
  7797. test->workspace = &ui->workspaceForTest();
  7798. test->ui = ui;
  7799. if (const auto ms = juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGWIN_STEP_MS", {}).getIntValue(); ms > 0)
  7800. test->stepMs = ms;
  7801. }
  7802. test->mainWindow->setVisible (true);
  7803. lynx::setMainWindowForOwnership (test->mainWindow.get());
  7804. if (test->workspace != nullptr)
  7805. {
  7806. using lynx::workspace::Panel;
  7807. for (auto p : { Panel::playlist, Panel::mixer, Panel::pianoRoll, Panel::channelRack })
  7808. test->workspace->show (p);
  7809. test->step ("dock_test=2 rack_visible=" + juce::String ((int) test->workspace->isPanelVisible (Panel::channelRack)));
  7810. }
  7811. auto& host = test->engine->getPluginHost();
  7812. test->step ("plugins_in_file=" + juce::String (host.addPluginFile (juce::File (pluginPath))));
  7813. std::optional<juce::PluginDescription> chosen;
  7814. for (const auto& type : host.getKnownPlugins().getTypes())
  7815. if ((juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginPath).getFileName() || type.fileOrIdentifier == pluginPath)
  7816. && (only.isEmpty() || type.name == only))
  7817. {
  7818. chosen = type;
  7819. break;
  7820. }
  7821. if (! chosen)
  7822. {
  7823. test->step ("result=FAILED (no plugin)");
  7824. test->done (false);
  7825. return;
  7826. }
  7827. test->instrument = chosen->isInstrument;
  7828. lynx::PluginRef ref;
  7829. ref.separateProcess = juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGWIN_SEPARATE", {}) == "1"; // (issue #96's other-process check)
  7830. ref.id = chosen->createIdentifierString().toStdString();
  7831. ref.name = chosen->name.toStdString();
  7832. test->engine->editSong ([&] (lynx::Song& song) {
  7833. if (test->instrument)
  7834. {
  7835. lynx::ChannelDef c;
  7836. c.name = ref.name;
  7837. c.instrument = lynx::InstrumentKind::plugin;
  7838. c.plugin = ref;
  7839. test->channelIndex = (int) song.channels.size();
  7840. song.channels.push_back (c);
  7841. }
  7842. else
  7843. {
  7844. while (song.mixer.size() < 2)
  7845. song.mixer.emplace_back();
  7846. lynx::EffectSlot slot;
  7847. slot.kind = lynx::EffectKind::plugin;
  7848. slot.plugin = ref;
  7849. song.mixer[1].effects.push_back (slot);
  7850. }
  7851. });
  7852. test->step ("plugin=" + chosen->name + " instrument=" + juce::String ((int) test->instrument));
  7853. test->startTimerHz (20);
  7854. }
  7855. void runEditorCrashTest (const juce::String& pluginPath, const juce::String& reportPath)
  7856. {
  7857. struct CrashTest final : juce::Timer
  7858. {
  7859. juce::String reportPath, report;
  7860. std::unique_ptr<lynx::PluginHost> host;
  7861. juce::AudioPluginInstance* plugin = nullptr;
  7862. std::shared_ptr<juce::AudioPluginInstance> keep; // a window whose plugin nobody else holds is closed as orphaned
  7863. std::function<void (bool)> done;
  7864. int ticks = 0, crashesBefore = 0;
  7865. void step (const juce::String& line)
  7866. {
  7867. report << line << "\n";
  7868. juce::File (reportPath).replaceWithText (report); // at each step: a crash leaves the last one
  7869. }
  7870. void timerCallback() override
  7871. {
  7872. ++ticks;
  7873. const auto crashes = lynx::PluginWindows::editorCrashCount() - crashesBefore;
  7874. const auto open = lynx::PluginWindows::isOpen (*plugin);
  7875. if ((crashes > 0 && ! open) || ticks >= 50) // 100 ms ticks: up to 5 s
  7876. {
  7877. stopTimer();
  7878. step ("editor_crashes=" + juce::String (crashes) + " window_open=" + juce::String ((int) open) + " ticks=" + juce::String (ticks));
  7879. bool traced = false;
  7880. if (crashes > 0)
  7881. {
  7882. const auto last = lynx::PluginWindows::editorCrashes().back();
  7883. traced = last.traceFile.existsAsFile() && last.traceFile.loadFileAsString().contains ("LYNX Test Crash");
  7884. step ("plugin=" + last.plugin + " detail=" + last.detail + " trace=" + last.traceFile.getFileName() + " traced="
  7885. + juce::String ((int) traced));
  7886. last.traceFile.deleteFile();
  7887. }
  7888. // still alive: one more message through the loop after the fault
  7889. juce::MessageManager::callAsync ([this, ok = crashes == 1 && ! open && traced] {
  7890. step ("message_loop_after_fault=1");
  7891. step (juce::String ("result=") + (ok ? "OK" : "FAILED"));
  7892. done (ok);
  7893. });
  7894. }
  7895. }
  7896. };
  7897. auto* test = new CrashTest();
  7898. test->reportPath = reportPath;
  7899. test->done = [this, test] (bool ok)
  7900. {
  7901. setApplicationReturnValue (ok ? 0 : 1);
  7902. juce::MessageManager::callAsync ([this, test] { lynx::PluginWindows::closeAll(); delete test; quit(); });
  7903. };
  7904. #if ! JUCE_WINDOWS
  7905. test->step ("result=SKIPPED (Windows only: on macOS / Linux a plugin fault is a signal, see docs/analise/REA_rodada174a.md)");
  7906. test->done (true);
  7907. return;
  7908. #else
  7909. _putenv_s ("LYNX_TEST_CRASH", "editor");
  7910. test->host = std::make_unique<lynx::PluginHost> (false);
  7911. test->step ("plugins_in_file=" + juce::String (test->host->addPluginFile (juce::File (pluginPath))));
  7912. std::shared_ptr<juce::AudioPluginInstance> instance;
  7913. for (const auto& type : test->host->getKnownPlugins().getTypes())
  7914. {
  7915. if (juce::File (type.fileOrIdentifier).getFileName() != juce::File (pluginPath).getFileName())
  7916. continue;
  7917. juce::String error;
  7918. instance = std::shared_ptr<juce::AudioPluginInstance> (lynx::createRightInstance (test->host->getFormats(), type, 48000.0, 512, error).release());
  7919. test->step ("plugin=" + type.name + (instance == nullptr ? " error=" + error : juce::String()));
  7920. break;
  7921. }
  7922. if (instance == nullptr || ! instance->hasEditor())
  7923. {
  7924. test->step ("result=FAILED (no plugin with an editor)");
  7925. test->done (false);
  7926. return;
  7927. }
  7928. lynx::preparePlugin (*instance, 48000.0, 512);
  7929. test->plugin = instance.get();
  7930. test->keep = instance;
  7931. test->crashesBefore = lynx::PluginWindows::editorCrashCount();
  7932. lynx::PluginWindows::open (instance, *instance, instance->getName()); // (the window keeps the plugin alive)
  7933. test->step ("window_open=" + juce::String ((int) lynx::PluginWindows::isOpen (*instance)));
  7934. test->startTimer (100);
  7935. #endif
  7936. }
  7937. void runEditorTest (const juce::String& pluginPath, const juce::String& reportPath, const juce::String& only)
  7938. {
  7939. struct EditorTest final : juce::Timer
  7940. {
  7941. juce::String reportPath, report;
  7942. std::unique_ptr<lynx::PluginHost> host;
  7943. std::unique_ptr<juce::AudioPluginInstance> plugin;
  7944. std::unique_ptr<juce::DocumentWindow> window;
  7945. std::function<void (bool)> done;
  7946. void step (const juce::String& line)
  7947. {
  7948. report << line << "\n";
  7949. juce::File (reportPath).replaceWithText (report); // written at each step: a crash leaves the last one
  7950. }
  7951. void timerCallback() override
  7952. {
  7953. stopTimer();
  7954. window = nullptr;
  7955. step ("step=closed");
  7956. plugin = nullptr;
  7957. step ("result=OK");
  7958. done (true);
  7959. }
  7960. };
  7961. auto* test = new EditorTest();
  7962. test->reportPath = reportPath;
  7963. test->done = [this, test] (bool ok)
  7964. {
  7965. setApplicationReturnValue (ok ? 0 : 1);
  7966. juce::MessageManager::callAsync ([this, test] { delete test; quit(); });
  7967. };
  7968. test->host = std::make_unique<lynx::PluginHost> (false);
  7969. test->step ("plugins_in_file=" + juce::String (test->host->addPluginFile (juce::File (pluginPath))));
  7970. test->step ("exe=" + juce::File::getSpecialLocation (juce::File::currentExecutableFile).getFullPathName());
  7971. for (const auto& type : test->host->getKnownPlugins().getTypes())
  7972. {
  7973. if (juce::File (type.fileOrIdentifier).getFileName() != juce::File (pluginPath).getFileName()
  7974. || (only.isNotEmpty() && type.name != only))
  7975. continue;
  7976. juce::String error;
  7977. test->plugin = lynx::createRightInstance (test->host->getFormats(), type, 48000.0, 512, error);
  7978. test->step ("plugin=" + type.name + (test->plugin == nullptr ? " error=" + error : juce::String()));
  7979. break;
  7980. }
  7981. if (test->plugin == nullptr)
  7982. {
  7983. test->step ("result=FAILED");
  7984. test->done (false);
  7985. return;
  7986. }
  7987. lynx::preparePlugin (*test->plugin, 48000.0, 512);
  7988. test->step ("step=create_editor");
  7989. test->window = std::make_unique<juce::DocumentWindow> (test->plugin->getName(), juce::Colours::black, juce::DocumentWindow::closeButton);
  7990. test->window->setUsingNativeTitleBar (true);
  7991. if (auto* editor = test->plugin->createEditorIfNeeded())
  7992. test->window->setContentOwned (editor, true);
  7993. else
  7994. test->step ("no_editor");
  7995. test->step ("step=show");
  7996. test->window->centreWithSize (test->window->getWidth(), test->window->getHeight());
  7997. test->window->setVisible (true);
  7998. test->step ("step=shown");
  7999. test->startTimer (4000);
  8000. }
  8001. void runFitTest (const juce::String& reportPath, int percent)
  8002. {
  8003. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  8004. struct FitTest final : juce::Timer
  8005. {
  8006. juce::String path, report;
  8007. bool ok = true;
  8008. int step = 0, percent = 150;
  8009. std::unique_ptr<juce::DocumentWindow> tall, big;
  8010. std::function<void()> done;
  8011. // `whole`: the window must fit entirely (a resizable one); else its title bar and close button must be on the screen
  8012. void check (const juce::String& what, juce::Component& w, bool whole)
  8013. {
  8014. juce::BorderSize<int> frame;
  8015. if (auto* peer = w.getPeer())
  8016. if (const auto f = peer->getFrameSizeIfPresent())
  8017. frame = *f;
  8018. auto outer = frame.addedTo (w.getBounds());
  8019. const auto* display = juce::Desktop::getInstance().getDisplays().getDisplayForRect (outer);
  8020. const auto area = display != nullptr ? display->userArea : outer;
  8021. #if JUCE_LINUX
  8022. // round 164: a compositor that draws the frame itself (WSLg's Weston) reports its invisible shadow in
  8023. // the frame (59 px on top, 38 around at 100%): only what is visible is checked, give or take 4 px
  8024. const auto shadow = frame.getLeft() >= 16 ? frame.getLeft() : 0;
  8025. outer = outer.reduced (shadow);
  8026. const auto slack = shadow > 0 ? 4 : 0;
  8027. #else
  8028. const auto slack = 0;
  8029. #endif
  8030. const auto passed = outer.getY() >= area.getY() - slack && outer.getRight() <= area.getRight() + slack && outer.getX() >= area.getX() - slack
  8031. && (! whole || outer.getBottom() <= area.getBottom() + 1 + slack);
  8032. report << (passed ? "ok " : "FAIL ") << what << " window=" << outer.toString() << " (frame " << frame.getTop() << ","
  8033. << frame.getLeft() << ") screen=" << area.toString() << "\n";
  8034. ok = ok && passed;
  8035. }
  8036. void start()
  8037. {
  8038. report << "scale=" << percent << "%\n";
  8039. juce::Desktop::getInstance().setGlobalScaleFactor ((float) percent / 100.0f);
  8040. // a tool window taller than the screen, centred (its title bar would be above the screen)
  8041. tall = std::make_unique<juce::DocumentWindow> ("LYNX fit test - tall", lynx::theme::colour::bg2, juce::DocumentWindow::closeButton);
  8042. tall->setUsingNativeTitleBar (true);
  8043. auto* content = new juce::Component();
  8044. const auto area = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea;
  8045. content->setSize (500, area.getHeight() + 200);
  8046. tall->setContentOwned (content, true);
  8047. tall->setCentrePosition (area.getCentre());
  8048. tall->setVisible (true);
  8049. lynx::keepAboveMainWindow (*tall);
  8050. // LYNX_FITTEST_MS: how long each window stays (default 700 ms; longer to take screenshots of them)
  8051. startTimer (juce::jlimit (300, 60000, juce::SystemStats::getEnvironmentVariable ("LYNX_FITTEST_MS", "700").getIntValue()));
  8052. }
  8053. void timerCallback() override
  8054. {
  8055. ++step;
  8056. if (step == 1)
  8057. {
  8058. check ("tall tool window: title bar and close button on the screen", *tall, false);
  8059. tall.reset();
  8060. // round 164: a fixed-size LYNX tool window whose content is taller than the screen: it scrolls
  8061. auto content = std::make_unique<juce::Component>();
  8062. const auto screen = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea;
  8063. content->setSize (520, screen.getHeight() + 300);
  8064. lynx::openToolWindow (std::move (content), "LYNX fit test - fixed size", "fittest-fixed");
  8065. return;
  8066. }
  8067. if (step == 2)
  8068. {
  8069. if (auto* w = lynx::findToolWindow ("fittest-fixed"))
  8070. {
  8071. check ("fixed-size tool window taller than the screen: fits (its content scrolls)", *w, true);
  8072. const auto scrolls = w->getContentComponent() != nullptr && w->getContentComponent()->getNumChildComponents() > 0
  8073. && dynamic_cast<juce::Viewport*> (w->getContentComponent()->getChildComponent (0)) != nullptr;
  8074. report << (scrolls ? "ok " : "FAIL ") << "its content is in a scrolling viewport\n";
  8075. ok = ok && scrolls;
  8076. }
  8077. else
  8078. {
  8079. report << "FAIL fixed-size tool window not found\n";
  8080. ok = false;
  8081. }
  8082. lynx::closeAllToolWindows();
  8083. // a resizable window that fits at 100%, then the zoom goes up (the main window's case)
  8084. juce::Desktop::getInstance().setGlobalScaleFactor (1.0f);
  8085. big = std::make_unique<juce::DocumentWindow> ("LYNX fit test - zoom", lynx::theme::colour::bg2, juce::DocumentWindow::allButtons);
  8086. big->setUsingNativeTitleBar (true);
  8087. big->setResizable (true, false);
  8088. big->setResizeLimits (400, 300, 10000, 10000);
  8089. const auto area = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea;
  8090. big->setBounds (area.getX() + 40, area.getY() + 60, area.getWidth() * 9 / 10 - 40, area.getHeight() * 9 / 10 - 60);
  8091. big->setVisible (true);
  8092. return;
  8093. }
  8094. if (step == 3)
  8095. {
  8096. juce::Desktop::getInstance().setGlobalScaleFactor ((float) percent / 100.0f);
  8097. juce::Timer::callAfterDelay (200, [] { lynx::fitAllWindowsOnScreen(); });
  8098. return;
  8099. }
  8100. if (step == 4)
  8101. {
  8102. check ("resizable window after the zoom change: fits the screen", *big, true);
  8103. big.reset();
  8104. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  8105. juce::File (path).replaceWithText (report);
  8106. stopTimer();
  8107. if (done)
  8108. done();
  8109. }
  8110. }
  8111. };
  8112. static std::unique_ptr<FitTest> test;
  8113. test = std::make_unique<FitTest>();
  8114. test->path = reportPath;
  8115. test->percent = juce::jlimit (50, 300, percent);
  8116. test->done = [this] { juce::MessageManager::callAsync ([this] { test.reset(); quit(); }); };
  8117. test->start();
  8118. }
  8119. void runFocusTest (const juce::String& reportPath)
  8120. {
  8121. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  8122. struct FocusTest final : juce::Timer
  8123. {
  8124. juce::String reportPath, report;
  8125. bool ok = true;
  8126. int stepIndex = 0;
  8127. std::unique_ptr<lynx::AudioEngine> engine;
  8128. lynx::MainComponent* ui = nullptr;
  8129. std::unique_ptr<juce::DocumentWindow> main;
  8130. std::function<void()> done;
  8131. void line (const juce::String& text)
  8132. {
  8133. report << text << "\n";
  8134. juce::File (reportPath).replaceWithText (report);
  8135. }
  8136. void check (const juce::String& what, bool passed)
  8137. {
  8138. line ((passed ? "ok " : "FAIL ") + what);
  8139. ok = ok && passed;
  8140. }
  8141. juce::ComponentPeer* mainPeer() const { return main != nullptr ? main->getPeer() : nullptr; }
  8142. bool focusInMain() const
  8143. {
  8144. auto* f = juce::Component::getCurrentlyFocusedComponent();
  8145. return f != nullptr && main->isParentOf (f);
  8146. }
  8147. // a click (press and release) at the middle of the panel's content, through the native window it is in
  8148. static void click (juce::Component& frame, bool right)
  8149. {
  8150. auto* peer = frame.getPeer();
  8151. if (peer == nullptr)
  8152. return;
  8153. const auto at = peer->getComponent().getLocalPoint (&frame, frame.getLocalBounds().getCentre().toFloat());
  8154. const auto button = right ? juce::ModifierKeys::rightButtonModifier : juce::ModifierKeys::leftButtonModifier;
  8155. const auto now = juce::Time::currentTimeMillis();
  8156. peer->handleMouseEvent (juce::MouseInputSource::InputSourceType::mouse, at, juce::ModifierKeys (button), 1.0f, 0.0f, now);
  8157. peer->handleMouseEvent (juce::MouseInputSource::InputSourceType::mouse, at, juce::ModifierKeys(), 1.0f, 0.0f, now + 40);
  8158. }
  8159. bool space()
  8160. {
  8161. auto* peer = mainPeer(); // (the system sends the key to the window with the focus: the main one)
  8162. return peer != nullptr && peer->handleKeyPress (juce::KeyPress (juce::KeyPress::spaceKey, juce::ModifierKeys(), ' '));
  8163. }
  8164. juce::TextEditor* firstField (juce::Component& c)
  8165. {
  8166. if (auto* t = dynamic_cast<juce::TextEditor*> (&c); t != nullptr && t->isShowing() && t->getWantsKeyboardFocus())
  8167. return t;
  8168. for (auto* child : c.getChildren())
  8169. if (auto* t = firstField (*child))
  8170. return t;
  8171. return nullptr;
  8172. }
  8173. // the user tabs away and comes back with a click in `panel`
  8174. void backWithClickIn (lynx::workspace::Panel panel, bool right)
  8175. {
  8176. auto& frame = ui->workspaceForTest().getFrame (panel);
  8177. const auto name = juce::String (lynx::workspace::panelId (panel)) + (right ? " (right click)" : "");
  8178. auto* peer = mainPeer();
  8179. line (name + ": native child window=" + juce::String ((int) lynx::nativechild::isAttached (frame)));
  8180. check (name + ": the main window has the keys before", ui->hasKeyboardFocus (true));
  8181. peer->handleFocusLoss(); // (another app is in front: the main window lost the system focus)
  8182. check (name + ": nothing in LYNX has the keys while it is in the background", ! focusInMain());
  8183. // the cause: JUCE answers the system's "activate?" from the panel's own component, which takes no focus on a click
  8184. line (name + ": JUCE's answer alone would activate the window=" + juce::String ((int) frame.getMouseClickGrabsKeyboardFocus()));
  8185. const auto activates = lynx::nativechild::clickActivatesWindow (frame, false);
  8186. check (name + ": a click in it activates the inactive main window", activates);
  8187. #if JUCE_WINDOWS
  8188. if (lynx::nativechild::isAttached (frame))
  8189. check (name + ": its native window answers WM_MOUSEACTIVATE with MA_ACTIVATE",
  8190. lynx::nativechild::mouseActivateAnswerForTest (frame, true) == 1 /* MA_ACTIVATE */);
  8191. #endif
  8192. if (activates)
  8193. peer->handleFocusGain(); // (the system activates the main window and gives it the focus)
  8194. click (frame, right);
  8195. }
  8196. void spacePlays (lynx::workspace::Panel panel, bool right)
  8197. {
  8198. const auto name = juce::String (lynx::workspace::panelId (panel)) + (right ? " (right click)" : "");
  8199. check (name + ": the main window has the keys after the click", ui->hasKeyboardFocus (true));
  8200. auto& transport = engine->getTransport();
  8201. if (transport.playing.load())
  8202. engine->stop();
  8203. const auto used = space();
  8204. check (name + ": Space starts playback", used && transport.playing.load());
  8205. engine->stop();
  8206. }
  8207. void timerCallback() override
  8208. {
  8209. using lynx::workspace::Panel;
  8210. auto& ws = ui->workspaceForTest();
  8211. switch (stepIndex++)
  8212. {
  8213. case 0:
  8214. line ("docking=" + juce::String ((int) lynx::nativechild::dockingEnabled()));
  8215. ws.show (Panel::playlist);
  8216. ws.show (Panel::pianoRoll);
  8217. ui->grabKeyboardFocus();
  8218. break;
  8219. case 1: backWithClickIn (Panel::playlist, false); break;
  8220. case 2: spacePlays (Panel::playlist, false); ui->grabKeyboardFocus(); break;
  8221. case 3: backWithClickIn (Panel::pianoRoll, false); break;
  8222. case 4: spacePlays (Panel::pianoRoll, false); ui->grabKeyboardFocus(); break;
  8223. case 5: backWithClickIn (Panel::playlist, true); break;
  8224. case 6:
  8225. juce::PopupMenu::dismissAllActiveMenus(); // (the right click's menu)
  8226. spacePlays (Panel::playlist, true);
  8227. break;
  8228. case 7:
  8229. {
  8230. // a text field (the Browser's search box) keeps the keys through a switch to another app and back:
  8231. // nothing in LYNX takes them from it (no periodic grab); inside the active window the click's
  8232. // activation answer is unchanged, and a click in the Playlist ends the typing as before (issue #9,
  8233. // as FL ends typing in its search field)
  8234. auto* field = firstField (*ui);
  8235. line ("text field found=" + juce::String ((int) (field != nullptr)));
  8236. if (field != nullptr)
  8237. {
  8238. auto& frame = ws.getFrame (Panel::playlist);
  8239. field->grabKeyboardFocus();
  8240. check ("the text field has the keys", field->hasKeyboardFocus (false));
  8241. mainPeer()->handleFocusLoss();
  8242. mainPeer()->handleFocusGain(); // (back with Alt+Tab, or a click that activates the window)
  8243. check ("the text field gets the keys back with the window", field->hasKeyboardFocus (false));
  8244. check ("active window: a click in a panel does not activate it again", ! lynx::nativechild::clickActivatesWindow (frame, true));
  8245. click (frame, false);
  8246. check ("a click in the Playlist ends the typing: the main window has the keys", ui->hasKeyboardFocus (true) && ! field->hasKeyboardFocus (false));
  8247. }
  8248. line (ok ? "result=OK" : "result=FAILED");
  8249. stopTimer();
  8250. done();
  8251. break;
  8252. }
  8253. default:
  8254. break;
  8255. }
  8256. }
  8257. };
  8258. auto* test = new FocusTest();
  8259. test->reportPath = reportPath;
  8260. startFocusTestWindow (*test);
  8261. test->startTimer (600);
  8262. }
  8263. // --simplekeytest (round 190fc, 0.1.27 RC H2): in the Simple layout Space often did nothing after a click in the
  8264. // window (the dock, a track header, the grid, the Lyrics button) or after a demo opened from Welcome › Start from. The
  8265. // main window in the Simple layout; each step clicks as the system would (through the native window under the point)
  8266. // and presses Space where the system sends it (the native window of the component with the focus): playback must
  8267. // start, except while a text field the user clicked into has the keys (it types). Shows a window (Windows: GUI lock).
  8268. void runSimpleKeyTest (const juce::String& reportPath)
  8269. {
  8270. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  8271. struct KeyTest final : juce::Timer
  8272. {
  8273. juce::String reportPath, report;
  8274. bool ok = true;
  8275. int stepIndex = 0, instrumentTrack = 0;
  8276. std::unique_ptr<lynx::AudioEngine> engine;
  8277. lynx::MainComponent* ui = nullptr;
  8278. std::unique_ptr<juce::DocumentWindow> main;
  8279. std::function<void()> done;
  8280. void line (const juce::String& text)
  8281. {
  8282. report << text << "\n";
  8283. juce::File (reportPath).replaceWithText (report);
  8284. }
  8285. void check (const juce::String& what, bool passed)
  8286. {
  8287. line ((passed ? "ok " : "FAIL ") + what);
  8288. ok = ok && passed;
  8289. }
  8290. static juce::String describe (juce::Component* c)
  8291. {
  8292. if (c == nullptr)
  8293. return "nothing";
  8294. juce::String path;
  8295. for (auto* p = c; p != nullptr && path.length() < 160; p = p->getParentComponent())
  8296. {
  8297. auto name = p->getComponentID().isNotEmpty() ? p->getComponentID() : p->getName();
  8298. if (name.isEmpty())
  8299. name = juce::String (typeid (*p).name()).fromLastOccurrenceOf ("::", false, false).substring (0, 28);
  8300. path << (path.isEmpty() ? "" : " < ") << name;
  8301. }
  8302. return path;
  8303. }
  8304. // the first showing component with this ID in the main window or a native child window of it
  8305. juce::Component* find (const juce::String& id)
  8306. {
  8307. std::function<juce::Component* (juce::Component&)> in = [&] (juce::Component& root) -> juce::Component* {
  8308. if (root.getComponentID() == id && root.isShowing())
  8309. return &root;
  8310. for (auto* c : root.getChildren())
  8311. if (auto* f = in (*c))
  8312. return f;
  8313. return nullptr;
  8314. };
  8315. if (auto* f = in (*main))
  8316. return f;
  8317. if (auto* peer = main->getPeer())
  8318. for (auto* attached : lynx::nativechild::attachedChildren (peer->getNativeHandle()))
  8319. if (auto* f = in (*attached))
  8320. return f;
  8321. return nullptr;
  8322. }
  8323. // a click (press and release) at `local` in `c`, through the native window it is in
  8324. juce::String lastHit;
  8325. void click (juce::Component& c, juce::Point<int> local)
  8326. {
  8327. auto* peer = c.getPeer();
  8328. if (peer == nullptr)
  8329. return;
  8330. const auto at = peer->getComponent().getLocalPoint (&c, local.toFloat());
  8331. lastHit = describe (peer->getComponent().getComponentAt (at.roundToInt()));
  8332. line (" click at " + local.toString() + " in " + describe (&c).upToFirstOccurrenceOf (" < ", false, false) + " -> " + lastHit);
  8333. const auto now = juce::Time::currentTimeMillis();
  8334. peer->handleMouseEvent (juce::MouseInputSource::InputSourceType::mouse, at, juce::ModifierKeys (juce::ModifierKeys::leftButtonModifier), 1.0f, 0.0f, now);
  8335. peer->handleMouseEvent (juce::MouseInputSource::InputSourceType::mouse, at, juce::ModifierKeys(), 1.0f, 0.0f, now + 40);
  8336. }
  8337. void click (juce::Component& c) { click (c, c.getLocalBounds().getCentre()); }
  8338. // Space where the system sends it: the native window of the focused component (else the main one)
  8339. bool space()
  8340. {
  8341. // Windows: posted to the window with the system's focus, as a real key goes (the system's own routing)
  8342. if (lynx::nativechild::pressSpaceForTest (main->getWindowHandle()))
  8343. return true;
  8344. auto* focused = juce::Component::getCurrentlyFocusedComponent();
  8345. auto* peer = focused != nullptr && focused->getPeer() != nullptr ? focused->getPeer() : main->getPeer();
  8346. return peer != nullptr && peer->handleKeyPress (juce::KeyPress (juce::KeyPress::spaceKey, juce::ModifierKeys(), ' '));
  8347. }
  8348. void spacePlays (const juce::String& after)
  8349. {
  8350. line (" keys at: " + describe (juce::Component::getCurrentlyFocusedComponent()));
  8351. auto& transport = engine->getTransport();
  8352. if (transport.playing.load())
  8353. engine->stop();
  8354. space();
  8355. check ("Space plays after " + after, transport.playing.load());
  8356. engine->stop();
  8357. }
  8358. void timerCallback() override
  8359. {
  8360. auto* simple = ui->getSimpleWorkflowForSnapshot();
  8361. auto& playlist = ui->getPlaylistForSnapshot();
  8362. switch (stepIndex++)
  8363. {
  8364. case 0:
  8365. ui->setLayoutStyle (lynx::layoutstyle::Style::simple);
  8366. ui->grabKeyboardFocus();
  8367. break;
  8368. case 1:
  8369. check ("the Simple workflow is up", simple != nullptr);
  8370. if (simple == nullptr)
  8371. return finish();
  8372. spacePlays ("the layout came up");
  8373. simple->showWelcome();
  8374. break;
  8375. case 2:
  8376. if (auto* demo = find ("tour.welcome.demo"))
  8377. click (*demo); // Welcome › Open a demo song: the Start from list
  8378. else
  8379. check ("Welcome > Open a demo song found", false);
  8380. break;
  8381. case 3:
  8382. {
  8383. if (! simple->isStartFromShowing()) // (X11: a child window just mapped may miss the first click)
  8384. if (auto* demo = find ("tour.welcome.demo"))
  8385. {
  8386. line (" the first click was not taken: once more");
  8387. click (*demo);
  8388. }
  8389. check ("Start from is up", simple->isStartFromShowing());
  8390. if (auto* start = dynamic_cast<lynx::StartFromPanel*> (simple->startFromForSnapshot()))
  8391. check ("a demo song opens from it", start->openForSnapshot (1));
  8392. break;
  8393. }
  8394. case 4:
  8395. check ("Start from closed with the demo open", ! simple->isStartFromShowing() && ! engine->getSong().playlist.empty());
  8396. spacePlays ("a demo opened from Welcome > Start from");
  8397. instrumentTrack = [] (const lynx::Song& song) { // the first Instrument track (the dock's Keyboard and Editor tabs are for it)
  8398. for (int t = 0; t < (int) song.playlistTracks.size(); ++t)
  8399. if (lynx::simpletracks::kindOf (song, t) == lynx::simpletracks::Kind::instrument)
  8400. return t;
  8401. return 0;
  8402. } (engine->getSong());
  8403. line ("instrument track: " + juce::String (instrumentTrack));
  8404. playlist.selectTrack (instrumentTrack);
  8405. simple->trackSelected (instrumentTrack);
  8406. break;
  8407. case 5:
  8408. if (auto* dock = simple->dockForSnapshot(); dock != nullptr && dock->isShowing())
  8409. {
  8410. click (*dock, { dock->getWidth() - 6, dock->getHeight() - 6 }); // (its empty corner)
  8411. spacePlays ("a click in the dock");
  8412. }
  8413. else
  8414. check ("the dock shows", false);
  8415. break;
  8416. case 6:
  8417. if (auto* tab = find ("simple.dock.keyboard"))
  8418. {
  8419. click (*tab);
  8420. spacePlays ("a click on a dock tab (Keyboard)");
  8421. }
  8422. if (auto* tab = find ("simple.dock.editor"))
  8423. {
  8424. click (*tab);
  8425. spacePlays ("a click on a dock tab (Editor)");
  8426. }
  8427. break;
  8428. case 7:
  8429. if (auto* lyrics = find ("simple.lyrics"))
  8430. {
  8431. click (*lyrics);
  8432. spacePlays ("a click on the Lyrics button");
  8433. }
  8434. else
  8435. check ("the Lyrics button found", false);
  8436. break;
  8437. case 8:
  8438. {
  8439. const auto lane = playlist.trackRowForSnapshot (instrumentTrack).withTrimmedLeft (playlist.headerWidth);
  8440. click (playlist, { juce::jmax (4, playlist.headerWidth / 2), lane.getCentreY() });
  8441. spacePlays ("a click on a track header");
  8442. click (playlist, lane.getCentre() + juce::Point<int> (40, 0));
  8443. spacePlays ("a click in the Playlist grid");
  8444. break;
  8445. }
  8446. case 9:
  8447. {
  8448. // a text field the user clicks into keeps its typing keys; a click outside gives Space back
  8449. // a dock knob clicked keeps the arrow keys, and Space still plays from it
  8450. for (auto tab : { lynx::SimpleDock::Tab::effects, lynx::SimpleDock::Tab::instrument })
  8451. {
  8452. juce::Component* knob = nullptr;
  8453. std::function<void (juce::Component&)> seek = [&] (juce::Component& c) {
  8454. if (knob == nullptr && c.isShowing() && (bool) c.getProperties().getWithDefault ("lynxClickKeepsKeys", false))
  8455. knob = &c;
  8456. for (auto* child : c.getChildren())
  8457. seek (*child);
  8458. };
  8459. if (auto* dock = simple->dockForSnapshot())
  8460. {
  8461. dock->setTab (tab);
  8462. seek (*dock);
  8463. }
  8464. if (knob != nullptr)
  8465. {
  8466. click (*knob);
  8467. spacePlays ("a click on a dock knob");
  8468. break;
  8469. }
  8470. }
  8471. if (auto* dock = simple->dockForSnapshot())
  8472. dock->setTab (lynx::SimpleDock::Tab::instrument);
  8473. juce::TextEditor* field = nullptr;
  8474. std::function<void (juce::Component&)> look = [&] (juce::Component& c) {
  8475. if (auto* t = dynamic_cast<juce::TextEditor*> (&c); t != nullptr && t->isShowing() && field == nullptr)
  8476. field = t;
  8477. for (auto* child : c.getChildren())
  8478. look (*child);
  8479. };
  8480. if (auto* dock = simple->dockForSnapshot())
  8481. look (*dock);
  8482. line ("text field in the dock found=" + juce::String ((int) (field != nullptr)));
  8483. if (field != nullptr)
  8484. {
  8485. click (*field);
  8486. const auto before = field->getText();
  8487. space();
  8488. check ("Space types into the text field the user clicked", field->getText() != before && ! engine->getTransport().playing.load());
  8489. engine->stop();
  8490. field->clear();
  8491. const auto lane = playlist.trackRowForSnapshot (instrumentTrack).withTrimmedLeft (playlist.headerWidth);
  8492. click (playlist, lane.getCentre() + juce::Point<int> (60, 0));
  8493. spacePlays ("a click in the grid after typing");
  8494. }
  8495. // H1: the first-song tour's card in front of the native panels, taking no keys (started on the demo
  8496. // as it is: Help's question about a new project is a dialog)
  8497. if (auto* tour = simple->tourForSnapshot())
  8498. tour->start();
  8499. break;
  8500. }
  8501. case 10:
  8502. {
  8503. auto* tour = simple->tourForSnapshot();
  8504. auto* card = tour != nullptr ? tour->cardForSnapshot() : nullptr;
  8505. check ("the tour runs", tour != nullptr && tour->isRunning() && card != nullptr && card->isVisible());
  8506. if (card == nullptr)
  8507. return finish();
  8508. auto& frame = ui->workspaceForTest().getFrame (lynx::workspace::Panel::playlist);
  8509. const auto native = lynx::nativechild::dockingEnabled() && lynx::nativechild::isAttached (frame);
  8510. line ("playlist native child window=" + juce::String ((int) native) + ", tour card native child window="
  8511. + juce::String ((int) lynx::nativechild::isAttached (*card)));
  8512. if (native)
  8513. {
  8514. check ("the tour card is a native child window of the main window (not under the panels)", lynx::nativechild::isAttached (*card));
  8515. #if JUCE_WINDOWS
  8516. check ("the tour card is above the Playlist's native window", lynx::nativechild::isAbove (card->getWindowHandle(), frame.getWindowHandle()));
  8517. juce::Component* layer = nullptr;
  8518. for (auto* c : lynx::nativechild::attachedChildren (main->getPeer()->getNativeHandle()))
  8519. if (c != nullptr && c->getComponentID() == "tour.layer")
  8520. layer = c;
  8521. check ("the ring's layer is above the Playlist too", layer != nullptr && lynx::nativechild::isAbove (layer->getWindowHandle(), frame.getWindowHandle()));
  8522. check ("the ring's layer lets clicks through to the Playlist",
  8523. layer != nullptr && lynx::nativechild::windowAt (*layer, layer->getLocalBounds().getCentre()) != layer->getWindowHandle());
  8524. #endif
  8525. }
  8526. check ("the tour card took no keys", ! card->hasKeyboardFocus (true));
  8527. spacePlays ("the tour came up");
  8528. if (auto* next = card->findChildWithID ("tour.next"); next != nullptr && next->isShowing())
  8529. {
  8530. click (*next);
  8531. check ("a click on the card took no keys", ! card->hasKeyboardFocus (true));
  8532. spacePlays ("a click on the tour card");
  8533. }
  8534. finish();
  8535. break;
  8536. }
  8537. default:
  8538. break;
  8539. }
  8540. }
  8541. void finish()
  8542. {
  8543. line (ok ? "result=OK" : "result=FAILED");
  8544. stopTimer();
  8545. done();
  8546. }
  8547. };
  8548. auto* test = new KeyTest();
  8549. test->reportPath = reportPath;
  8550. startFocusTestWindow (*test);
  8551. // Windows: kept above other apps' windows for its few seconds (JUCE takes a button-down only where the system finds
  8552. // its window under the point, and the test clicks through LYNX's own peers, not the system's input)
  8553. #if JUCE_WINDOWS
  8554. test->main->setAlwaysOnTop (true); // (Linux: JUCE makes the X11 window again for it; the private X server has no other windows)
  8555. #endif
  8556. test->startTimer (700);
  8557. }
  8558. template <typename Test>
  8559. void startFocusTestWindow (Test& t)
  8560. {
  8561. auto* test = &t;
  8562. test->engine = std::make_unique<lynx::AudioEngine> (false);
  8563. test->main = std::make_unique<juce::DocumentWindow> ("LYNX focus test", lynx::theme::window, juce::DocumentWindow::allButtons);
  8564. test->main->setUsingNativeTitleBar (true);
  8565. test->ui = new lynx::MainComponent (*test->engine, false);
  8566. test->main->setContentOwned (test->ui, true);
  8567. test->main->setResizable (true, true);
  8568. test->main->centreWithSize (1280, 760);
  8569. test->main->setVisible (true);
  8570. lynx::setMainWindowForOwnership (test->main.get());
  8571. test->done = [this, test] {
  8572. setApplicationReturnValue (test->ok ? 0 : 1);
  8573. juce::MessageManager::callAsync ([this, test] {
  8574. lynx::setMainWindowForOwnership (nullptr);
  8575. test->main = nullptr;
  8576. delete test;
  8577. quit();
  8578. });
  8579. };
  8580. }
  8581. void runWindowTest (const juce::String& reportPath)
  8582. {
  8583. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  8584. struct WindowTest final : juce::Timer
  8585. {
  8586. juce::String reportPath, report;
  8587. bool ok = true;
  8588. int stepIndex = 0;
  8589. std::unique_ptr<lynx::AudioEngine> engine;
  8590. lynx::MainComponent* ui = nullptr;
  8591. std::unique_ptr<juce::DocumentWindow> main, pluginLike;
  8592. juce::TextEditor* pluginField = nullptr;
  8593. std::unique_ptr<juce::AlertWindow> nameDialog;
  8594. std::function<void()> done;
  8595. void line (const juce::String& text)
  8596. {
  8597. report << text << "\n";
  8598. juce::File (reportPath).replaceWithText (report);
  8599. }
  8600. void check (const juce::String& what, bool passed)
  8601. {
  8602. line ((passed ? "ok " : "FAIL ") + what);
  8603. ok = ok && passed;
  8604. }
  8605. bool isAbove (juce::Component* w) { return w != nullptr && lynx::isAboveMainWindow (*w); }
  8606. bool focusIn (juce::Component* w)
  8607. {
  8608. auto* f = juce::Component::getCurrentlyFocusedComponent();
  8609. return w != nullptr && f != nullptr && (f == w || w->isParentOf (f));
  8610. }
  8611. void timerCallback() override
  8612. {
  8613. switch (stepIndex++)
  8614. {
  8615. case 0:
  8616. line ("foreground=" + juce::String (juce::Process::isForegroundProcess() ? 1 : 0));
  8617. ui->openQuickAddForTest();
  8618. break;
  8619. case 1:
  8620. {
  8621. auto* w = lynx::findToolWindow ("quickadd");
  8622. check ("quick-add palette open", w != nullptr);
  8623. check ("quick-add palette active", w != nullptr && w->isActiveWindow());
  8624. check ("quick-add palette owned by the main window", w != nullptr && lynx::isOwnedByMainWindow (*w));
  8625. check ("quick-add palette above the main window", isAbove (w));
  8626. auto* f = juce::Component::getCurrentlyFocusedComponent();
  8627. check ("quick-add search box has the keyboard focus", focusIn (w) && dynamic_cast<juce::TextEditor*> (f) != nullptr && f->hasKeyboardFocus (false) && w->isActiveWindow());
  8628. lynx::closeAllToolWindows();
  8629. lynx::openAudioEditor (*engine);
  8630. break;
  8631. }
  8632. case 2:
  8633. {
  8634. auto* w = lynx::findToolWindow ("audioeditor");
  8635. check ("audio editor open", w != nullptr);
  8636. check ("audio editor active", w != nullptr && w->isActiveWindow());
  8637. check ("audio editor owned by the main window", w != nullptr && lynx::isOwnedByMainWindow (*w));
  8638. check ("audio editor above the main window", isAbove (w));
  8639. lynx::forceForegroundForTest (*main); // the user clicks the main window
  8640. break;
  8641. }
  8642. case 3:
  8643. {
  8644. auto* w = lynx::findToolWindow ("audioeditor");
  8645. check ("audio editor stays above the main window after clicking it", isAbove (w));
  8646. lynx::closeAllToolWindows();
  8647. // a plugin editor's window: its own controls keep the keyboard focus
  8648. pluginLike = std::make_unique<juce::DocumentWindow> ("Plugin", juce::Colours::black, juce::DocumentWindow::closeButton);
  8649. pluginLike->setUsingNativeTitleBar (true);
  8650. auto* field = new juce::TextEditor();
  8651. field->setSize (300, 120);
  8652. pluginLike->setContentOwned (field, true);
  8653. pluginLike->centreWithSize (300, 120);
  8654. pluginLike->setVisible (true);
  8655. lynx::keepAboveMainWindow (*pluginLike);
  8656. pluginLike->toFront (true);
  8657. field->grabKeyboardFocus();
  8658. pluginField = field;
  8659. break;
  8660. }
  8661. case 4:
  8662. check ("plugin window active", pluginLike->isActiveWindow());
  8663. check ("plugin window keeps the keyboard focus", pluginField->hasKeyboardFocus (false) && pluginLike->isActiveWindow());
  8664. check ("plugin window above the main window", isAbove (pluginLike.get()));
  8665. pluginLike = nullptr;
  8666. lynx::forceForegroundForTest (*main);
  8667. juce::Component::unfocusAllComponents();
  8668. break;
  8669. case 5:
  8670. check ("main window takes the keyboard focus back when it is active", ui->hasKeyboardFocus (true));
  8671. // round 165q: a name dialog (F4's next empty pattern, Rename and color...) opens ready to type
  8672. nameDialog = lynx::makeNameAndColourDialog ("Rename pattern", "Pattern 2", 0xff808080u);
  8673. nameDialog->enterModalState (true, nullptr, false);
  8674. lynx::keepAboveMainWindow (*nameDialog);
  8675. break;
  8676. case 6:
  8677. {
  8678. auto* f = juce::Component::getCurrentlyFocusedComponent();
  8679. auto* field = dynamic_cast<juce::TextEditor*> (f);
  8680. check ("name dialog: its text field has the keyboard focus", field != nullptr && focusIn (nameDialog.get()));
  8681. if (field != nullptr)
  8682. field->keyPressed (juce::KeyPress ('x', {}, 'x'));
  8683. check ("name dialog: typing replaces the name", nameDialog->getTextEditorContents ("name") == "x");
  8684. nameDialog->exitModalState (0);
  8685. nameDialog = nullptr;
  8686. line (ok ? "result=OK" : "result=FAILED");
  8687. stopTimer();
  8688. done();
  8689. break;
  8690. }
  8691. default:
  8692. break;
  8693. }
  8694. }
  8695. };
  8696. auto* test = new WindowTest();
  8697. test->reportPath = reportPath;
  8698. test->engine = std::make_unique<lynx::AudioEngine> (false);
  8699. test->main = std::make_unique<juce::DocumentWindow> ("LYNX window test", lynx::theme::window, juce::DocumentWindow::allButtons);
  8700. test->main->setUsingNativeTitleBar (true);
  8701. test->ui = new lynx::MainComponent (*test->engine, false);
  8702. test->main->setContentOwned (test->ui, true);
  8703. test->main->setResizable (true, true);
  8704. test->main->centreWithSize (1280, 760);
  8705. test->main->setVisible (true);
  8706. lynx::setMainWindowForOwnership (test->main.get());
  8707. lynx::forceForegroundForTest (*test->main);
  8708. test->main->toFront (true);
  8709. test->done = [this, test] {
  8710. setApplicationReturnValue (test->ok ? 0 : 1);
  8711. juce::MessageManager::callAsync ([this, test] {
  8712. lynx::closeAllToolWindows();
  8713. lynx::setMainWindowForOwnership (nullptr);
  8714. test->main = nullptr;
  8715. delete test;
  8716. quit();
  8717. });
  8718. };
  8719. test->startTimer (1500);
  8720. }
  8721. // --minimizeclicktest (issue #188): see the option. The main window holds a component that counts its mouse-downs.
  8722. void runMinimizeClickTest (const juce::String& reportPath)
  8723. {
  8724. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  8725. struct ClickPad final : juce::Component
  8726. {
  8727. int downs = 0;
  8728. void paint (juce::Graphics& g) override { g.fillAll (juce::Colours::darkslategrey); }
  8729. void mouseDown (const juce::MouseEvent&) override { ++downs; }
  8730. };
  8731. struct MinimizeTest final : juce::Timer
  8732. {
  8733. juce::String reportPath, report;
  8734. bool ok = true;
  8735. int stepIndex = 0, waits = 0;
  8736. std::unique_ptr<juce::DocumentWindow> main;
  8737. ClickPad* pad = nullptr;
  8738. juce::DocumentWindow* tool = nullptr;
  8739. juce::Point<int> inside, outside; // screen points: where the tool window is, and beside it
  8740. std::function<void()> done;
  8741. void line (const juce::String& text)
  8742. {
  8743. report << text << "\n";
  8744. juce::File (reportPath).replaceWithText (report);
  8745. }
  8746. void check (const juce::String& what, bool passed)
  8747. {
  8748. line ((passed ? "ok " : "FAIL ") + what);
  8749. ok = ok && passed;
  8750. }
  8751. // a left click at a screen point through the main window's peer: the path an X ButtonPress takes
  8752. bool clickReachesPad (juce::Point<int> screen)
  8753. {
  8754. auto* peer = main->getPeer();
  8755. if (peer == nullptr)
  8756. return false;
  8757. const auto before = pad->downs;
  8758. const auto local = peer->globalToLocal (screen.toFloat());
  8759. const auto now = juce::Time::currentTimeMillis();
  8760. peer->handleMouseEvent (juce::MouseInputSource::InputSourceType::mouse, local, juce::ModifierKeys (juce::ModifierKeys::leftButtonModifier),
  8761. juce::MouseInputSource::defaultPressure, juce::MouseInputSource::defaultOrientation, now);
  8762. peer->handleMouseEvent (juce::MouseInputSource::InputSourceType::mouse, local, juce::ModifierKeys(),
  8763. juce::MouseInputSource::defaultPressure, juce::MouseInputSource::defaultOrientation, now + 1);
  8764. return pad->downs == before + 1;
  8765. }
  8766. bool toolMinimised() const { return tool != nullptr && tool->getPeer() != nullptr && tool->getPeer()->isMinimised(); }
  8767. void timerCallback() override
  8768. {
  8769. switch (stepIndex)
  8770. {
  8771. case 0:
  8772. {
  8773. auto content = std::make_unique<juce::Component>();
  8774. content->setSize (420, 300);
  8775. tool = lynx::openToolWindow (std::move (content), "Tap tempo (test)", "minimizetest");
  8776. ++stepIndex;
  8777. return;
  8778. }
  8779. case 1:
  8780. {
  8781. check ("tool window open", tool != nullptr && tool->isShowing());
  8782. if (tool == nullptr)
  8783. break;
  8784. const auto r = tool->getScreenBounds();
  8785. inside = r.getCentre();
  8786. outside = { main->getScreenBounds().getX() + 40, main->getScreenBounds().getBottom() - 40 };
  8787. line ("main " + main->getScreenBounds().toString() + " tool " + r.toString());
  8788. lynx::matchWindowOrderToScreen();
  8789. check ("a click beside the tool window reaches the main window", clickReachesPad (outside));
  8790. check ("a click on the shown tool window does not reach the main window", ! clickReachesPad (inside));
  8791. tool->setMinimised (true);
  8792. ++stepIndex;
  8793. return;
  8794. }
  8795. case 2:
  8796. if (! toolMinimised() && ++waits < 20)
  8797. return;
  8798. check ("the window manager minimised the tool window", toolMinimised());
  8799. check ("the tool window stays visible for JUCE (as in the report)", tool->isVisible());
  8800. main->toFront (true); // a click on the main window: LYNX puts its secondary windows back above it in JUCE's list
  8801. lynx::matchWindowOrderToScreen();
  8802. ++stepIndex;
  8803. return;
  8804. case 3:
  8805. check ("a click where the minimised tool window was reaches the main window", clickReachesPad (inside));
  8806. check ("a click beside it still reaches the main window", clickReachesPad (outside));
  8807. tool->setMinimised (false);
  8808. waits = 0;
  8809. ++stepIndex;
  8810. return;
  8811. case 4:
  8812. if (toolMinimised() && ++waits < 20)
  8813. return;
  8814. tool->toFront (false);
  8815. lynx::matchWindowOrderToScreen();
  8816. ++stepIndex;
  8817. return;
  8818. case 5:
  8819. check ("the tool window is back", ! toolMinimised());
  8820. check ("a click on the restored tool window does not reach the main window", ! clickReachesPad (inside));
  8821. break;
  8822. default:
  8823. return;
  8824. }
  8825. line (ok ? "result=OK" : "result=FAILED");
  8826. stopTimer();
  8827. done();
  8828. }
  8829. };
  8830. auto* test = new MinimizeTest();
  8831. test->reportPath = reportPath;
  8832. test->main = std::make_unique<juce::DocumentWindow> ("LYNX minimise test", lynx::theme::window, juce::DocumentWindow::allButtons);
  8833. test->main->setUsingNativeTitleBar (true);
  8834. test->pad = new ClickPad();
  8835. test->pad->setSize (1200, 760);
  8836. test->main->setContentOwned (test->pad, true);
  8837. test->main->setTopLeftPosition (60, 60);
  8838. test->main->setVisible (true);
  8839. lynx::setMainWindowForOwnership (test->main.get());
  8840. test->main->toFront (true);
  8841. test->done = [this, test] {
  8842. setApplicationReturnValue (test->ok ? 0 : 1);
  8843. juce::MessageManager::callAsync ([this, test] {
  8844. lynx::closeAllToolWindows();
  8845. lynx::setMainWindowForOwnership (nullptr);
  8846. test->main = nullptr;
  8847. delete test;
  8848. quit();
  8849. });
  8850. };
  8851. test->startTimer (700);
  8852. }
  8853. // LYNX.exe --plugintest plugin.vst3 report.txt ["name"]: loads the plugin (or the one named in a shell), plays notes if it is an
  8854. // instrument (and runs audio through it if it is an effect) and measures the audio.
  8855. // Round 190fw: an instrument plugin file on channel 5 of an offline engine (Image-Line's "FL Studio VSTi", which
  8856. // runs FL Studio inside it). Without a project: four chords at 137 BPM, rendered (notes.wav), the plugin's state
  8857. // saved in <folder>/vstitest.lynx. With a project (one saved by LYNX with the plugin on a channel, e.g. after its
  8858. // window was used): that project. Then: the project loaded back from the file renders the same (reload.wav) and
  8859. // gives the same state back; the project's own notes removed, rendered at 100 and 150 BPM (tempo-100/150.wav), the
  8860. // onsets of what the plugin plays by itself must follow the host tempo; and the outputs the plugin offers.
  8861. void runVstiTest (const juce::String& pluginPath, const juce::String& folderPath, const juce::String& projectPath)
  8862. {
  8863. juce::String report;
  8864. auto ok = true;
  8865. const juce::File folder (folderPath);
  8866. folder.createDirectory();
  8867. const auto check = [&] (const juce::String& name, bool passed) {
  8868. report << name << "=" << (passed ? "OK" : "FAILED") << "\n";
  8869. ok = ok && passed;
  8870. };
  8871. struct Take
  8872. {
  8873. float peak = 0.0f;
  8874. std::vector<float> left;
  8875. };
  8876. // renders `song` with the plugin file known to the engine's host; `wav` (in the folder) gets the audio
  8877. const auto render = [&] (const lynx::Song& song, double seconds, const juce::String& wav, std::function<void (lynx::AudioEngine&)> after = {}) {
  8878. Take take;
  8879. lynx::AudioEngine engine (false);
  8880. engine.getPluginHost().addPluginFile (juce::File (pluginPath));
  8881. engine.setSong (song);
  8882. const auto file = folder.getChildFile (wav);
  8883. file.deleteFile();
  8884. std::unique_ptr<juce::AudioFormatWriter> writer;
  8885. if (auto stream = file.createOutputStream())
  8886. {
  8887. juce::WavAudioFormat format;
  8888. writer.reset (format.createWriterFor (stream.get(), 48000.0, 2, 24, {}, 0));
  8889. if (writer != nullptr)
  8890. stream.release();
  8891. }
  8892. lynx::AudioEngine::RenderOptions o;
  8893. o.seconds = seconds;
  8894. o.sampleRate = 48000.0;
  8895. o.output = writer.get();
  8896. o.capture = [&take] (const float* l, const float*, int n) { take.left.insert (take.left.end(), l, l + n); };
  8897. take.peak = engine.renderOffline (o);
  8898. writer.reset();
  8899. if (after)
  8900. after (engine);
  8901. return take;
  8902. };
  8903. // the channel that holds the plugin
  8904. const auto pluginChannel = [&] (const lynx::Song& song) {
  8905. for (std::size_t c = 0; c < song.channels.size(); ++c)
  8906. if (song.channels[c].instrument == lynx::InstrumentKind::plugin
  8907. && juce::String (song.channels[c].plugin.name).containsIgnoreCase (juce::File (pluginPath).getFileNameWithoutExtension().upToFirstOccurrenceOf (" (", false, false)))
  8908. return (int) c;
  8909. return -1;
  8910. };
  8911. lynx::Song song;
  8912. const auto saved = folder.getChildFile ("vstitest.lynx");
  8913. if (projectPath.isEmpty())
  8914. {
  8915. lynx::AudioEngine scanner (false);
  8916. report << "plugins_in_file=" << scanner.getPluginHost().addPluginFile (juce::File (pluginPath)) << "\n";
  8917. std::optional<juce::PluginDescription> type;
  8918. for (const auto& t : scanner.getPluginHost().getKnownPlugins().getTypes())
  8919. if (t.isInstrument && juce::File (t.fileOrIdentifier) == juce::File (pluginPath))
  8920. type = t;
  8921. check ("instrument_found", type.has_value());
  8922. if (! type)
  8923. {
  8924. juce::File (folder.getChildFile ("report.txt")).replaceWithText (report + "result=FAILED\n");
  8925. setApplicationReturnValue (1);
  8926. quit();
  8927. return;
  8928. }
  8929. report << "plugin=" << type->name << " (" << type->manufacturerName << ") outputs=" << type->numOutputChannels << "\n";
  8930. song = lynx::Song::makeDefault();
  8931. song.bpm = 137.0;
  8932. auto& c = song.channels[4];
  8933. c.instrument = lynx::InstrumentKind::plugin;
  8934. c.plugin = {};
  8935. c.plugin.id = type->createIdentifierString().toStdString();
  8936. c.plugin.name = type->name.toStdString();
  8937. c.name = type->name.toStdString();
  8938. c.volume = 1.0f;
  8939. for (std::size_t k = 0; k < song.channels.size(); ++k)
  8940. song.channels[k].muted = k != 4;
  8941. song.patterns[0].notes.clear();
  8942. for (int beat = 0; beat < 8; ++beat) // a chord per beat, two bars
  8943. for (int key : { 60, 64, 67 })
  8944. song.patterns[0].notes.push_back ({ (std::int64_t) beat * lynx::ppq, lynx::ppq / 2, 4, key + (beat / 4) * 5, 0.9f });
  8945. song.patterns[0].sortNotes();
  8946. const auto notes = render (song, 4.0, "notes.wav", [&song] (lynx::AudioEngine& engine) {
  8947. engine.capturePluginStates();
  8948. song = engine.getSong();
  8949. });
  8950. report << "notes_peak=" << notes.peak << "\n";
  8951. check ("notes_play", notes.peak > 0.001f && notes.peak < 10.0f);
  8952. juce::String error;
  8953. check ("project_saved", lynx::ProjectFile::save (song, saved, error));
  8954. }
  8955. else
  8956. {
  8957. juce::String error;
  8958. const auto loaded = lynx::ProjectFile::load (juce::File (projectPath), error);
  8959. check ("project_loaded", loaded.has_value());
  8960. if (loaded)
  8961. song = *loaded;
  8962. juce::File (projectPath).copyFileTo (saved);
  8963. }
  8964. const auto channel = pluginChannel (song);
  8965. check ("plugin_channel", channel >= 0);
  8966. if (channel >= 0)
  8967. {
  8968. const auto& plugin = song.channels[(std::size_t) channel].plugin;
  8969. juce::MemoryBlock state;
  8970. state.fromBase64Encoding (juce::String (plugin.state));
  8971. report << "channel=" << channel + 1 << " state_bytes=" << (int) state.getSize() << "\n";
  8972. check ("state_saved", state.getSize() > 0);
  8973. // the project read back from the file: the same sound, and the same state handed back
  8974. juce::String error;
  8975. const auto again = lynx::ProjectFile::load (saved, error);
  8976. check ("project_reloaded", again.has_value());
  8977. if (again)
  8978. {
  8979. std::string stateBack;
  8980. const auto first = render (*again, 4.0, "reload-a.wav");
  8981. const auto second = render (*again, 4.0, "reload-b.wav", [&] (lynx::AudioEngine& engine) {
  8982. engine.capturePluginStates();
  8983. stateBack = engine.getSong().channels[(std::size_t) channel].plugin.state;
  8984. });
  8985. // two loads of the same project: the same audio (sample for sample, or within -60 dB for a plugin
  8986. // with free-running modulation)
  8987. double energy = 0.0, difference = 0.0;
  8988. const auto n = std::min (first.left.size(), second.left.size());
  8989. for (std::size_t k = 0; k < n; ++k)
  8990. {
  8991. energy += (double) first.left[k] * first.left[k];
  8992. difference += ((double) first.left[k] - second.left[k]) * ((double) first.left[k] - second.left[k]);
  8993. }
  8994. const auto ratioDb = energy > 0.0 ? 10.0 * std::log10 (std::max (difference, 1e-30) / energy) : 0.0;
  8995. report << "reload_peak=" << first.peak << " reload_difference_db=" << juce::String (ratioDb, 1) << "\n";
  8996. check ("reload_plays", first.peak > 0.001f);
  8997. check ("reload_same_sound", energy > 0.0 && ratioDb < -60.0);
  8998. juce::MemoryBlock back;
  8999. back.fromBase64Encoding (juce::String (stateBack));
  9000. report << "state_back_bytes=" << (int) back.getSize() << " identical=" << (int) (back == state) << "\n";
  9001. check ("state_handed_back", back.getSize() > 0);
  9002. }
  9003. // the host tempo: what the plugin plays by itself (FL Studio's own patterns inside FL Studio VSTi) at two
  9004. // tempos, without the project's notes
  9005. auto self = song;
  9006. for (std::size_t k = 0; k < self.channels.size(); ++k)
  9007. self.channels[k].muted = (int) k != channel;
  9008. for (auto& pattern : self.patterns)
  9009. pattern.notes.erase (std::remove_if (pattern.notes.begin(), pattern.notes.end(), [channel] (const lynx::Note& n) { return n.channel == channel; }),
  9010. pattern.notes.end());
  9011. const auto onsets = [] (const std::vector<float>& x) {
  9012. // envelope rises over a threshold (10 ms hold-off of 60 ms): the times in seconds
  9013. std::vector<double> at;
  9014. float peak = 0.0f;
  9015. for (const auto v : x)
  9016. peak = std::max (peak, std::abs (v));
  9017. const auto threshold = peak * 0.3f;
  9018. auto quietFor = 1 << 30;
  9019. for (std::size_t k = 0; k < x.size(); ++k)
  9020. {
  9021. const auto loud = std::abs (x[k]) >= threshold;
  9022. if (loud && quietFor >= 48000 * 60 / 1000)
  9023. at.push_back ((double) k / 48000.0);
  9024. quietFor = loud ? 0 : quietFor + 1;
  9025. }
  9026. return at;
  9027. };
  9028. const auto medianGap = [] (const std::vector<double>& at) {
  9029. std::vector<double> gaps;
  9030. for (std::size_t k = 1; k < at.size(); ++k)
  9031. gaps.push_back (at[k] - at[k - 1]);
  9032. if (gaps.empty())
  9033. return 0.0;
  9034. std::sort (gaps.begin(), gaps.end());
  9035. return gaps[gaps.size() / 2];
  9036. };
  9037. self.bpm = 100.0;
  9038. const auto slow = render (self, 6.0, "tempo-100.wav");
  9039. self.bpm = 150.0;
  9040. const auto fast = render (self, 6.0, "tempo-150.wav");
  9041. const auto gapSlow = medianGap (onsets (slow.left)), gapFast = medianGap (onsets (fast.left));
  9042. report << "self_peak_100=" << slow.peak << " self_peak_150=" << fast.peak << " onsets_100=" << (int) onsets (slow.left).size()
  9043. << " onsets_150=" << (int) onsets (fast.left).size() << " gap_100=" << juce::String (gapSlow, 4) << " gap_150="
  9044. << juce::String (gapFast, 4) << "\n";
  9045. if (slow.peak > 0.001f && gapFast > 0.0)
  9046. {
  9047. report << "tempo_ratio=" << juce::String (gapSlow / gapFast, 3) << " (expected 1.5)\n";
  9048. check ("follows_host_tempo", std::abs (gapSlow / gapFast - 1.5) < 0.05);
  9049. }
  9050. else
  9051. report << "tempo: the plugin plays nothing by itself in this project\n";
  9052. // the outputs it offers (FL Studio VSTi (Multi): FL's mixer tracks as separate outputs)
  9053. lynx::AudioEngine engine (false);
  9054. engine.getPluginHost().addPluginFile (juce::File (pluginPath));
  9055. engine.setSong (song);
  9056. engine.renderOffline (0.2, 48000.0);
  9057. if (auto instrument = std::dynamic_pointer_cast<lynx::PluginInstrument> (engine.getChannelInstrument (channel)))
  9058. {
  9059. report << "outputs=" << (int) instrument->outputs().size() << ":";
  9060. for (const auto& o : instrument->outputs())
  9061. report << " [" << o.name << "]";
  9062. report << "\n";
  9063. check ("outputs_listed", ! instrument->outputs().empty());
  9064. }
  9065. else
  9066. check ("instrument_loaded", false);
  9067. }
  9068. report << "plugin_crashes=" << lynx::pluginCrashCount() << "\n";
  9069. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  9070. folder.getChildFile ("report.txt").replaceWithText (report);
  9071. setApplicationReturnValue (ok ? 0 : 1);
  9072. quit();
  9073. }
  9074. void runPluginTest (const juce::String& pluginPath, const juce::String& reportPath, const juce::String& only = {})
  9075. {
  9076. juce::String report;
  9077. bool ok = false;
  9078. {
  9079. lynx::AudioEngine offline (false);
  9080. auto& host = offline.getPluginHost();
  9081. const auto added = host.addPluginFile (juce::File (pluginPath));
  9082. report << "plugins_in_file=" << added << "\n";
  9083. juce::PluginDescription instrument, effect;
  9084. bool hasInstrument = false, hasEffect = false;
  9085. for (const auto& type : host.getKnownPlugins().getTypes())
  9086. {
  9087. if (juce::File (type.fileOrIdentifier).getFileName() != juce::File (pluginPath).getFileName()
  9088. || (only.isNotEmpty() && type.name != only))
  9089. continue;
  9090. report << " " << (type.isInstrument ? "instrument: " : "effect: ") << type.name << " (" << type.manufacturerName
  9091. << ") in " << type.fileOrIdentifier << "\n";
  9092. if (type.isInstrument && ! hasInstrument) { instrument = type; hasInstrument = true; }
  9093. if (! type.isInstrument && ! hasEffect) { effect = type; hasEffect = true; }
  9094. }
  9095. auto song = lynx::Song::makeDefault();
  9096. if (hasInstrument)
  9097. {
  9098. auto& c = song.channels[4]; // the "Synth" channel becomes the plugin
  9099. c.instrument = lynx::InstrumentKind::plugin;
  9100. c.plugin.id = instrument.createIdentifierString().toStdString();
  9101. c.plugin.name = instrument.name.toStdString();
  9102. c.volume = 1.0f;
  9103. for (int i = 0; i < 4; ++i) // one chord per beat
  9104. for (int key : { 60, 64, 67 })
  9105. song.patterns[0].notes.push_back ({ (std::int64_t) i * lynx::ppq, lynx::ppq / 2, 4, key, 0.9f });
  9106. song.patterns[0].sortNotes();
  9107. }
  9108. if (hasEffect)
  9109. {
  9110. lynx::EffectSlot slot;
  9111. slot.kind = lynx::EffectKind::plugin;
  9112. slot.plugin.id = effect.createIdentifierString().toStdString();
  9113. slot.plugin.name = effect.name.toStdString();
  9114. song.mixer[0].effects.push_back (slot);
  9115. }
  9116. const auto effectSlot = (int) song.mixer[0].effects.size() - 1; // (the default master may hold effects already)
  9117. offline.setSong (song);
  9118. // after a render: the rack (and its plugins) is built when the engine is prepared
  9119. const auto peak = offline.renderOffline (3.0, 48000.0);
  9120. const auto* loadedInstrument = dynamic_cast<lynx::PluginInstrument*> (offline.getChannelInstrument (4).get());
  9121. const auto* loadedEffect = dynamic_cast<lynx::PluginEffect*> (offline.getEffect (0, effectSlot).get());
  9122. report << "instrument_loaded=" << (loadedInstrument != nullptr ? "yes" : "no") << "\n"
  9123. << "effect_loaded=" << (loadedEffect != nullptr ? "yes" : "no") << "\n";
  9124. if (host.getLoadFailures().size() > 0) // why: the host's own message (license, missing file, load failure)
  9125. report << "load_failures=" << host.getLoadFailures().joinIntoString (" | ") << "\n";
  9126. report << "peak=" << peak << "\n";
  9127. // plugins that crashed inside a call, were caught and switched off (round 111)
  9128. report << "plugin_crashes=" << lynx::pluginCrashCount() << "\n";
  9129. for (const auto& c : lynx::pluginCrashes())
  9130. report << " crashed: " << c.plugin << " (" << lynx::crashguard::describe (c.code) << ")\n";
  9131. offline.capturePluginStates();
  9132. const auto stateSize = hasInstrument ? offline.getSong().channels[4].plugin.state.size() : (size_t) 0;
  9133. report << "state_bytes_base64=" << (int) stateSize << "\n";
  9134. ok = (hasInstrument || hasEffect) && (! hasInstrument || loadedInstrument != nullptr)
  9135. && (! hasEffect || loadedEffect != nullptr) && peak > 0.001f && peak < 10.0f;
  9136. }
  9137. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  9138. juce::File (reportPath).replaceWithText (report);
  9139. setApplicationReturnValue (ok ? 0 : 1);
  9140. quit();
  9141. }
  9142. // Round 190gg (B4): --crashguardtest plugin report.txt thread | ui. "thread": the plugin's own thread faults in its 40th
  9143. // block (Linux / macOS): that thread is parked, LYNX switches the plugin off (as the main window's timer does) and goes
  9144. // on; the other inserts play; Reload brings it back. "ui": the calls the UI makes into a plugin, under the guard: a
  9145. // preset load that crashes (the Plugin window's preset menu path) and making the editor (PluginWindows::open, the CLAP
  9146. // test plugin's "editor-create": a display is needed, e.g. Xvfb); each switches the plugin off, LYNX goes on.
  9147. void runCrashGuardThreadOrUiTest (const juce::String& pluginPath, const juce::String& reportPath, const juce::String& mode)
  9148. {
  9149. juce::String report;
  9150. bool ok = true;
  9151. const auto expect = [&] (const char* name, bool value) {
  9152. report << name << "=" << (value ? 1 : 0) << "\n";
  9153. ok = ok && value;
  9154. };
  9155. const auto setEnv = [] (const char* name, const char* value) {
  9156. #if JUCE_WINDOWS
  9157. _putenv_s (name, value);
  9158. #else
  9159. setenv (name, value, 1);
  9160. #endif
  9161. };
  9162. const auto render = [] (lynx::AudioEngine& engine, double seconds, float* peak) {
  9163. lynx::AudioEngine::RenderOptions o;
  9164. o.seconds = seconds;
  9165. o.sampleRate = 48000.0;
  9166. o.pluginWarmUp = false;
  9167. if (peak != nullptr)
  9168. o.capture = [peak] (const float* l, const float* r, int n) {
  9169. for (int k = 0; k < n; ++k)
  9170. *peak = std::max (*peak, std::max (std::abs (l[k]), std::abs (r[k])));
  9171. };
  9172. return engine.renderOffline (o);
  9173. };
  9174. report << "mode=" << mode << "\nthread_guard=" << (lynx::crashguard::pluginThreadFaultsCaught() ? "on" : "off") << "\n";
  9175. setEnv ("LYNX_TEST_CRASH", mode == "thread" ? "thread" : "");
  9176. setEnv ("LYNX_TEST_CRASH_AFTER", "40");
  9177. const auto tmp = juce::File::getSpecialLocation (juce::File::tempDirectory)
  9178. .getChildFile ("lynx-crashguardtest-" + juce::String::toHexString (juce::Random::getSystemRandom().nextInt64()));
  9179. tmp.createDirectory();
  9180. {
  9181. lynx::AudioEngine offline (false);
  9182. auto& host = offline.getPluginHost();
  9183. host.addPluginFile (juce::File (pluginPath));
  9184. juce::PluginDescription effect;
  9185. bool found = false;
  9186. for (const auto& type : host.getKnownPlugins().getTypes())
  9187. if (! found && ! type.isInstrument && juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginPath).getFileName())
  9188. {
  9189. effect = type;
  9190. found = true;
  9191. }
  9192. expect ("plugin_found", found);
  9193. auto song = lynx::Song::makeDefault();
  9194. lynx::EffectSlot slot;
  9195. slot.kind = lynx::EffectKind::plugin;
  9196. slot.plugin.id = effect.createIdentifierString().toStdString();
  9197. slot.plugin.name = effect.name.toStdString();
  9198. song.mixer[1].effects.push_back (slot);
  9199. offline.setSong (song);
  9200. const lynx::AudioEngine::HostedSlot where { -1, 1, 0 };
  9201. render (offline, 0.05, nullptr);
  9202. offline.editSong ([] (lynx::Song& s) { s.channels[0].volume = 0.85f; }, false);
  9203. render (offline, 0.05, nullptr);
  9204. auto* first = dynamic_cast<lynx::PluginEffect*> (offline.getEffect (1, 0).get());
  9205. expect ("plugin_loaded", first != nullptr);
  9206. const auto crashesBefore = lynx::pluginCrashCount();
  9207. if (mode == "thread")
  9208. {
  9209. const auto faultsBefore = lynx::crashguard::pluginThreadFaultCount();
  9210. float peak = 0.0f;
  9211. render (offline, 3.0, &peak); // (the plugin starts its faulting thread in its 40th block)
  9212. for (int i = 0; i < 200 && lynx::crashguard::pluginThreadFaultCount() == faultsBefore; ++i)
  9213. juce::Thread::sleep (10);
  9214. const auto faults = lynx::crashguard::pluginThreadFaults();
  9215. expect ("thread_fault_parked", lynx::crashguard::pluginThreadFaultCount() == faultsBefore + 1 && ! faults.empty());
  9216. if (! faults.empty())
  9217. report << "thread_fault=" << faults.back().where << " (" << lynx::crashguard::describe (faults.back().code) << ")\n";
  9218. expect ("not_yet_counted_as_a_call_crash", lynx::pluginCrashCount() == crashesBefore);
  9219. // what the main window's timer does
  9220. // (every instance of that module: the engine may hold more than the slot's, e.g. the offline render's)
  9221. if (first != nullptr)
  9222. report << "slot_file=" << first->getInstance().getPluginDescription().fileOrIdentifier << "\n";
  9223. const auto switched = lynx::switchOffPluginsOfThreadFaults();
  9224. report << "switched_off=" << switched << "\n";
  9225. expect ("plugin_switched_off", switched >= 1 && first != nullptr && first->hasCrashed() && lynx::pluginCrashCount() == crashesBefore + switched);
  9226. expect ("only_once", lynx::switchOffPluginsOfThreadFaults() == 0);
  9227. const auto down = offline.downHostedPlugins();
  9228. expect ("slot_down", down.size() == 1 && down[0] == where);
  9229. float after = 0.0f;
  9230. render (offline, 1.0, &after);
  9231. report << "peak_after=" << after << "\n";
  9232. expect ("audio_after_fault", after > 0.01f);
  9233. offline.editSong ([] (lynx::Song& s) { s.channels[0].volume = 0.0f; }, false);
  9234. float others = 0.0f;
  9235. render (offline, 1.0, &others);
  9236. expect ("other_inserts_play", others > 0.01f);
  9237. offline.editSong ([] (lynx::Song& s) { s.channels[0].volume = 0.85f; }, false);
  9238. const auto running = offline.reloadHostedPlugins (down);
  9239. auto* again = dynamic_cast<lynx::PluginEffect*> (offline.getEffect (1, 0).get());
  9240. float reloaded = 0.0f;
  9241. render (offline, 1.0, &reloaded);
  9242. expect ("reloaded_plays", running == 1 && again != nullptr && again != first && ! again->hasCrashed() && reloaded > 0.01f);
  9243. }
  9244. else
  9245. {
  9246. // a preset that crashes the plugin (the preset menu's load), saved first from the running plugin
  9247. auto& instance = first->getInstance();
  9248. const auto preset = tmp.getChildFile ("crash.lynxpreset");
  9249. juce::String error;
  9250. expect ("preset_saved", lynx::pluginpresetui::save (instance, preset, "crash", error) && preset.existsAsFile());
  9251. setEnv ("LYNX_TEST_CRASH", "state");
  9252. const auto loaded = lynx::pluginpresetui::load (instance, preset, error);
  9253. setEnv ("LYNX_TEST_CRASH", "");
  9254. report << "preset_error=" << error << "\n";
  9255. expect ("preset_crash_caught", ! loaded && lynx::pluginCrashCount() == crashesBefore + 1 && first->hasCrashed());
  9256. expect ("preset_plugin_down", offline.hostedPluginDown (where) && lynx::pluginInstanceDown (instance));
  9257. expect ("not_called_again", ! lynx::callPluginFromUi (instance, "test", [] {}) && lynx::pluginCrashCount() == crashesBefore + 1);
  9258. float after = 0.0f;
  9259. render (offline, 1.0, &after);
  9260. expect ("audio_after_preset_crash", after > 0.01f);
  9261. // Reload; then its editor crashes as it is made (PluginWindows::open): no window, the plugin is down
  9262. setEnv ("LYNX_TEST_CRASH", "editor-create");
  9263. const auto running = offline.reloadHostedPlugins (offline.downHostedPlugins());
  9264. auto held = offline.getEffect (1, 0);
  9265. auto* again = dynamic_cast<lynx::PluginEffect*> (held.get());
  9266. expect ("reloaded", running == 1 && again != nullptr && again != first && ! again->hasCrashed());
  9267. if (again != nullptr)
  9268. {
  9269. lynx::PluginWindows::open (held, again->getInstance(), "crash test", {});
  9270. expect ("editor_crash_caught", lynx::pluginCrashCount() == crashesBefore + 2 && again->hasCrashed());
  9271. expect ("no_window", ! lynx::PluginWindows::isOpen (again->getInstance()));
  9272. float editorAfter = 0.0f;
  9273. render (offline, 1.0, &editorAfter);
  9274. expect ("audio_after_editor_crash", editorAfter > 0.01f);
  9275. }
  9276. setEnv ("LYNX_TEST_CRASH", "");
  9277. }
  9278. }
  9279. setEnv ("LYNX_TEST_CRASH", "");
  9280. // LYNX's own faults (also on its own threads) stay crashes (child processes; the selftest runs the same)
  9281. const auto own = faultReportSelfTest();
  9282. report << "own_faults=" << own << "\n";
  9283. ok = ok && ! own.startsWith ("ERROR");
  9284. for (const auto& c : lynx::pluginCrashes())
  9285. report << " crashed: " << c.plugin << " (" << lynx::crashguard::describe (c.code) << ")\n";
  9286. tmp.deleteRecursively();
  9287. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  9288. juce::File (reportPath).replaceWithText (report);
  9289. setApplicationReturnValue (ok ? 0 : 1);
  9290. quit();
  9291. }
  9292. // LYNX --crashguardtest plugin report.txt [process|memcpy] (round 190dt): see the dispatch in initialise().
  9293. void runCrashGuardTest (const juce::String& pluginPath, const juce::String& reportPath, const juce::String& mode)
  9294. {
  9295. if (mode == "thread" || mode == "ui")
  9296. {
  9297. runCrashGuardThreadOrUiTest (pluginPath, reportPath, mode);
  9298. return;
  9299. }
  9300. juce::String report;
  9301. bool ok = true;
  9302. const auto expect = [&] (const char* name, bool value) {
  9303. report << name << "=" << (value ? 1 : 0) << "\n";
  9304. ok = ok && value;
  9305. };
  9306. const auto setEnv = [] (const char* name, const char* value) {
  9307. #if JUCE_WINDOWS
  9308. _putenv_s (name, value);
  9309. #else
  9310. setenv (name, value, 1);
  9311. #endif
  9312. };
  9313. // renders without the plugin warm-up (its silent blocks would count towards the crash)
  9314. const auto render = [] (lynx::AudioEngine& engine, double seconds, const std::function<void (const float*, const float*, int)>& capture) {
  9315. lynx::AudioEngine::RenderOptions o;
  9316. o.seconds = seconds;
  9317. o.sampleRate = 48000.0;
  9318. o.pluginWarmUp = false;
  9319. o.capture = capture;
  9320. return engine.renderOffline (o);
  9321. };
  9322. const auto peakOf = [] (float& peak) {
  9323. return [&peak] (const float* l, const float* r, int n) {
  9324. for (int k = 0; k < n; ++k)
  9325. peak = std::max (peak, std::max (std::abs (l[k]), std::abs (r[k])));
  9326. };
  9327. };
  9328. report << "guard=" << (lynx::crashguard::pluginFaultsCaught() ? "on" : "off") << "\nmode=" << mode << "\n";
  9329. setEnv ("LYNX_TEST_CRASH", mode == "memcpy" ? "memcpy" : "process");
  9330. setEnv ("LYNX_TEST_CRASH_AFTER", "40");
  9331. const auto tmp = juce::File::getSpecialLocation (juce::File::tempDirectory)
  9332. .getChildFile ("lynx-crashguardtest-" + juce::String::toHexString (juce::Random::getSystemRandom().nextInt64()));
  9333. tmp.createDirectory();
  9334. std::optional<lynx::Song> saved;
  9335. std::string savedState;
  9336. {
  9337. lynx::AudioEngine offline (false);
  9338. auto& host = offline.getPluginHost();
  9339. host.addPluginFile (juce::File (pluginPath));
  9340. juce::PluginDescription effect;
  9341. bool found = false;
  9342. for (const auto& type : host.getKnownPlugins().getTypes())
  9343. if (! found && ! type.isInstrument && juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginPath).getFileName())
  9344. {
  9345. effect = type;
  9346. found = true;
  9347. }
  9348. expect ("plugin_found", found);
  9349. // the plugin on insert 1 (the kick's); the clap and the hat play on inserts 2 and 3
  9350. auto song = lynx::Song::makeDefault();
  9351. lynx::EffectSlot slot;
  9352. slot.kind = lynx::EffectKind::plugin;
  9353. slot.plugin.id = effect.createIdentifierString().toStdString();
  9354. slot.plugin.name = effect.name.toStdString();
  9355. song.mixer[1].effects.push_back (slot);
  9356. offline.setSong (song);
  9357. const lynx::AudioEngine::HostedSlot where { -1, 1, 0 };
  9358. // the rack is published at the engine's rate and an offline render runs at its own (48 kHz) without publishing:
  9359. // one edit after a first render puts the rack (and the plugin) at the render's rate, so later edits keep it
  9360. render (offline, 0.05, {}); // (a few blocks, far from the 40th)
  9361. offline.editSong ([] (lynx::Song& s) { s.channels[0].volume = 0.85f; }, false);
  9362. render (offline, 0.05, {});
  9363. auto* first = dynamic_cast<lynx::PluginEffect*> (offline.getEffect (1, 0).get());
  9364. expect ("plugin_loaded", first != nullptr);
  9365. offline.capturePluginStates();
  9366. savedState = offline.getSong().mixer[1].effects[0].plugin.state;
  9367. expect ("state_captured", ! savedState.empty());
  9368. // the crash: 3 s, the plugin faults in its 40th block
  9369. const auto crashesBefore = lynx::pluginCrashCount();
  9370. juce::int64 position = 0, crashAt = -1;
  9371. float peakAfter = 0.0f;
  9372. const auto afterPeak = peakOf (peakAfter);
  9373. const auto peak = render (offline, 3.0, [&] (const float* l, const float* r, int n) {
  9374. if (crashAt < 0 && lynx::pluginCrashCount() != crashesBefore)
  9375. crashAt = position;
  9376. else if (crashAt >= 0)
  9377. afterPeak (l, r, n);
  9378. position += n;
  9379. });
  9380. report << "peak=" << peak << "\ncrash_at_sample=" << crashAt << "\npeak_after_crash=" << peakAfter << "\n";
  9381. const auto crashes = lynx::pluginCrashes();
  9382. expect ("crash_caught", lynx::pluginCrashCount() == crashesBefore + 1 && ! crashes.empty() && ! crashes.back().onLoad);
  9383. if (! crashes.empty())
  9384. report << "crash=" << crashes.back().plugin << " (" << lynx::crashguard::describe (crashes.back().code) << ")\n";
  9385. expect ("slot_marked_crashed", first != nullptr && offline.getEffect (1, 0).get() == first && first->hasCrashed());
  9386. const auto down = offline.downHostedPlugins();
  9387. expect ("slot_down", down.size() == 1 && down[0] == where);
  9388. expect ("audio_after_crash", crashAt >= 0 && peakAfter > 0.01f);
  9389. // the other inserts: with the kick (through the crashed slot) silent, the clap and the hat still play
  9390. offline.editSong ([] (lynx::Song& s) { s.channels[0].volume = 0.0f; }, false);
  9391. float othersPeak = 0.0f;
  9392. render (offline, 1.0, peakOf (othersPeak));
  9393. report << "other_inserts_peak=" << othersPeak << "\n";
  9394. expect ("other_inserts_play", othersPeak > 0.01f);
  9395. expect ("nothing_reloads_by_itself", offline.hostedPluginDown (where) && offline.getEffect (1, 0).get() == first);
  9396. offline.editSong ([] (lynx::Song& s) { s.channels[0].volume = 0.85f; }, false);
  9397. // the project saves with the settings the plugin had before it crashed, and opens again
  9398. offline.capturePluginStates();
  9399. expect ("state_kept", offline.getSong().mixer[1].effects[0].plugin.state == savedState);
  9400. const auto file = tmp.getChildFile ("crashed.lynx");
  9401. juce::String error;
  9402. expect ("project_saved", lynx::ProjectFile::save (offline.getSong(), file, error) && file.existsAsFile());
  9403. saved = lynx::ProjectFile::load (file, error);
  9404. expect ("project_reopens", saved.has_value() && saved->mixer.size() > 1 && saved->mixer[1].effects.size() == 1
  9405. && saved->mixer[1].effects[0].plugin.state == savedState);
  9406. // Reload (the prompt's button, round 190ao): a new instance; the module's block count is past 40 now
  9407. const auto running = offline.reloadHostedPlugins (down);
  9408. auto* again = dynamic_cast<lynx::PluginEffect*> (offline.getEffect (1, 0).get());
  9409. expect ("reloaded", running == 1 && again != nullptr && again != first && ! again->hasCrashed());
  9410. float reloadedPeak = 0.0f;
  9411. render (offline, 1.0, peakOf (reloadedPeak));
  9412. report << "reloaded_peak=" << reloadedPeak << "\n";
  9413. expect ("reloaded_plays", reloadedPeak > 0.01f && lynx::pluginCrashCount() == crashesBefore + 1 && again != nullptr && ! again->hasCrashed());
  9414. }
  9415. // the saved project opens again with the plugin crashing on its saved settings: left out, the rest plays, the
  9416. // settings stay in the project
  9417. setEnv ("LYNX_TEST_CRASH", "state");
  9418. if (saved.has_value())
  9419. {
  9420. lynx::AudioEngine reopened (false);
  9421. reopened.getPluginHost().addPluginFile (juce::File (pluginPath));
  9422. const auto before = lynx::pluginCrashCount();
  9423. reopened.setSong (*saved);
  9424. float reopenedPeak = 0.0f;
  9425. render (reopened, 1.0, peakOf (reopenedPeak));
  9426. const auto crashes = lynx::pluginCrashes();
  9427. report << "reopened_peak=" << reopenedPeak << "\n";
  9428. if (reopened.getPluginHost().getLoadFailures().size() > 0)
  9429. report << "load_failures=" << reopened.getPluginHost().getLoadFailures().joinIntoString (" | ") << "\n";
  9430. expect ("state_crash_caught", lynx::pluginCrashCount() == before + 1 && ! crashes.empty() && crashes.back().onLoad);
  9431. expect ("state_crash_left_out", dynamic_cast<lynx::PluginEffect*> (reopened.getEffect (1, 0).get()) == nullptr);
  9432. expect ("state_crash_project_plays", reopenedPeak > 0.01f);
  9433. reopened.capturePluginStates();
  9434. expect ("state_crash_settings_kept", reopened.getSong().mixer[1].effects.size() == 1
  9435. && reopened.getSong().mixer[1].effects[0].plugin.state == savedState);
  9436. }
  9437. setEnv ("LYNX_TEST_CRASH", "");
  9438. // LYNX's own faults inside a guarded call stay crashes (child processes; the selftest runs the same)
  9439. const auto own = faultReportSelfTest();
  9440. report << "own_faults=" << own << "\n";
  9441. ok = ok && ! own.startsWith ("ERROR");
  9442. report << "plugin_crashes=" << lynx::pluginCrashCount() << "\n";
  9443. for (const auto& c : lynx::pluginCrashes())
  9444. report << " crashed: " << c.plugin << " (" << lynx::crashguard::describe (c.code) << (c.onLoad ? ", loading its state" : "") << ")\n";
  9445. tmp.deleteRecursively();
  9446. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  9447. juce::File (reportPath).replaceWithText (report);
  9448. setApplicationReturnValue (ok ? 0 : 1);
  9449. quit();
  9450. }
  9451. // LYNX.exe --mpetest "LYNX Test MPE.clap" report.txt (tools/testplugin/lynx_test_mpe.c, issue #108): a hosted CLAP
  9452. // instrument with the wrapper's MPE switch on gets each note on its own member channel, its fine pitch / Mod X /
  9453. // Mod Y as tuning / brightness / pressure note expressions before the note on, and a sounding note's expression
  9454. // on that note's channel alone. The plugin writes down what it received; no window, no audio device.
  9455. // Round 190hy: see --mpeplaytest190hy. Note A (C4, 1 s): its pitch curve holds 0 for 0.5 s, rises an octave over
  9456. // 0.25 s and holds it; then note B (G4, 0.5 s), no curve: it must not inherit A's bend. The frequencies come from the
  9457. // rendered audio's zero crossings (a silent logging plugin: its log shows the expressions instead).
  9458. void runMpePlayTest190hy (const juce::String& pluginPath, const juce::String& reportPath)
  9459. {
  9460. const auto log = juce::File (reportPath).getSiblingFile (juce::File (reportPath).getFileNameWithoutExtension() + "-plugin.txt");
  9461. log.deleteFile();
  9462. #if JUCE_WINDOWS
  9463. _putenv_s ("LYNX_TEST_MPE_REPORT", log.getFullPathName().toRawUTF8());
  9464. #else
  9465. setenv ("LYNX_TEST_MPE_REPORT", log.getFullPathName().toRawUTF8(), 1);
  9466. #endif
  9467. juce::String report;
  9468. auto ok = false;
  9469. const auto wavFile = juce::File (reportPath).withFileExtension ("wav");
  9470. constexpr double rate = 44100.0;
  9471. {
  9472. lynx::AudioEngine offline (false);
  9473. auto& host = offline.getPluginHost();
  9474. report << "plugins_in_file=" << host.addPluginFile (juce::File (pluginPath)) << "\n";
  9475. const auto wanted = juce::File (pluginPath).hasFileExtension ("clap") ? "CLAP" : "VST3";
  9476. std::optional<juce::PluginDescription> type;
  9477. for (const auto& t : host.getKnownPlugins().getTypes())
  9478. if (t.pluginFormatName == wanted && t.isInstrument && ! type)
  9479. type = t;
  9480. report << "format=" << wanted << " found=" << (type ? type->name : juce::String ("none")) << "\n";
  9481. if (type)
  9482. {
  9483. lynx::Song s;
  9484. s.mixer = lynx::Song::defaultMixer (2);
  9485. s.bpm = 120.0;
  9486. lynx::ChannelDef c;
  9487. c.name = type->name.toStdString();
  9488. c.instrument = lynx::InstrumentKind::plugin;
  9489. c.plugin.id = type->createIdentifierString().toStdString();
  9490. c.plugin.name = type->name.toStdString();
  9491. c.plugin.mpe = true;
  9492. c.mixerTrack = 1;
  9493. s.channels.push_back (c);
  9494. s.patterns.emplace_back();
  9495. auto& p = s.patterns[0];
  9496. lynx::Note a;
  9497. a.channel = 0;
  9498. a.key = 60;
  9499. a.length = 2 * lynx::ppq;
  9500. a.velocity = 0.8f;
  9501. lynx::NoteCurves curves;
  9502. curves.lane (lynx::NoteCurveLane::pitch) = { { 0.0f, 0.0f }, { (float) lynx::ppq, 0.0f }, { 1.5f * (float) lynx::ppq, 1200.0f },
  9503. { 2.0f * (float) lynx::ppq, 1200.0f } };
  9504. a.curves = curves;
  9505. auto b = a;
  9506. b.key = 67;
  9507. b.start = 2 * lynx::ppq;
  9508. b.length = lynx::ppq;
  9509. b.curves.clear();
  9510. p.notes = { a, b };
  9511. p.lengthTicks = 16 * lynx::ppq; // (one pass: the notes play once in the 1.2 s rendered)
  9512. offline.setSong (std::move (s));
  9513. wavFile.deleteFile();
  9514. juce::WavAudioFormat wav;
  9515. std::unique_ptr<juce::AudioFormatWriter> writer (wav.createWriterFor (wavFile.createOutputStream().release(), rate, 2, 24, {}, 0));
  9516. const auto peak = writer != nullptr ? offline.renderOffline (1.6, rate, writer.get()) : 0.0f;
  9517. writer.reset();
  9518. report << "peak=" << peak << "\n";
  9519. ok = writer == nullptr && wavFile.existsAsFile();
  9520. }
  9521. } // (the plugin writes its log, if any, as it is destroyed)
  9522. // the frequency of [from, to) seconds of the left channel from its rising zero crossings
  9523. juce::AudioBuffer<float> audio;
  9524. {
  9525. juce::AudioFormatManager formats;
  9526. formats.registerBasicFormats();
  9527. if (std::unique_ptr<juce::AudioFormatReader> reader (formats.createReaderFor (wavFile)); reader != nullptr)
  9528. {
  9529. audio.setSize (1, (int) reader->lengthInSamples);
  9530. reader->read (&audio, 0, (int) reader->lengthInSamples, 0, true, false);
  9531. }
  9532. }
  9533. const auto frequency = [&audio] (double from, double to) {
  9534. const auto* x = audio.getReadPointer (0);
  9535. const auto n = audio.getNumSamples();
  9536. long first = -1, last = -1;
  9537. auto crossings = 0;
  9538. for (auto i = juce::jmax (1, (int) (from * rate)); i < juce::jmin (n, (int) (to * rate)); ++i)
  9539. if (x[i - 1] <= 0.0f && x[i] > 0.0f)
  9540. {
  9541. if (first < 0)
  9542. first = i;
  9543. else
  9544. ++crossings, last = i;
  9545. }
  9546. return crossings > 0 ? crossings * rate / (double) (last - first) : 0.0;
  9547. };
  9548. if (audio.getNumSamples() > 0 && audio.getMagnitude (0, 0, audio.getNumSamples()) > 0.001f)
  9549. {
  9550. const auto before = frequency (0.1, 0.45), during = frequency (0.55, 0.7), after = frequency (0.8, 0.98), next = frequency (1.1, 1.45);
  9551. report << "a_before_hz=" << before << " a_rising_hz=" << during << " a_after_hz=" << after << " b_hz=" << next << "\n";
  9552. report << "a_after_over_before=" << (before > 0.0 ? after / before : 0.0) << " (an octave: 2)\n";
  9553. report << "b_over_a_before=" << (before > 0.0 ? next / before : 0.0) << " (a fifth: 1.498)\n";
  9554. }
  9555. else
  9556. report << "audio=silent\n";
  9557. if (log.existsAsFile())
  9558. report << "--- plugin log ---\n" << log.loadFileAsString();
  9559. report << "result=" << (ok ? "RENDERED" : "FAILED") << "\n";
  9560. juce::File (reportPath).replaceWithText (report);
  9561. setApplicationReturnValue (ok ? 0 : 1);
  9562. quit();
  9563. }
  9564. void runMpeTest (const juce::String& pluginPath, const juce::String& reportPath)
  9565. {
  9566. const auto log = juce::File (reportPath).getSiblingFile (juce::File (reportPath).getFileNameWithoutExtension() + "-plugin.txt");
  9567. log.deleteFile();
  9568. #if JUCE_WINDOWS
  9569. _putenv_s ("LYNX_TEST_MPE_REPORT", log.getFullPathName().toRawUTF8());
  9570. #else
  9571. setenv ("LYNX_TEST_MPE_REPORT", log.getFullPathName().toRawUTF8(), 1);
  9572. #endif
  9573. juce::String report;
  9574. auto failures = 0;
  9575. {
  9576. lynx::AudioEngine engine (false);
  9577. auto& host = engine.getPluginHost();
  9578. report << "plugins_in_file=" << host.addPluginFile (juce::File (pluginPath)) << "\n";
  9579. std::optional<juce::PluginDescription> clap;
  9580. for (const auto& type : host.getKnownPlugins().getTypes())
  9581. if (type.pluginFormatName == "CLAP" && juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginPath).getFileName())
  9582. clap = type;
  9583. lynx::PluginRef ref;
  9584. if (clap)
  9585. {
  9586. ref.id = clap->createIdentifierString().toStdString();
  9587. ref.name = clap->name.toStdString();
  9588. }
  9589. ref.mpe = true;
  9590. juce::String error;
  9591. auto instrument = clap ? host.makeInstrument (ref, 48000.0, &error) : nullptr;
  9592. report << "instrument_loaded=" << (instrument != nullptr ? "yes" : "no") << (error.isNotEmpty() ? " (" + error + ")" : juce::String()) << "\n";
  9593. if (instrument != nullptr)
  9594. {
  9595. std::vector<float> l (256), r (256);
  9596. auto block = [&] { instrument->render (l.data(), r.data(), 256, 1.0f, 1.0f); };
  9597. block(); // (the zone's setup)
  9598. instrument->setNextNoteFinePitch (30.0f); // +30 cents
  9599. instrument->setNextNoteModulation (0.75f, 1.0f); // timbre 0.75, full pressure
  9600. instrument->noteOn (60, 0.8f);
  9601. instrument->noteOn (64, 0.5f); // a second note: its own channel, centre values
  9602. block();
  9603. instrument->noteExpression (60, (int) lynx::vfx::Prop::pitch, 200.0f, 0.0f);
  9604. instrument->noteExpression (64, (int) lynx::vfx::Prop::modX, 0.25f, 0.0f);
  9605. instrument->noteExpression (60, (int) lynx::vfx::Prop::modY, 0.75f, 0.0f);
  9606. block();
  9607. instrument->noteOff (60);
  9608. instrument->noteOff (64);
  9609. block();
  9610. }
  9611. else
  9612. ++failures;
  9613. } // (the plugin writes its log as it is destroyed)
  9614. struct Line
  9615. {
  9616. juce::String kind;
  9617. int a = 0, b = 0, c = 0, d = 0;
  9618. };
  9619. std::vector<Line> lines;
  9620. for (const auto& text : juce::StringArray::fromLines (log.loadFileAsString()))
  9621. {
  9622. const auto t = juce::StringArray::fromTokens (text, " ", "");
  9623. if (t.size() >= 3)
  9624. 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 });
  9625. }
  9626. report << "plugin_events=" << (int) lines.size() << "\n";
  9627. // the first line at or after `from` that matches (−1 = none); `value` within `tolerance` (thousandths)
  9628. auto find = [&lines] (const juce::String& kind, int a, int b, int value, int tolerance, int from = 0) {
  9629. for (auto i = (std::size_t) from; i < lines.size(); ++i)
  9630. {
  9631. const auto& x = lines[i];
  9632. const auto v = kind == "expr" ? x.d : x.c;
  9633. if (x.kind == kind && x.a == a && x.b == b && std::abs (v - value) <= tolerance)
  9634. return (int) i;
  9635. }
  9636. return -1;
  9637. };
  9638. auto check = [&] (const char* what, bool ok) {
  9639. report << what << "=" << (ok ? "ok" : "FAILED") << "\n";
  9640. failures += ok ? 0 : 1;
  9641. };
  9642. // (CLAP expression ids: 2 tuning in semitones, 5 brightness, 6 pressure; channels 0-based: the first member = 1)
  9643. const auto on60 = find ("on", 1, 60, 800, 5), on64 = find ("on", 2, 64, 500, 5);
  9644. check ("zone_setup_sent", find ("midi", 176, 6, 15, 0) >= 0 && find ("midi", 177, 6, 48, 0) >= 0);
  9645. check ("notes_on_their_own_channels", on60 >= 0 && on64 > on60);
  9646. const auto tune = find ("expr", 2, 1, 300, 3), bright = find ("expr", 5, 1, 756, 4), press = find ("expr", 6, 1, 1000, 1);
  9647. check ("expression_before_the_note_on", tune >= 0 && bright >= 0 && press >= 0 && tune < on60 && bright < on60 && press < on60);
  9648. 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);
  9649. const auto later = std::max (on60, on64) + 1;
  9650. check ("sounding_note_expression", later > 0 && find ("expr", 2, 1, 2000, 3, later) >= 0 && find ("expr", 5, 2, 252, 4, later) >= 0
  9651. && find ("expr", 6, 1, 504, 4, later) >= 0);
  9652. check ("other_note_untouched", later > 0 && find ("expr", 2, 2, 2000, 3, later) < 0 && find ("expr", 6, 2, 504, 4, later) < 0);
  9653. check ("notes_off_on_their_channels", find ("off", 1, 60, 0, 100000) >= 0 && find ("off", 2, 64, 0, 100000) >= 0);
  9654. auto expressionAsMidi = false; // (a CLAP-dialect plugin gets no raw bend / pressure / CC 74 on a member channel)
  9655. for (const auto& x : lines)
  9656. if (x.kind == "midi" && (x.a & 0x0f) != 0 && ((x.a & 0xf0) == 0xe0 || (x.a & 0xf0) == 0xd0 || ((x.a & 0xf0) == 0xb0 && x.b == 74)))
  9657. expressionAsMidi = true;
  9658. check ("no_duplicate_midi_expression", ! expressionAsMidi);
  9659. report << "--- plugin log ---\n" << log.loadFileAsString() << "result=" << (failures == 0 ? "OK" : "FAILED") << "\n";
  9660. juce::File (reportPath).replaceWithText (report);
  9661. setApplicationReturnValue (failures == 0 ? 0 : 1);
  9662. quit();
  9663. }
  9664. // LYNX.exe --claprestarttest "LYNX Test Restart.clap" report.txt (tools/testplugin/lynx_test_restart.c, PR #29): a
  9665. // CLAP effect on the Master that asks for a restart every 8 blocks while an export renders on a thread of its own
  9666. // (the message thread is free to run the restarts, as with the Export window). The plugin aborts the process when
  9667. // start / stop_processing run off the audio thread or activate / deactivate off the main thread (issue #46, as u-he
  9668. // Presswerk does; an export at 44.1 kHz and prepare calls from the export's thread check the latter) and counts deactivations that
  9669. // landed inside its process() call (must be none), the restarts must happen, and the delay compensation must end on
  9670. // the latency the plugin reports after its last restart.
  9671. void runClapRestartTest (const juce::String& pluginPath, const juce::String& reportPath)
  9672. {
  9673. struct Run
  9674. {
  9675. std::unique_ptr<lynx::AudioEngine> engine;
  9676. juce::String report;
  9677. int slot = -1;
  9678. std::thread render;
  9679. std::atomic<bool> done { false };
  9680. double renderSeconds = 0.0;
  9681. };
  9682. auto run = std::make_shared<Run>();
  9683. const auto counters = juce::File (reportPath).getSiblingFile (juce::File (reportPath).getFileNameWithoutExtension() + "-plugin.txt");
  9684. counters.deleteFile();
  9685. #if JUCE_WINDOWS
  9686. _putenv_s ("LYNX_TEST_RESTART_REPORT", counters.getFullPathName().toRawUTF8());
  9687. #else
  9688. setenv ("LYNX_TEST_RESTART_REPORT", counters.getFullPathName().toRawUTF8(), 1);
  9689. #endif
  9690. const auto fail = [this, reportPath] (juce::String report) {
  9691. report << "result=FAILED\n";
  9692. juce::File (reportPath).replaceWithText (report);
  9693. setApplicationReturnValue (1);
  9694. quit();
  9695. };
  9696. run->engine = std::make_unique<lynx::AudioEngine> (false);
  9697. auto& host = run->engine->getPluginHost();
  9698. run->report << "plugins_in_file=" << host.addPluginFile (juce::File (pluginPath)) << "\n";
  9699. std::optional<juce::PluginDescription> clap;
  9700. for (const auto& type : host.getKnownPlugins().getTypes())
  9701. if (type.pluginFormatName == "CLAP" && juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginPath).getFileName())
  9702. clap = type;
  9703. if (! clap)
  9704. {
  9705. fail (run->report + "no CLAP plugin in the file\n");
  9706. return;
  9707. }
  9708. auto song = lynx::Song::makeDefault();
  9709. lynx::EffectSlot slot;
  9710. slot.kind = lynx::EffectKind::plugin;
  9711. slot.plugin.id = clap->createIdentifierString().toStdString();
  9712. slot.plugin.name = clap->name.toStdString();
  9713. slot.smartDisable = false; // (processed every block, as with music playing: the export itself is silent)
  9714. song.mixer[0].effects = { slot }; // alone on the Master: the delay compensation is the plugin's latency
  9715. run->slot = (int) song.mixer[0].effects.size() - 1;
  9716. run->engine->setSong (song);
  9717. run->engine->renderOffline (0.1, 48000.0); // builds the rack (and the plugin) on the message thread
  9718. if (dynamic_cast<lynx::PluginEffect*> (run->engine->getEffect (0, run->slot).get()) == nullptr)
  9719. {
  9720. fail (run->report + "effect_loaded=no\n");
  9721. return;
  9722. }
  9723. auto effect = std::dynamic_pointer_cast<lynx::PluginEffect> (run->engine->getEffect (0, run->slot));
  9724. run->render = std::thread ([run, effect] () mutable {
  9725. const auto start = juce::Time::getMillisecondCounterHiRes();
  9726. run->engine->renderOffline (30.0, 48000.0);
  9727. run->renderSeconds = (juce::Time::getMillisecondCounterHiRes() - start) * 0.001;
  9728. // issue #46: an export at another rate / block size prepares the plugin from the export's thread; the
  9729. // plugin aborts unless activate / deactivate reach the main thread
  9730. auto& instance = effect->getInstance();
  9731. instance.prepareToPlay (44100.0, 1024);
  9732. instance.releaseResources();
  9733. instance.prepareToPlay (48000.0, 512);
  9734. run->engine->renderOffline (3.0, 44100.0); // (the engine rebuilds its rack at that rate)
  9735. // The engine has replaced this instance (made for 48 kHz) by then, so this is its last reference: it is
  9736. // deleted here, on the export's thread, and its deactivate / destroy go to the message thread, which this
  9737. // waits for. That has to happen before `done`: once the message thread sees it, it blocks in join() until
  9738. // this thread ends, and an instance deleted after that waited 10 s for it and then deactivated the plugin
  9739. // right here, off the main thread (the plugin aborts: about 1 run in 40 under load, round 190au).
  9740. effect.reset();
  9741. run->done = true;
  9742. });
  9743. // after the render: a second for the restarts still queued and the engine's timer (the new PDC plan)
  9744. auto finish = std::make_shared<std::function<void()>>();
  9745. *finish = [this, run, counters, reportPath, fail, finish] {
  9746. if (! run->done)
  9747. {
  9748. juce::Timer::callAfterDelay (50, *finish);
  9749. return;
  9750. }
  9751. run->render.join();
  9752. juce::Timer::callAfterDelay (1000, [this, run, counters, reportPath, fail] {
  9753. auto report = run->report;
  9754. int pluginLatency = -1;
  9755. if (const auto effect = run->engine->getEffect (0, run->slot)) // (not held past the engine's reset)
  9756. pluginLatency = effect->latencySamples();
  9757. const auto pdc = run->engine->getLatencySamples();
  9758. report << "render_seconds=" << juce::String (run->renderSeconds, 2) << "\n"
  9759. << "plugin_latency=" << pluginLatency << "\npdc_total=" << pdc << "\n"
  9760. << "plugin_crashes=" << lynx::pluginCrashCount() << "\n";
  9761. run->engine.reset(); // destroys the plugin: it writes its counters
  9762. // one line per plugin instance (the engine may have made more than one): none may have been
  9763. // deactivated inside process(), and the one that rendered must have restarted
  9764. int overlapped = 0, inactive = 0, requests = 0, activations = 0, lines = 0, wrongThread = 0, misordered = 0, unstopped = 0;
  9765. bool otherRate = false;
  9766. for (const auto& line : juce::StringArray::fromLines (counters.loadFileAsString()))
  9767. {
  9768. juce::StringPairArray values;
  9769. for (const auto& token : juce::StringArray::fromTokens (line, " ", ""))
  9770. if (token.contains ("="))
  9771. values.set (token.upToFirstOccurrenceOf ("=", false, false), token.fromFirstOccurrenceOf ("=", false, false));
  9772. if (values.size() == 0)
  9773. continue;
  9774. ++lines;
  9775. report << "instance: " << line << "\n";
  9776. overlapped += values["overlapped"].getIntValue();
  9777. inactive += values["inactive_blocks"].getIntValue();
  9778. // issue #46: activate / deactivate on the main thread, start / stop_processing on the audio thread
  9779. // (the plugin aborts the process otherwise, as u-he's do), in order, every start stopped
  9780. wrongThread += values["wrong_thread"].getIntValue();
  9781. misordered += values["misordered"].getIntValue();
  9782. unstopped += values["starts"].getIntValue() - values["stops"].getIntValue();
  9783. otherRate = otherRate || values["last_rate"].getIntValue() == 44100;
  9784. if (values["requests"].getIntValue() > requests)
  9785. {
  9786. requests = values["requests"].getIntValue();
  9787. activations = values["activations"].getIntValue();
  9788. }
  9789. }
  9790. report << "wrong_thread=" << wrongThread << "\nmisordered=" << misordered << "\nunstopped=" << unstopped
  9791. << "\nactivated_at_44100=" << (otherRate ? "yes" : "no") << "\n";
  9792. const auto ok = lines > 0 && requests > 0 && activations > requests / 2 && overlapped == 0 && inactive == 0
  9793. && wrongThread == 0 && misordered == 0 && unstopped == 0 && otherRate
  9794. && pluginLatency > 0 && pdc == pluginLatency && lynx::pluginCrashCount() == 0;
  9795. if (! ok)
  9796. {
  9797. fail (report);
  9798. return;
  9799. }
  9800. report << "result=OK\n";
  9801. juce::File (reportPath).replaceWithText (report);
  9802. setApplicationReturnValue (0);
  9803. quit();
  9804. });
  9805. };
  9806. juce::Timer::callAfterDelay (50, *finish);
  9807. }
  9808. // LYNX.exe --vst2test "LYNX Test Synth.dll" report.txt (tools/testplugin/lynx_test_vst2.c): LYNX's own VST2 host.
  9809. // Scans the DLL, imports it the way an .flp holds it (Fruity Wrapper VST2 state with a chunk, REA_rodada89 §2),
  9810. // renders with two saved gains (the level must follow the restored state) and checks the plugin saw the song tempo.
  9811. void runVst2Test (const juce::String& pluginPath, const juce::String& reportPath)
  9812. {
  9813. juce::String report;
  9814. bool ok = false;
  9815. {
  9816. lynx::AudioEngine offline (false);
  9817. auto& host = offline.getPluginHost();
  9818. report << "plugins_in_file=" << host.addPluginFile (juce::File (pluginPath)) << "\n";
  9819. std::optional<juce::PluginDescription> vst2;
  9820. for (const auto& type : host.getKnownPlugins().getTypes())
  9821. if (type.pluginFormatName == "VST")
  9822. vst2 = type;
  9823. auto render = [&] (float gain, float& tempoSeen, int& adopted) {
  9824. lynx::FlVst2State state;
  9825. state.flags = 8;
  9826. state.chunk = { 'L', 'X', 'V', '2', 0, 0, 0, 0 };
  9827. std::memcpy (state.chunk.data() + 4, &gain, 4);
  9828. auto song = lynx::Song::makeDefault();
  9829. song.bpm = 137.0;
  9830. auto& f = song.channels[4].plugin.foreign;
  9831. f.format = lynx::ForeignPlugin::Format::vst2;
  9832. f.vst2Id = (std::uint32_t) vst2->uniqueId;
  9833. f.name = "Some other name"; // found by the VST2 ID
  9834. f.state = lynx::writeFlVst2State (state);
  9835. song.channels[4].volume = 1.0f;
  9836. song.patterns[0].notes.clear();
  9837. song.patterns[0].notes.push_back ({ 0, 4 * lynx::ppq, 4, 69, 1.0f });
  9838. for (std::size_t c = 0; c < song.channels.size(); ++c)
  9839. if (c != 4)
  9840. song.channels[c].muted = true;
  9841. adopted = host.adoptFlPlugins (song);
  9842. offline.setSong (song);
  9843. const auto peak = offline.renderOffline (1.0, 48000.0);
  9844. offline.capturePluginStates();
  9845. juce::MemoryBlock saved;
  9846. saved.fromBase64Encoding (juce::String (offline.getSong().channels[4].plugin.state));
  9847. lynx::FlVst2State back;
  9848. tempoSeen = 0.0f;
  9849. if (lynx::parseFlVst2State (std::vector<std::uint8_t> ((const std::uint8_t*) saved.getData(), (const std::uint8_t*) saved.getData() + saved.getSize()), back)
  9850. && back.chunk.size() >= 12)
  9851. std::memcpy (&tempoSeen, back.chunk.data() + 8, 4);
  9852. return peak;
  9853. };
  9854. if (vst2)
  9855. {
  9856. report << "plugin=" << vst2->name << " id=" << vst2->uniqueId << " instrument=" << (int) vst2->isInstrument << "\n";
  9857. float tempoA = 0, tempoB = 0;
  9858. int adoptedA = 0, adoptedB = 0;
  9859. const auto quiet = render (0.1f, tempoA, adoptedA);
  9860. const auto loud = render (0.4f, tempoB, adoptedB);
  9861. report << "adopted=" << adoptedA << "," << adoptedB << " peak_gain_0.1=" << quiet << " peak_gain_0.4=" << loud
  9862. << " tempo_seen=" << tempoB * 1000.0f << "\n";
  9863. ok = adoptedA == 1 && adoptedB == 1 && quiet > 0.01f && std::abs (loud / quiet - 4.0f) < 0.2f
  9864. && std::abs (tempoB * 1000.0f - 137.0f) < 0.01f;
  9865. }
  9866. }
  9867. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  9868. juce::File (reportPath).replaceWithText (report);
  9869. setApplicationReturnValue (ok ? 0 : 1);
  9870. quit();
  9871. }
  9872. // LYNX --vst3noteidtest "LYNX Test Synth.vst3" report.txt (round 190fg, cmake/LynxPatchJuce.cmake fix 26): the VST3
  9873. // test synth (tools/testplugin/lynx_test_synth_vst3.cpp: voices kept by noteId, its log the ids it got) plays two
  9874. // 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).
  9875. // 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
  9876. // 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).
  9877. void runVst3NoteIdTest (const juce::String& pluginPath, const juce::String& reportPath)
  9878. {
  9879. juce::String report;
  9880. bool ok = false;
  9881. const auto logBase = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-noteid-" + juce::String (juce::Time::currentTimeMillis()));
  9882. // (read by each new instance)
  9883. #if JUCE_WINDOWS
  9884. _putenv_s ("LYNX_TEST_SYNTH_LOG", logBase.getFullPathName().toRawUTF8());
  9885. #else
  9886. setenv ("LYNX_TEST_SYNTH_LOG", logBase.getFullPathName().toRawUTF8(), 1);
  9887. #endif
  9888. struct E
  9889. {
  9890. bool on = false;
  9891. int key = 0, id = -1;
  9892. };
  9893. // (the lines each render added: a running instance keeps its log file open, so the files stay until the end)
  9894. std::map<juce::String, int> linesRead;
  9895. const auto readLog = [&logBase, &linesRead] {
  9896. std::vector<E> events;
  9897. for (const auto& f : logBase.getParentDirectory().findChildFiles (juce::File::findFiles, false, logBase.getFileName() + ".*"))
  9898. {
  9899. juce::StringArray lines;
  9900. f.readLines (lines);
  9901. auto& done = linesRead[f.getFullPathName()];
  9902. for (int i = done; i < lines.size(); ++i)
  9903. {
  9904. const auto p = juce::StringArray::fromTokens (lines[i], " ", {});
  9905. if (p.size() >= 5 && p[0].startsWith ("E"))
  9906. events.push_back ({ p[1] == "on", p[2].getIntValue(), p[4].getIntValue() });
  9907. }
  9908. done = lines.size() - (lines.isEmpty() || lines[lines.size() - 1].isNotEmpty() ? 0 : 1);
  9909. }
  9910. return events;
  9911. };
  9912. {
  9913. lynx::AudioEngine offline (false);
  9914. auto& host = offline.getPluginHost();
  9915. report << "plugins_in_file=" << host.addPluginFile (juce::File (pluginPath)) << "\n";
  9916. std::optional<juce::PluginDescription> vst3;
  9917. for (const auto& type : host.getKnownPlugins().getTypes())
  9918. if (type.pluginFormatName == "VST3" && type.isInstrument)
  9919. vst3 = type;
  9920. const auto render = [&] (bool tags) {
  9921. auto song = lynx::Song::makeDefault();
  9922. song.bpm = 120.0;
  9923. auto& c = song.channels[0];
  9924. c.instrument = lynx::InstrumentKind::plugin;
  9925. c.plugin.id = vst3->createIdentifierString().toStdString();
  9926. c.plugin.name = vst3->name.toStdString();
  9927. for (std::size_t k = 1; k < song.channels.size(); ++k)
  9928. song.channels[k].muted = true;
  9929. auto& notes = song.patterns[0].notes;
  9930. notes.clear();
  9931. const auto beat = (std::int64_t) lynx::ppq;
  9932. notes.push_back ({ 0, 4 * beat, 0, 60, 0.8f }); // A
  9933. notes.push_back ({ 2 * beat, 4 * beat, 0, 60, 0.8f }); // B
  9934. notes.push_back ({ 8 * beat, 6 * beat, 0, 64, 0.8f }); // C
  9935. notes.push_back ({ 10 * beat, 2 * beat, 0, 64, 0.8f }); // D (inside C)
  9936. song.patterns[0].sortNotes();
  9937. song.patterns[0].lengthTicks = 16 * beat;
  9938. offline.setSong (song);
  9939. offline.dispatchPendingMessages();
  9940. if (! tags)
  9941. juce::lynxNoteTagHook = nullptr; // (fix 14 alone: the oldest sounding id; the next instance sets it again)
  9942. offline.renderOffline (7.9, 48000.0); // (C ends at 7 s; the 8 s pattern does not loop yet)
  9943. return readLog();
  9944. };
  9945. const auto check = [&report] (const char* name, const std::vector<E>& events, bool expectOwn) {
  9946. // ons and offs of each key in the order the plugin got them
  9947. std::map<int, std::vector<int>> ons, offs;
  9948. for (const auto& e : events)
  9949. (e.on ? ons : offs)[e.key].push_back (e.id);
  9950. const auto& a = ons[60]; const auto& o60 = offs[60];
  9951. const auto& c = ons[64]; const auto& o64 = offs[64];
  9952. report << name << ": key 60 ons";
  9953. for (auto id : a) report << " " << id;
  9954. report << " offs";
  9955. for (auto id : o60) report << " " << id;
  9956. report << "; key 64 ons";
  9957. for (auto id : c) report << " " << id;
  9958. report << " offs";
  9959. for (auto id : o64) report << " " << id;
  9960. report << "\n";
  9961. if (a.size() != 2 || o60.size() != 2 || c.size() != 2 || o64.size() != 2 || a[0] < 0 || c[0] < 0)
  9962. return false;
  9963. const auto fifo = o60[0] == a[0] && o60[1] == a[1]; // A ends first: A's id either way
  9964. // LIFO: D (c[1]) ends first; its own id with the tags, C's (the oldest) without
  9965. const auto lifo = expectOwn ? (o64[0] == c[1] && o64[1] == c[0]) : (o64[0] == c[0] && o64[1] == c[1]);
  9966. return fifo && lifo;
  9967. };
  9968. if (vst3)
  9969. {
  9970. report << "plugin=" << vst3->name << "\n";
  9971. const auto withTags = render (true);
  9972. const auto okTags = check ("with_tags", withTags, true);
  9973. const auto withoutTags = render (false);
  9974. const auto okBefore = check ("fix14_only", withoutTags, false);
  9975. report << "own_ids=" << (okTags ? "yes" : "NO") << " fix14_only_oldest=" << (okBefore ? "yes" : "NO") << "\n";
  9976. ok = okTags && okBefore;
  9977. }
  9978. }
  9979. if (ok) // (a failure leaves the logs for a look: their path is in the report)
  9980. for (const auto& f : logBase.getParentDirectory().findChildFiles (juce::File::findFiles, false, logBase.getFileName() + ".*"))
  9981. f.deleteFile();
  9982. else
  9983. report << "synth_logs=" << logBase.getFullPathName() << ".*\n";
  9984. #if JUCE_WINDOWS
  9985. _putenv_s ("LYNX_TEST_SYNTH_LOG", "");
  9986. #else
  9987. unsetenv ("LYNX_TEST_SYNTH_LOG");
  9988. #endif
  9989. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  9990. juce::File (reportPath).replaceWithText (report);
  9991. setApplicationReturnValue (ok ? 0 : 1);
  9992. quit();
  9993. }
  9994. // Round 181c: a wrapper MIDI option changed on a running plugin must act like the same option on a new one. For each
  9995. // option: a control engine whose plugin is created with the option set (proves the test can see it), then an engine
  9996. // whose plugin is already running when the option changes through editSong, as the wrapper page does it. What the
  9997. // plugin received comes from the test plugin's own log. The running instance must also stay the same one.
  9998. void runWrapperMidiTest (const juce::String& pluginPath, const juce::String& reportPath)
  9999. {
  10000. juce::String report;
  10001. auto ok = true;
  10002. const juce::File logFile (juce::SystemStats::getEnvironmentVariable ("LYNX_TEST_VST2_MIDILOG", {}));
  10003. struct Event { juce::String instance; int status, data1, data2; };
  10004. auto take = [&] {
  10005. std::vector<Event> out;
  10006. juce::StringArray lines;
  10007. logFile.readLines (lines);
  10008. for (const auto& line : lines)
  10009. {
  10010. const auto p = juce::StringArray::fromTokens (line, " ", {});
  10011. if (p.size() == 4)
  10012. out.push_back ({ p[0], p[1].getIntValue(), p[2].getIntValue(), p[3].getIntValue() });
  10013. }
  10014. logFile.deleteFile();
  10015. return out;
  10016. };
  10017. auto count = [] (const std::vector<Event>& events, int status, int data1, int data2) {
  10018. int n = 0;
  10019. for (const auto& e : events)
  10020. n += (e.status & 0xF0) == status && (data1 < 0 || e.data1 == data1) && (data2 < 0 || e.data2 == data2) ? 1 : 0;
  10021. return n;
  10022. };
  10023. struct Option
  10024. {
  10025. const char* name;
  10026. std::function<void (lynx::PluginRef&)> before, change;
  10027. std::function<juce::String (const std::vector<Event>&)> seen;
  10028. };
  10029. const Option options[] = {
  10030. { "Send note release velocity off", {}, [] (lynx::PluginRef& r) { r.releaseVelocity = false; },
  10031. [&] (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)); } },
  10032. { "Send pitch bend range on", {}, [] (lynx::PluginRef& r) { r.sendBendRange = true; },
  10033. [&] (const std::vector<Event>& e) { return "rpn_range_12=" + juce::String (count (e, 0xB0, 6, 12)); } },
  10034. { "Pitch bend range 24", [] (lynx::PluginRef& r) { r.sendBendRange = true; }, [] (lynx::PluginRef& r) { r.bendRange = 24; },
  10035. [&] (const std::vector<Event>& e) { return "rpn_range_24=" + juce::String (count (e, 0xB0, 6, 24)); } },
  10036. { "Send MOD X as polyphonic aftertouch on", {}, [] (lynx::PluginRef& r) { r.modXAftertouch = true; },
  10037. [&] (const std::vector<Event>& e) { return "aftertouch=" + juce::String (count (e, 0xA0, 69, -1)); } },
  10038. { "Send All Notes Off when playback stops off", {}, [] (lynx::PluginRef& r) { r.allNotesOffOnStop = false; },
  10039. [&] (const std::vector<Event>& e) { return "cc123=" + juce::String (count (e, 0xB0, 123, -1)); } },
  10040. };
  10041. // each phase has its own engine: an engine keeps the running instance across setSong, so one engine would
  10042. // carry the control's plugin into the "before" phase
  10043. lynx::AudioEngine scanner (false);
  10044. auto& host = scanner.getPluginHost();
  10045. report << "plugins_in_file=" << host.addPluginFile (juce::File (pluginPath)) << "\n";
  10046. std::optional<juce::PluginDescription> vst2;
  10047. for (const auto& type : host.getKnownPlugins().getTypes())
  10048. if (type.pluginFormatName == "VST")
  10049. vst2 = type;
  10050. if (! vst2 || logFile.getFullPathName().isEmpty())
  10051. ok = false;
  10052. else
  10053. for (const auto& option : options)
  10054. {
  10055. auto makeSong = [&] (bool changed) {
  10056. auto song = lynx::Song::makeDefault();
  10057. auto& channel = song.channels[0];
  10058. channel.instrument = lynx::InstrumentKind::plugin;
  10059. channel.plugin = {};
  10060. channel.plugin.id = vst2->createIdentifierString().toStdString();
  10061. channel.plugin.name = vst2->name.toStdString();
  10062. if (option.before)
  10063. option.before (channel.plugin);
  10064. if (changed)
  10065. option.change (channel.plugin);
  10066. song.patterns[0].notes.clear();
  10067. lynx::Note note;
  10068. note.start = 0;
  10069. note.length = lynx::ppq;
  10070. note.channel = 0;
  10071. note.key = 69;
  10072. note.velocity = 1.0f;
  10073. note.release = 0.25f; // 32 of 127
  10074. note.modX = 0.75f;
  10075. song.patterns[0].notes.push_back (note);
  10076. for (std::size_t c = 1; c < song.channels.size(); ++c)
  10077. song.channels[c].muted = true;
  10078. return song;
  10079. };
  10080. // a block of the song, then a note held across "playback stopped", as the options act on either
  10081. auto play = [&] (lynx::AudioEngine& engine) {
  10082. logFile.deleteFile();
  10083. engine.renderOffline (1.0, 48000.0);
  10084. if (auto instrument = engine.getChannelInstrument (0))
  10085. {
  10086. instrument->noteOn (60, 1.0f);
  10087. instrument->transportStopped();
  10088. }
  10089. engine.renderOffline (0.1, 48000.0);
  10090. return take();
  10091. };
  10092. auto newEngine = [&] {
  10093. auto engine = std::make_unique<lynx::AudioEngine> (false);
  10094. engine->getPluginHost().addPluginFile (juce::File (pluginPath));
  10095. return engine;
  10096. };
  10097. std::vector<Event> control;
  10098. {
  10099. auto engine = newEngine();
  10100. engine->setSong (makeSong (true));
  10101. control = play (*engine);
  10102. }
  10103. auto engine = newEngine();
  10104. engine->setSong (makeSong (false));
  10105. const auto before = play (*engine);
  10106. const auto instrumentBefore = engine->getChannelInstrument (0).get();
  10107. engine->capturePluginStates(); // as the wrapper page does
  10108. engine->editSong ([&] (lynx::Song& song) { option.change (song.channels[0].plugin); });
  10109. const auto after = play (*engine);
  10110. const auto sameInstance = engine->getChannelInstrument (0).get() == instrumentBefore;
  10111. // the counts differ between phases (how many blocks the note spans, how many instances the phase made):
  10112. // what matters is whether each kind of event is there at all
  10113. auto shape = [] (const juce::String& seen) {
  10114. juce::String out;
  10115. for (const auto& token : juce::StringArray::fromTokens (seen, " ", {}))
  10116. out << token.upToFirstOccurrenceOf ("=", false, false) << (token.fromFirstOccurrenceOf ("=", false, false).getIntValue() > 0 ? "=yes " : "=no ");
  10117. return out;
  10118. };
  10119. auto instances = [] (const std::vector<Event>& events) {
  10120. std::set<juce::String> made;
  10121. for (const auto& e : events)
  10122. made.insert (e.instance);
  10123. return (int) made.size();
  10124. };
  10125. const auto a = option.seen (control) + " instances=" + juce::String (instances (control)),
  10126. b = option.seen (before) + " instances=" + juce::String (instances (before)),
  10127. c = option.seen (after) + " instances=" + juce::String (instances (after));
  10128. const auto visible = shape (option.seen (control)) != shape (option.seen (before));
  10129. const auto works = shape (option.seen (after)) == shape (option.seen (control));
  10130. report << option.name << ": control " << a << " | before " << b << " | after the change " << c << " | same_instance=" << (int) sameInstance
  10131. << " | test_sees_the_option=" << (int) visible << " | " << (! visible ? "NOT PROVEN" : works ? "acts on the plugin" : "DEAD until re-created") << "\n";
  10132. ok = ok && visible && works;
  10133. }
  10134. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  10135. juce::File (reportPath).replaceWithText (report);
  10136. setApplicationReturnValue (ok ? 0 : 1);
  10137. quit();
  10138. }
  10139. // LYNX.exe --wrappershot "LYNX Test Drums.dll" <folder> (round 188d): the wrapper's Processing tab drawn offscreen
  10140. // (no window, no focus) for the FL | LYNX review: wrap-default.png (a fresh plugin), wrap-automap.png (Auto map
  10141. // outputs, output 3 off: FL's shot b23), wrap-settings.png. Scale 1.5 (FL's shots are at 150 %).
  10142. void runWrapperShot (const juce::String& pluginPath, const juce::String& folderPath)
  10143. {
  10144. const juce::File folder (folderPath);
  10145. folder.createDirectory();
  10146. auto ok = false;
  10147. lynx::AudioEngine engine (false);
  10148. engine.getPluginHost().addPluginFile (juce::File (pluginPath));
  10149. std::optional<juce::PluginDescription> vst2;
  10150. for (const auto& type : engine.getPluginHost().getKnownPlugins().getTypes())
  10151. if (type.pluginFormatName == "VST" && juce::File (type.fileOrIdentifier) == juce::File (pluginPath))
  10152. vst2 = type; // (the profile may know other test plugins)
  10153. if (vst2 && ! vst2->isInstrument)
  10154. {
  10155. // an effect (round 188d): on insert 1, with insert 2 routed there as a sidechain (FL's k65 / k78 shots):
  10156. // wrap-fx-default.png, wrap-fx-automap.png (Auto map inputs and outputs)
  10157. auto song = lynx::Song::makeDefault();
  10158. if (song.mixer.size() < 4)
  10159. song.mixer.resize (4);
  10160. auto slot = lynx::makeEffectSlot (lynx::EffectKind::plugin);
  10161. slot.plugin.id = vst2->createIdentifierString().toStdString();
  10162. slot.plugin.name = vst2->name.toStdString();
  10163. song.mixer[1].effects = { slot };
  10164. lynx::mixerops::sidechainTo (song, 2, 1);
  10165. engine.setSong (song);
  10166. engine.renderOffline (0.05, 48000.0);
  10167. if (auto fx = std::dynamic_pointer_cast<lynx::PluginEffect> (engine.getEffect (1, 0)))
  10168. {
  10169. auto find = [] (lynx::Song& s) -> lynx::PluginRef* {
  10170. return s.mixer.size() < 2 || s.mixer[1].effects.empty() ? nullptr : &s.mixer[1].effects[0].plugin;
  10171. };
  10172. auto save = [&] (const char* name) {
  10173. const auto image = lynx::wrapperSettingsSnapshot (engine, find, fx->getInstance(), false, 1, 1.5f, 1, 0);
  10174. juce::FileOutputStream out (folder.getChildFile (name));
  10175. out.setPosition (0);
  10176. out.truncate();
  10177. return out.openedOk() && juce::PNGImageFormat().writeImageToStream (image, out);
  10178. };
  10179. ok = save ("wrap-fx-default.png");
  10180. engine.editSong ([] (lynx::Song& s) {
  10181. lynx::autoMapOutputs (s.mixer[1].effects[0].plugin.inputs, 2);
  10182. lynx::autoMapOutputs (s.mixer[1].effects[0].plugin.outputs, 2);
  10183. s.mixer[1].effects[0].sidechain = lynx::mixerops::sidechainIndexSource (s, 1, 1);
  10184. });
  10185. ok = ok && save ("wrap-fx-automap.png") && engine.getSong().mixer[1].effects[0].sidechain == 2;
  10186. }
  10187. }
  10188. else if (vst2)
  10189. {
  10190. auto song = lynx::Song::makeDefault();
  10191. auto& channel = song.channels[0];
  10192. channel.instrument = lynx::InstrumentKind::plugin;
  10193. channel.plugin = {};
  10194. channel.plugin.id = vst2->createIdentifierString().toStdString();
  10195. channel.plugin.name = vst2->name.toStdString();
  10196. channel.mixerTrack = 5;
  10197. engine.setSong (song);
  10198. engine.renderOffline (0.05, 48000.0); // (the plugin is hosted by then)
  10199. if (auto instrument = std::dynamic_pointer_cast<lynx::PluginInstrument> (engine.getChannelInstrument (0)))
  10200. {
  10201. auto find = [] (lynx::Song& s) -> lynx::PluginRef* { return s.channels.empty() ? nullptr : &s.channels[0].plugin; };
  10202. auto save = [&] (const char* name, int tab) {
  10203. const auto image = lynx::wrapperSettingsSnapshot (engine, find, instrument->getInstance(), true, tab, 1.5f);
  10204. juce::FileOutputStream out (folder.getChildFile (name));
  10205. out.setPosition (0);
  10206. out.truncate();
  10207. return out.openedOk() && juce::PNGImageFormat().writeImageToStream (image, out);
  10208. };
  10209. ok = save ("wrap-default.png", 1) && save ("wrap-settings.png", 0);
  10210. engine.editSong ([] (lynx::Song& s) {
  10211. lynx::autoMapOutputs (s.channels[0].plugin.outputs, 8);
  10212. s.channels[0].plugin.outputs.resize (8);
  10213. s.channels[0].plugin.outputs[2].active = 0;
  10214. s.channels[0].plugin.processInactive = false; // (as an LED click does, FL's b23)
  10215. });
  10216. ok = ok && save ("wrap-automap.png", 1);
  10217. }
  10218. }
  10219. setApplicationReturnValue (ok ? 0 : 1);
  10220. quit();
  10221. }
  10222. // LYNX.exe --multiouttest "LYNX Test Drums.dll" report.txt (round 188d, issue #114): a multi-output VST2
  10223. // (tools/testplugin/lynx_test_drums_vst2.c: key 36 = output 1 at 110 Hz, key 37 = output 2 at 220 Hz) on a
  10224. // channel routed to insert 1; the wrapper's Processing › Connections as FL plays them [EXEC fl188d]: every output
  10225. // on the channel's insert by default, an offset to another insert, an inactive output silent, the channel's
  10226. // volume on all of them. Measured on the master with insert 1 muted or not.
  10227. void runMultiOutTest (const juce::String& pluginPath, const juce::String& reportPath)
  10228. {
  10229. juce::String report;
  10230. auto ok = true;
  10231. lynx::AudioEngine scanner (false);
  10232. report << "plugins_in_file=" << scanner.getPluginHost().addPluginFile (juce::File (pluginPath)) << "\n";
  10233. std::optional<juce::PluginDescription> vst2;
  10234. for (const auto& type : scanner.getPluginHost().getKnownPlugins().getTypes())
  10235. if (type.pluginFormatName == "VST" && juce::File (type.fileOrIdentifier) == juce::File (pluginPath))
  10236. vst2 = type; // (the profile may know other test plugins)
  10237. struct Case
  10238. {
  10239. const char* name;
  10240. std::vector<lynx::PluginOutputRoute> routes;
  10241. bool muteInsert1;
  10242. float volume;
  10243. bool kick, snare; // expected on the master
  10244. };
  10245. const Case cases[] = {
  10246. { "defaults", {}, false, -1.0f, true, true },
  10247. { "defaults, insert 1 muted", {}, true, -1.0f, false, false },
  10248. { "auto map, insert 1 muted", { { 0, 1 }, { 1, 1 } }, true, -1.0f, false, true },
  10249. { "auto map", { { 0, 1 }, { 1, 1 } }, false, -1.0f, true, true },
  10250. { "output 2 inactive", { { 0, 1 }, { 1, 0 } }, false, -1.0f, true, false },
  10251. { "output 1 inactive", { { 0, 0 } }, false, -1.0f, false, true },
  10252. { "auto map, channel volume 0", { { 0, 1 }, { 1, 1 } }, false, 0.0f, false, false },
  10253. { "output 2 inactive, Process inactive inputs and outputs on", { { 0, 1 }, { 1, 0 } }, false, -1.0f, true, true },
  10254. };
  10255. auto tone = [] (const std::vector<float>& x, double hz) {
  10256. // Goertzel magnitude over the buffer (normalised to a sine's amplitude)
  10257. const auto w = 2.0 * juce::MathConstants<double>::pi * hz / 48000.0;
  10258. double s1 = 0.0, s2 = 0.0;
  10259. for (const auto v : x)
  10260. {
  10261. const auto s0 = v + 2.0 * std::cos (w) * s1 - s2;
  10262. s2 = s1;
  10263. s1 = s0;
  10264. }
  10265. 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());
  10266. };
  10267. if (! vst2)
  10268. ok = false;
  10269. else
  10270. for (const auto& c : cases)
  10271. {
  10272. lynx::AudioEngine engine (false);
  10273. engine.getPluginHost().addPluginFile (juce::File (pluginPath));
  10274. auto song = lynx::Song::makeDefault();
  10275. auto& channel = song.channels[0];
  10276. channel.instrument = lynx::InstrumentKind::plugin;
  10277. channel.plugin = {};
  10278. channel.plugin.id = vst2->createIdentifierString().toStdString();
  10279. channel.plugin.name = vst2->name.toStdString();
  10280. channel.plugin.outputs = c.routes;
  10281. // (FL's "Process inactive inputs and outputs" plays an inactive output: off but for the case named so)
  10282. channel.plugin.processInactive = juce::String (c.name).contains ("Process inactive");
  10283. channel.mixerTrack = 1;
  10284. if (c.volume >= 0.0f)
  10285. channel.volume = c.volume;
  10286. for (std::size_t k = 1; k < song.channels.size(); ++k)
  10287. song.channels[k].muted = true;
  10288. if (song.mixer.size() < 4)
  10289. song.mixer.resize (4);
  10290. song.mixer[1].muted = c.muteInsert1;
  10291. song.patterns[0].notes.clear();
  10292. for (const auto key : { 36, 37 })
  10293. {
  10294. lynx::Note note;
  10295. note.start = 0;
  10296. note.length = lynx::ppq;
  10297. note.channel = 0;
  10298. note.key = key;
  10299. note.velocity = 1.0f;
  10300. song.patterns[0].notes.push_back (note);
  10301. }
  10302. engine.setSong (song);
  10303. std::vector<float> master;
  10304. lynx::AudioEngine::RenderOptions options;
  10305. options.seconds = 0.25;
  10306. options.sampleRate = 48000.0;
  10307. options.capture = [&master] (const float* l, const float*, int n) { master.insert (master.end(), l, l + n); };
  10308. engine.renderOffline (options);
  10309. const auto kick = tone (master, 110.0), snare = tone (master, 220.0);
  10310. const auto pass = (kick > 0.01) == c.kick && (snare > 0.01) == c.snare;
  10311. report << c.name << ": kick_110Hz=" << juce::String (kick, 4) << " snare_220Hz=" << juce::String (snare, 4) << " expected kick="
  10312. << (int) c.kick << " snare=" << (int) c.snare << (pass ? " OK" : " FAILED") << "\n";
  10313. ok = ok && pass;
  10314. if (auto instrument = std::dynamic_pointer_cast<lynx::PluginInstrument> (engine.getChannelInstrument (0)))
  10315. if (&c == &cases[0])
  10316. {
  10317. report << "outputs=" << (int) instrument->outputs().size();
  10318. for (const auto& o : instrument->outputs())
  10319. report << " [" << o.name << " ch" << o.channel << "x" << o.channels << "]";
  10320. report << "\n";
  10321. ok = ok && instrument->outputs().size() == 8 && instrument->outputs()[1].name == "Snare";
  10322. }
  10323. }
  10324. // round 189j: "LYNX Test SC.dll" next to it (tools/testplugin/lynx_test_sc_vst2.c) as an effect on insert 1
  10325. const auto sc = juce::File (pluginPath).getSiblingFile ("LYNX Test SC.dll");
  10326. if (sc.existsAsFile())
  10327. ok = runEffectConnectionsTest (sc, report) && ok;
  10328. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  10329. juce::File (reportPath).replaceWithText (report);
  10330. setApplicationReturnValue (ok ? 0 : 1);
  10331. quit();
  10332. }
  10333. // Round 189j: a hosted effect's Processing › Connections against FL 2026's own renders of the same projects
  10334. // [EXEC fxconn189j: FL /R renders of LYNX's .flp exports, docs/analise/REA_rodada189j.md]. Insert 1: a 440 Hz
  10335. // sampler and "LYNX Test SC" (output 1 = input 1, output 2 = input 2); inserts 2 (1000 Hz) and 3 (1500 Hz) routed
  10336. // to insert 1 at level 0 only; insert 4 a 2500 Hz reference on the Master; insert 1 routed to the Master and at
  10337. // level 0 to inserts 5 (panned left) and 6 (right). Each tone's level per side, in dB from the reference's, must be
  10338. // FL's within 0.5 dB (absent: 50 dB under it).
  10339. bool runEffectConnectionsTest (const juce::File& scFile, juce::String& report)
  10340. {
  10341. lynx::AudioEngine scanner (false);
  10342. scanner.getPluginHost().addPluginFile (scFile);
  10343. std::optional<juce::PluginDescription> sc;
  10344. for (const auto& type : scanner.getPluginHost().getKnownPlugins().getTypes())
  10345. if (type.pluginFormatName == "VST" && juce::File (type.fileOrIdentifier) == scFile)
  10346. sc = type;
  10347. report << "effect_plugin=" << (sc ? sc->name : juce::String ("not found")) << "\n";
  10348. if (! sc)
  10349. return false;
  10350. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-fxconn189j");
  10351. dir.createDirectory();
  10352. const double tones[] = { 440.0, 1000.0, 1500.0, 2500.0 };
  10353. for (const auto hz : tones)
  10354. {
  10355. const auto wav = dir.getChildFile ("sine" + juce::String ((int) hz) + ".wav");
  10356. if (wav.existsAsFile())
  10357. continue;
  10358. juce::AudioBuffer<float> sine (1, 44100 * 3);
  10359. for (int i = 0; i < sine.getNumSamples(); ++i)
  10360. sine.setSample (0, i, 0.25f * (float) std::sin (2.0 * juce::MathConstants<double>::pi * hz * i / 44100.0));
  10361. juce::WavAudioFormat format;
  10362. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  10363. if (auto* w = format.createWriterFor (out.get(), 44100.0, 1, 16, {}, 0))
  10364. {
  10365. out.release();
  10366. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  10367. writer->writeFromAudioSampleBuffer (sine, 0, sine.getNumSamples());
  10368. }
  10369. }
  10370. using Route = lynx::PluginOutputRoute;
  10371. constexpr float none = -999.0f;
  10372. struct Case
  10373. {
  10374. const char* name;
  10375. std::vector<Route> inputs, outputs;
  10376. int tweak; // 1 no Master route, 2 insert 1 fader at 0.4, 3 Process inactive off, 4 Master route level 0, 5 route
  10377. // to 7 too, 6 insert 2 fader at 0.4, 7 insert 2 muted, 8 insert 2 panned left
  10378. float level[3][2]; // 440 / 1000 / 1500 Hz, left / right: dB from the reference, FL's
  10379. };
  10380. const Route d { 0, 1 };
  10381. const Case cases[] = {
  10382. { "e00 FL defaults", { d, d }, {}, 0, { { 6.1f, 6.1f }, { none, none }, { none, none } } },
  10383. { "e01 input 1 at 1", { { 1, 1 } }, {}, 0, { { 0, 0 }, { 0, 0 }, { none, none } } },
  10384. { "e02 input 1 at 2", { { 2, 1 } }, {}, 0, { { 0, 0 }, { none, none }, { 0, 0 } } },
  10385. { "e03 input 2 at 1", { d, { 1, 1 } }, {}, 0, { { 0, 0 }, { 0, 0 }, { none, none } } },
  10386. { "e04 output 2 at 1 (Master)", { d, { 1, 1 } }, { d, { 1, 1 } }, 0, { { 0, 0 }, { 0, 0 }, { none, none } } },
  10387. { "e05 output 2 at 2 (insert 5)", { d, { 1, 1 } }, { d, { 2, 1 } }, 0, { { 0, 0 }, { 3.0f, none }, { none, none } } },
  10388. { "e06 output 1 at 1", {}, { { 1, 1 } }, 0, { { 6.1f, 6.1f }, { none, none }, { none, none } } },
  10389. { "e07 output 2 at 5 (past the list)", { d, { 1, 1 } }, { d, { 5, 1 } }, 0, { { 0, 0 }, { none, 3.0f }, { none, none } } },
  10390. { "e08 inputs 1 and 2 at 1", { { 1, 1 }, { 1, 1 } }, {}, 0, { { none, none }, { 6.1f, 6.1f }, { none, none } } },
  10391. { "e09 output 2 inactive", { d, { 1, 1 } }, { d, { 0, 0 } }, 0, { { 0, 0 }, { 0, 0 }, { none, none } } },
  10392. { "e10 input 1 at 5 (past the list)", { { 5, 1 } }, {}, 0, { { 6.1f, 6.1f }, { none, none }, { none, none } } },
  10393. { "e11 output 2 at 3 (insert 6)", { d, { 1, 1 } }, { d, { 3, 1 } }, 0, { { 0, 0 }, { none, 3.0f }, { none, none } } },
  10394. { "e13 no Master route, output 2 at 1", { d, { 1, 1 } }, { d, { 1, 1 } }, 1, { { none, none }, { 3.0f, none }, { none, none } } },
  10395. { "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 } } },
  10396. { "e15 input 2 inactive", { d, { 1, 0 } }, { d, d }, 3, { { 0, 0 }, { none, none }, { none, none } } },
  10397. { "e16 output 2 inactive", { d, { 1, 1 } }, { d, { 0, 0 } }, 3, { { 0, 0 }, { none, none }, { none, none } } },
  10398. { "e18 route to 7 too, output 2 at 3", { d, { 1, 1 } }, { d, { 3, 1 } }, 5, { { 0, 0 }, { none, 3.0f }, { none, none } } },
  10399. { "e19 Master route at 0, output 2 at 1", { d, { 1, 1 } }, { d, { 1, 1 } }, 4, { { none, none }, { 0, 0 }, { none, none } } },
  10400. { "e22 input 1 at 1 inactive", { { 1, 0 } }, {}, 3, { { 0, 0 }, { none, none }, { none, none } } },
  10401. { "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 } } },
  10402. { "e24 input 1 at 1, insert 2 fader 0.4", { { 1, 1 } }, {}, 6, { { 0, 0 }, { -12.7f, -12.7f }, { none, none } } },
  10403. { "e25 input 1 at 1, insert 2 muted", { { 1, 1 } }, {}, 7, { { 0, 0 }, { none, none }, { none, none } } },
  10404. { "e26 input 1 at 1, insert 2 panned left", { { 1, 1 } }, {}, 8, { { 0, 0 }, { 3.0f, none }, { none, none } } },
  10405. };
  10406. auto goertzel = [] (const std::vector<float>& x, double hz) {
  10407. const auto w = 2.0 * juce::MathConstants<double>::pi * hz / 44100.0;
  10408. double s1 = 0.0, s2 = 0.0;
  10409. for (const auto v : x)
  10410. {
  10411. const auto s0 = v + 2.0 * std::cos (w) * s1 - s2;
  10412. s2 = s1;
  10413. s1 = s0;
  10414. }
  10415. 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());
  10416. return a > 1e-7 ? 20.0 * std::log10 (a) : -140.0;
  10417. };
  10418. auto ok = true;
  10419. for (const auto& c : cases)
  10420. {
  10421. lynx::AudioEngine engine (false);
  10422. engine.getPluginHost().addPluginFile (scFile);
  10423. auto song = lynx::Song::makeDefault();
  10424. song.bpm = 120.0;
  10425. song.channels.clear();
  10426. song.automations.clear();
  10427. for (auto& p : song.patterns)
  10428. p.notes.clear();
  10429. for (int k = 0; k < 4; ++k)
  10430. {
  10431. lynx::ChannelDef ch;
  10432. ch.name = "S" + std::to_string ((int) tones[k]);
  10433. ch.instrument = lynx::InstrumentKind::sampler;
  10434. ch.samplePath = dir.getChildFile ("sine" + juce::String ((int) tones[k]) + ".wav").getFullPathName().toStdString();
  10435. ch.mixerTrack = k + 1;
  10436. song.channels.push_back (ch);
  10437. lynx::Note note;
  10438. note.start = 0;
  10439. note.length = 8 * lynx::ppq;
  10440. note.channel = k;
  10441. note.key = 60;
  10442. note.velocity = 0.78f;
  10443. song.patterns[0].notes.push_back (note);
  10444. }
  10445. if (song.mixer.size() < 10)
  10446. song.mixer.resize (10);
  10447. for (auto& t : song.mixer)
  10448. {
  10449. t.effects.clear();
  10450. t.sends.clear();
  10451. t.toMaster = true;
  10452. }
  10453. lynx::EffectSlot fx;
  10454. fx.kind = lynx::EffectKind::plugin;
  10455. fx.plugin.id = sc->createIdentifierString().toStdString();
  10456. fx.plugin.name = sc->name.toStdString();
  10457. fx.plugin.inputs = c.inputs;
  10458. fx.plugin.outputs = c.outputs;
  10459. fx.plugin.processInactive = c.tweak != 3;
  10460. auto& one = song.mixer[1];
  10461. one.effects.push_back (fx);
  10462. one.sends = { { 5, 0.0f }, { 6, 0.0f } };
  10463. for (const int t : { 2, 3 })
  10464. {
  10465. song.mixer[(std::size_t) t].toMaster = false;
  10466. song.mixer[(std::size_t) t].sends = { { 1, 0.0f } };
  10467. }
  10468. song.mixer[5].pan = -1.0f;
  10469. song.mixer[6].pan = 1.0f;
  10470. one.toMaster = c.tweak != 1;
  10471. if (c.tweak == 2)
  10472. one.volume = 0.4f;
  10473. if (c.tweak == 4)
  10474. one.masterLevel = 0.0f;
  10475. if (c.tweak == 6)
  10476. song.mixer[2].volume = 0.4f;
  10477. song.mixer[2].muted = c.tweak == 7;
  10478. song.mixer[2].pan = c.tweak == 8 ? -1.0f : 0.0f;
  10479. if (c.tweak == 5)
  10480. {
  10481. one.sends = { { 7, 0.0f }, { 5, 0.0f }, { 6, 0.0f } };
  10482. song.mixer[7].pan = 0.5f;
  10483. }
  10484. // (input 2's index sets the slot's side input source, as the Connections page and the import do)
  10485. if (c.inputs.size() > 1 && c.inputs[1].offset > 0)
  10486. one.effects[0].sidechain = lynx::mixerops::sidechainIndexSource (song, 1, c.inputs[1].offset);
  10487. engine.setSong (song);
  10488. std::vector<float> left, right;
  10489. lynx::AudioEngine::RenderOptions options;
  10490. options.seconds = 1.2;
  10491. options.sampleRate = 44100.0;
  10492. options.capture = [&] (const float* l, const float* r, int n) {
  10493. left.insert (left.end(), l, l + n);
  10494. right.insert (right.end(), r, r + n);
  10495. };
  10496. engine.renderOffline (options);
  10497. const auto from = (std::size_t) 22050, to = (std::size_t) 44100;
  10498. if (right.size() < to)
  10499. {
  10500. report << c.name << ": rendered " << (int) right.size() << " samples FAILED\n";
  10501. ok = false;
  10502. continue;
  10503. }
  10504. const std::vector<float> l (left.begin() + (std::ptrdiff_t) from, left.begin() + (std::ptrdiff_t) to);
  10505. const std::vector<float> r (right.begin() + (std::ptrdiff_t) from, right.begin() + (std::ptrdiff_t) to);
  10506. const auto ref = 0.5 * (goertzel (l, 2500.0) + goertzel (r, 2500.0));
  10507. auto pass = ref > -60.0;
  10508. report << c.name << ": ref=" << juce::String (ref, 1);
  10509. for (int k = 0; k < 3; ++k)
  10510. for (int side = 0; side < 2; ++side)
  10511. {
  10512. const auto got = goertzel (side == 0 ? l : r, tones[k]) - ref;
  10513. const auto want = c.level[k][side];
  10514. const auto good = want == none ? got < -50.0 : std::abs (got - want) < 0.5;
  10515. pass = pass && good;
  10516. report << " " << (int) tones[k] << (side == 0 ? "L" : "R") << "=" << (got < -50.0 ? juce::String ("-") : juce::String (got, 1))
  10517. << (good ? "" : "(FL " + (want == none ? juce::String ("-") : juce::String (want, 1)) + ")");
  10518. }
  10519. report << (pass ? " OK" : " FAILED") << "\n";
  10520. ok = ok && pass;
  10521. }
  10522. return ok;
  10523. }
  10524. // LYNX.exe --wrappertest plugin.vst3 report.txt: builds a VST3 state the way FL's Fruity
  10525. // Wrapper stores it (REA_rodada5 §3.2), runs it through the import (adoptFlPlugins) and checks
  10526. // that the plugin comes back with the changed parameter.
  10527. void runWrapperTest (const juce::String& pluginPath, const juce::String& reportPath)
  10528. {
  10529. juce::String report;
  10530. bool ok = false;
  10531. {
  10532. lynx::AudioEngine offline (false);
  10533. auto& host = offline.getPluginHost();
  10534. host.addPluginFile (juce::File (pluginPath));
  10535. const juce::PluginDescription* vst3 = nullptr;
  10536. const auto types = host.getKnownPlugins().getTypes(); // copy: the pointer below points into it
  10537. for (const auto& type : types)
  10538. if (type.pluginFormatName == "VST3" && type.isInstrument)
  10539. vst3 = &type;
  10540. if (vst3 != nullptr)
  10541. {
  10542. juce::String error;
  10543. auto plugin = host.getFormats().createPluginInstance (*vst3, 48000.0, 512, error);
  10544. auto* parameter = plugin != nullptr && ! plugin->getParameters().isEmpty() ? plugin->getParameters()[0] : nullptr;
  10545. if (parameter != nullptr)
  10546. {
  10547. const auto target = parameter->getValue() > 0.5f ? 0.13f : 0.87f;
  10548. parameter->setValueNotifyingHost (target);
  10549. juce::MemoryBlock juceState;
  10550. plugin->getStateInformation (juceState);
  10551. report << "parameter=" << parameter->getName (64) << " target=" << target << "\n";
  10552. // JUCE state -> FL container: u32 1 + records 1 (flags), 3 (component), 2 (controller)
  10553. std::vector<std::uint8_t> flState;
  10554. auto put32 = [&] (std::uint32_t v) { for (int b = 0; b < 4; ++b) flState.push_back ((std::uint8_t) (v >> (8 * b))); };
  10555. auto record = [&] (std::uint32_t id, const juce::MemoryBlock& data) {
  10556. put32 (id);
  10557. put32 ((std::uint32_t) data.getSize());
  10558. put32 (0);
  10559. flState.insert (flState.end(), (const std::uint8_t*) data.getData(), (const std::uint8_t*) data.getData() + data.getSize());
  10560. };
  10561. put32 (1);
  10562. record (1, juce::MemoryBlock (64, true));
  10563. // record 4 (REA_rodada22 §2.3): slots 0/1 hold the ParamIDs of parameters 2 and 0, so FL's
  10564. // automations k = 0, 1, 2 mean positions 2, 0 and 1 (the first parameter without a slot)
  10565. juce::MemoryBlock slots;
  10566. const auto paramId = [&] (int i) {
  10567. const auto* hosted = dynamic_cast<const juce::HostedAudioProcessorParameter*> (plugin->getParameters()[i]);
  10568. return hosted != nullptr ? (std::uint32_t) hosted->getParameterID().getLargeIntValue() : 0u;
  10569. };
  10570. const bool reorder = plugin->getParameters().size() >= 3;
  10571. if (reorder)
  10572. {
  10573. for (auto v : { 2u, paramId (2), paramId (0) })
  10574. slots.append (&v, 4);
  10575. report << "slot_param_ids=" << (juce::int64) paramId (2) << "," << (juce::int64) paramId (0) << "\n";
  10576. }
  10577. if (auto xml = juce::AudioProcessor::getXmlFromBinary (juceState.getData(), (int) juceState.getSize()))
  10578. for (auto [tag, id] : { std::pair { "IComponent", 3u }, { "IEditController", 2u } })
  10579. if (auto* child = xml->getChildByName (tag))
  10580. {
  10581. juce::MemoryBlock data;
  10582. data.fromBase64Encoding (child->getAllSubText());
  10583. record (id, data);
  10584. report << tag << "_bytes=" << (int) data.getSize() << "\n";
  10585. }
  10586. if (reorder)
  10587. record (4, slots);
  10588. plugin.reset();
  10589. auto song = lynx::Song::makeDefault();
  10590. auto& f = song.channels[4].plugin.foreign;
  10591. f.format = lynx::ForeignPlugin::Format::vst3;
  10592. f.name = vst3->name.toStdString(); // no class ID: find it by name (fallback)
  10593. f.state = flState;
  10594. {
  10595. std::vector<std::uint8_t> comp, ctrl;
  10596. report << "split=" << (int) lynx::splitFlVst3State (flState, comp, ctrl) << " component=" << (int) comp.size()
  10597. << " saved_slots=" << (int) lynx::flVst3ParamSlots (flState).size() << "\n";
  10598. }
  10599. for (int k = 0; k < 3; ++k)
  10600. {
  10601. lynx::Automation a;
  10602. a.target = { lynx::AutomationTargetKind::channelParam, 4, 0, k };
  10603. song.automations.push_back (a);
  10604. }
  10605. const auto adopted = host.adoptFlPlugins (song);
  10606. report << "adopted=" << adopted << "\n";
  10607. juce::String mapped;
  10608. for (const auto& a : song.automations)
  10609. if (a.target.kind == lynx::AutomationTargetKind::channelParam && a.target.index == 4)
  10610. mapped << (mapped.isEmpty() ? "" : ",") << a.target.param;
  10611. report << "slot_positions=" << mapped << "\n";
  10612. const auto slotsOk = ! reorder || mapped == "2,0,1";
  10613. offline.setSong (song);
  10614. if (auto* loaded = dynamic_cast<lynx::PluginInstrument*> (offline.getChannelInstrument (4).get()))
  10615. {
  10616. const auto value = loaded->getInstance().getParameters()[0]->getValue();
  10617. report << "restored_value=" << value << "\n";
  10618. ok = adopted == 1 && std::abs (value - target) < 0.02f && slotsOk;
  10619. }
  10620. }
  10621. }
  10622. }
  10623. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  10624. juce::File (reportPath).replaceWithText (report);
  10625. setApplicationReturnValue (ok ? 0 : 1);
  10626. quit();
  10627. }
  10628. void runDemoSongs (const juce::String& folderPath)
  10629. {
  10630. const juce::File folder (folderPath);
  10631. folder.createDirectory();
  10632. bool ok = true;
  10633. for (int d = 1; d < lynx::demos::count; ++d)
  10634. {
  10635. juce::String error;
  10636. ok = lynx::ProjectFile::save (lynx::demos::make (d), folder.getChildFile (lynx::demos::fileName (d)), error) && ok;
  10637. }
  10638. setApplicationReturnValue (ok ? 0 : 1);
  10639. quit();
  10640. }
  10641. // --perfgen (round perfgate190id): each synthetic project of the performance gate written as <folder>/<name>.lynx, its
  10642. // audio as 16-bit WAVs in <folder>/<name>/ (written once: the same code makes the same audio). The report gives, per
  10643. // project, the .lynx size, the time to write it (ProjectFile::save, which reads it back) and to read it
  10644. // (ProjectFile::load), the medians of 5, and a hash of its text.
  10645. void runPerfGen (const juce::String& folderPath, const juce::String& reportPath, const juce::String& only)
  10646. {
  10647. const juce::File folder (folderPath);
  10648. folder.createDirectory();
  10649. const auto wanted = juce::StringArray::fromTokens (only, ",", "");
  10650. juce::String report;
  10651. bool ok = true;
  10652. auto median = [] (std::vector<double> v) {
  10653. std::sort (v.begin(), v.end());
  10654. return v[v.size() / 2];
  10655. };
  10656. for (const auto& name : lynx::perfprojects::names())
  10657. {
  10658. if (! wanted.isEmpty() && ! wanted.contains (juce::String (name)))
  10659. continue;
  10660. lynx::Song song;
  10661. lynx::perfprojects::Samples samples;
  10662. const auto audioFolder = folder.getChildFile (juce::String (name));
  10663. lynx::perfprojects::make (name, song, samples, audioFolder.getFullPathName().toStdString());
  10664. for (const auto& [path, data] : samples)
  10665. {
  10666. const juce::File wav { juce::String (path) };
  10667. if (wav.existsAsFile())
  10668. continue;
  10669. wav.getParentDirectory().createDirectory();
  10670. const auto frames = (int) data->frames();
  10671. juce::AudioBuffer<float> audio (2, frames);
  10672. audio.copyFrom (0, 0, data->leftData(), frames);
  10673. audio.copyFrom (1, 0, data->rightData(), frames);
  10674. juce::WavAudioFormat format;
  10675. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  10676. if (auto* w = out != nullptr ? format.createWriterFor (out.get(), data->sampleRate, 2, 16, {}, 0) : nullptr)
  10677. {
  10678. out.release();
  10679. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  10680. ok = writer->writeFromAudioSampleBuffer (audio, 0, frames) && ok;
  10681. }
  10682. else
  10683. ok = false;
  10684. }
  10685. const auto file = folder.getChildFile (juce::String (name) + ".lynx");
  10686. std::vector<double> saveMs, loadMs;
  10687. juce::String error;
  10688. bool loadedOk = true;
  10689. for (int rep = 0; rep < 5; ++rep)
  10690. {
  10691. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  10692. ok = lynx::ProjectFile::save (song, file, error) && ok;
  10693. const auto t1 = juce::Time::getMillisecondCounterHiRes();
  10694. const auto loaded = lynx::ProjectFile::load (file, error);
  10695. const auto t2 = juce::Time::getMillisecondCounterHiRes();
  10696. loadedOk = loadedOk && loaded.has_value() && loaded->channels.size() == song.channels.size()
  10697. && loaded->playlist.size() == song.playlist.size() && loaded->automations.size() == song.automations.size();
  10698. saveMs.push_back (t1 - t0);
  10699. loadMs.push_back (t2 - t1);
  10700. }
  10701. ok = ok && loadedOk;
  10702. const auto text = file.loadFileAsString();
  10703. std::uint64_t h = 1469598103934665603ull;
  10704. for (auto* c = text.toRawUTF8(); *c != 0; ++c)
  10705. h = (h ^ (std::uint8_t) *c) * 1099511628211ull;
  10706. report << name << ": channels=" << (int) song.channels.size() << " inserts=" << (int) song.mixer.size() - 1
  10707. << " clips=" << (int) song.playlist.size() << " automations=" << (int) song.automations.size()
  10708. << " wavs=" << (int) samples.size() << " lynx_kb=" << juce::String ((double) file.getSize() / 1024.0, 1)
  10709. << " save_ms=" << juce::String (median (saveMs), 2) << " load_ms=" << juce::String (median (loadMs), 2)
  10710. << " roundtrip=" << (loadedOk ? "OK" : "FAILED") << " text_hash=" << juce::String::toHexString ((juce::int64) h)
  10711. << (error.isNotEmpty() ? " error=" + error : juce::String()) << "\n";
  10712. }
  10713. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  10714. if (reportPath.isNotEmpty())
  10715. juce::File (reportPath).replaceWithText (report);
  10716. else
  10717. std::fputs (report.toRawUTF8(), stdout);
  10718. setApplicationReturnValue (ok ? 0 : 1);
  10719. quit();
  10720. }
  10721. void runShowcase (const juce::String& outputPath, int currentPattern)
  10722. {
  10723. const auto song = lynx::makeShowcaseSong (currentPattern);
  10724. juce::String error;
  10725. const auto ok = lynx::ProjectFile::save (song, juce::File (outputPath), error);
  10726. setApplicationReturnValue (ok ? 0 : 1);
  10727. quit();
  10728. }
  10729. // LYNX.exe --sandboxtest plugin.vst3 report.txt: opens the instrument in a separate process, plays a
  10730. // note, changes a parameter, checks the state (back in an in-process plugin) and makes the child hang
  10731. // to check that LYNX keeps going (silence, without waiting longer than the timeout).
  10732. // --sandboxtest: plays an instrument (a note) or an effect (a 440 Hz tone through it); render() adds into l / r
  10733. struct TestVoice
  10734. {
  10735. explicit TestVoice (std::unique_ptr<juce::AudioPluginInstance> p)
  10736. {
  10737. if (p->acceptsMidi() && p->getTotalNumInputChannels() == 0)
  10738. instrument = std::make_unique<lynx::PluginInstrument> (std::move (p), 512);
  10739. else
  10740. effect = std::move (p);
  10741. }
  10742. void noteOn()
  10743. {
  10744. if (instrument != nullptr)
  10745. instrument->noteOn (60, 0.9f);
  10746. }
  10747. void render (float* l, float* r, int n, float gainLeft, float gainRight)
  10748. {
  10749. if (instrument != nullptr)
  10750. {
  10751. instrument->render (l, r, n, gainLeft, gainRight);
  10752. return;
  10753. }
  10754. const auto channels = juce::jmax (2, effect->getTotalNumInputChannels(), effect->getTotalNumOutputChannels());
  10755. juce::AudioBuffer<float> block (channels, 512);
  10756. juce::MidiBuffer midi;
  10757. for (int done = 0; done < n; done += 512)
  10758. {
  10759. const auto k = juce::jmin (512, n - done);
  10760. block.setSize (channels, k, false, false, true);
  10761. for (int i = 0; i < k; ++i)
  10762. {
  10763. const auto v = 0.25f * (float) std::sin (phase);
  10764. phase += 2.0 * juce::MathConstants<double>::pi * 440.0 / 48000.0;
  10765. for (int c = 0; c < channels; ++c)
  10766. block.setSample (c, i, v);
  10767. }
  10768. effect->processBlock (block, midi);
  10769. for (int i = 0; i < k; ++i)
  10770. {
  10771. l[done + i] += gainLeft * block.getSample (0, i);
  10772. r[done + i] += gainRight * block.getSample (1, i);
  10773. }
  10774. }
  10775. }
  10776. void release()
  10777. {
  10778. instrument.reset();
  10779. effect.reset();
  10780. }
  10781. std::unique_ptr<lynx::PluginInstrument> instrument;
  10782. std::unique_ptr<juce::AudioPluginInstance> effect;
  10783. double phase = 0.0;
  10784. };
  10785. void runSandboxTest (const juce::String& pluginPath, const juce::String& reportPath)
  10786. {
  10787. juce::String report;
  10788. bool ok = false;
  10789. lynx::setPluginSandboxAlerts (false);
  10790. const juce::File log (reportPath + ".log");
  10791. auto step = [&] (const char* what) { log.appendText (juce::String (what) + "\n"); };
  10792. log.deleteFile();
  10793. {
  10794. lynx::PluginHost host (false);
  10795. host.addPluginFile (juce::File (pluginPath));
  10796. const auto types = host.getKnownPlugins().getTypes(); // getTypes() returns a copy
  10797. // the file's instrument, else its first effect (round 161: effects too, e.g. a Windows effect through yabridge)
  10798. const juce::PluginDescription* instrument = nullptr;
  10799. for (const auto& type : types)
  10800. if (type.isInstrument)
  10801. instrument = &type;
  10802. for (const auto& type : types)
  10803. if (instrument == nullptr && ! type.isInstrument)
  10804. instrument = &type;
  10805. step ("host");
  10806. juce::String error;
  10807. auto remote = instrument != nullptr ? lynx::createSandboxedPlugin (*instrument, 48000.0, 512, {}, error) : nullptr;
  10808. report << "opened=" << (remote != nullptr ? 1 : 0) << " error=" << error << "\n";
  10809. step ("created");
  10810. if (remote != nullptr)
  10811. {
  10812. auto& proxy = *remote;
  10813. TestVoice voice (std::move (remote));
  10814. std::vector<float> l (48000), r (48000);
  10815. auto peakOf = [&] {
  10816. float peak = 0.0f;
  10817. for (std::size_t k = 0; k < l.size(); ++k)
  10818. peak = std::max ({ peak, std::abs (l[k]), std::abs (r[k]) });
  10819. return peak;
  10820. };
  10821. const auto start = juce::Time::getMillisecondCounterHiRes();
  10822. voice.noteOn();
  10823. voice.render (l.data(), r.data(), 48000, 1.0f, 1.0f);
  10824. const auto renderMs = juce::Time::getMillisecondCounterHiRes() - start;
  10825. const auto peak = peakOf();
  10826. step ("played");
  10827. if (juce::JUCEApplication::getCommandLineParameters().contains ("--expect-crash"))
  10828. {
  10829. // a plugin that crashes while playing (round 161 test plugin): LYNX notices, mutes it and keeps running
  10830. const auto dead = lynx::isSandboxedPluginDead (proxy);
  10831. std::fill (l.begin(), l.end(), 0.0f);
  10832. std::fill (r.begin(), r.end(), 0.0f);
  10833. voice.render (l.data(), r.data(), 4096, 1.0f, 1.0f);
  10834. report << "peak=" << peak << " render_1s_ms=" << renderMs << " dead=" << (dead ? 1 : 0) << " peak_after=" << peakOf() << "\n";
  10835. ok = dead && peak > 1e-4f && renderMs < 2000.0 && peakOf() == 0.0f;
  10836. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  10837. juce::File (reportPath).replaceWithText (report);
  10838. setApplicationReturnValue (ok ? 0 : 1);
  10839. quit();
  10840. return;
  10841. }
  10842. report << "plugin=" << proxy.getName() << (instrument->isInstrument ? " (instrument)" : " (effect)") << " parameters="
  10843. << proxy.getParameters().size() << " peak=" << peak << " render_1s_ms=" << renderMs << "\n";
  10844. if (juce::JUCEApplication::getCommandLineParameters().contains ("--editor") && proxy.hasEditor())
  10845. {
  10846. // the plugin's own window, opened by the child process (4 s on screen); the child must stay responsive
  10847. std::unique_ptr<juce::AudioProcessorEditor> editor (proxy.createEditorIfNeeded());
  10848. juce::Thread::sleep (4000);
  10849. juce::MemoryBlock state;
  10850. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  10851. proxy.getStateInformation (state);
  10852. report << "editor_shown=1 state_with_editor_ms=" << (juce::Time::getMillisecondCounterHiRes() - t0) << " dead=" << (lynx::isSandboxedPluginDead (proxy) ? 1 : 0) << "\n";
  10853. editor.reset();
  10854. }
  10855. // parameter -> state -> in-process plugin
  10856. bool stateOk = false;
  10857. if (! proxy.getParameters().isEmpty())
  10858. {
  10859. auto* p = proxy.getParameters()[0];
  10860. const auto target = p->getValue() > 0.5f ? 0.13f : 0.87f;
  10861. p->setValue (target);
  10862. std::fill (l.begin(), l.end(), 0.0f);
  10863. voice.render (l.data(), r.data(), 512, 1.0f, 1.0f); // carries the change to the child
  10864. juce::MemoryBlock state;
  10865. proxy.getStateInformation (state);
  10866. if (auto local = host.getFormats().createPluginInstance (*instrument, 48000.0, 512, error))
  10867. {
  10868. local->setStateInformation (state.getData(), (int) state.getSize());
  10869. const auto back = local->getParameters()[0]->getValue();
  10870. // the same steps without the sandbox: some plugins quantise the value or keep it out of their state
  10871. auto control = target;
  10872. if (auto a = host.getFormats().createPluginInstance (*instrument, 48000.0, 512, error))
  10873. {
  10874. a->enableAllBuses();
  10875. a->prepareToPlay (48000.0, 512);
  10876. a->getParameters()[0]->setValue (target);
  10877. juce::AudioBuffer<float> block (juce::jmax (2, a->getTotalNumInputChannels(), a->getTotalNumOutputChannels()), 512);
  10878. block.clear();
  10879. juce::MidiBuffer none;
  10880. a->processBlock (block, none);
  10881. juce::MemoryBlock direct;
  10882. a->getStateInformation (direct);
  10883. if (auto b = host.getFormats().createPluginInstance (*instrument, 48000.0, 512, error))
  10884. {
  10885. b->setStateInformation (direct.getData(), (int) direct.getSize());
  10886. control = b->getParameters()[0]->getValue();
  10887. }
  10888. a->releaseResources();
  10889. }
  10890. report << "state_bytes=" << (int) state.getSize() << " target=" << target << " in_process=" << back << " in_process_control=" << control << "\n";
  10891. stateOk = std::abs (back - control) < 0.02f;
  10892. }
  10893. }
  10894. step ("state");
  10895. // hung child: the block returns in ~0.5 s, muted, and the plugin is marked dead
  10896. lynx::hangSandboxedPluginForTest (proxy);
  10897. juce::Thread::sleep (200);
  10898. std::fill (l.begin(), l.end(), 1.0f);
  10899. std::fill (r.begin(), r.end(), 1.0f);
  10900. const auto hangStart = juce::Time::getMillisecondCounterHiRes();
  10901. voice.render (l.data(), r.data(), 4096, 0.0f, 0.0f);
  10902. std::fill (l.begin(), l.end(), 0.0f);
  10903. std::fill (r.begin(), r.end(), 0.0f);
  10904. voice.render (l.data(), r.data(), 4096, 1.0f, 1.0f);
  10905. const auto hangMs = juce::Time::getMillisecondCounterHiRes() - hangStart;
  10906. const auto dead = lynx::isSandboxedPluginDead (proxy);
  10907. const auto hangPeak = peakOf();
  10908. report << "hung_ms=" << hangMs << " dead=" << (dead ? 1 : 0) << " peak_after=" << hangPeak << "\n";
  10909. // crashed child (round 161): a second instance aborts; LYNX notices, mutes it and keeps running
  10910. bool crashOk = false;
  10911. if (auto second = lynx::createSandboxedPlugin (*instrument, 48000.0, 512, {}, error))
  10912. {
  10913. auto& proxy2 = *second;
  10914. TestVoice voice2 (std::move (second));
  10915. voice2.noteOn();
  10916. voice2.render (l.data(), r.data(), 512, 1.0f, 1.0f);
  10917. lynx::crashSandboxedPluginForTest (proxy2);
  10918. const auto crashStart = juce::Time::getMillisecondCounterHiRes();
  10919. while (! lynx::isSandboxedPluginDead (proxy2) && juce::Time::getMillisecondCounterHiRes() - crashStart < 5000.0)
  10920. {
  10921. voice2.render (l.data(), r.data(), 512, 1.0f, 1.0f);
  10922. juce::Thread::sleep (5);
  10923. }
  10924. const auto crashMs = juce::Time::getMillisecondCounterHiRes() - crashStart;
  10925. std::fill (l.begin(), l.end(), 0.0f);
  10926. std::fill (r.begin(), r.end(), 0.0f);
  10927. voice2.render (l.data(), r.data(), 4096, 1.0f, 1.0f);
  10928. const auto crashDead = lynx::isSandboxedPluginDead (proxy2);
  10929. report << "crash_ms=" << crashMs << " crash_dead=" << (crashDead ? 1 : 0) << " crash_peak_after=" << peakOf() << "\n";
  10930. crashOk = crashDead && crashMs < 3000.0;
  10931. // issue #159: freeing the crashed plugin doesn't wait on its pipe (JUCE waited up to 10 s there for
  10932. // the gone child, on the message thread when the rack freed it); its teardown ends on its own
  10933. const auto freeStart = juce::Time::getMillisecondCounterHiRes();
  10934. voice2.release();
  10935. const auto freeMs = juce::Time::getMillisecondCounterHiRes() - freeStart;
  10936. const auto endedAll = lynx::finishSandboxTeardowns (15000);
  10937. report << "crashed_free_ms=" << freeMs << " teardown_done=" << (endedAll ? 1 : 0) << "\n";
  10938. crashOk = crashOk && freeMs < 250.0 && endedAll;
  10939. }
  10940. step ("crash");
  10941. ok = peak > 1e-4f && stateOk && dead && hangMs < 1500.0 && hangPeak == 0.0f && crashOk;
  10942. }
  10943. }
  10944. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  10945. juce::File (reportPath).replaceWithText (report);
  10946. setApplicationReturnValue (ok ? 0 : 1);
  10947. quit();
  10948. }
  10949. // --timertest (round 174f): a view's polling timer follows the view and its parents, and survives a minimised window
  10950. void runTimerTest (const juce::File& report)
  10951. {
  10952. struct Ticks final : juce::Timer
  10953. {
  10954. void timerCallback() override {}
  10955. } timer;
  10956. juce::Component top, parent, view;
  10957. parent.addChildComponent (view);
  10958. top.addChildComponent (parent);
  10959. top.setSize (320, 200);
  10960. lynx::ui::TimerWhileShowing watch (view, timer, 30);
  10961. juce::String text;
  10962. auto failures = 0;
  10963. auto expect = [&] (const char* step, bool running) {
  10964. const auto ok = timer.isTimerRunning() == running;
  10965. failures += ok ? 0 : 1;
  10966. text << step << ": timer " << (timer.isTimerRunning() ? "running" : "stopped") << (ok ? "" : " FAIL") << "\n";
  10967. };
  10968. expect ("never shown", false);
  10969. view.setVisible (true);
  10970. parent.setVisible (true);
  10971. expect ("view and parent visible, not on the desktop", false);
  10972. top.addToDesktop (juce::ComponentPeer::windowHasTitleBar);
  10973. top.setVisible (true);
  10974. expect ("window shown", true);
  10975. parent.setVisible (false);
  10976. expect ("parent hidden", false);
  10977. parent.setVisible (true);
  10978. expect ("parent shown", true);
  10979. view.setVisible (false);
  10980. expect ("view hidden", false);
  10981. top.getPeer()->setMinimised (true);
  10982. view.setVisible (true);
  10983. expect ("view shown while minimised", true);
  10984. top.getPeer()->setMinimised (false);
  10985. expect ("window restored", true);
  10986. top.setVisible (false);
  10987. expect ("window hidden", false);
  10988. top.setVisible (true);
  10989. expect ("window shown again", true);
  10990. top.removeFromDesktop();
  10991. text << "failures: " << failures << "\nresult=" << (failures == 0 ? "OK" : "FAIL") << "\n";
  10992. report.replaceWithText (text);
  10993. setApplicationReturnValue (failures == 0 ? 0 : 1);
  10994. quit();
  10995. }
  10996. // --cachetest (round 174f): PlaylistComponent::cacheSelfTest on the project, the Playlist off screen at 1466 x 930
  10997. void runCacheTest (const juce::File& project, const juce::File& report)
  10998. {
  10999. engine = std::make_unique<lynx::AudioEngine>();
  11000. juce::String error;
  11001. auto ok = false;
  11002. if (project.hasFileExtension ("flp"))
  11003. ok = engine->importFlpFile (project, error);
  11004. else if (auto song = lynx::ProjectFile::load (project, error))
  11005. {
  11006. engine->setSong (std::move (*song));
  11007. ok = true;
  11008. }
  11009. juce::String text = "project: " + project.getFullPathName() + "\n";
  11010. if (ok)
  11011. {
  11012. auto playlist = std::make_unique<lynx::PlaylistComponent> (*engine);
  11013. playlist->setBounds (0, 0, 1466, 930);
  11014. playlist->setVisible (true);
  11015. text << playlist->cacheSelfTest ([] { lynx::ui::WaveformCache::getInstance()->waitUntilIdle (60000); }, report.getParentDirectory());
  11016. }
  11017. else
  11018. text << "result=ERROR " << error << "\n";
  11019. report.replaceWithText (text);
  11020. setApplicationReturnValue (ok && text.contains ("result=OK") ? 0 : 1);
  11021. quit();
  11022. }
  11023. // --picturetest (round 190bm): ui/PictureCheck.h on the Playlist and the Mixer, at a window's usual size, at a 4K
  11024. // screen's, and wider than a GPU bitmap can be (16384 px)
  11025. void runPictureTest (const juce::File& report, const juce::File& project)
  11026. {
  11027. engine = std::make_unique<lynx::AudioEngine>();
  11028. juce::String error, text;
  11029. if (project != juce::File())
  11030. {
  11031. auto ok = false;
  11032. if (project.hasFileExtension ("flp"))
  11033. ok = engine->importFlpFile (project, error);
  11034. else if (auto song = lynx::ProjectFile::load (project, error))
  11035. {
  11036. engine->setSong (std::move (*song));
  11037. ok = true;
  11038. }
  11039. text << "project: " << project.getFullPathName() << (ok ? "" : " (not loaded: " + error + ")") << "\n";
  11040. }
  11041. #if JUCE_WINDOWS
  11042. text << "native image: " << juce::NativeImageType().create (juce::Image::RGB, 8, 8, true)->createType()->getTypeID()
  11043. << " (software = " << juce::SoftwareImageType().getTypeID() << ")\n";
  11044. #endif
  11045. auto failures = 0;
  11046. struct Size
  11047. {
  11048. int width, height;
  11049. std::vector<float> scales;
  11050. };
  11051. const auto folder = report.getParentDirectory();
  11052. 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 } } })
  11053. {
  11054. const auto label = [&size] (const char* name) { return juce::String (name) + " " + juce::String (size.width) + " x " + juce::String (size.height); };
  11055. {
  11056. auto playlist = std::make_unique<lynx::PlaylistComponent> (*engine);
  11057. playlist->setBounds (0, 0, size.width, size.height);
  11058. playlist->setVisible (true);
  11059. {
  11060. juce::Image warm (juce::Image::RGB, 64, 64, true); // (one paint asks for the waveforms, then they are waited for)
  11061. juce::Graphics g (warm);
  11062. playlist->paintEntireComponent (g, true);
  11063. }
  11064. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (60000);
  11065. text << lynx::ui::picturecheck::run (*playlist, label ("Playlist"), size.scales, failures, folder);
  11066. }
  11067. {
  11068. auto mixer = std::make_unique<lynx::MixerComponent> (*engine);
  11069. mixer->setBounds (0, 0, size.width, juce::jmin (size.height, 700));
  11070. mixer->setVisible (true);
  11071. text << lynx::ui::picturecheck::run (*mixer, label ("Mixer"), size.scales, failures, folder);
  11072. }
  11073. }
  11074. text << "failures: " << failures << "\nresult=" << (failures == 0 ? "OK" : "FAIL") << "\n";
  11075. report.replaceWithText (text);
  11076. setApplicationReturnValue (failures == 0 ? 0 : 1);
  11077. quit();
  11078. }
  11079. // --uiperf (round 161): opens the project in the normal window, plays it, and drives the heavy UI cases of round 151
  11080. // through the window's own event path — the default layout, the Mixer maximised (meters while playing, then
  11081. // scrolled), the Playlist maximised (scroll down, scroll sideways, zoom in and out) and the Channel rack scrolled.
  11082. // Every frame is painted right after its event (ComponentPeer::performAnyPendingRepaintsNow) and timed; the report
  11083. // has, per case, the time to show it and the frames' mean / p95 / max, how many took longer than 16 ms, and the
  11084. // process CPU. The same on every OS, so Linux (X11, XWayland) and Windows numbers can be put side by side.
  11085. void runUiPerf (const juce::File& project, const juce::File& report)
  11086. {
  11087. if (const auto profile = juce::SystemStats::getEnvironmentVariable ("LYNX_PROFILE_MAIN", {}); profile.isNotEmpty())
  11088. lynx::crashguard::startMainProfiler (profile.toStdString()); // (stopped in shutdown)
  11089. startupOptions = lynx::StartupOptions::load();
  11090. engine = std::make_unique<lynx::AudioEngine>();
  11091. lynx::videoview::install (*engine); // (Fruity Video Player channels: their sound tracks)
  11092. crashEngine = engine.get();
  11093. createMainWindow();
  11094. mainWindow->reveal();
  11095. // LYNX_UIPERF_SIZE=WxH, LYNX_UIPERF_SCALE=<percent> (round 179a): a large window, a HiDPI desktop's scale
  11096. if (const auto scale = juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_SCALE", {}).getIntValue(); scale > 0)
  11097. juce::Desktop::getInstance().setGlobalScaleFactor ((float) scale / 100.0f);
  11098. if (const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_SIZE", {}), "x", ""); size.size() == 2)
  11099. mainWindow->setBounds (0, 0, size[0].getIntValue(), size[1].getIntValue());
  11100. juce::String error;
  11101. auto ok = false;
  11102. const auto loadStart = juce::Time::getMillisecondCounterHiRes();
  11103. if (project.hasFileExtension ("flp;als;flm;band")) // (round 190gr: a Live set, its Session clips in the grid)
  11104. ok = engine->importFlpFile (project, error);
  11105. else if (auto song = lynx::ProjectFile::load (project, error))
  11106. {
  11107. engine->setSong (std::move (*song));
  11108. ok = true;
  11109. }
  11110. const auto loadMs = juce::Time::getMillisecondCounterHiRes() - loadStart;
  11111. if (! ok)
  11112. {
  11113. report.replaceWithText ("project: " + project.getFullPathName() + "\nresult=ERROR " + error + "\n");
  11114. setApplicationReturnValue (1);
  11115. quit();
  11116. return;
  11117. }
  11118. // LYNX_UIPERF_MUTE=1: the Master fader down (the meters of the inserts still move): a run on a desktop someone uses
  11119. if (juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_MUTE", {}) == "1")
  11120. engine->editSong ([] (lynx::Song& s) { if (! s.mixer.empty()) s.mixer[0].volume = 0.0f; }, false);
  11121. struct Step
  11122. {
  11123. juce::String name;
  11124. std::function<void()> setup;
  11125. std::function<void (int)> action; // per frame; none: the step watches the window for `frames` ms
  11126. int frames;
  11127. std::function<juce::String()> finish = {}; // round 173f: after the step, its own lines for the report
  11128. };
  11129. struct UiPerf final : juce::Timer
  11130. {
  11131. LynxApplication& app;
  11132. juce::File report;
  11133. juce::String text;
  11134. std::vector<Step> steps;
  11135. std::size_t step = 0;
  11136. int frame = -1;
  11137. std::vector<double> times, rendered; // whole frames (event + paint + blit, when this timer paints) / the window's paints
  11138. std::vector<double> frames; // round 173f: the time of every frame the window painted (ui/FrameProbe.h)
  11139. double paintedPixels = 0.0; // round 190ge: the dirty area of those frames, summed (overdraw / repaint storms)
  11140. double setupMs = 0.0, wallStart = 0.0;
  11141. double cpuStart = 0.0; // process CPU seconds (std::clock is wall time on Windows)
  11142. bool threadsWanted = juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_THREADS", {}) == "1";
  11143. std::vector<lynx::ThreadCpu> threadsStart;
  11144. double messageCpuStart = 0.0; // the message thread's CPU seconds
  11145. double audioLoadSum = 0.0; // the device's CPU use (AudioDeviceManager::getCpuUsage), summed per tick
  11146. int audioLoadTicks = 0;
  11147. UiPerf (LynxApplication& a, juce::File r) : app (a), report (std::move (r)) {}
  11148. juce::ComponentPeer* peer() const { return app.mainWindow != nullptr ? app.mainWindow->getPeer() : nullptr; }
  11149. double paintNow() const
  11150. {
  11151. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  11152. if (auto* p = peer())
  11153. p->performAnyPendingRepaintsNow();
  11154. return juce::Time::getMillisecondCounterHiRes() - t0;
  11155. }
  11156. void timerCallback() override
  11157. {
  11158. if (step >= steps.size())
  11159. {
  11160. stopTimer();
  11161. finish();
  11162. return;
  11163. }
  11164. auto& s = steps[step];
  11165. if (frame < 0)
  11166. {
  11167. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  11168. if (s.setup)
  11169. s.setup();
  11170. paintNow();
  11171. setupMs = juce::Time::getMillisecondCounterHiRes() - t0;
  11172. times.clear();
  11173. rendered.clear();
  11174. frames.clear();
  11175. paintedPixels = 0.0;
  11176. wallStart = juce::Time::getMillisecondCounterHiRes();
  11177. cpuStart = lynx::processCpuSeconds();
  11178. messageCpuStart = lynx::threadCpuSeconds();
  11179. if (threadsWanted) // round 190ih: LYNX_UIPERF_THREADS=1, the CPU of every thread over the step
  11180. threadsStart = lynx::threadCpuList();
  11181. lynx::grossBeatPaintStats (true);
  11182. audioLoadSum = 0.0;
  11183. audioLoadTicks = 0;
  11184. frame = 0;
  11185. return;
  11186. }
  11187. audioLoadSum += app.engine->getDeviceManager().getCpuUsage();
  11188. ++audioLoadTicks;
  11189. if (s.action)
  11190. s.action (frame);
  11191. if (const auto ms = paintNow(); ms > 0.25) // (nothing to paint: not a frame)
  11192. times.push_back (ms);
  11193. ++frame;
  11194. if (s.action ? frame < s.frames : juce::Time::getMillisecondCounterHiRes() - wallStart < (double) s.frames)
  11195. return;
  11196. const auto wall = juce::Time::getMillisecondCounterHiRes() - wallStart;
  11197. const auto cpu = 1000.0 * (lynx::processCpuSeconds() - cpuStart);
  11198. const auto messageCpu = 1000.0 * (lynx::threadCpuSeconds() - messageCpuStart);
  11199. text << s.name << ": show " << juce::String (setupMs, 1) << " ms\n"
  11200. << " painted frames: " << stats (rendered) << "\n"
  11201. << " timed here (event + paint + blit): " << stats (times)
  11202. << "\n window frames (probe): " << lynx::ui::FrameStats::of (frames, wall).describe()
  11203. << ", painted " << juce::String (wall > 0.0 ? paintedPixels / wall / 1000.0 : 0.0, 2) << " Mpx/s"
  11204. << "\n CPU " << juce::String (wall > 0.0 ? 100.0 * cpu / wall : 0.0, 0) << "% (process, " << juce::String (wall / 1000.0, 1) << " s), message thread "
  11205. << juce::String (wall > 0.0 ? 100.0 * messageCpu / wall : 0.0, 1) << "%, audio device "
  11206. << juce::String (audioLoadTicks > 0 ? 100.0 * audioLoadSum / audioLoadTicks : 0.0, 1) << "%\n";
  11207. if (threadsWanted && wall > 0.0)
  11208. {
  11209. std::vector<std::pair<double, juce::String>> rows;
  11210. for (const auto& t : lynx::threadCpuList())
  11211. {
  11212. auto before = 0.0;
  11213. for (const auto& b : threadsStart)
  11214. if (b.id == t.id)
  11215. before = b.seconds;
  11216. if (const auto used = t.seconds - before; used > 0.0005)
  11217. rows.push_back ({ 100.0 * 1000.0 * used / wall, juce::String (t.id) + " " + (t.name.empty() ? juce::String ("(unnamed)") : juce::String (t.name)) });
  11218. }
  11219. std::sort (rows.begin(), rows.end(), [] (const auto& a, const auto& b) { return a.first > b.first; });
  11220. text << " threads:";
  11221. for (std::size_t k = 0; k < rows.size() && k < 10; ++k)
  11222. text << " " << rows[k].second << " " << juce::String (rows[k].first, 1) << "%;";
  11223. text << "\n";
  11224. }
  11225. if (const auto gb = lynx::grossBeatPaintStats (false); gb.isNotEmpty())
  11226. text << " " << gb << "\n";
  11227. if (s.finish)
  11228. text << s.finish();
  11229. juce::File (report).replaceWithText (text);
  11230. ++step;
  11231. frame = -1;
  11232. }
  11233. static juce::String stats (std::vector<double> sorted)
  11234. {
  11235. std::sort (sorted.begin(), sorted.end());
  11236. 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()))]; };
  11237. double sum = 0.0;
  11238. int over = 0;
  11239. for (auto t : sorted)
  11240. {
  11241. sum += t;
  11242. over += t > 16.0 ? 1 : 0;
  11243. }
  11244. return juce::String ((int) sorted.size()) + ", mean " + juce::String (sorted.empty() ? 0.0 : sum / (double) sorted.size(), 1)
  11245. + " ms, p95 " + juce::String (at (0.95), 1) + " ms, max " + juce::String (sorted.empty() ? 0.0 : sorted.back(), 1)
  11246. + " ms, >16 ms " + juce::String (over);
  11247. }
  11248. void finish()
  11249. {
  11250. // the cost of asking where the mouse is (X11: a round trip to the display server)
  11251. const auto q0 = juce::Time::getMillisecondCounterHiRes();
  11252. for (int i = 0; i < 100; ++i)
  11253. juce::ignoreUnused (juce::Desktop::getInstance().getMainMouseSource().getScreenPosition());
  11254. text << "mouse position query: " << juce::String ((juce::Time::getMillisecondCounterHiRes() - q0) / 100.0, 3) << " ms\n";
  11255. app.mainWindow->onFrame = nullptr;
  11256. app.mainWindow->watchFrames ({});
  11257. app.engine->stop();
  11258. text << "result=OK\n";
  11259. report.replaceWithText (text);
  11260. app.setApplicationReturnValue (0);
  11261. app.quit();
  11262. }
  11263. };
  11264. auto* ui = &mainWindow->getContent();
  11265. auto wheelAt = [this] (juce::Component& target, float dx, float dy, juce::ModifierKeys mods) {
  11266. auto* peer = mainWindow->getPeer();
  11267. if (peer == nullptr || ! target.isShowing())
  11268. return;
  11269. juce::ModifierKeys::currentModifiers = mods;
  11270. const auto local = peer->globalToLocal (target.localPointToGlobal (target.getLocalBounds().getCentre()).toFloat());
  11271. juce::MouseWheelDetails wheel { dx, dy, false, false, false };
  11272. peer->handleMouseWheel (juce::MouseInputSource::InputSourceType::mouse, local, juce::Time::currentTimeMillis(), wheel);
  11273. juce::ModifierKeys::currentModifiers = {};
  11274. };
  11275. auto run = std::make_unique<UiPerf> (*this, report);
  11276. mainWindow->onFrame = [r = run.get()] (double ms) { if (r->frame >= 0) r->rendered.push_back (ms); };
  11277. // round 173f: every frame the window paints; a fader drag's moves count as shown when a frame covers the fader
  11278. auto drag = std::make_shared<UiPerfDrag>();
  11279. mainWindow->watchFrames ([r = run.get(), drag] (double now, juce::Rectangle<int> area) {
  11280. if (r->frame >= 0)
  11281. {
  11282. r->frames.push_back (now);
  11283. r->paintedPixels += (double) area.getWidth() * (double) area.getHeight();
  11284. }
  11285. drag->framePainted (now, area);
  11286. });
  11287. run->text << "project: " << project.getFullPathName() << "\n"
  11288. << "LYNX " << getApplicationVersion() << ", " << juce::SystemStats::getOperatingSystemName() << ", "
  11289. << juce::SystemStats::getCpuModel() << ", window " << mainWindow->getWidth() << "x" << mainWindow->getHeight()
  11290. << ", scale " << juce::String (juce::Desktop::getInstance().getDisplays().getPrimaryDisplay() != nullptr
  11291. ? juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->scale : 1.0, 2)
  11292. << ", audio device " << (engine->getDeviceManager().getCurrentAudioDevice() != nullptr ? engine->getDeviceManager().getCurrentAudioDevice()->getName() : juce::String ("none")) << "\n"
  11293. << "load " << juce::String (loadMs / 1000.0, 2) << " s\n";
  11294. const auto none = juce::ModifierKeys();
  11295. // discussion #10 (round 173f): the reporter's screen — the Channel Rack and the Mixer open, the pattern playing —
  11296. // watched as it is, then insert 3's fader dragged up and down with the mouse (125 moves a second through the
  11297. // window's own mouse path, the frames painted as the window paints them)
  11298. const auto dragTrack = engine->getSong().mixer.size() > 3 ? 3 : 1;
  11299. run->steps.push_back ({ "rack + mixer, pattern playing", [this, ui] {
  11300. ui->showPanelsForSnapshot ({ lynx::workspace::Panel::channelRack, lynx::workspace::Panel::mixer });
  11301. engine->getTransport().songMode = false;
  11302. engine->rewind();
  11303. engine->play();
  11304. }, {}, 4000 });
  11305. run->steps.push_back ({ "fader drag by mouse, rack + mixer, pattern playing", [this, ui, drag, dragTrack] {
  11306. auto& strips = ui->getMixerForSnapshot().getStripsForSnapshot();
  11307. const auto rail = strips.faderRailForSnapshot (dragTrack);
  11308. drag->start (*mainWindow, strips, rail, engine.get(), dragTrack);
  11309. }, {}, 3000, [drag] { return drag->stop(); } });
  11310. run->steps.push_back ({ "song stopped during the drag", {}, {}, 500, [drag] { return drag->release(); } });
  11311. run->steps.push_back ({ "after the drag (released)", {}, {}, 600, [drag] { return drag->released(); } });
  11312. run->steps.push_back ({ "desktop, playing", [this, ui] { ui->showDesktopForSnapshot (false); engine->rewind(); engine->play(); }, {}, 3000 });
  11313. run->steps.push_back ({ "mixer maximised, playing", [ui] { ui->selectTabForSnapshot (3); }, {}, 3000 });
  11314. // round 177a: only the meters move, so the strips' picture must stay valid, also with a folded group's tab and VCA
  11315. // strips on screen (their levels are drawn over the picture, like the inserts' meters)
  11316. run->steps.push_back ({ "mixer meters over the picture, playing", [this, ui] {
  11317. ui->selectTabForSnapshot (3);
  11318. engine->getTransport().songMode = false;
  11319. engine->rewind();
  11320. engine->play();
  11321. ui->getMixerForSnapshot().getStripsForSnapshot().cacheCountersForPerf();
  11322. }, {}, 6000, [this, ui, report] {
  11323. const auto [spoiled, refills] = ui->getMixerForSnapshot().getStripsForSnapshot().cacheCountersForPerf();
  11324. if (juce::FileOutputStream out (report.withFileExtension ("png")); out.openedOk())
  11325. {
  11326. out.setPosition (0);
  11327. out.truncate();
  11328. juce::PNGImageFormat().writeImageToStream (mainWindow->createComponentSnapshot (mainWindow->getLocalBounds()), out);
  11329. }
  11330. return juce::String (" mixer picture: spoiled ") + juce::String (spoiled) + " times, drawn again " + juce::String (refills) + " times\n";
  11331. } });
  11332. run->steps.push_back ({ "mixer scroll", {}, [wheelAt, ui, none] (int f) { wheelAt (ui->getMixerForSnapshot(), 0.0f, f < 30 ? -0.25f : 0.25f, none); }, 60 });
  11333. // a fader dragged while the song plays (round 171c, discussion #10): 4 mouse moves per frame on insert 1's fader,
  11334. // through the old path (a whole snapshot per move) and through editLevels
  11335. auto faderMove = [this] (bool levels, int f) {
  11336. for (int k = 0; k < 4; ++k)
  11337. {
  11338. const auto v = 0.5f + 0.3f * std::sin ((float) (f * 4 + k) * 0.05f);
  11339. const auto edit = [v] (lynx::Song& s) { if (s.mixer.size() > 1) s.mixer[1].volume = v; };
  11340. if (levels)
  11341. engine->editLevels (edit, false); // (no undo step: in a real drag only the press saves one)
  11342. else
  11343. engine->editSong (edit, false);
  11344. }
  11345. };
  11346. run->steps.push_back ({ "mixer fader drag, playing, rebuild per move (before 171c)", {}, [faderMove] (int f) { faderMove (false, f); }, 60 });
  11347. run->steps.push_back ({ "mixer fader drag, playing, live levels (171c)", {}, [faderMove, this] (int f) { faderMove (true, f); if (f == 59) engine->flushLevels(); }, 60 });
  11348. // F8's Plugin picker (round 171c): opening it (the "show" time = building it + its first paint), its pictures
  11349. // loading while it stays open, pointing at the tiles, then closing it
  11350. run->steps.push_back ({ "plugin picker open (F8)", [ui] { ui->togglePluginPickerForSnapshot(); }, {}, 2500 });
  11351. run->steps.push_back ({ "plugin picker, pointing at tiles", {}, [ui] (int f) {
  11352. // (round 175b: the picker is its own window)
  11353. if (auto* picker = ui->pluginPickerForSnapshot(); picker != nullptr && picker->getPeer() != nullptr)
  11354. {
  11355. const auto p = picker->localPointToGlobal (juce::Point<int> (60 + (f * 37) % juce::jmax (1, picker->getWidth() - 120),
  11356. 90 + (f * 53) % juce::jmax (1, picker->getHeight() - 200)));
  11357. const auto local = picker->getPeer()->globalToLocal (p.toFloat());
  11358. picker->getPeer()->handleMouseEvent (juce::MouseInputSource::InputSourceType::mouse, local, {}, 0.0f, 0.0f,
  11359. juce::Time::currentTimeMillis());
  11360. }
  11361. }, 60 });
  11362. run->steps.push_back ({ "plugin picker close", [ui] { ui->togglePluginPickerForSnapshot(); }, {}, 300 });
  11363. run->steps.push_back ({ "playlist maximised, playing", [ui] { ui->selectTabForSnapshot (2); }, {}, 3000 });
  11364. run->steps.push_back ({ "playlist scroll down/up", [this] { engine->stop(); },
  11365. [wheelAt, ui, none] (int f) { wheelAt (ui->getPlaylistForSnapshot(), 0.0f, f < 40 ? -0.15f : 0.15f, none); }, 80 });
  11366. run->steps.push_back ({ "playlist scroll sideways", {},
  11367. [wheelAt, ui, none] (int f) { wheelAt (ui->getPlaylistForSnapshot(), f < 40 ? -0.15f : 0.15f, 0.0f, none); }, 80 });
  11368. // round 174f: Ctrl+wheel zoom, a notch every third frame (~20 a second), three in then three out, as dupmon drives it
  11369. run->steps.push_back ({ "playlist zoom (Ctrl+wheel)", {},
  11370. [wheelAt, ui] (int f) {
  11371. if (f % 3 == 0)
  11372. wheelAt (ui->getPlaylistForSnapshot(), 0.0f, (f / 9) % 2 == 0 ? 0.15f : -0.15f, juce::ModifierKeys (juce::ModifierKeys::ctrlModifier));
  11373. }, 120 });
  11374. run->steps.push_back ({ "playlist after the zoom (settles)", {}, {}, 500 });
  11375. run->steps.push_back ({ "whole window repainted", {}, [this] (int) { mainWindow->repaint(); }, 40 });
  11376. run->steps.push_back ({ "channel rack scroll", [ui] { ui->selectTabForSnapshot (0); },
  11377. [wheelAt, ui, none] (int f) { wheelAt (ui->getRackViewportForSnapshot(), 0.0f, f < 30 ? -0.25f : 0.25f, none); }, 60 });
  11378. // round 190ge: the other main views while the pattern plays, then every view with the transport stopped and
  11379. // nothing moving (an idle view should paint nothing: its frames and painted area are the repaint storms), then
  11380. // the Clip-launch grid playing
  11381. auto playPattern = [this] {
  11382. engine->getTransport().songMode = false;
  11383. engine->rewind();
  11384. engine->play();
  11385. };
  11386. run->steps.push_back ({ "piano roll maximised, pattern playing", [ui, playPattern] { ui->selectTabForSnapshot (1); playPattern(); }, {}, 3000 });
  11387. run->steps.push_back ({ "channel rack maximised, pattern playing", [ui, playPattern] { ui->selectTabForSnapshot (0); playPattern(); }, {}, 3000 });
  11388. const char* idleViews[] { "channel rack", "piano roll", "playlist", "mixer" };
  11389. for (int view = 0; view < 4; ++view)
  11390. run->steps.push_back ({ juce::String ("idle: ") + idleViews[view] + ", stopped", [this, ui, view] { engine->stop(); ui->selectTabForSnapshot (view); }, {}, 3000 });
  11391. run->steps.push_back ({ "idle: desktop, stopped", [this, ui] { engine->stop(); ui->showDesktopForSnapshot (false); }, {}, 3000 });
  11392. run->steps.push_back ({ "clip grid, song playing", [this, ui] {
  11393. ui->selectTabForSnapshot (2);
  11394. ui->setClipLaunchWorkflow (true);
  11395. ui->setClipGridView (lynx::PlaylistArea::GridView::grid);
  11396. engine->getTransport().songMode = true;
  11397. engine->rewind();
  11398. engine->play();
  11399. }, {}, 3000 });
  11400. // round 190gr: the grid's clips launched (every scene that has clips, one after the other: the playing cells'
  11401. // progress bars move, the launches blink until their grid point)
  11402. run->steps.push_back ({ "clip grid, clips launched", [this] {
  11403. engine->getTransport().songMode = true;
  11404. if (const auto& grid = engine->getSong().clipGrid)
  11405. for (int scene = 0; scene < juce::jmin (8, (int) grid->scenes.size()); ++scene)
  11406. engine->launcherCommand ({ lynx::launcher::Command::Type::launchScene, 0, scene });
  11407. }, {}, 3000, [this] {
  11408. int playing = 0;
  11409. if (const auto* state = engine->launcherState())
  11410. for (const auto& t : state->tracks)
  11411. playing += t.playing.load() >= 0 ? 1 : 0;
  11412. engine->launcherCommand ({ lynx::launcher::Command::Type::stopAll });
  11413. return " tracks playing a clip: " + juce::String (playing) + "\n";
  11414. } });
  11415. run->steps.push_back ({ "idle: clip grid, stopped", [this] { engine->stop(); }, {}, 3000, [ui] { ui->setClipLaunchWorkflow (false); return juce::String(); } });
  11416. // round 190ih: the plugin windows with live parts — Gross Beat (its locator), the Formula Controller (its monitor),
  11417. // the Envelope Controller (its meters and key line) — idle with the song stopped, then Gross Beat while it plays
  11418. // (CPU and frames; the windows are their own, so the main window's painted area stays the main window's)
  11419. run->steps.push_back ({ "idle: Gross Beat + Formula + Envelope controller windows, stopped", [this] {
  11420. engine->stop();
  11421. auto& song = engine->getSong();
  11422. int gbTrack = -1, gbSlot = -1;
  11423. for (int t = 0; t < (int) song.mixer.size() && gbTrack < 0; ++t)
  11424. for (int k = 0; k < (int) song.mixer[(std::size_t) t].effects.size(); ++k)
  11425. if (song.mixer[(std::size_t) t].effects[(std::size_t) k].kind == lynx::EffectKind::grossBeat)
  11426. {
  11427. gbTrack = t;
  11428. gbSlot = k;
  11429. break;
  11430. }
  11431. const auto last = (int) song.mixer.size() - 1;
  11432. const auto formulaSlot = last >= 1 ? (int) song.mixer[(std::size_t) last].effects.size() : -1;
  11433. engine->editSong ([last] (lynx::Song& s) {
  11434. if (last >= 1 && s.mixer[(std::size_t) last].effects.size() < (std::size_t) lynx::maxEffectSlots)
  11435. s.mixer[(std::size_t) last].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::formulaController));
  11436. lynx::ChannelDef env;
  11437. env.name = "Envelope Controller";
  11438. env.instrument = lynx::InstrumentKind::controller;
  11439. env.controllerState = lynx::writeEnvelopeController (lynx::defaultEnvelopeController());
  11440. s.channels.push_back (env);
  11441. }, false);
  11442. engine->dispatchPendingMessages();
  11443. // LYNX_UIPERF_WINDOWS: which of them (G Gross Beat, F Formula, E Envelope Controller; default all)
  11444. const auto which = juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_WINDOWS", "GFE");
  11445. if (gbTrack >= 0 && which.containsChar ('G'))
  11446. lynx::NativeEffectWindows::open (*engine, gbTrack, gbSlot);
  11447. if (formulaSlot >= 0 && which.containsChar ('F'))
  11448. lynx::FormulaControllerWindows::open (*engine, last, formulaSlot);
  11449. if (which.containsChar ('E'))
  11450. lynx::openChannelSettings (*engine, (int) engine->getSong().channels.size() - 1);
  11451. }, {}, 3000 });
  11452. // round 190ih: LYNX_UIPERF_GBAB=n — n cycles over Gross Beat's live-display variants, playing, 2.5 s each, in one
  11453. // process (other load hits every variant alike): the names carry the LYNX_GB_DIAG mask
  11454. if (const auto cycles = juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_GBAB", "0").getIntValue(); cycles > 0)
  11455. {
  11456. run->steps.push_back ({ "Gross Beat A/B start", [this] {
  11457. engine->getTransport().songMode = true;
  11458. engine->rewind();
  11459. engine->play();
  11460. }, {}, 1500 });
  11461. // (off, the default, 30 / s, off, 10 / s; LYNX_UIPERF_GBAB_MASKS="1,2,0" picks others, e.g. round 190iy's
  11462. // locator on the GPU overlay (0) against the repaint path (2))
  11463. std::vector<int> masks { 1, 0, 30 << 8, 1, 10 << 8 };
  11464. if (const auto list = juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_GBAB_MASKS", {}); list.isNotEmpty())
  11465. {
  11466. masks.clear();
  11467. for (const auto& m : juce::StringArray::fromTokens (list, ",", {}))
  11468. masks.push_back (m.trim().getIntValue());
  11469. }
  11470. for (int c = 0; c < cycles; ++c)
  11471. for (const int mask : masks)
  11472. run->steps.push_back ({ "Gross Beat A/B mask " + juce::String (mask) + " cycle " + juce::String (c + 1),
  11473. [this, mask] {
  11474. lynx::setGrossBeatDiagnostics (mask);
  11475. if (! engine->getTransport().playing.load()) // (the song ended: again)
  11476. {
  11477. engine->rewind();
  11478. engine->play();
  11479. }
  11480. }, {}, 2500 });
  11481. }
  11482. run->steps.push_back ({ "Gross Beat window, song playing", [this] {
  11483. engine->getTransport().songMode = true;
  11484. engine->rewind();
  11485. engine->play();
  11486. }, {}, 3000, [this] {
  11487. engine->stop();
  11488. lynx::NativeEffectWindows::closeAll();
  11489. lynx::FormulaControllerWindows::closeAll();
  11490. return juce::String();
  11491. } });
  11492. // LYNX_UIPERF_ONLY=text: only the steps whose name has that text
  11493. if (const auto only = juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_ONLY", {}); only.isNotEmpty())
  11494. 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());
  11495. // let the window draw the project first
  11496. perf = std::move (run);
  11497. juce::Timer::callAfterDelay (1500, [this] { if (perf != nullptr) perf->startTimer (16); });
  11498. }
  11499. // --rtstress: opens the project in the normal window with the saved audio device, plays it from the start for
  11500. // `seconds` and writes the real-time statistics (deadline misses, late device calls, load histogram, heaviest units)
  11501. // --rtstress --backuptest N (round 177d): while the project plays, a device's MIDI clock (10/s) and active sensing
  11502. // (3/s) arrive, and the project counts as changed. N > 0 also forces a backup every N seconds on top of the timed ones.
  11503. // The report tells how many backups were written, when, and what the MIDI counters did.
  11504. struct BackupTest final : juce::Timer
  11505. {
  11506. lynx::AudioEngine* engine = nullptr;
  11507. lynx::MainComponent* ui = nullptr;
  11508. double everyMs = 0.0, startMs = 0.0, lastForcedMs = 0.0, longestCallMs = 0.0;
  11509. int ticks = 0, forced = 0;
  11510. std::uint64_t seenOver = 0, seenNear = 0;
  11511. juce::String misses; // each callback over (or near) its deadline: how long after the last forced backup
  11512. void timerCallback() override
  11513. {
  11514. engine->injectMidiInput (juce::MidiMessage (0xf8));
  11515. if (++ticks % 3 == 0)
  11516. engine->injectMidiInput (juce::MidiMessage (0xfe));
  11517. const auto now = juce::Time::getMillisecondCounterHiRes();
  11518. const auto s = engine->getRtStats().snapshot();
  11519. if (s.overBudget != seenOver || s.nearBudget != seenNear)
  11520. {
  11521. misses << " +" << juce::String ((now - lastForcedMs) / 1000.0, 1) << " s after the last forced backup (or the start): over +"
  11522. << (juce::int64) (s.overBudget - seenOver) << ", near +" << (juce::int64) (s.nearBudget - seenNear) << "\n";
  11523. seenOver = s.overBudget;
  11524. seenNear = s.nearBudget;
  11525. }
  11526. if (everyMs > 0.0 && now - lastForcedMs >= everyMs)
  11527. {
  11528. lastForcedMs = now;
  11529. ++forced;
  11530. ui->backupNowForTest();
  11531. longestCallMs = juce::jmax (longestCallMs, juce::Time::getMillisecondCounterHiRes() - now);
  11532. }
  11533. }
  11534. };
  11535. std::unique_ptr<BackupTest> backupTest;
  11536. void startBackupTest()
  11537. {
  11538. const auto& cli = juce::JUCEApplication::getCommandLineParameterArray();
  11539. const auto at = cli.indexOf ("--backuptest");
  11540. auto* ui = mainWindow != nullptr ? dynamic_cast<lynx::MainComponent*> (mainWindow->getContentComponent()) : nullptr;
  11541. if (at < 0 || ui == nullptr)
  11542. return;
  11543. backupTest = std::make_unique<BackupTest>();
  11544. backupTest->engine = engine.get();
  11545. backupTest->ui = ui;
  11546. backupTest->everyMs = cli[at + 1].getDoubleValue() * 1000.0;
  11547. backupTest->startMs = backupTest->lastForcedMs = juce::Time::getMillisecondCounterHiRes();
  11548. // (the project counts as changed, so a backup has something to write; the Master's fader is down, so a long run
  11549. // makes no sound: everything else is processed as usual)
  11550. engine->editSong ([] (lynx::Song& s) {
  11551. if (! s.mixer.empty())
  11552. s.mixer[0].volume = 0.0f;
  11553. });
  11554. backupTest->startTimer (100);
  11555. }
  11556. juce::String finishBackupTest()
  11557. {
  11558. if (backupTest == nullptr)
  11559. return {};
  11560. backupTest->stopTimer();
  11561. juce::String text;
  11562. const auto played = engine->getMidiPlayed();
  11563. text << " backup test: MIDI light count " << (int) engine->getMidiActivity() << ", played count " << (int) played << " (clock and active sensing only)\n";
  11564. text << " backup test: " << backupTest->forced << " forced, longest forced call on the message thread "
  11565. << juce::String (backupTest->longestCallMs, 1) << " ms\n";
  11566. if (backupTest->misses.isNotEmpty())
  11567. text << " backup test: callbacks over or near the deadline (seen within 100 ms):\n" << backupTest->misses;
  11568. auto files = lynx::autosaveFolder().findChildFiles (juce::File::findFiles, false, "*.lynx");
  11569. text << " backup test: " << files.size() << " file(s) in the backup folder:\n";
  11570. for (const auto& f : files)
  11571. text << " " << juce::String ((f.getLastModificationTime().toMilliseconds() - juce::Time::getCurrentTime().toMilliseconds()) / 1000) << " s before the end: "
  11572. << f.getFileName() << " (" << f.getSize() << " bytes)\n";
  11573. engine->injectMidiInput (juce::MidiMessage::noteOn (1, 60, (juce::uint8) 1));
  11574. engine->injectMidiInput (juce::MidiMessage::noteOff (1, 60));
  11575. text << " backup test: after a played note, played count " << (int) engine->getMidiPlayed() << "\n";
  11576. backupTest.reset();
  11577. return text;
  11578. }
  11579. void runRealtimeStress (const juce::File& project, const juce::File& report, double seconds, int bufferSize,
  11580. const juce::String& deviceType, const juce::String& deviceName, const juce::String& recordTo = {})
  11581. {
  11582. startupOptions = lynx::StartupOptions::load();
  11583. engine = std::make_unique<lynx::AudioEngine>();
  11584. lynx::videoview::install (*engine); // (Fruity Video Player channels: their sound tracks)
  11585. crashEngine = engine.get();
  11586. // the user's saved device stays as it was: this run's choices are undone before quitting
  11587. savedDeviceState = engine->getDeviceManager().createStateXml();
  11588. auto& devices = engine->getDeviceManager();
  11589. const auto driverFile = addDriverFileDeviceType();
  11590. const auto type = deviceType.isEmpty() && driverFile ? juce::String (lynx::dllAsioTypeName) : deviceType;
  11591. if (type.isNotEmpty() && devices.getCurrentAudioDeviceType() != type)
  11592. devices.setCurrentAudioDeviceType (type, true);
  11593. if (bufferSize > 0 || deviceName.isNotEmpty())
  11594. {
  11595. auto setup = devices.getAudioDeviceSetup();
  11596. if (bufferSize > 0)
  11597. setup.bufferSize = bufferSize;
  11598. if (deviceName.isNotEmpty())
  11599. setup.outputDeviceName = deviceName;
  11600. const auto error = devices.setAudioDeviceSetup (setup, true);
  11601. if (error.isNotEmpty())
  11602. report.replaceWithText ("device error: " + error + "\n");
  11603. }
  11604. createMainWindow();
  11605. if (! juce::JUCEApplication::getCommandLineParameters().contains ("--no-window")) // --no-window: is it the UI?
  11606. mainWindow->reveal();
  11607. juce::String error;
  11608. auto ok = false;
  11609. const auto loadStart = juce::Time::getMillisecondCounterHiRes();
  11610. if (project.hasFileExtension ("flp"))
  11611. ok = engine->importFlpFile (project, error);
  11612. else if (auto song = lynx::ProjectFile::load (project, error))
  11613. {
  11614. engine->setSong (std::move (*song));
  11615. ok = true;
  11616. }
  11617. const auto loadMs = juce::Time::getMillisecondCounterHiRes() - loadStart;
  11618. if (! ok)
  11619. {
  11620. report.replaceWithText ("project: " + project.getFullPathName() + "\nresult=ERROR " + error + "\n");
  11621. restoreSavedDeviceState();
  11622. setApplicationReturnValue (1);
  11623. quit();
  11624. return;
  11625. }
  11626. if (recordTo.isNotEmpty())
  11627. engine->setAudioRecordingArmed (true); // opens the input of the driver
  11628. // let the window draw the project, then play from the start with fresh statistics
  11629. juce::Timer::callAfterDelay (1500, [this, project, report, seconds, loadMs, recordTo] {
  11630. if (engine == nullptr)
  11631. return;
  11632. engine->stop();
  11633. engine->rewind();
  11634. engine->getRtStats().reset();
  11635. engine->takeUiPulse();
  11636. if (recordTo.isNotEmpty())
  11637. engine->setRecording (true);
  11638. // --log folder: the audio logger records what the Master plays during the run (realtime vs export checks)
  11639. const auto& cli = juce::JUCEApplication::getCommandLineParameterArray();
  11640. if (const auto at = cli.indexOf ("--log"); at >= 0 && at + 1 < cli.size())
  11641. engine->getAudioLogger().start (juce::File (cli[at + 1].unquoted()), engine->getDeviceManager().getCurrentAudioDevice() != nullptr
  11642. ? engine->getDeviceManager().getCurrentAudioDevice()->getCurrentSampleRate() : 44100.0);
  11643. engine->play();
  11644. startBackupTest();
  11645. juce::Timer::callAfterDelay ((int) (seconds * 1000.0), [this, project, report, seconds, loadMs, recordTo] {
  11646. if (engine == nullptr)
  11647. return;
  11648. const auto backupReport = finishBackupTest();
  11649. engine->stop();
  11650. juce::String recording;
  11651. if (engine->getAudioLogger().isLogging())
  11652. {
  11653. recording << " logged: " << engine->getAudioLogger().currentFile().getFullPathName() << "\n";
  11654. engine->getAudioLogger().stop();
  11655. }
  11656. if (recordTo.isNotEmpty())
  11657. recording = finishStressTake (juce::File (recordTo), seconds);
  11658. const auto& cli = juce::JUCEApplication::getCommandLineParameterArray();
  11659. const auto s = engine->getRtStats().snapshot();
  11660. juce::String text;
  11661. text << "project: " << project.getFullPathName() << "\n"
  11662. << "LYNX " << getApplicationVersion() << ", " << juce::SystemStats::getOperatingSystemName() << ", "
  11663. << juce::SystemStats::getNumCpus() << " logical CPUs (" << juce::SystemStats::getNumPhysicalCpus() << " cores), "
  11664. << juce::SystemStats::getCpuModel() << "\n"
  11665. << "load " << juce::String (loadMs / 1000.0, 1) << " s, played " << juce::String (seconds, 0) << " s\n"
  11666. << engine->describeRealtime();
  11667. const auto pulse = engine->takeUiPulse();
  11668. text << " UI: the 30 Hz engine timer ran " << pulse.calls << " times (" << juce::String (pulse.calls / seconds, 1)
  11669. << "/s), longest gap " << juce::String (pulse.maxGapMs, 0) << " ms" << (mainWindow == nullptr || ! mainWindow->isVisible() ? " (window hidden)" : "") << "\n";
  11670. text << " load histogram (share of the deadline: callbacks):";
  11671. for (std::size_t b = 0; b < s.histogram.size(); ++b)
  11672. if (s.histogram[b] > 0)
  11673. text << " " << (int) (b * 10) << (b + 1 == s.histogram.size() ? juce::String ("+") : "-" + juce::String ((int) (b * 10 + 10))) << "%:" << (juce::int64) s.histogram[b];
  11674. text << "\n";
  11675. text << recording << backupReport;
  11676. // --settingsshot file.png (round 161): Options > Audio settings of this run's device, as a picture
  11677. if (const auto at = cli.indexOf ("--settingsshot"); at >= 0 && at + 1 < cli.size())
  11678. {
  11679. auto page = lynx::makeSettingsPanel (*engine, lynx::SettingsPage::audio);
  11680. juce::Image image (juce::Image::ARGB, page->getWidth(), page->getHeight(), true);
  11681. {
  11682. juce::Graphics g (image);
  11683. g.fillAll (lynx::theme::panel);
  11684. page->paintEntireComponent (g, false);
  11685. }
  11686. const juce::File shot (cli[at + 1].unquoted());
  11687. shot.deleteFile();
  11688. if (auto out = shot.createOutputStream())
  11689. juce::PNGImageFormat().writeImageToStream (image, *out);
  11690. }
  11691. text << "result=" << (s.callbacks == 0 ? "ERROR no audio callbacks" : s.overBudget == 0 && s.lateCalls == 0 ? "OK" : "GLITCHES") << "\n";
  11692. report.replaceWithText (text);
  11693. restoreSavedDeviceState();
  11694. setApplicationReturnValue (s.callbacks == 0 ? 1 : 0);
  11695. quit();
  11696. });
  11697. });
  11698. }
  11699. // --bendrectest (round 167a): see the command line above
  11700. void runBendRecordTest (const juce::File& report, bool songMode)
  11701. {
  11702. engine = std::make_unique<lynx::AudioEngine>();
  11703. auto text = std::make_shared<juce::String>();
  11704. auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
  11705. auto finish = [this] (int code) {
  11706. setApplicationReturnValue (code);
  11707. quit();
  11708. };
  11709. auto* device = engine->getDeviceManager().getCurrentAudioDevice();
  11710. if (device == nullptr)
  11711. {
  11712. step ("result=ERROR no audio device");
  11713. finish (1);
  11714. return;
  11715. }
  11716. step ("device=" + device->getTypeName() + " | " + device->getName() + " | mode " + (songMode ? "song" : "pattern"));
  11717. auto song = lynx::Song::makeDefault();
  11718. song.bpm = 120.0;
  11719. song.mode = songMode ? lynx::PlayMode::song : lynx::PlayMode::pattern;
  11720. engine->setSong (std::move (song));
  11721. auto o = engine->getRecordOptions();
  11722. o.mode = lynx::RecordMode::overdub;
  11723. o.recordNotes = true;
  11724. o.recordAutomation = true;
  11725. o.countInBars = 0;
  11726. o.waitForInput = false;
  11727. o.quantiseAutomation = false;
  11728. o.punchLoopRegion = false;
  11729. o.preRollBars = o.postRollBars = 0;
  11730. engine->setRecordOptions (o);
  11731. engine->stop();
  11732. engine->rewind();
  11733. engine->setRecording (true);
  11734. engine->startPlayback();
  11735. // 2 s of wheel at ~100 messages a second: 0 → +1 (0.5 s), +1 → −1 (1 s), −1 → 0 (0.5 s)
  11736. auto sent = std::make_shared<std::vector<std::pair<double, float>>>();
  11737. auto t0 = std::make_shared<double> (juce::Time::getMillisecondCounterHiRes());
  11738. engine->injectMidiInput (juce::MidiMessage::noteOn (1, 60, (juce::uint8) 100));
  11739. auto tick = std::make_shared<std::function<void()>>();
  11740. *tick = [this, sent, t0, tick, step, finish, songMode] {
  11741. if (engine == nullptr)
  11742. return;
  11743. const auto ms = juce::Time::getMillisecondCounterHiRes() - *t0;
  11744. if (ms < 2000.0)
  11745. {
  11746. const auto x = ms / 1000.0;
  11747. 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);
  11748. const auto wheel = juce::jlimit (0, 16383, 8192 + juce::roundToInt (v * 8191.0f));
  11749. engine->injectMidiInput (juce::MidiMessage::pitchWheel (1, wheel));
  11750. sent->push_back ({ ms, (float) (wheel - 8192) / 8192.0f });
  11751. juce::Timer::callAfterDelay (10, *tick);
  11752. return;
  11753. }
  11754. engine->injectMidiInput (juce::MidiMessage::pitchWheel (1, 8192));
  11755. engine->injectMidiInput (juce::MidiMessage::noteOff (1, 60));
  11756. juce::Timer::callAfterDelay (400, [this, sent, step, finish, songMode] {
  11757. if (engine == nullptr)
  11758. return;
  11759. engine->stop();
  11760. juce::Timer::callAfterDelay (600, [this, sent, step, finish, songMode] {
  11761. if (engine == nullptr)
  11762. return;
  11763. engine->setRecording (false);
  11764. const auto& s = engine->getSong();
  11765. // the channel's pitch bend (MIDI channel 1), recorded as a lane or a clip
  11766. std::vector<std::pair<std::int64_t, float>> got;
  11767. juce::String where = "nothing";
  11768. for (const auto& a : s.automations)
  11769. if (a.target.kind == lynx::AutomationTargetKind::channelParam && lynx::midictl::isPitchBend (a.target.param))
  11770. {
  11771. where = "automation clip \"" + juce::String (a.name) + "\"";
  11772. for (const auto& pt : a.points)
  11773. got.push_back ({ pt.tick, pt.value });
  11774. }
  11775. for (const auto& p : s.patterns)
  11776. for (const auto& lane : p.events)
  11777. if (lane.target.kind == lynx::AutomationTargetKind::channelParam && lynx::midictl::isPitchBend (lane.target.param))
  11778. {
  11779. where = "pattern \"" + juce::String (p.name) + "\" event lane";
  11780. for (const auto& e : lane.events)
  11781. got.push_back ({ e.tick, e.value });
  11782. }
  11783. int notes = 0;
  11784. for (const auto& p : s.patterns)
  11785. notes += (int) p.notes.size();
  11786. float lo = 1.0f, hi = 0.0f;
  11787. for (const auto& [t, v] : got)
  11788. lo = std::min (lo, v), hi = std::max (hi, v);
  11789. // ticks: in order, spread over the ~2 s sweep (8 beats of 96 ticks at 120 bpm ≈ 4 beats)
  11790. const auto span = got.empty() ? 0 : got.back().first - got.front().first;
  11791. const auto sorted = std::is_sorted (got.begin(), got.end(), [] (const auto& a, const auto& b) { return a.first < b.first; });
  11792. step ("sent=" + juce::String ((int) sent->size()) + " wheel messages over 2 s");
  11793. step ("recorded=" + juce::String ((int) got.size()) + " points in " + where + ", value " + juce::String (lo, 3) + " .. "
  11794. + juce::String (hi, 3) + " (0.5 = centre), ticks " + juce::String (span) + " apart, " + (sorted ? "in order" : "OUT OF ORDER")
  11795. + ", notes " + juce::String (notes));
  11796. if (! got.empty())
  11797. step ("last=" + juce::String (got.back().second, 3));
  11798. // song mode: a clip over the take, ending back at the centre. Pattern mode: the take loops the 1-bar pattern
  11799. // (4.6 beats of take), so the lane spans the bar and the last wheel message (the centre) lands inside it
  11800. const auto centred = std::any_of (got.begin(), got.end(), [] (const auto& p) { return std::abs (p.second - 0.5f) < 0.02f; });
  11801. const auto ok = got.size() >= 20 && hi > 0.97f && lo < 0.03f && sorted && notes >= 1
  11802. && (songMode ? span > lynx::ppq * 3 && span < lynx::ppq * 6 && std::abs (got.back().second - 0.5f) < 0.02f
  11803. : span > lynx::ppq * 2 && span <= lynx::ppq * 4 && centred);
  11804. step (ok ? "result=OK" : "result=FAILED");
  11805. finish (ok ? 0 : 1);
  11806. });
  11807. });
  11808. };
  11809. juce::Timer::callAfterDelay (300, *tick);
  11810. }
  11811. // --countinrectest (round 170d): see the command line above.
  11812. void runCountInRecordTest (const juce::File& report)
  11813. {
  11814. engine = std::make_unique<lynx::AudioEngine>();
  11815. engine->getDeviceManager().closeAudioDevice(); // the engine's callback is driven by hand below
  11816. struct StandIn final : juce::AudioIODevice
  11817. {
  11818. StandIn() : juce::AudioIODevice ("countin", "test") {}
  11819. juce::StringArray getOutputChannelNames() override { return { "L", "R" }; }
  11820. juce::StringArray getInputChannelNames() override { return {}; }
  11821. juce::Array<double> getAvailableSampleRates() override { return { 48000.0 }; }
  11822. juce::Array<int> getAvailableBufferSizes() override { return { 512 }; }
  11823. int getDefaultBufferSize() override { return 512; }
  11824. juce::String open (const juce::BigInteger&, const juce::BigInteger&, double, int) override { return {}; }
  11825. void close() override {}
  11826. bool isOpen() override { return true; }
  11827. void start (juce::AudioIODeviceCallback*) override {}
  11828. void stop() override {}
  11829. bool isPlaying() override { return true; }
  11830. juce::String getLastError() override { return {}; }
  11831. int getCurrentBufferSizeSamples() override { return 512; }
  11832. double getCurrentSampleRate() override { return 48000.0; }
  11833. int getCurrentBitDepth() override { return 32; }
  11834. juce::BigInteger getActiveOutputChannels() const override
  11835. {
  11836. juce::BigInteger b;
  11837. b.setRange (0, 2, true);
  11838. return b;
  11839. }
  11840. juce::BigInteger getActiveInputChannels() const override { return {}; }
  11841. int getOutputLatencyInSamples() override { return 256; }
  11842. int getInputLatencyInSamples() override { return 0; }
  11843. };
  11844. auto device = std::make_shared<StandIn>();
  11845. auto text = std::make_shared<juce::String>();
  11846. auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
  11847. auto finish = [this] (int code) {
  11848. setApplicationReturnValue (code);
  11849. quit();
  11850. };
  11851. constexpr std::int64_t bar = 4 * lynx::ppq; // 120 BPM, 4/4
  11852. lynx::Song song; // (as --cliplooptest: one synth channel on insert 1, an empty pattern)
  11853. song.bpm = 120.0;
  11854. song.mixer = lynx::Song::defaultMixer (2);
  11855. song.channels.resize (1);
  11856. song.channels[0].mixerTrack = 1;
  11857. song.patterns.emplace_back();
  11858. song.mode = lynx::PlayMode::song;
  11859. song.currentPattern = 0;
  11860. engine->setSong (song);
  11861. engine->getTransport().metronome.store (true);
  11862. auto o = engine->getRecordOptions();
  11863. o.mode = lynx::RecordMode::overdub;
  11864. o.countInBars = 1;
  11865. o.catchWindow = lynx::ppq / 4;
  11866. o.compensateOutput = true;
  11867. o.recordNotes = true;
  11868. o.recordAudio = false;
  11869. o.recordAutomation = false;
  11870. o.waitForInput = false;
  11871. o.quantise = 0;
  11872. o.placeSongClip = true;
  11873. o.recordingMarkers = false;
  11874. o.punchLoopRegion = false;
  11875. o.preRollBars = o.postRollBars = 0;
  11876. engine->setRecordOptions (o);
  11877. engine->deviceCallback().audioDeviceAboutToStart (device.get());
  11878. 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");
  11879. // an event heard at output sample `heard` (counted from the first block after Play), sent as MIDI input
  11880. struct Event
  11881. {
  11882. std::int64_t heard;
  11883. juce::MidiMessage message;
  11884. };
  11885. struct Pass
  11886. {
  11887. std::vector<float> out;
  11888. std::vector<Event> events;
  11889. std::int64_t playingAt = -1; // the first sample of the block the song started in
  11890. int block = 0, blocks = 0;
  11891. std::function<void()> done;
  11892. };
  11893. constexpr int n = 512;
  11894. constexpr double rate = 48000.0;
  11895. // one pass: the take recorded from bar 3, `blocks` blocks driven by hand, 8 at a time between the engine's timer
  11896. // ticks (the take is committed there); then stopped and its results left to the timer
  11897. auto runPass = std::make_shared<std::function<void (std::shared_ptr<Pass>)>>();
  11898. *runPass = [this] (std::shared_ptr<Pass> pass) {
  11899. auto& cb = engine->deviceCallback();
  11900. std::vector<float> l (n), r (n);
  11901. float* outs[] = { l.data(), r.data() };
  11902. juce::AudioIODeviceCallbackContext context;
  11903. if (pass->block == 0)
  11904. {
  11905. engine->stop();
  11906. engine->seek ((double) (2 * bar));
  11907. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, n, context); // (the seek, stopped)
  11908. engine->setRecording (true);
  11909. engine->startPlayback(); // the count-in starts
  11910. }
  11911. for (int k = 0; k < 8 && pass->block < pass->blocks; ++k, ++pass->block)
  11912. {
  11913. // the events heard in this block: stamped the way the engine's clock maps time to heard samples
  11914. const auto blockStart = (std::int64_t) pass->block * n;
  11915. const auto clock = engine->liveClock();
  11916. const auto compMs = 1000.0 * (n + 256) / rate;
  11917. for (auto& e : pass->events)
  11918. if (e.heard >= blockStart && e.heard < blockStart + n)
  11919. {
  11920. auto m = e.message;
  11921. m.setTimeStamp ((clock.timeMs + compMs + (double) (e.heard - blockStart) * 1000.0 / rate) * 0.001);
  11922. engine->injectMidiInput (m);
  11923. }
  11924. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, n, context);
  11925. pass->out.insert (pass->out.end(), l.begin(), l.end());
  11926. if (pass->playingAt < 0 && engine->getTransport().playing.load())
  11927. pass->playingAt = blockStart;
  11928. }
  11929. };
  11930. // (the recursion through the message loop; written out so each step lets the engine's timer run)
  11931. auto drive = std::make_shared<std::function<void (std::shared_ptr<Pass>)>>();
  11932. *drive = [this, runPass, drive, device] (std::shared_ptr<Pass> pass) { // (the stand-in lives while the passes run)
  11933. if (engine == nullptr)
  11934. return;
  11935. (*runPass) (pass);
  11936. if (pass->block < pass->blocks)
  11937. {
  11938. juce::Timer::callAfterDelay (40, [pass, drive] { (*drive) (pass); });
  11939. return;
  11940. }
  11941. engine->stop();
  11942. juce::Timer::callAfterDelay (300, [this, pass] {
  11943. if (engine == nullptr)
  11944. return;
  11945. engine->setRecording (false);
  11946. juce::Timer::callAfterDelay (200, [pass] { pass->done(); });
  11947. });
  11948. };
  11949. auto onsets = [] (const std::vector<float>& out) {
  11950. std::vector<std::int64_t> at;
  11951. std::int64_t last = -100000;
  11952. for (std::size_t i = 0; i < out.size(); ++i)
  11953. if (std::abs (out[i]) > 0.02f && (std::int64_t) i - last > 4000)
  11954. {
  11955. at.push_back ((std::int64_t) i);
  11956. last = (std::int64_t) i;
  11957. }
  11958. else if (std::abs (out[i]) > 0.02f)
  11959. last = (std::int64_t) i;
  11960. return at;
  11961. };
  11962. // the graph is (re)built on the message thread: start once it has settled
  11963. juce::Timer::callAfterDelay (1500, [this, step, finish, drive, onsets] {
  11964. if (engine == nullptr)
  11965. return;
  11966. auto first = std::make_shared<Pass>();
  11967. first->blocks = (int) (rate * 18.0 / n); // count-in + 8 bars
  11968. first->done = [this, first, step, finish, drive, onsets] {
  11969. const auto clicks = onsets (first->out);
  11970. juce::String list;
  11971. for (std::size_t i = 0; i < std::min<std::size_t> (clicks.size(), 8); ++i)
  11972. list << clicks[i] << " ";
  11973. step ("pass 1: clicks heard at samples " + list + "…, the song started in the block at " + juce::String (first->playingAt));
  11974. // the bar-3 downbeat: the click at the block the song started in
  11975. std::int64_t down = -1;
  11976. for (auto c : clicks)
  11977. if (std::abs (c - first->playingAt) < n)
  11978. down = c;
  11979. if (down < 0 || engine->getSong().patterns[0].notes.size() != 0)
  11980. {
  11981. step ("result=FAILED no downbeat click found (or notes recorded without input)");
  11982. finish (1);
  11983. return;
  11984. }
  11985. const auto ms = [down] (double t) { return down + (std::int64_t) std::llround (t * rate / 1000.0); };
  11986. auto second = std::make_shared<Pass>();
  11987. second->blocks = first->blocks;
  11988. auto add = [&second] (std::int64_t at, int key, bool on) {
  11989. second->events.push_back ({ at, on ? juce::MidiMessage::noteOn (1, key, (juce::uint8) 100) : juce::MidiMessage::noteOff (1, key) });
  11990. };
  11991. for (int key : { 60, 64, 67 }) // the chord, 15 ms early, held half a second
  11992. {
  11993. add (ms (-15.0), key, true);
  11994. add (ms (500.0), key, false);
  11995. }
  11996. add (ms (-1500.0), 62, true); // beat 2 of the count-in bar (bar 2)
  11997. add (ms (-1250.0), 62, false);
  11998. add (ms (503.0), 77, true); // 3 ms after beat 2
  11999. add (ms (603.0), 77, false);
  12000. for (int b = 1; b <= 6; ++b) // a note a bar ("it stopped after two bars")
  12001. {
  12002. add (ms (b * 2000.0), 70 + b, true);
  12003. add (ms (b * 2000.0 + 250.0), 70 + b, false);
  12004. }
  12005. second->done = [this, step, finish] {
  12006. const auto& s = engine->getSong();
  12007. const auto& p = s.patterns[0];
  12008. const lynx::Clip* clip = nullptr;
  12009. for (const auto& c : s.playlist)
  12010. if (c.kind == lynx::ClipKind::pattern && c.pattern == 0)
  12011. clip = &c;
  12012. const auto origin = clip != nullptr ? clip->start - clip->offset : -1;
  12013. step ("pass 2: " + juce::String ((int) p.notes.size()) + " notes recorded, clip at " + juce::String (clip != nullptr ? clip->start : -1));
  12014. auto ok = clip != nullptr && origin == bar && p.notes.size() == 11;
  12015. // where each one was heard (song ticks): 0.5 ms = ~1 tick
  12016. const std::vector<std::pair<int, double>> want = { { 60, 2.0 * bar }, { 64, 2.0 * bar }, { 67, 2.0 * bar },
  12017. { 62, 2.0 * bar - 3 * lynx::ppq }, { 77, 2.0 * bar + lynx::ppq + 3.0 * 1.92 },
  12018. { 71, 3.0 * bar }, { 72, 4.0 * bar }, { 73, 5.0 * bar },
  12019. { 74, 6.0 * bar }, { 75, 7.0 * bar }, { 76, 8.0 * bar } };
  12020. for (const auto& [key, tick] : want)
  12021. {
  12022. const lynx::Note* found = nullptr;
  12023. for (const auto& note : p.notes)
  12024. if (note.key == key)
  12025. found = &note;
  12026. const auto at = found != nullptr ? (double) (origin + found->start) : -1.0;
  12027. const auto good = found != nullptr && std::abs (at - tick) <= 2.0;
  12028. ok = ok && good;
  12029. step ("key " + juce::String (key) + ": heard at tick " + juce::String (tick, 2) + ", recorded at " + juce::String (at, 0)
  12030. + (good ? " ok" : " WRONG"));
  12031. }
  12032. const auto* chord = [&p] () -> const lynx::Note* {
  12033. for (const auto& note : p.notes)
  12034. if (note.key == 60)
  12035. return &note;
  12036. return nullptr;
  12037. }();
  12038. if (chord != nullptr)
  12039. step ("chord length " + juce::String (chord->length) + " ticks (caught 15 ms early, released 500 ms after bar 3: 960)");
  12040. step (ok ? "result=OK" : "result=FAILED");
  12041. finish (ok ? 0 : 1);
  12042. };
  12043. (*drive) (second);
  12044. };
  12045. (*drive) (first);
  12046. });
  12047. }
  12048. // --cliplooptest (round 167q): see the command line above.
  12049. // --slicexedittest (round 190aj): see the command line above
  12050. void runDirectWaveEditTest (const juce::String& project, const juce::File& script, const juce::File& report, const juce::String& prefix)
  12051. {
  12052. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  12053. juce::StringArray lines;
  12054. {
  12055. lynx::AudioEngine offline (false);
  12056. lynx::MainComponent ui (offline, false);
  12057. ui.setSize (1280, 720);
  12058. if (project == "new")
  12059. {
  12060. if (auto c = lynx::natives::makeChannel (lynx::InstrumentKind::directwave, {}))
  12061. offline.editSong ([c] (lynx::Song& s) { s.channels.push_back (*c); });
  12062. }
  12063. else
  12064. ui.openFile (juce::File (project));
  12065. offline.dispatchPendingMessages();
  12066. int channel = -1;
  12067. for (int c = 0; c < (int) offline.getSong().channels.size() && channel < 0; ++c)
  12068. if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::directwave)
  12069. channel = c;
  12070. if (channel < 0)
  12071. lines.add ("no DirectWave channel in " + project);
  12072. else
  12073. {
  12074. auto panel = lynx::makeChannelSettingsPanel (offline, channel);
  12075. juce::Component frame;
  12076. frame.setSize (panel->getWidth(), panel->getHeight());
  12077. frame.setOpaque (true);
  12078. frame.addAndMakeVisible (*panel);
  12079. panel->setTopLeftPosition (0, 0);
  12080. offline.dispatchPendingMessages();
  12081. juce::StringArray commands;
  12082. script.readLines (commands);
  12083. for (const auto& raw : commands)
  12084. {
  12085. const auto command = raw.trim();
  12086. if (command.isEmpty() || command.startsWith ("#"))
  12087. {
  12088. lines.add (command);
  12089. continue;
  12090. }
  12091. if (command.startsWith ("shot "))
  12092. {
  12093. frame.setSize (panel->getWidth(), panel->getHeight());
  12094. juce::Image image (juce::Image::ARGB, frame.getWidth(), frame.getHeight(), true);
  12095. {
  12096. juce::Graphics g (image);
  12097. g.fillAll (lynx::theme::panel);
  12098. frame.paintEntireComponent (g, false);
  12099. }
  12100. const juce::File file (prefix + command.fromFirstOccurrenceOf (" ", false, false).trim() + ".png");
  12101. file.deleteFile();
  12102. juce::PNGImageFormat png;
  12103. if (auto out = file.createOutputStream())
  12104. png.writeImageToStream (image, *out);
  12105. lines.add (command + " -> " + file.getFileName());
  12106. continue;
  12107. }
  12108. if (command.startsWith ("savestate "))
  12109. {
  12110. const auto& st = offline.getSong().channels[(std::size_t) channel].pluginState;
  12111. juce::File (command.fromFirstOccurrenceOf (" ", false, false).trim()).replaceWithData (st.data(), st.size());
  12112. lines.add (command + " -> " + juce::String ((int) st.size()) + " bytes");
  12113. continue;
  12114. }
  12115. const auto result = lynx::directWaveEditorTest (*panel, command);
  12116. offline.dispatchPendingMessages();
  12117. lines.add (command + " -> " + result);
  12118. }
  12119. }
  12120. }
  12121. report.replaceWithText (lines.joinIntoString ("\n") + "\nresult=DONE\n");
  12122. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  12123. quit();
  12124. }
  12125. void runSlicexEditTest (const juce::File& project, const juce::File& script, const juce::File& report, const juce::String& prefix)
  12126. {
  12127. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  12128. juce::StringArray lines;
  12129. {
  12130. lynx::AudioEngine offline (false);
  12131. lynx::MainComponent ui (offline, false);
  12132. ui.setSize (1280, 720);
  12133. ui.openFile (project);
  12134. offline.dispatchPendingMessages();
  12135. int channel = -1;
  12136. for (int c = 0; c < (int) offline.getSong().channels.size() && channel < 0; ++c)
  12137. if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::slicex)
  12138. channel = c;
  12139. if (channel < 0)
  12140. lines.add ("no Slicex channel in " + project.getFullPathName());
  12141. else
  12142. {
  12143. auto panel = lynx::makeChannelSettingsPanel (offline, channel);
  12144. juce::Component frame;
  12145. frame.setSize (panel->getWidth(), panel->getHeight());
  12146. frame.setOpaque (true);
  12147. frame.addAndMakeVisible (*panel);
  12148. panel->setTopLeftPosition (0, 0);
  12149. offline.dispatchPendingMessages();
  12150. juce::StringArray commands;
  12151. script.readLines (commands);
  12152. for (const auto& raw : commands)
  12153. {
  12154. const auto command = raw.trim();
  12155. if (command.isEmpty() || command.startsWith ("#"))
  12156. {
  12157. lines.add (command);
  12158. continue;
  12159. }
  12160. if (command.startsWith ("shot "))
  12161. {
  12162. frame.setSize (panel->getWidth(), panel->getHeight()); // (round 190hg: the display modes resize the editor)
  12163. juce::Image image (juce::Image::ARGB, frame.getWidth(), frame.getHeight(), true);
  12164. {
  12165. juce::Graphics g (image);
  12166. g.fillAll (lynx::theme::panel);
  12167. frame.paintEntireComponent (g, false);
  12168. }
  12169. const juce::File file (prefix + command.fromFirstOccurrenceOf (" ", false, false).trim() + ".png");
  12170. file.deleteFile();
  12171. juce::PNGImageFormat png;
  12172. if (auto out = file.createOutputStream())
  12173. png.writeImageToStream (image, *out);
  12174. lines.add (command + " -> " + file.getFileName());
  12175. continue;
  12176. }
  12177. const auto result = lynx::slicexEditorTest (*panel, command);
  12178. offline.dispatchPendingMessages();
  12179. lines.add (command + " -> " + result);
  12180. }
  12181. }
  12182. }
  12183. report.replaceWithText (lines.joinIntoString ("\n") + "\nresult=DONE\n");
  12184. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  12185. quit();
  12186. }
  12187. // --slicexkeytest (round 190ac): see the command line above
  12188. void runSlicexKeyTest (const juce::File& report)
  12189. {
  12190. engine = std::make_unique<lynx::AudioEngine>();
  12191. engine->getDeviceManager().closeAudioDevice(); // the engine's callback is driven by hand below
  12192. struct StandIn final : juce::AudioIODevice
  12193. {
  12194. StandIn() : juce::AudioIODevice ("slicexkey", "test") {}
  12195. juce::StringArray getOutputChannelNames() override { return { "L", "R" }; }
  12196. juce::StringArray getInputChannelNames() override { return {}; }
  12197. juce::Array<double> getAvailableSampleRates() override { return { 48000.0 }; }
  12198. juce::Array<int> getAvailableBufferSizes() override { return { 512 }; }
  12199. int getDefaultBufferSize() override { return 512; }
  12200. juce::String open (const juce::BigInteger&, const juce::BigInteger&, double, int) override { return {}; }
  12201. void close() override {}
  12202. bool isOpen() override { return true; }
  12203. void start (juce::AudioIODeviceCallback*) override {}
  12204. void stop() override {}
  12205. bool isPlaying() override { return true; }
  12206. juce::String getLastError() override { return {}; }
  12207. int getCurrentBufferSizeSamples() override { return 512; }
  12208. double getCurrentSampleRate() override { return 48000.0; }
  12209. int getCurrentBitDepth() override { return 32; }
  12210. juce::BigInteger getActiveOutputChannels() const override
  12211. {
  12212. juce::BigInteger b;
  12213. b.setRange (0, 2, true);
  12214. return b;
  12215. }
  12216. juce::BigInteger getActiveInputChannels() const override { return {}; }
  12217. int getOutputLatencyInSamples() override { return 0; }
  12218. int getInputLatencyInSamples() override { return 0; }
  12219. };
  12220. auto device = std::make_shared<StandIn>();
  12221. auto text = std::make_shared<juce::String>();
  12222. auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
  12223. // 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
  12224. // × region number), so the region a key played can be read from the output
  12225. constexpr int rate = 48000, regionFrames = rate / 4;
  12226. const auto wavFile = report.getSiblingFile ("slicexkey-deck.wav");
  12227. {
  12228. juce::MemoryOutputStream w;
  12229. auto chunk = [&w] (const char* id, const juce::MemoryBlock& body) {
  12230. w.write (id, 4);
  12231. w.writeInt ((int) body.getSize());
  12232. w.write (body.getData(), body.getSize());
  12233. };
  12234. juce::MemoryOutputStream fmt, data, cue;
  12235. fmt.writeShort (1);
  12236. fmt.writeShort (1);
  12237. fmt.writeInt (rate);
  12238. fmt.writeInt (rate * 2);
  12239. fmt.writeShort (2);
  12240. fmt.writeShort (16);
  12241. for (int i = 0; i < 4 * regionFrames; ++i)
  12242. data.writeShort ((short) std::lround (12000.0 * std::sin (juce::MathConstants<double>::twoPi * 200.0 * (double) (i / regionFrames + 1) * (double) i / rate)));
  12243. cue.writeInt (4);
  12244. for (int k = 0; k < 4; ++k)
  12245. {
  12246. cue.writeInt (k + 1);
  12247. cue.writeInt (k * regionFrames);
  12248. cue.write ("data", 4);
  12249. cue.writeInt (0);
  12250. cue.writeInt (0);
  12251. cue.writeInt (k * regionFrames);
  12252. }
  12253. juce::MemoryOutputStream riff;
  12254. riff.write ("WAVE", 4);
  12255. w.reset();
  12256. chunk ("fmt ", fmt.getMemoryBlock());
  12257. chunk ("data", data.getMemoryBlock());
  12258. chunk ("cue ", cue.getMemoryBlock());
  12259. riff.write (w.getData(), w.getDataSize());
  12260. juce::MemoryOutputStream file;
  12261. file.write ("RIFF", 4);
  12262. file.writeInt ((int) riff.getDataSize());
  12263. file.write (riff.getData(), riff.getDataSize());
  12264. wavFile.replaceWithData (file.getData(), file.getDataSize());
  12265. }
  12266. lynx::Song song;
  12267. song.bpm = 120.0;
  12268. song.mixer = lynx::Song::defaultMixer (2);
  12269. song.channels.resize (1);
  12270. auto& channel = song.channels[0];
  12271. channel.instrument = lynx::InstrumentKind::slicex;
  12272. channel.mixerTrack = 1;
  12273. channel.samplePath = wavFile.getFullPathName().toStdString();
  12274. {
  12275. auto state = lynx::slicex::fresh();
  12276. lynx::slicex::setDeckFile (state, 0, channel.samplePath, 4);
  12277. lynx::slicex::setDeckBeats (state, 0, 0.0, 2.0);
  12278. channel.pluginState = lynx::slicex::write (state);
  12279. }
  12280. song.patterns.emplace_back();
  12281. engine->setSong (song);
  12282. auto& callback = engine->deviceCallback();
  12283. callback.audioDeviceAboutToStart (device.get());
  12284. 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");
  12285. juce::Timer::callAfterDelay (2000, [this, device, step] {
  12286. if (engine == nullptr)
  12287. return;
  12288. auto& cb = engine->deviceCallback();
  12289. auto pump = [&cb] (int blocks) {
  12290. std::vector<float> l (512), r (512), out;
  12291. float* outs[] = { l.data(), r.data() };
  12292. juce::AudioIODeviceCallbackContext context;
  12293. for (int k = 0; k < blocks; ++k)
  12294. {
  12295. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, 512, context);
  12296. out.insert (out.end(), l.begin(), l.end());
  12297. }
  12298. return out;
  12299. };
  12300. auto rms = [] (const std::vector<float>& x, int from, int count) {
  12301. double sum = 0.0;
  12302. for (int i = from; i < from + count && i < (int) x.size(); ++i)
  12303. sum += (double) x[(std::size_t) i] * x[(std::size_t) i];
  12304. return std::sqrt (sum / juce::jmax (1, count));
  12305. };
  12306. // the tone's frequency from its rising zero crossings over a stretch
  12307. auto hertz = [] (const std::vector<float>& x, int from, int count) {
  12308. int crossings = 0, first = -1, last = -1;
  12309. for (int i = from + 1; i < from + count && i < (int) x.size(); ++i)
  12310. if (x[(std::size_t) i - 1] < 0.0f && x[(std::size_t) i] >= 0.0f)
  12311. {
  12312. first = first < 0 ? i : first;
  12313. last = i;
  12314. ++crossings;
  12315. }
  12316. return crossings > 1 ? 48000.0 * (double) (crossings - 1) / (double) (last - first) : 0.0;
  12317. };
  12318. bool ok = true;
  12319. auto check = [&ok, step] (bool good, const juce::String& what) {
  12320. ok = ok && good;
  12321. step ((good ? "ok " : "FAIL ") + what);
  12322. };
  12323. const auto idle = pump (20);
  12324. engine->getMeters().takePeak (1, 0);
  12325. check (rms (idle, 0, (int) idle.size()) < 1.0e-6, "idle: rms " + juce::String (rms (idle, 0, (int) idle.size()), 9));
  12326. // 4 regions map to keys 60…63 (FL's automatic map); the editor's click: velocity 100 / 128
  12327. engine->sendLiveNote (0, 60, 0.78125f, true);
  12328. const auto first = pump (16); // 8192 frames = 171 ms, inside region 1 (250 ms)
  12329. const auto meter = engine->getMeters().takePeak (1, 0);
  12330. 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");
  12331. check (std::abs (hertz (first, 1024, 6000) - 200.0) < 4.0, "key 60 plays region 1 (200 Hz)");
  12332. check (meter > 0.01f, "mixer track 1 meter peak " + juce::String (meter, 6));
  12333. engine->sendLiveNote (0, 60, 0.0f, false);
  12334. const auto tail = pump (60);
  12335. 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));
  12336. engine->sendLiveNote (0, 62, 0.78125f, true);
  12337. const auto third = pump (16);
  12338. check (rms (third, 1024, 6000) > 0.01 && std::abs (hertz (third, 1024, 6000) - 600.0) < 8.0,
  12339. "key 62 plays region 3 (600 Hz): rms " + juce::String (rms (third, 1024, 6000), 6) + ", " + juce::String (hertz (third, 1024, 6000), 1) + " Hz");
  12340. engine->sendLiveNote (0, 62, 0.0f, false);
  12341. engine->sendLiveNote (0, 72, 0.78125f, true); // a key without a region
  12342. const auto none = pump (60);
  12343. 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));
  12344. engine->sendLiveNote (0, 72, 0.0f, false);
  12345. step (ok ? "result=OK" : "result=FAILED");
  12346. setApplicationReturnValue (ok ? 0 : 1);
  12347. quit();
  12348. });
  12349. }
  12350. // --renderaheadtest (round 190gq): see the command line above
  12351. void runRenderAheadTest (const juce::File& report, const juce::StringArray& projects, int block, double seconds)
  12352. {
  12353. struct StandIn final : juce::AudioIODevice
  12354. {
  12355. explicit StandIn (int b) : juce::AudioIODevice ("renderahead", "test"), block (b) {}
  12356. const int block;
  12357. juce::StringArray getOutputChannelNames() override { return { "L", "R" }; }
  12358. juce::StringArray getInputChannelNames() override { return {}; }
  12359. juce::Array<double> getAvailableSampleRates() override { return { 48000.0 }; }
  12360. juce::Array<int> getAvailableBufferSizes() override { return { block }; }
  12361. int getDefaultBufferSize() override { return block; }
  12362. juce::String open (const juce::BigInteger&, const juce::BigInteger&, double, int) override { return {}; }
  12363. void close() override {}
  12364. bool isOpen() override { return true; }
  12365. void start (juce::AudioIODeviceCallback*) override {}
  12366. void stop() override {}
  12367. bool isPlaying() override { return true; }
  12368. juce::String getLastError() override { return {}; }
  12369. int getCurrentBufferSizeSamples() override { return block; }
  12370. double getCurrentSampleRate() override { return 48000.0; }
  12371. int getCurrentBitDepth() override { return 32; }
  12372. juce::BigInteger getActiveOutputChannels() const override
  12373. {
  12374. juce::BigInteger b;
  12375. b.setRange (0, 2, true);
  12376. return b;
  12377. }
  12378. juce::BigInteger getActiveInputChannels() const override { return {}; }
  12379. int getOutputLatencyInSamples() override { return 0; }
  12380. int getInputLatencyInSamples() override { return 0; }
  12381. };
  12382. struct Scenario
  12383. {
  12384. juce::String name;
  12385. juce::File file; // a project, or none: the showcase song
  12386. int mode = 0; // 0 Song mode from the start, 1 a loop region, 2 Pattern mode
  12387. };
  12388. auto scenarios = std::make_shared<std::vector<Scenario>>();
  12389. scenarios->push_back ({ "showcase, Song mode", {}, 0 });
  12390. scenarios->push_back ({ "showcase, a loop region wrapping mid-block", {}, 1 });
  12391. scenarios->push_back ({ "showcase, Pattern mode", {}, 2 });
  12392. for (const auto& p : projects)
  12393. scenarios->push_back ({ juce::File (p).getFileName(), juce::File (p), 0 });
  12394. auto text = std::make_shared<juce::String>();
  12395. auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
  12396. step ("render-ahead test: blocks of " + juce::String (block) + " at 48 kHz, " + juce::String (seconds, 1) + " s per run");
  12397. auto outputs = std::make_shared<std::vector<std::vector<float>>>();
  12398. auto ok = std::make_shared<bool> (true);
  12399. auto run = std::make_shared<std::function<void (std::size_t, int)>>();
  12400. *run = [this, scenarios, step, outputs, ok, run, block, seconds, report] (std::size_t index, int pass) {
  12401. if (index >= scenarios->size())
  12402. {
  12403. lynx::renderAheadOption().store (true);
  12404. step (juce::String ("result=") + (*ok ? "OK" : "FAIL"));
  12405. setApplicationReturnValue (*ok ? 0 : 1);
  12406. engine.reset();
  12407. quit();
  12408. return;
  12409. }
  12410. const auto& sc = (*scenarios)[index];
  12411. lynx::renderAheadOption().store (pass == 1);
  12412. engine = std::make_unique<lynx::AudioEngine>();
  12413. engine->getDeviceManager().closeAudioDevice(); // the engine's callback is driven by hand below
  12414. engine->setRenderAheadAlways (true); // (the showcase song is light: the app would leave it real-time)
  12415. juce::String error;
  12416. auto loaded = true;
  12417. if (sc.file == juce::File())
  12418. {
  12419. auto song = lynx::makeShowcaseSong (0);
  12420. if (sc.mode == 1)
  12421. {
  12422. song.loopStart = 4 * lynx::ppq * song.beatsPerBar + 37; // (not on a block boundary)
  12423. song.loopEnd = 6 * lynx::ppq * song.beatsPerBar + 211;
  12424. song.loopOff = false;
  12425. }
  12426. if (sc.mode == 2)
  12427. song.mode = lynx::PlayMode::pattern;
  12428. engine->setSong (std::move (song));
  12429. }
  12430. else if (sc.file.hasFileExtension ("flp"))
  12431. loaded = engine->importFlpFile (sc.file, error);
  12432. else if (auto song = lynx::ProjectFile::load (sc.file, error))
  12433. engine->setSong (std::move (*song));
  12434. else
  12435. loaded = false;
  12436. if (! loaded)
  12437. {
  12438. step ("FAIL " + sc.name + ": " + error);
  12439. *ok = false;
  12440. (*run) (index + 1, 0);
  12441. return;
  12442. }
  12443. auto device = std::make_shared<StandIn> (block);
  12444. engine->deviceCallback().audioDeviceAboutToStart (device.get());
  12445. // the graph is (re)built on the message thread: the run starts once it has settled
  12446. juce::Timer::callAfterDelay (1500, [this, scenarios, step, outputs, ok, run, block, seconds, index, pass, device] {
  12447. if (engine == nullptr)
  12448. return;
  12449. const auto& sc = (*scenarios)[index];
  12450. auto& cb = engine->deviceCallback();
  12451. std::vector<float> l ((std::size_t) block), r ((std::size_t) block), out;
  12452. float* outs[] = { l.data(), r.data() };
  12453. juce::AudioIODeviceCallbackContext context;
  12454. engine->stop();
  12455. engine->seek (0.0);
  12456. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, block, context); // (the seek, stopped)
  12457. engine->play();
  12458. const auto blocks = (int) (seconds * 48000.0 / block);
  12459. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  12460. for (int k = 0; k < blocks; ++k)
  12461. {
  12462. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, block, context);
  12463. out.insert (out.end(), l.begin(), l.end());
  12464. out.insert (out.end(), r.begin(), r.end());
  12465. // (about the device's pace at the start of each second, so the render-ahead thread gets ahead)
  12466. if (k % (48000 / block) < 48000 / block / 2)
  12467. std::this_thread::sleep_for (std::chrono::microseconds ((int) (block * 1.0e6 / 48000.0 * 0.6)));
  12468. }
  12469. const auto ms = juce::Time::getMillisecondCounterHiRes() - t0;
  12470. engine->stop();
  12471. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, block, context);
  12472. const auto* st = engine->renderAheadStats();
  12473. auto n = [] (const std::atomic<std::uint64_t>& v) { return (juce::int64) v.load(); };
  12474. juce::String line = sc.name + (pass == 1 ? ", render ahead on: " : ", render ahead off: ") + juce::String (ms / 1000.0, 1) + " s";
  12475. if (st != nullptr && pass == 1)
  12476. line << "; blocks " << n (st->blocks) << ", from the ring " << n (st->fromRing) << ", waited " << n (st->waited) << ", in the callback "
  12477. << n (st->inline_) << ", dropped " << n (st->flushes) << ", drained " << n (st->drains) << ", started " << n (st->engagements)
  12478. << ", boundary mismatches " << n (st->splitMismatches) << "; ahead " << st->aheadChannels.load() << " channels / "
  12479. << st->aheadTracks.load() << " inserts, boundary " << st->boundary.load() << ", window " << st->window.load();
  12480. step (" " + line);
  12481. if (pass == 0)
  12482. {
  12483. outputs->assign (1, std::move (out));
  12484. (*run) (index, 1);
  12485. return;
  12486. }
  12487. const auto& off = outputs->front();
  12488. std::size_t first = off.size() == out.size() ? off.size() : 0;
  12489. for (std::size_t s = 0; s < std::min (off.size(), out.size()); ++s)
  12490. if (std::memcmp (&off[s], &out[s], sizeof (float)) != 0)
  12491. {
  12492. first = s;
  12493. break;
  12494. }
  12495. const auto same = off.size() == out.size() && first == off.size();
  12496. const auto clean = st != nullptr && st->flushes.load() == 0 && st->splitMismatches.load() == 0 && st->engagements.load() >= 1
  12497. && st->fromRing.load() > st->blocks.load() / 4;
  12498. *ok = *ok && same && clean;
  12499. 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))
  12500. + (clean ? "" : ", render-ahead counters off (see above)"));
  12501. (*run) (index + 1, 0);
  12502. });
  12503. };
  12504. (*run) (0, 0);
  12505. }
  12506. void runClipLoopTest (const juce::File& report, const juce::File& wavFile)
  12507. {
  12508. engine = std::make_unique<lynx::AudioEngine>();
  12509. engine->getDeviceManager().closeAudioDevice(); // the engine's callback is driven by hand below
  12510. struct StandIn final : juce::AudioIODevice
  12511. {
  12512. StandIn() : juce::AudioIODevice ("cliploop", "test") {}
  12513. juce::StringArray getOutputChannelNames() override { return { "L", "R" }; }
  12514. juce::StringArray getInputChannelNames() override { return {}; }
  12515. juce::Array<double> getAvailableSampleRates() override { return { 48000.0 }; }
  12516. juce::Array<int> getAvailableBufferSizes() override { return { 512 }; }
  12517. int getDefaultBufferSize() override { return 512; }
  12518. juce::String open (const juce::BigInteger&, const juce::BigInteger&, double, int) override { return {}; }
  12519. void close() override {}
  12520. bool isOpen() override { return true; }
  12521. void start (juce::AudioIODeviceCallback*) override {}
  12522. void stop() override {}
  12523. bool isPlaying() override { return true; }
  12524. juce::String getLastError() override { return {}; }
  12525. int getCurrentBufferSizeSamples() override { return 512; }
  12526. double getCurrentSampleRate() override { return 48000.0; }
  12527. int getCurrentBitDepth() override { return 32; }
  12528. juce::BigInteger getActiveOutputChannels() const override
  12529. {
  12530. juce::BigInteger b;
  12531. b.setRange (0, 2, true);
  12532. return b;
  12533. }
  12534. juce::BigInteger getActiveInputChannels() const override { return {}; }
  12535. int getOutputLatencyInSamples() override { return 0; }
  12536. int getInputLatencyInSamples() override { return 0; }
  12537. };
  12538. auto device = std::make_shared<StandIn>();
  12539. auto text = std::make_shared<juce::String>();
  12540. auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
  12541. constexpr int bar = 96000, beat = bar / 4; // 120 BPM, 48 kHz
  12542. const auto ppq = (double) lynx::ppq;
  12543. lynx::Song song;
  12544. song.bpm = 120.0;
  12545. song.mixer = lynx::Song::defaultMixer (2);
  12546. song.channels.resize (1); // the synth of a new channel: deterministic
  12547. song.channels[0].mixerTrack = 1;
  12548. auto& pattern = song.patterns.emplace_back(); // 1 bar: C5 on beat 0, C6 on beat 2
  12549. for (auto [b, key] : { std::pair { 0, 60 }, std::pair { 2, 72 } })
  12550. {
  12551. lynx::Note n;
  12552. n.start = b * lynx::ppq;
  12553. n.length = lynx::ppq / 4;
  12554. n.key = key;
  12555. pattern.notes.push_back (n);
  12556. }
  12557. lynx::Clip clip;
  12558. clip.pattern = 0;
  12559. clip.length = 16 * lynx::ppq; // stretched to 4 bars
  12560. song.playlist.push_back (clip);
  12561. song.mode = lynx::PlayMode::song;
  12562. {
  12563. // the Windows GUI check's project: the same song with a 1-bar clip, to stretch with the mouse
  12564. auto gui = song;
  12565. gui.playlist[0].length = 4 * lynx::ppq;
  12566. juce::String error;
  12567. lynx::ProjectFile::save (gui, report.getSiblingFile ("cliploop-gui.lynx"), error);
  12568. }
  12569. engine->setSong (song);
  12570. auto& callback = engine->deviceCallback();
  12571. callback.audioDeviceAboutToStart (device.get());
  12572. step ("song=1-bar synth pattern, clip stretched to 4 bars, 120 BPM, 48 kHz, blocks of 512");
  12573. // the graph is (re)built on the message thread: the scenarios run once it has settled
  12574. juce::Timer::callAfterDelay (1500, [this, device, step, wavFile, ppq] {
  12575. if (engine == nullptr)
  12576. return;
  12577. auto& cb = engine->deviceCallback();
  12578. // plays `samples` from tick `from` through the device callback; `between` runs after each block (block index)
  12579. auto play = [this, &cb] (double from, int samples, const std::function<void (int)>& between = {}) {
  12580. engine->stop();
  12581. engine->seek (from);
  12582. std::vector<float> l (512), r (512), out;
  12583. float* outs[] = { l.data(), r.data() };
  12584. juce::AudioIODeviceCallbackContext context;
  12585. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, 512, context); // (the seek, stopped)
  12586. engine->play();
  12587. for (int k = 0; (int) out.size() < samples; ++k)
  12588. {
  12589. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, 512, context);
  12590. out.insert (out.end(), l.begin(), l.end());
  12591. if (between)
  12592. between (k);
  12593. }
  12594. engine->stop();
  12595. for (int k = 0; k < 400; ++k) // the tails of the scenario die out
  12596. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, 512, context);
  12597. out.resize ((std::size_t) samples);
  12598. return out;
  12599. };
  12600. auto rms = [] (const std::vector<float>& x, int from, int count) {
  12601. double sum = 0.0;
  12602. for (int i = from; i < from + count && i < (int) x.size(); ++i)
  12603. sum += (double) x[(std::size_t) i] * x[(std::size_t) i];
  12604. return std::sqrt (sum / juce::jmax (1, count));
  12605. };
  12606. auto diff = [] (const std::vector<float>& a, int aFrom, const std::vector<float>& b, int bFrom, int count) {
  12607. double m = 0.0;
  12608. for (int i = 0; i < count && aFrom + i < (int) a.size() && bFrom + i < (int) b.size(); ++i)
  12609. m = juce::jmax (m, (double) std::abs (a[(std::size_t) (aFrom + i)] - b[(std::size_t) (bFrom + i)]));
  12610. return m;
  12611. };
  12612. auto num = [] (double v) { return juce::String (v, 6); };
  12613. bool ok = true;
  12614. auto check = [&ok, step] (bool good, const juce::String& what) {
  12615. ok = ok && good;
  12616. step ((good ? "ok " : "FAIL ") + what);
  12617. };
  12618. lynx::setStretchedClipsLoop (true);
  12619. const auto a = play (0.0, 4 * bar);
  12620. const auto bar1 = rms (a, 0, bar);
  12621. check (bar1 > 0.01, "play from the start: bar 1 RMS " + num (bar1));
  12622. for (int k = 1; k < 4; ++k)
  12623. {
  12624. const auto rk = rms (a, k * bar, bar), d = diff (a, k * bar, a, 0, bar);
  12625. check (std::abs (rk / bar1 - 1.0) < 1.0e-3 && d < 1.0e-4,
  12626. "bar " + juce::String (k + 1) + " RMS " + num (rk) + " (x" + num (rk / bar1) + " of bar 1), max |bar - bar 1| " + juce::String (d, 9));
  12627. }
  12628. {
  12629. const auto x = play (10 * ppq, bar + bar / 2);
  12630. const auto d = juce::jmax (diff (x, 0, a, 2 * beat, bar / 2), diff (x, bar / 2, a, 0, bar));
  12631. check (rms (x, 0, bar / 2) > 0.01 && d < 1.0e-4,
  12632. "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));
  12633. }
  12634. {
  12635. // a seek while playing, after 6.99 beats, to bar 4 beat 3 (a ruler click)
  12636. const auto jumpBlock = 7 * beat / 512 - 1;
  12637. const auto x = play (0.0, 2 * bar, [this, jumpBlock, ppq] (int k) {
  12638. if (k == jumpBlock)
  12639. engine->seek (14 * ppq);
  12640. });
  12641. // (the best of 0-2 samples late: anything but 0 fails)
  12642. const auto at = (jumpBlock + 1) * 512;
  12643. int lag = 0;
  12644. auto d = 1.0e9;
  12645. for (int l = 0; l <= 2; ++l)
  12646. if (const auto dl = diff (x, at + l, a, 2 * beat, beat - 2); dl < d)
  12647. d = dl, lag = l;
  12648. d = lag == 0 ? d : 1.0;
  12649. const auto ratio = rms (x, at, beat) / rms (a, 2 * beat, beat);
  12650. check (std::abs (ratio - 1.0) < 1.0e-3 && d < 1.0e-4,
  12651. "jump mid-clip to bar 4 beat 3: RMS " + num (rms (x, at, beat)) + " (x" + num (ratio) + " of bar 1 beat 3), max diff "
  12652. + juce::String (d, 9) + " (" + juce::String (lag) + " sample(s) late)");
  12653. }
  12654. {
  12655. engine->editSong ([ppq] (lynx::Song& s) {
  12656. s.loopStart = (std::int64_t) (4 * ppq);
  12657. s.loopEnd = (std::int64_t) (12 * ppq);
  12658. }, false);
  12659. const auto x = play (0.0, 7 * bar);
  12660. double d = 0.0;
  12661. juce::String lags;
  12662. for (int k = 1; k < 7; ++k) // (the best of 0-2 samples late after a wrap, as after a jump)
  12663. {
  12664. auto best = 1.0e9;
  12665. int lag = 0;
  12666. for (int l = 0; l <= 2; ++l)
  12667. if (const auto dl = diff (x, k * bar + l, a, 0, bar - 2); dl < best)
  12668. best = dl, lag = l;
  12669. d = juce::jmax (d, lag == 0 ? best : 1.0); // a sample gained at a wrap fails (round 167q loopwrap)
  12670. lags << (k > 1 ? "," : "") << lag;
  12671. }
  12672. const auto r = rms (x, bar, 6 * bar);
  12673. check (std::abs (r / bar1 - 1.0) < 1.0e-3 && d < 1.0e-4,
  12674. "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)
  12675. + " (samples late, bars 2-7: " + lags + ")");
  12676. engine->editSong ([] (lynx::Song& s) { s.loopStart = s.loopEnd = 0; }, false);
  12677. }
  12678. {
  12679. // 100 wraps of a 1-bar loop region (bar 2): every pass on its sample, none gained (round 167q loopwrap: each
  12680. // wrap used to play one sample more)
  12681. engine->editSong ([ppq] (lynx::Song& s) {
  12682. s.loopStart = (std::int64_t) (4 * ppq);
  12683. s.loopEnd = (std::int64_t) (8 * ppq);
  12684. }, false);
  12685. const auto x = play (0.0, 101 * bar);
  12686. double d = 0.0;
  12687. int worst = 0;
  12688. for (int k = 1; k <= 100; ++k)
  12689. if (const auto dk = diff (x, k * bar, a, 0, bar); dk > d)
  12690. d = dk, worst = k + 1;
  12691. check (d < 1.0e-4, "loop region bar 2, 100 wraps: max diff of every pass vs bar 1 " + juce::String (d, 9)
  12692. + (d < 1.0e-4 ? juce::String() : " (worst: bar " + juce::String (worst) + ")"));
  12693. engine->editSong ([] (lynx::Song& s) { s.loopStart = s.loopEnd = 0; }, false);
  12694. }
  12695. lynx::setStretchedClipsLoop (false);
  12696. {
  12697. const auto x = play (0.0, 4 * bar);
  12698. const auto r = juce::jmax (rms (x, bar, bar), juce::jmax (rms (x, 2 * bar, bar), rms (x, 3 * bar, bar)));
  12699. 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));
  12700. }
  12701. lynx::setStretchedClipsLoop (true);
  12702. cb.audioDeviceStopped();
  12703. // the export: a WAV of the 4 bars, read back from the file
  12704. if (wavFile != juce::File())
  12705. {
  12706. for (const auto loops : { true, false })
  12707. {
  12708. lynx::setStretchedClipsLoop (loops);
  12709. const auto file = loops ? wavFile : wavFile.getSiblingFile (wavFile.getFileNameWithoutExtension() + "-off.wav");
  12710. file.deleteFile();
  12711. {
  12712. juce::WavAudioFormat wav;
  12713. std::unique_ptr<juce::AudioFormatWriter> writer (wav.createWriterFor (file.createOutputStream().release(), 48000.0, 2, 32, {}, 0));
  12714. engine->stop();
  12715. engine->seek (0.0);
  12716. lynx::AudioEngine::RenderOptions o;
  12717. o.seconds = 8.0;
  12718. o.sampleRate = 48000.0;
  12719. o.output = writer.get();
  12720. engine->renderOffline (o);
  12721. }
  12722. juce::WavAudioFormat wav;
  12723. std::unique_ptr<juce::AudioFormatReader> reader (wav.createReaderFor (file.createInputStream().release(), true));
  12724. std::vector<float> x;
  12725. if (reader != nullptr)
  12726. {
  12727. juce::AudioBuffer<float> buffer (2, (int) reader->lengthInSamples);
  12728. reader->read (&buffer, 0, (int) reader->lengthInSamples, 0, true, true);
  12729. x.assign (buffer.getReadPointer (0), buffer.getReadPointer (0) + buffer.getNumSamples());
  12730. }
  12731. const auto b1 = rms (x, 0, bar);
  12732. juce::String line = juce::String (loops ? "export" : "export, option off") + " (" + file.getFileName() + ", " + juce::String ((int) x.size()) + " samples): bar 1 RMS " + num (b1);
  12733. bool good = x.size() >= (std::size_t) 4 * bar && b1 > 0.01;
  12734. for (int k = 1; k < 4; ++k)
  12735. {
  12736. const auto rk = rms (x, k * bar, bar);
  12737. line << ", bar " << (k + 1) << " " << num (rk);
  12738. 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);
  12739. }
  12740. if (loops)
  12741. 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);
  12742. check (good, line);
  12743. }
  12744. lynx::setStretchedClipsLoop (true);
  12745. }
  12746. step (ok ? "result=OK" : "result=FAILED");
  12747. setApplicationReturnValue (ok ? 0 : 1);
  12748. quit();
  12749. });
  12750. }
  12751. // --rectest (round 163): see the command line above. Writes report lines step by step (a driver that ends the
  12752. // process leaves what was done).
  12753. void runRecordTest (const juce::File& report, double seconds, const juce::String& deviceType, const juce::String& deviceName,
  12754. const juce::String& inputName, int mode, int pdcSamples, int bufferSize)
  12755. {
  12756. engine = std::make_unique<lynx::AudioEngine>();
  12757. lynx::videoview::install (*engine); // (Fruity Video Player channels: their sound tracks)
  12758. savedDeviceState = engine->getDeviceManager().createStateXml();
  12759. auto text = std::make_shared<juce::String>();
  12760. auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
  12761. auto finish = [this, step] (int code) {
  12762. restoreSavedDeviceState();
  12763. setApplicationReturnValue (code);
  12764. quit();
  12765. };
  12766. auto& devices = engine->getDeviceManager();
  12767. if (deviceType.isNotEmpty() && devices.getCurrentAudioDeviceType() != deviceType)
  12768. devices.setCurrentAudioDeviceType (deviceType, true);
  12769. {
  12770. auto setup = devices.getAudioDeviceSetup();
  12771. if (deviceName.isNotEmpty())
  12772. setup.outputDeviceName = deviceName;
  12773. if (bufferSize > 0)
  12774. setup.bufferSize = bufferSize;
  12775. if (const auto error = devices.setAudioDeviceSetup (setup, true); error.isNotEmpty())
  12776. step ("device_error=" + error);
  12777. }
  12778. if (const auto r = engine->openAudioInput (inputName.isNotEmpty() ? inputName : deviceName); r.issue != lynx::AudioEngine::InputIssue::none)
  12779. step ("input_error=" + juce::String ((int) r.issue) + " " + r.detail);
  12780. // takes go next to the report, not into the user's recordings folder
  12781. engine->setRecordingTarget (report.getSiblingFile (report.getFileNameWithoutExtension() + "-takes"), {});
  12782. auto* device = devices.getCurrentAudioDevice();
  12783. if (device == nullptr || engine->getInputChannelNames().empty())
  12784. {
  12785. step ("result=ERROR no device / no input");
  12786. finish (1);
  12787. return;
  12788. }
  12789. const auto rate = device->getCurrentSampleRate();
  12790. step ("device=" + device->getTypeName() + " | " + device->getName() + " | " + juce::String (rate) + " Hz | block " + juce::String (device->getCurrentBufferSizeSamples())
  12791. + " | driver latency in " + juce::String (device->getInputLatencyInSamples()) + " out " + juce::String (device->getOutputLatencyInSamples()));
  12792. // a click (the ping's pulse) on every beat at 120 bpm: beat k at sample k * rate / 2
  12793. const auto beats = (int) std::ceil (seconds * 2.0) + 8;
  12794. const auto clickFile = report.getSiblingFile (report.getFileNameWithoutExtension() + "-clicks.wav");
  12795. {
  12796. lynx::takes::WavTakeWriter w;
  12797. w.open (clickFile.getFullPathName().toStdString(), rate, 1, lynx::takes::SampleFormat::float32);
  12798. const auto total = (juce::int64) std::llround ((double) beats * rate / 2.0);
  12799. std::vector<float> block (4096);
  12800. for (juce::int64 at = 0; at < total; at += (juce::int64) block.size())
  12801. {
  12802. std::fill (block.begin(), block.end(), 0.0f);
  12803. for (int k = 0; k < (int) block.size(); ++k)
  12804. {
  12805. const auto f = at + k;
  12806. const auto beat = (juce::int64) std::floor ((double) f / (rate / 2.0));
  12807. const auto rel = f - (juce::int64) std::llround ((double) beat * rate / 2.0);
  12808. static constexpr float shape[] { 0.25f, 0.75f, 1.0f, 0.75f, 0.25f };
  12809. if (rel >= 0 && rel < 5)
  12810. block[(std::size_t) k] = 0.5f * shape[rel];
  12811. }
  12812. const float* d[] { block.data() };
  12813. w.write (d, (int) std::min<juce::int64> ((juce::int64) block.size(), total - at));
  12814. }
  12815. w.close();
  12816. }
  12817. lynx::Song song = lynx::Song::makeDefault();
  12818. song.bpm = 120.0;
  12819. song.mode = lynx::PlayMode::song;
  12820. song.playlist.clear();
  12821. lynx::ChannelDef c;
  12822. c.name = "Clicks";
  12823. c.instrument = lynx::InstrumentKind::audioClip;
  12824. c.samplePath = clickFile.getFullPathName().toStdString();
  12825. c.mixerTrack = 0;
  12826. c.volume = 1.0f;
  12827. song.channels.push_back (c);
  12828. lynx::Clip clip;
  12829. clip.kind = lynx::ClipKind::audio;
  12830. clip.channel = (int) song.channels.size() - 1;
  12831. clip.track = 0;
  12832. clip.start = 0;
  12833. clip.length = (std::int64_t) beats * lynx::ppq;
  12834. song.playlist.push_back (clip);
  12835. if (mode == 1) // loop recording, bars 2-4
  12836. {
  12837. song.loopStart = 4 * lynx::ppq;
  12838. song.loopEnd = 16 * lynx::ppq;
  12839. }
  12840. else if (mode == 2) // punch in/out, bars 3-4
  12841. {
  12842. song.loopStart = 8 * lynx::ppq;
  12843. song.loopEnd = 16 * lynx::ppq;
  12844. }
  12845. if (song.mixer.size() > 1)
  12846. {
  12847. song.mixer[1].name = "Loop In";
  12848. song.mixer[1].monitor = lynx::InputMonitor::off; // (the loopback must not hear itself)
  12849. }
  12850. engine->setSong (std::move (song));
  12851. engine->setInsertInput (1, 0, false);
  12852. juce::ignoreUnused (pdcSamples);
  12853. // 1) the ping
  12854. if (const auto error = engine->startLatencyPing(); error.isNotEmpty())
  12855. step ("ping_error=" + error);
  12856. juce::Timer::callAfterDelay (3500, [this, step, finish, seconds, rate, report, mode] {
  12857. if (engine == nullptr)
  12858. return;
  12859. if (engine->isPinging())
  12860. engine->cancelLatencyPing();
  12861. const auto r = engine->finishLatencyPing();
  12862. step ("ping=" + juce::String (r.ok ? "ok" : "FAILED " + juce::String (r.problem)) + " samples " + juce::String (r.samples) + " spread " + juce::String (r.spread)
  12863. + " found " + juce::String (r.found) + "/" + juce::String (r.sent) + " peak " + juce::String (juce::Decibels::gainToDecibels (r.peak, -150.0f), 1) + " dB");
  12864. const auto l = engine->currentLatency();
  12865. step ("compensation=" + juce::String (l.total()) + " (round trip " + juce::String (l.roundTrip()) + ", manual " + juce::String (l.manual) + ", pdc " + juce::String (l.pdc) + ")");
  12866. // 2) record
  12867. engine->setInsertArmed (1, true);
  12868. auto o = engine->getRecordOptions();
  12869. o.recordAudio = true;
  12870. o.countInBars = 0;
  12871. o.waitForInput = false;
  12872. o.punchLoopRegion = mode == 2;
  12873. o.preRollBars = mode == 2 ? 1 : 0;
  12874. o.postRollBars = mode == 2 ? 1 : 0;
  12875. // (round 177c: LYNX_RECTEST_BLEND_OFF=1: Blend off; LYNX_RECTEST_LAST_PASS=1: "only the last pass plays")
  12876. o.mode = juce::SystemStats::getEnvironmentVariable ("LYNX_RECTEST_BLEND_OFF", {}) == "1" ? lynx::RecordMode::replace
  12877. : lynx::RecordMode::overdub;
  12878. o.lastLoopPassPlays = juce::SystemStats::getEnvironmentVariable ("LYNX_RECTEST_LAST_PASS", {}) == "1";
  12879. engine->setRecordOptions (o);
  12880. engine->stop();
  12881. engine->rewind();
  12882. engine->setRecording (true);
  12883. juce::Timer::callAfterDelay (300, [this, step, finish, seconds, rate, report, mode] {
  12884. if (engine == nullptr)
  12885. return;
  12886. engine->startPlayback(); // (as the Play button: pre-roll / punch)
  12887. juce::Timer::callAfterDelay ((int) (seconds * 1000.0), [this, step, finish, seconds, rate, report, mode] {
  12888. if (engine == nullptr)
  12889. return;
  12890. if (mode == 2)
  12891. step (juce::String ("stopped_by_post_roll=") + (engine->getTransport().playing.load() ? "no" : "yes"));
  12892. engine->stop();
  12893. juce::Timer::callAfterDelay (500, [this, step, finish, seconds, rate, report, mode] {
  12894. if (engine == nullptr)
  12895. return;
  12896. engine->setRecording (false);
  12897. const auto& s = engine->getSong();
  12898. const auto tps = 120.0 * lynx::ppq / (60.0 * rate);
  12899. int take = -1;
  12900. for (int ch = 0; ch < (int) s.channels.size(); ++ch)
  12901. if (s.channels[(std::size_t) ch].instrument == lynx::InstrumentKind::audioClip && s.channels[(std::size_t) ch].name != "Clicks")
  12902. take = ch;
  12903. if (take < 0)
  12904. {
  12905. step ("result=ERROR no take (" + engine->getLastRecordingError() + ")");
  12906. finish (1);
  12907. return;
  12908. }
  12909. std::vector<std::vector<float>> audio;
  12910. double takeRate = 0.0;
  12911. const auto& path = s.channels[(std::size_t) take].samplePath;
  12912. lynx::takes::readWav (path, audio, &takeRate);
  12913. const auto frames = audio.empty() ? (juce::int64) 0 : (juce::int64) audio[0].size();
  12914. step ("take=" + juce::String::fromUTF8 (path.c_str()) + " frames " + juce::String (frames) + " (" + juce::String ((double) frames / rate, 3)
  12915. + " s of " + juce::String (seconds, 1) + " s played) lost " + juce::String (engine->getLostRecordingFrames()));
  12916. // the clicks in the file (peaks above -12 dBFS, one per 1/8 s at most)
  12917. std::vector<juce::int64> peaks;
  12918. if (! audio.empty())
  12919. for (juce::int64 f = 1; f + 1 < frames; ++f)
  12920. {
  12921. const auto x = std::abs (audio[0][(std::size_t) f]);
  12922. if (x > 0.25f && x >= std::abs (audio[0][(std::size_t) f - 1]) && x > std::abs (audio[0][(std::size_t) f + 1])
  12923. && (peaks.empty() || f - peaks.back() > (juce::int64) (rate / 8)))
  12924. peaks.push_back (f);
  12925. }
  12926. // every clip of the take: each click inside it against the nearest beat
  12927. int clips = 0, checked = 0, muted = 0;
  12928. double worst = 0.0, sum = 0.0;
  12929. for (const auto& c : s.playlist)
  12930. {
  12931. if (c.kind != lynx::ClipKind::audio || c.channel != take)
  12932. continue;
  12933. ++clips;
  12934. muted += c.muted ? 1 : 0;
  12935. const auto skip = ((double) c.offset + (double) c.offsetFraction) / tps; // file samples before the clip start
  12936. for (const auto f : peaks)
  12937. {
  12938. const auto intoClip = (double) f - skip;
  12939. if (intoClip < 0.0 || intoClip * tps >= (double) c.length)
  12940. continue;
  12941. const auto songTick = (double) c.start + intoClip * tps - 2.0 * tps; // (the pulse's peak is its 3rd sample)
  12942. const auto beat = std::round (songTick / lynx::ppq) * lynx::ppq;
  12943. const auto error = (songTick - beat) / tps;
  12944. worst = std::max (worst, std::abs (error));
  12945. sum += error;
  12946. ++checked;
  12947. }
  12948. step ("clip track " + juce::String (c.track) + " start " + juce::String ((juce::int64) c.start) + " length " + juce::String ((juce::int64) c.length)
  12949. + " offset " + juce::String ((juce::int64) c.offset) + juce::String (c.offsetFraction >= 0.0f ? "+" : "") + juce::String (c.offsetFraction, 4)
  12950. + (c.muted ? " (muted lane)" : ""));
  12951. }
  12952. step ("clicks_in_file=" + juce::String ((int) peaks.size()) + " checked=" + juce::String (checked) + " clips=" + juce::String (clips)
  12953. + " muted_lanes=" + juce::String (muted));
  12954. step ("placement_error_samples=max " + juce::String (worst, 3) + " mean " + juce::String (checked > 0 ? sum / checked : 0.0, 3));
  12955. auto ok = checked > 0 && worst <= 1.0 && engine->getLostRecordingFrames() == 0;
  12956. if (mode == 2) // one clip, exactly the punch range, its 8 beats
  12957. {
  12958. const auto& sp = engine->getSong();
  12959. bool exact = false;
  12960. for (const auto& c : sp.playlist)
  12961. if (c.kind == lynx::ClipKind::audio && c.channel == take)
  12962. exact = c.start == sp.loopStart && c.start + c.length == sp.loopEnd;
  12963. step (juce::String ("punch_clip_matches_range=") + (exact ? "yes" : "no"));
  12964. ok = ok && clips == 1 && exact && checked == 8;
  12965. }
  12966. report.getSiblingFile (report.getFileNameWithoutExtension() + "-project.lynx").replaceWithText (lynx::ProjectFile::toJson (engine->getSong()));
  12967. step (juce::String ("result=") + (ok ? "OK" : "FAILED"));
  12968. finish (ok ? 0 : 1);
  12969. });
  12970. });
  12971. });
  12972. });
  12973. }
  12974. // --hwinserttest (round 164d): see the command line above.
  12975. void runHwInsertTest (const juce::File& report, double seconds, const juce::String& deviceType, const juce::String& deviceName,
  12976. const juce::String& inputName, int bufferSize, bool inPatcher = false, juce::File bounceFile = {})
  12977. {
  12978. engine = std::make_unique<lynx::AudioEngine>();
  12979. lynx::videoview::install (*engine); // (Fruity Video Player channels: their sound tracks)
  12980. savedDeviceState = engine->getDeviceManager().createStateXml();
  12981. auto text = std::make_shared<juce::String>();
  12982. auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
  12983. auto finish = [this] (int code) {
  12984. if (engine != nullptr)
  12985. engine->getMeters().capture.setSource (lynx::AudioCapture::off);
  12986. restoreSavedDeviceState();
  12987. setApplicationReturnValue (code);
  12988. quit();
  12989. };
  12990. auto& devices = engine->getDeviceManager();
  12991. if (deviceType.isNotEmpty() && devices.getCurrentAudioDeviceType() != deviceType)
  12992. devices.setCurrentAudioDeviceType (deviceType, true);
  12993. {
  12994. auto setup = devices.getAudioDeviceSetup();
  12995. if (deviceName.isNotEmpty())
  12996. setup.outputDeviceName = deviceName;
  12997. if (bufferSize > 0)
  12998. setup.bufferSize = bufferSize;
  12999. if (const auto error = devices.setAudioDeviceSetup (setup, true); error.isNotEmpty())
  13000. step ("device_error=" + error);
  13001. }
  13002. if (const auto r = engine->openAudioInput (inputName.isNotEmpty() ? inputName : deviceName); r.issue != lynx::AudioEngine::InputIssue::none)
  13003. step ("input_error=" + juce::String ((int) r.issue) + " " + r.detail);
  13004. auto* device = devices.getCurrentAudioDevice();
  13005. if (device == nullptr || engine->getInputChannelNames().empty())
  13006. {
  13007. step ("result=ERROR no device / no input");
  13008. finish (1);
  13009. return;
  13010. }
  13011. const auto rate = device->getCurrentSampleRate();
  13012. step ("device=" + device->getTypeName() + " | " + device->getName() + " | " + juce::String (rate) + " Hz | block " + juce::String (device->getCurrentBufferSizeSamples()));
  13013. // the click track: the ping's pulse on every beat at 120 bpm
  13014. const auto beats = (int) std::ceil (seconds * 2.0) + 8;
  13015. const auto clickFile = report.getSiblingFile (report.getFileNameWithoutExtension() + "-clicks.wav");
  13016. {
  13017. lynx::takes::WavTakeWriter w;
  13018. w.open (clickFile.getFullPathName().toStdString(), rate, 1, lynx::takes::SampleFormat::float32);
  13019. const auto total = (juce::int64) std::llround ((double) beats * rate / 2.0);
  13020. std::vector<float> block (4096);
  13021. for (juce::int64 at = 0; at < total; at += (juce::int64) block.size())
  13022. {
  13023. std::fill (block.begin(), block.end(), 0.0f);
  13024. for (int k = 0; k < (int) block.size(); ++k)
  13025. {
  13026. const auto f = at + k;
  13027. const auto beat = (juce::int64) std::floor ((double) f / (rate / 2.0));
  13028. const auto rel = f - (juce::int64) std::llround ((double) beat * rate / 2.0);
  13029. static constexpr float shape[] { 0.25f, 0.75f, 1.0f, 0.75f, 0.25f };
  13030. if (rel >= 0 && rel < 5)
  13031. block[(std::size_t) k] = 0.5f * shape[rel];
  13032. }
  13033. const float* d[] { block.data() };
  13034. w.write (d, (int) std::min<juce::int64> ((juce::int64) block.size(), total - at));
  13035. }
  13036. w.close();
  13037. }
  13038. lynx::Song song = lynx::Song::makeDefault();
  13039. song.bpm = 120.0;
  13040. song.mode = lynx::PlayMode::song;
  13041. song.playlist.clear();
  13042. song.channels.clear();
  13043. for (int k = 0; k < 2; ++k)
  13044. {
  13045. lynx::ChannelDef c;
  13046. c.name = k == 0 ? "Wet" : "Dry";
  13047. c.instrument = lynx::InstrumentKind::audioClip;
  13048. c.samplePath = clickFile.getFullPathName().toStdString();
  13049. c.mixerTrack = k + 1;
  13050. c.volume = 1.0f;
  13051. song.channels.push_back (c);
  13052. lynx::Clip clip;
  13053. clip.kind = lynx::ClipKind::audio;
  13054. clip.channel = k;
  13055. clip.track = k;
  13056. clip.start = 0;
  13057. clip.length = (std::int64_t) beats * lynx::ppq;
  13058. song.playlist.push_back (clip);
  13059. }
  13060. song.mixer[0].outputChannel = lynx::outputNone; // (the cable carries the send only)
  13061. for (auto& fx : song.mixer[0].effects) // (no Master effects: the default limiter's PDC would hide nothing, but keep it plain)
  13062. fx.enabled = false;
  13063. song.mixer[1].pan = -1.0f;
  13064. song.mixer[2].pan = 1.0f;
  13065. auto hw = lynx::makeEffectSlot (lynx::EffectKind::hardwareInsert);
  13066. hw.params[lynx::hwinsert::output] = lynx::hwinsert::channelValue (0);
  13067. hw.params[lynx::hwinsert::input] = lynx::hwinsert::channelValue (0);
  13068. hw.params[lynx::hwinsert::inputStereo] = 1.0f;
  13069. song.mixer[1].effects.clear();
  13070. lynx::AudioEngine::HardwareInsertRef ref { false, 1, 0, {} };
  13071. if (inPatcher) // (round 165c) From LYNX -> Hardware Insert -> To LYNX
  13072. {
  13073. auto slot = lynx::makeEffectSlot (lynx::EffectKind::patcher);
  13074. lynx::PatchNode node;
  13075. node.effect = hw;
  13076. slot.patcher.nodes = { node };
  13077. lynx::PatchWire in, out;
  13078. in.from = lynx::patchFromHost;
  13079. in.to = 0;
  13080. out.from = 0;
  13081. out.to = lynx::patchToHost;
  13082. slot.patcher.wires = { in, out };
  13083. song.mixer[1].effects.push_back (slot);
  13084. ref.nodes = { 0 };
  13085. }
  13086. else
  13087. song.mixer[1].effects.push_back (hw);
  13088. engine->setSong (std::move (song));
  13089. step (juce::String ("insert=") + (inPatcher ? "inside a Patcher on Insert 1" : "Insert 1 slot 1"));
  13090. const auto meter = [this, ref] (int output) {
  13091. const auto fx = engine->runningHardwareInsert (ref);
  13092. return fx != nullptr ? fx->controlOutput (output) : 0.0f;
  13093. };
  13094. // 1) the insert's ping (as its Ping button: a momentary value flipped)
  13095. juce::Timer::callAfterDelay (500, [this, report, step, finish, seconds, rate, meter, ref, inPatcher, bounceFile] {
  13096. if (engine == nullptr)
  13097. return;
  13098. engine->pingHardwareInserts ({ ref });
  13099. juce::Timer::callAfterDelay (3500, [this, report, step, finish, seconds, rate, meter, ref, inPatcher, bounceFile] {
  13100. if (engine == nullptr)
  13101. return;
  13102. // (round 165c) the engine makes a ping's result the slot's round trip with the device setup it belongs to; the
  13103. // new round trip rebuilds the insert (its latency), so the result is read from the slot
  13104. const auto* slot = lynx::AudioEngine::locateHardwareInsert (const_cast<lynx::Song&> (engine->getSong()), ref);
  13105. const auto samples = slot != nullptr ? lynx::hwinsert::roundTripOf (slot->params[lynx::hwinsert::roundTrip]) : 0;
  13106. const auto setup = slot != nullptr ? lynx::hwinsert::measuredSetup (*slot) : std::string();
  13107. const auto state = meter (lynx::hwinsert::pingState);
  13108. const auto ok = samples > 0 && setup == engine->currentSetupKey();
  13109. step ("ping_round_trip=" + juce::String (samples) + " measured_setup=" + juce::String (setup) + (ok ? " (ok)" : " (FAILED)")
  13110. + " live_ping_state=" + juce::String (state, 3) + " status_flags=" + juce::String (juce::roundToInt (meter (lynx::hwinsert::status) * 16.0f)));
  13111. if (! ok)
  13112. {
  13113. step ("result=FAILED ping");
  13114. finish (1);
  13115. return;
  13116. }
  13117. // a stale setup is noticed: another setup key on the slot gives the notice, the real one none
  13118. step ("stale_now=" + juce::String ((int) engine->staleHardwareInserts().size()));
  13119. // 2) play, capturing the Master
  13120. juce::Timer::callAfterDelay (500, [this, report, step, finish, seconds, rate, samples, ref, inPatcher, bounceFile] {
  13121. if (engine == nullptr)
  13122. return;
  13123. step ("pdc_total=" + juce::String (engine->getLatencySamples()) + " (expected " + juce::String (samples) + ")");
  13124. // saved in the project: the slot comes back the same (routing, round trip), and its latency with it — also an
  13125. // odd round trip (12345 samples: the project keeps it to the sample)
  13126. if (! inPatcher)
  13127. {
  13128. auto odd = engine->getSong();
  13129. odd.mixer[1].effects[0].params[lynx::hwinsert::roundTrip] = lynx::hwinsert::roundTripValue (12345);
  13130. juce::String error;
  13131. auto same = true;
  13132. for (const auto* song : { &engine->getSong(), (const lynx::Song*) &odd })
  13133. {
  13134. const auto file = report.getSiblingFile (report.getFileNameWithoutExtension() + (song == &odd ? "-odd.lynx" : ".lynx"));
  13135. const auto saved = lynx::ProjectFile::save (*song, file, error);
  13136. const auto loaded = saved ? lynx::ProjectFile::load (file, error) : std::nullopt;
  13137. same = same && loaded && loaded->mixer.size() > 1 && ! loaded->mixer[1].effects.empty()
  13138. && loaded->mixer[1].effects[0].kind == lynx::EffectKind::hardwareInsert
  13139. && loaded->mixer[1].effects[0].params == song->mixer[1].effects[0].params
  13140. && lynx::makeEffect (loaded->mixer[1].effects[0])->latencySamples() == (song == &odd ? 12345 : samples);
  13141. }
  13142. const auto file = report.getSiblingFile (report.getFileNameWithoutExtension() + ".lynx");
  13143. step (juce::String ("project_round_trip=") + (same ? "same" : "DIFFERENT " + error) + " (" + file.getFileName() + ")");
  13144. if (! same)
  13145. {
  13146. step ("result=FAILED project");
  13147. finish (1);
  13148. return;
  13149. }
  13150. }
  13151. auto left = std::make_shared<std::vector<float>>(), right = std::make_shared<std::vector<float>>();
  13152. engine->stop();
  13153. engine->rewind();
  13154. engine->getMeters().capture.setSource (0);
  13155. engine->play();
  13156. auto pulls = std::make_shared<int> ((int) (seconds * 5.0));
  13157. auto pull = std::make_shared<std::function<void()>>();
  13158. *pull = [this, report, step, finish, seconds, rate, samples, left, right, pulls, pull, ref, inPatcher, bounceFile] {
  13159. if (engine == nullptr)
  13160. return;
  13161. engine->getMeters().capture.pull (*left, *right);
  13162. if (*pulls == 10) // the insert's editor while it plays (next to the report)
  13163. for (const auto scale : { 1.0f, 1.5f })
  13164. {
  13165. auto editor = inPatcher ? lynx::makeNodeEffectEditor (
  13166. *engine, [ref] (lynx::Song& s) { return lynx::AudioEngine::locateHardwareInsert (s, ref); },
  13167. [this, ref] { return engine->runningHardwareInsert (ref); }, "Insert 1 (Patcher)", scale)
  13168. : lynx::makeNativeEffectEditor (*engine, 1, 0, scale, 0);
  13169. juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
  13170. {
  13171. juce::Graphics g (image);
  13172. g.fillAll (lynx::theme::panel);
  13173. editor->paintEntireComponent (g, false);
  13174. }
  13175. const auto file = report.getSiblingFile (report.getFileNameWithoutExtension() + (scale > 1.0f ? "-editor150.png" : "-editor.png"));
  13176. file.deleteFile();
  13177. juce::PNGImageFormat png;
  13178. if (auto stream = file.createOutputStream())
  13179. png.writeImageToStream (image, *stream);
  13180. }
  13181. if (--*pulls > 0)
  13182. {
  13183. juce::Timer::callAfterDelay (200, *pull);
  13184. return;
  13185. }
  13186. engine->stop();
  13187. const auto dropped = engine->getMeters().capture.droppedFrames();
  13188. engine->getMeters().capture.setSource (lynx::AudioCapture::off);
  13189. // the clicks of each side (peaks above -12 dBFS, one per 1/8 s at most)
  13190. auto peaksOf = [rate] (const std::vector<float>& x) {
  13191. std::vector<juce::int64> peaks;
  13192. for (std::size_t f = 1; f + 1 < x.size(); ++f)
  13193. 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])
  13194. && (peaks.empty() || (juce::int64) f - peaks.back() > (juce::int64) (rate / 8)))
  13195. peaks.push_back ((juce::int64) f);
  13196. return peaks;
  13197. };
  13198. const auto wet = peaksOf (*left), dry = peaksOf (*right);
  13199. int pairs = 0;
  13200. juce::int64 worst = 0;
  13201. double gainSum = 0.0, residual = 0.0, energy = 0.0;
  13202. for (const auto w : wet)
  13203. {
  13204. 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); });
  13205. if (best == dry.end() || std::abs (*best - w) > (juce::int64) (rate / 8))
  13206. continue;
  13207. ++pairs;
  13208. worst = std::max (worst, std::abs (*best - w));
  13209. gainSum += (*left)[(std::size_t) w] / (*right)[(std::size_t) *best];
  13210. }
  13211. const auto gain = pairs > 0 ? gainSum / pairs : 1.0;
  13212. // dry clicks with no wet click beside them (a dropout of the cable / device), listed
  13213. juce::String unmatched;
  13214. for (const auto d : dry)
  13215. if (std::none_of (wet.begin(), wet.end(), [d, rate] (juce::int64 w) { return std::abs (w - d) <= (juce::int64) (rate / 8); }))
  13216. unmatched << " " << (juce::int64) d << " (" << juce::String ((*left)[(std::size_t) d], 3) << ")";
  13217. if (unmatched.isNotEmpty())
  13218. step ("dry_clicks_without_wet=" + unmatched);
  13219. // the null test: left − gain · right around each click (both sides aligned → only the cable's colour remains)
  13220. for (const auto w : wet)
  13221. for (juce::int64 f = std::max<juce::int64> (0, w - 16); f < std::min<juce::int64> ((juce::int64) left->size(), w + 16); ++f)
  13222. {
  13223. const auto d = (double) (*left)[(std::size_t) f] - gain * (double) (*right)[(std::size_t) f];
  13224. residual += d * d;
  13225. energy += (double) (*left)[(std::size_t) f] * (*left)[(std::size_t) f];
  13226. }
  13227. const auto nullDb = energy > 0.0 ? 10.0 * std::log10 (std::max (1e-30, residual / energy)) : 0.0;
  13228. step ("captured=" + juce::String ((int) left->size()) + " frames dropped=" + juce::String (dropped) + " wet_clicks=" + juce::String ((int) wet.size())
  13229. + " dry_clicks=" + juce::String ((int) dry.size()) + " pairs=" + juce::String (pairs));
  13230. step ("alignment_error_samples=max " + juce::String ((int) worst) + " cable_gain=" + juce::String (gain, 4) + " null_residual_db=" + juce::String (nullDb, 1));
  13231. auto* dev = engine->getDeviceManager().getCurrentAudioDevice();
  13232. const auto xruns = dev != nullptr ? dev->getXRunCount() : -1;
  13233. step ("device_xruns=" + juce::String (xruns) + " (a dropout loses what was on the cable then: its clicks are excused)");
  13234. const auto excused = xruns > 0 ? 2 * xruns : 0;
  13235. const auto ok = pairs >= (int) (seconds * 2.0) - 2 - excused && worst == 0 && dropped == 0 && engine->getLatencySamples() == samples;
  13236. step (juce::String ("result=") + (ok ? "OK" : "FAILED"));
  13237. // (round 165c) then the re-ping notice after a buffer size change
  13238. auto then = [this, ref, step, finish] (int code) {
  13239. if (code != 0)
  13240. finish (code);
  13241. else
  13242. runRepingCheck (ref, step, finish);
  13243. };
  13244. if (! ok)
  13245. {
  13246. finish (1);
  13247. return;
  13248. }
  13249. if (bounceFile == juce::File())
  13250. then (0);
  13251. else
  13252. runBounceCheck (bounceFile, step, then);
  13253. };
  13254. juce::Timer::callAfterDelay (200, *pull);
  13255. });
  13256. });
  13257. });
  13258. }
  13259. // --hwinserttest --bounce (round 165c): Export › "Render through the hardware in real time" of the test song next to
  13260. // the offline export of the same song. Through the loopback cable (gain 1) the return is the send delayed by the
  13261. // pinged round trip, so the real-time file must equal the offline one (which passes the dry signal at that delay)
  13262. // to float rounding, with the wet clicks (left) on the dry clicks' samples (right).
  13263. // --hwinserttest (round 165c): the buffer size changes (another round trip on the device): the engine notices the
  13264. // insert measured for the old setup (the app's "Ping now?" prompt), "Ping now" measures it again for the new one
  13265. void runRepingCheck (lynx::AudioEngine::HardwareInsertRef ref, std::function<void (const juce::String&)> step, std::function<void (int)> finish)
  13266. {
  13267. auto& devices = engine->getDeviceManager();
  13268. auto setup = devices.getAudioDeviceSetup();
  13269. const auto before = setup.bufferSize;
  13270. setup.bufferSize = before == 512 ? 256 : 512;
  13271. if (const auto error = devices.setAudioDeviceSetup (setup, true); error.isNotEmpty())
  13272. step ("reping_device_error=" + error);
  13273. engine->takeHardwareInsertNotice(); // (whatever was pending before the change)
  13274. juce::Timer::callAfterDelay (1500, [this, ref, step, finish, before] {
  13275. if (engine == nullptr)
  13276. return;
  13277. auto* device = engine->getDeviceManager().getCurrentAudioDevice();
  13278. const auto block = device != nullptr ? device->getCurrentBufferSizeSamples() : 0;
  13279. const auto notice = engine->takeHardwareInsertNotice();
  13280. step ("reping_buffer=" + juce::String (before) + "->" + juce::String (block) + " notice=" + juce::String ((int) notice.size())
  13281. + " stale=" + juce::String ((int) engine->staleHardwareInserts().size()));
  13282. if (notice.size() != 1 || ! (notice[0] == ref))
  13283. {
  13284. step ("result_reping=FAILED (no notice)");
  13285. finish (1);
  13286. return;
  13287. }
  13288. engine->pingHardwareInserts (notice); // ("Ping now")
  13289. juce::Timer::callAfterDelay (3500, [this, ref, step, finish, block] {
  13290. if (engine == nullptr)
  13291. return;
  13292. const auto* slot = lynx::AudioEngine::locateHardwareInsert (const_cast<lynx::Song&> (engine->getSong()), ref);
  13293. const auto samples = slot != nullptr ? lynx::hwinsert::roundTripOf (slot->params[lynx::hwinsert::roundTrip]) : 0;
  13294. const auto stale = (int) engine->staleHardwareInserts().size();
  13295. step ("reping_round_trip=" + juce::String (samples) + " pdc_total=" + juce::String (engine->getLatencySamples()) + " stale=" + juce::String (stale));
  13296. const auto ok = stale == 0 && samples > 0 && engine->getLatencySamples() == samples;
  13297. step (juce::String ("result_reping=") + (ok ? "OK" : "FAILED") + " (device block " + juce::String (block) + ")");
  13298. finish (ok ? 0 : 1);
  13299. });
  13300. });
  13301. }
  13302. void runBounceCheck (const juce::File& bounceFile, std::function<void (const juce::String&)> step, std::function<void (int)> finish)
  13303. {
  13304. // the Export window as the user sees it with the real-time option ticked (next to the report)
  13305. lynx::showExportDialog (*engine, bounceFile.getParentDirectory(), "bounce", 0);
  13306. for (int k = 0; k < juce::TopLevelWindow::getNumTopLevelWindows(); ++k)
  13307. if (auto* w = juce::TopLevelWindow::getTopLevelWindow (k))
  13308. {
  13309. std::function<juce::ToggleButton* (juce::Component&)> find = [&find] (juce::Component& c) -> juce::ToggleButton* {
  13310. if (auto* t = dynamic_cast<juce::ToggleButton*> (&c); t != nullptr && t->getButtonText() == lynx::tr ("Render through the hardware in real time"))
  13311. return t;
  13312. for (auto* child : c.getChildren())
  13313. if (auto* t = find (*child))
  13314. return t;
  13315. return nullptr;
  13316. };
  13317. if (auto* toggle = find (*w))
  13318. {
  13319. step (juce::String ("export_option_visible=") + (toggle->isVisible() ? "yes" : "NO"));
  13320. toggle->setToggleState (true, juce::sendNotificationSync); // (calls its onClick, as a click)
  13321. auto* c = dynamic_cast<juce::DocumentWindow*> (w) != nullptr ? static_cast<juce::DocumentWindow*> (w)->getContentComponent() : w;
  13322. if (c != nullptr)
  13323. {
  13324. const auto file = bounceFile.getSiblingFile (bounceFile.getFileNameWithoutExtension() + "-export.png");
  13325. file.deleteFile();
  13326. juce::FileOutputStream out (file);
  13327. juce::PNGImageFormat png;
  13328. if (out.openedOk())
  13329. png.writeImageToStream (c->createComponentSnapshot (c->getLocalBounds()), out);
  13330. }
  13331. delete w;
  13332. break;
  13333. }
  13334. }
  13335. lynx::exportopts::Options o;
  13336. o.format = lynx::exportopts::Format::wav;
  13337. o.wavBits = 32;
  13338. o.dither = lynx::exportopts::DitherMode::none;
  13339. o.tail = lynx::exportopts::TailMode::cut;
  13340. o.range = lynx::exportopts::Range::song;
  13341. o.trimPdc = true;
  13342. o.hqAllPlugins = false;
  13343. o.pluginWarmUp = false;
  13344. const auto offlineFile = bounceFile.getSiblingFile (bounceFile.getFileNameWithoutExtension() + "-offline.wav");
  13345. auto realtimeJob = std::make_shared<lynx::ExportJob> (*engine, o, bounceFile);
  13346. o.sampleRate = engine->getTransport().sampleRate.load();
  13347. auto offlineJob = std::make_shared<lynx::ExportJob> (engine->getSong(), o, offlineFile);
  13348. struct Shared
  13349. {
  13350. std::atomic<int> done { 0 };
  13351. bool okRealtime = false, okOffline = false;
  13352. juce::String errorRealtime, errorOffline;
  13353. double lastProgress = 0.0;
  13354. double started = juce::Time::getMillisecondCounterHiRes();
  13355. };
  13356. auto shared = std::make_shared<Shared>();
  13357. // (the jobs stay owned by the message thread's poll below: they are destroyed there)
  13358. juce::Thread::launch ([rt = realtimeJob.get(), off = offlineJob.get(), shared] {
  13359. shared->okRealtime = rt->run ([shared] (double p) { shared->lastProgress = p; return true; }, shared->errorRealtime);
  13360. shared->okOffline = off->run ({}, shared->errorOffline);
  13361. shared->done.store (1);
  13362. });
  13363. auto poll = std::make_shared<std::function<void()>>();
  13364. *poll = [this, poll, shared, realtimeJob, offlineJob, bounceFile, offlineFile, step, finish] {
  13365. if (shared->done.load() == 0)
  13366. {
  13367. juce::Timer::callAfterDelay (100, *poll);
  13368. return;
  13369. }
  13370. const auto seconds = (juce::Time::getMillisecondCounterHiRes() - shared->started) / 1000.0;
  13371. step ("bounce_realtime=" + juce::String (shared->okRealtime ? "ok" : "FAILED " + shared->errorRealtime) + " offline="
  13372. + juce::String (shared->okOffline ? "ok" : "FAILED " + shared->errorOffline) + " took=" + juce::String (seconds, 1) + " s (music "
  13373. + juce::String (realtimeJob->getMusicSeconds(), 1) + " s)" + (realtimeJob->getNotice().isNotEmpty() ? " notice=" + realtimeJob->getNotice() : juce::String()));
  13374. juce::AudioFormatManager formats;
  13375. formats.registerBasicFormats();
  13376. std::unique_ptr<juce::AudioFormatReader> a (formats.createReaderFor (bounceFile)), b (formats.createReaderFor (offlineFile));
  13377. if (! shared->okRealtime || ! shared->okOffline || a == nullptr || b == nullptr)
  13378. {
  13379. step ("result=FAILED bounce");
  13380. finish (1);
  13381. return;
  13382. }
  13383. const auto frames = (int) std::min (a->lengthInSamples, b->lengthInSamples);
  13384. juce::AudioBuffer<float> x (2, frames), y (2, frames);
  13385. a->read (&x, 0, frames, 0, true, true);
  13386. b->read (&y, 0, frames, 0, true, true);
  13387. double residual = 0.0, energy = 0.0, wetDry = 0.0;
  13388. for (int ch = 0; ch < 2; ++ch)
  13389. for (int i = 0; i < frames; ++i)
  13390. {
  13391. const double d = x.getSample (ch, i) - y.getSample (ch, i);
  13392. residual += d * d;
  13393. energy += (double) y.getSample (ch, i) * y.getSample (ch, i);
  13394. }
  13395. for (int i = 0; i < frames; ++i) // the wet side against the dry side of the real-time file
  13396. wetDry += std::pow ((double) x.getSample (0, i) - x.getSample (1, i), 2.0);
  13397. const auto db = [energy] (double r) { return energy > 0.0 ? 10.0 * std::log10 (std::max (1e-30, r / energy)) : 0.0; };
  13398. step ("bounce_frames=" + juce::String ((juce::int64) a->lengthInSamples) + " offline_frames=" + juce::String ((juce::int64) b->lengthInSamples)
  13399. + " rate=" + juce::String (a->sampleRate) + " bounce_vs_offline_db=" + juce::String (db (residual), 1)
  13400. + " wet_vs_dry_db=" + juce::String (db (2.0 * wetDry), 1) + " peak=" + juce::String (realtimeJob->getPeak(), 3));
  13401. const auto ok = std::abs (a->lengthInSamples - b->lengthInSamples) <= 1 && db (residual) < -100.0 && realtimeJob->getPeak() > 0.1f;
  13402. step (juce::String ("result_bounce=") + (ok ? "OK" : "FAILED"));
  13403. finish (ok ? 0 : 1);
  13404. };
  13405. juce::Timer::callAfterDelay (100, *poll);
  13406. }
  13407. // --rtstress --record: stops recording (the take becomes a clip of the song, as in the app), moves the take's WAV to
  13408. // `target` and describes it: length against the time played, channels, peak, the latencies the driver reported.
  13409. juce::String finishStressTake (const juce::File& target, double seconds)
  13410. {
  13411. juce::String text;
  13412. auto* device = engine->getDeviceManager().getCurrentAudioDevice();
  13413. text << " recording: input " << (device != nullptr ? device->getActiveInputChannels().countNumberOfSetBits() : 0) << " channel(s)";
  13414. if (device != nullptr)
  13415. text << ", input latency " << device->getInputLatencyInSamples() << " + output latency " << device->getOutputLatencyInSamples() << " samples";
  13416. engine->setRecording (false); // closes the take: a clip of the song
  13417. juce::File take;
  13418. for (const auto& c : engine->getSong().channels)
  13419. if (c.instrument == lynx::InstrumentKind::audioClip)
  13420. take = juce::File (juce::String::fromUTF8 (c.samplePath.c_str()));
  13421. if (! take.existsAsFile())
  13422. return text + "\n recording: no take (" + engine->getLastRecordingError() + ")\n";
  13423. target.deleteFile();
  13424. if (! take.moveFileTo (target))
  13425. take.copyFileTo (target);
  13426. juce::AudioFormatManager formats;
  13427. formats.registerBasicFormats();
  13428. if (std::unique_ptr<juce::AudioFormatReader> reader (formats.createReaderFor (target)); reader != nullptr)
  13429. {
  13430. juce::AudioBuffer<float> audio ((int) reader->numChannels, (int) reader->lengthInSamples);
  13431. reader->read (&audio, 0, (int) reader->lengthInSamples, 0, true, true);
  13432. const auto peak = audio.getMagnitude (0, audio.getNumSamples());
  13433. const auto length = (double) reader->lengthInSamples / reader->sampleRate;
  13434. text << "\n recording: take " << juce::String (length, 3) << " s of " << juce::String (seconds, 0) << " s played, "
  13435. << (int) reader->numChannels << " ch @ " << (int) reader->sampleRate << " Hz, peak "
  13436. << juce::String (juce::Decibels::gainToDecibels (peak, -150.0f), 1) << " dBFS -> " << target.getFullPathName() << "\n";
  13437. }
  13438. else
  13439. text << "\n recording: take unreadable (" << target.getFullPathName() << ")\n";
  13440. return text;
  13441. }
  13442. // LYNX.exe --render project.(flp|lynx) output.wav [seconds]
  13443. // Exports the current pattern to 24-bit WAV (for an imported .flp, the one with the most notes).
  13444. void runRender (const juce::String& inputPath, const juce::String& outputPath, double seconds)
  13445. {
  13446. lynx::AudioEngine offline (false);
  13447. const juce::File input (inputPath);
  13448. juce::String error, report;
  13449. bool ok = false;
  13450. if (input.hasFileExtension ("flp;als;flm;songtmpl;band")) // (round 190ic: a GarageBand .band folder too)
  13451. ok = offline.importFlpFile (input, error);
  13452. else if (auto song = lynx::ProjectFile::load (input, error))
  13453. {
  13454. offline.setSong (std::move (*song));
  13455. ok = true;
  13456. }
  13457. int samplers = 0, samplersLoaded = 0;
  13458. if (ok)
  13459. {
  13460. for (const auto& c : offline.getSong().channels)
  13461. if (c.instrument == lynx::InstrumentKind::sampler || c.instrument == lynx::InstrumentKind::audioClip)
  13462. {
  13463. ++samplers;
  13464. samplersLoaded += offline.getSampleLibrary().load (juce::String::fromUTF8 (c.samplePath.c_str())) != nullptr;
  13465. }
  13466. const juce::File output (outputPath);
  13467. output.deleteFile();
  13468. juce::WavAudioFormat wav;
  13469. std::unique_ptr<juce::AudioFormatWriter> writer (
  13470. wav.createWriterFor (output.createOutputStream().release(), 44100.0, 2, 24, {}, 0));
  13471. if (writer == nullptr)
  13472. {
  13473. ok = false;
  13474. error = lynx::utf8 ("could not create ") + outputPath;
  13475. }
  13476. else
  13477. {
  13478. const auto peak = offline.renderOffline (seconds > 0.0 ? seconds : 10.0, 44100.0, writer.get());
  13479. report << "peak=" << peak << "\n";
  13480. ok = peak > 0.001f;
  13481. }
  13482. }
  13483. report << "samples=" << samplersLoaded << "/" << samplers << "\n"
  13484. << "result=" << (ok ? "OK" : "ERROR " + error) << "\n";
  13485. juce::File (outputPath + ".txt").replaceWithText (report);
  13486. setApplicationReturnValue (ok ? 0 : 1);
  13487. quit();
  13488. }
  13489. // LYNX.exe --export-flp project.(lynx|flp|als) output.(flp|zip) [--substitute] (round 171e): File › Export › FL Studio
  13490. // project without the window (option A unless --substitute; the renders next to a .flp in "<name> audio"); the
  13491. // report goes to output.txt
  13492. void runAlsExport (const juce::String& inputPath, const juce::String& folderPath, bool live11, bool reference)
  13493. {
  13494. juce::String error;
  13495. juce::StringArray notes;
  13496. juce::File als;
  13497. {
  13498. lynx::AudioEngine loader (false);
  13499. const juce::File input (inputPath);
  13500. bool ok = false;
  13501. // --scan: the targeted plugin scan an open runs first (child processes), so the set's plugins load
  13502. if (juce::JUCEApplication::getCommandLineParameterArray().contains ("--scan") && input.hasFileExtension ("flp;als;flm;songtmpl"))
  13503. {
  13504. juce::MemoryBlock data;
  13505. if (input.loadFileAsData (data))
  13506. {
  13507. const std::vector<std::uint8_t> bytes (static_cast<const std::uint8_t*> (data.getData()),
  13508. static_cast<const std::uint8_t*> (data.getData()) + data.getSize());
  13509. try
  13510. {
  13511. const auto uses = input.hasFileExtension ("als") ? lynx::alsForeignPlugins (bytes)
  13512. : lynx::flpForeignPlugins (flp::parseProject ({ bytes.data(), bytes.size() }));
  13513. loader.getPluginHost().scanFiles (loader.getPluginHost().filesToScanFor (uses), {});
  13514. }
  13515. catch (const std::exception&)
  13516. {
  13517. }
  13518. }
  13519. }
  13520. if (input.hasFileExtension ("flp;als;flm;songtmpl;band"))
  13521. ok = loader.importFlpFile (input, error);
  13522. else if (auto song = lynx::ProjectFile::load (input, error))
  13523. {
  13524. loader.setSong (std::move (*song));
  13525. ok = true;
  13526. }
  13527. if (ok)
  13528. {
  13529. loader.capturePluginStates();
  13530. const juce::File folder (folderPath);
  13531. folder.createDirectory();
  13532. als = lynx::writeAlsProject (loader.getSong(), &loader.getPluginHost(), live11 ? lynx::AlsVersion::live11 : lynx::AlsVersion::live12, ! reference, folder,
  13533. input.getFileNameWithoutExtension(), notes, error);
  13534. }
  13535. }
  13536. juce::String report;
  13537. report << (als != juce::File() ? "ok " + als.getFullPathName() : "error=" + error) << "\n" << notes.joinIntoString ("\n") << "\n";
  13538. juce::File (folderPath).getChildFile ("export-als.txt").replaceWithText (report);
  13539. setApplicationReturnValue (als != juce::File() ? 0 : 1);
  13540. quit();
  13541. }
  13542. // --versionsshot <prefix> (round 190ap): everything the round adds, offscreen (no window on the desktop):
  13543. // -versions.png / -versions-unsaved.png the Versions panel (a project with versions, backups and labels; a new one)
  13544. // -menu-file.png / -menu-file-pluginsoff.png the File menu, and as it is while the plugins are off
  13545. // -pluginsoff-window.png / -pluginsoff-mixer.png a project opened without its third-party plugins (the tags)
  13546. // -pluginsoff-panel.png / -pluginsoff-panel-one.png the list, all off, then after "Switch on" for one
  13547. // -export-default.png / -export.png the Export window as it opens, and with the additions in use
  13548. bool runLinkShot (const juce::String& prefix)
  13549. {
  13550. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  13551. juce::StringArray report;
  13552. bool allOk = true;
  13553. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  13554. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  13555. allOk = allOk && ok;
  13556. };
  13557. const auto shoot = [&prefix] (juce::Component& c, const char* name) {
  13558. savePng (c.createComponentSnapshot (c.getLocalBounds()), prefix + "-" + name + ".png");
  13559. };
  13560. using lynx::AutomationTarget;
  13561. using lynx::AutomationTargetKind;
  13562. using lynx::MidiLink;
  13563. lynx::AudioEngine engine (false);
  13564. const AutomationTarget volume { AutomationTargetKind::channelVolume, 0 }, pan { AutomationTargetKind::channelPan, 0 },
  13565. insert { AutomationTargetKind::mixerVolume, 1 };
  13566. // ---- the window as it opens on a control with no link (FL's defaults)
  13567. {
  13568. auto panel = lynx::makeRemoteControlPanel (engine, { volume }, false);
  13569. shoot (*panel, "remote-default");
  13570. check ("default_state", lynx::remoteControlPanelState (*panel).startsWith ("-1|1|-1|Input|"), lynx::remoteControlPanelState (*panel));
  13571. // Auto detect: the controller that sends next fills the fields
  13572. engine.injectControllerForTest (74, 2, 100, 5);
  13573. lynx::remoteControlPanelPoll (*panel);
  13574. check ("auto_detect", lynx::remoteControlPanelState (*panel).startsWith ("5|3|74|"), lynx::remoteControlPanelState (*panel));
  13575. // a formula preset, smoothing; Accept writes the link
  13576. lynx::remoteControlPanelSetController (*panel, -1, 1, 7);
  13577. lynx::remoteControlPanelSetFormula (*panel, "Tension(Input,10)");
  13578. lynx::remoteControlPanelSetSmoothing (*panel, true, 469);
  13579. shoot (*panel, "remote-formula-smoothing");
  13580. lynx::remoteControlPanelPress (*panel, 2);
  13581. const auto& links = engine.getSong().midiLinks;
  13582. check ("accept_writes_link", links.size() == 1 && links[0].cc == 7 && links[0].channel == 0 && links[0].port == -1
  13583. && links[0].formula == "Tension(Input,10)" && links[0].smooth && links[0].target == volume);
  13584. }
  13585. // ---- a broken formula: the message, the red text
  13586. {
  13587. auto panel = lynx::makeRemoteControlPanel (engine, { volume }, false);
  13588. lynx::remoteControlPanelSetFormula (*panel, "Min(Input*2,");
  13589. shoot (*panel, "remote-formula-error");
  13590. check ("formula_error_shown", ! lynx::remoteControlPanelState (*panel).contains ("Compiled ok."), lynx::remoteControlPanelState (*panel));
  13591. }
  13592. // ---- the engine: formula, port, conflicts, omni
  13593. {
  13594. engine.editSong ([&] (lynx::Song& s) {
  13595. s.midiLinks.clear();
  13596. MidiLink inverted { 20, 0, volume };
  13597. inverted.formula = "1-Input";
  13598. MidiLink ported { 21, 0, pan };
  13599. ported.port = 3;
  13600. s.midiLinks = { inverted, ported };
  13601. });
  13602. engine.injectControllerForTest (20, 0, 127);
  13603. check ("formula_inverts", std::abs (engine.currentTargetValue (volume)) < 0.01f, juce::String (engine.currentTargetValue (volume)));
  13604. engine.injectControllerForTest (20, 0, 0);
  13605. check ("formula_inverts_back", std::abs (engine.currentTargetValue (volume) - 1.0f) < 0.01f, juce::String (engine.currentTargetValue (volume)));
  13606. const auto panBefore = engine.currentTargetValue (pan);
  13607. engine.injectControllerForTest (21, 0, 127); // no port: not this link's device
  13608. check ("port_must_match", std::abs (engine.currentTargetValue (pan) - panBefore) < 0.001f);
  13609. engine.injectControllerForTest (21, 0, 127, 3);
  13610. check ("port_matches", std::abs (engine.currentTargetValue (pan) - 1.0f) < 0.01f, juce::String (engine.currentTargetValue (pan)));
  13611. // the window on a control whose controller another control uses: Remove conflicts in red; Accept removes it
  13612. auto panel = lynx::makeRemoteControlPanel (engine, { insert }, false);
  13613. lynx::remoteControlPanelSetController (*panel, -1, 1, 20);
  13614. shoot (*panel, "remote-conflict");
  13615. check ("conflict_counted", lynx::remoteControlPanelState (*panel).contains ("|1|"), lynx::remoteControlPanelState (*panel));
  13616. lynx::remoteControlPanelPress (*panel, 2);
  13617. const auto& links = engine.getSong().midiLinks;
  13618. check ("conflict_removed", links.size() == 2
  13619. && std::none_of (links.begin(), links.end(), [&] (const MidiLink& l) { return l.target == volume; })
  13620. && std::any_of (links.begin(), links.end(), [&] (const MidiLink& l) { return l.target == insert && l.cc == 20; }));
  13621. engine.undo();
  13622. check ("accept_is_one_undo_step", engine.getSong().midiLinks.size() == 2 && engine.getSong().midiLinks[0].target == volume);
  13623. }
  13624. // ---- an existing link opened again: "Link 1" / "New link"
  13625. {
  13626. auto panel = lynx::makeRemoteControlPanel (engine, { volume }, false);
  13627. shoot (*panel, "remote-existing-link");
  13628. check ("existing_link_loaded", lynx::remoteControlPanelState (*panel).startsWith ("-1|1|20|1-Input|"), lynx::remoteControlPanelState (*panel));
  13629. // Reset, then Accept: a link without a controller is removed
  13630. lynx::remoteControlPanelPress (*panel, 0);
  13631. check ("reset_state", lynx::remoteControlPanelState (*panel).startsWith ("-1|1|-1|Input|"), lynx::remoteControlPanelState (*panel));
  13632. lynx::remoteControlPanelPress (*panel, 2);
  13633. const auto& links = engine.getSong().midiLinks;
  13634. check ("reset_accept_unlinks", std::none_of (links.begin(), links.end(), [&] (const MidiLink& l) { return l.target == volume; }));
  13635. }
  13636. // ---- several controls ("Link to controllers..."): Accept and Skip step through them
  13637. {
  13638. auto panel = lynx::makeRemoteControlPanel (engine, { volume, pan, insert }, false, [] {});
  13639. shoot (*panel, "remote-multilink");
  13640. const auto parameter = [&panel] { return juce::StringArray::fromTokens (lynx::remoteControlPanelState (*panel), "|", "")[6]; };
  13641. const auto first = parameter();
  13642. check ("multilink_caption_and_skip", first.startsWith ("1/3") && first.contains (lynx::tr ("Channel volume"))
  13643. && lynx::remoteControlPanelState (*panel).contains ("S|omni"),
  13644. lynx::remoteControlPanelState (*panel));
  13645. lynx::remoteControlPanelSetController (*panel, -1, 1, 30);
  13646. lynx::remoteControlPanelPress (*panel, 2); // Accept: volume linked, on to pan
  13647. const auto second = parameter();
  13648. lynx::remoteControlPanelPress (*panel, 1); // Skip: pan untouched, on to the insert
  13649. const auto third = parameter();
  13650. const auto beforeLast = lynx::remoteControlPanelFinished (*panel);
  13651. lynx::remoteControlPanelPress (*panel, 1); // Skip on the last one: done
  13652. const auto closed = ! beforeLast && lynx::remoteControlPanelFinished (*panel);
  13653. const auto& links = engine.getSong().midiLinks;
  13654. check ("multilink_steps", first != second && second != third && closed
  13655. && std::any_of (links.begin(), links.end(), [&] (const MidiLink& l) { return l.target == volume && l.cc == 30; }),
  13656. first + " > " + second + " > " + third);
  13657. }
  13658. // ---- Global link settings
  13659. {
  13660. auto panel = lynx::makeRemoteControlPanel (engine, { volume }, true);
  13661. shoot (*panel, "global-default");
  13662. lynx::remoteControlPanelSetController (*panel, 2, 1, 11);
  13663. lynx::remoteControlPanelSetFormula (*panel, "Input*0.5");
  13664. lynx::remoteControlPanelPress (*panel, 2);
  13665. const auto global = engine.globalLinkOf (volume);
  13666. check ("global_link_written", global && global->cc == 11 && global->port == 2 && global->formula == "Input*0.5");
  13667. const auto text = engine.getMidiPrefs().toText();
  13668. const auto back = lynx::prefs::MidiPrefs::fromText (text);
  13669. check ("global_link_settings_round_trip", back.globalLinks == engine.getMidiPrefs().globalLinks && text.find ("linkset=2|0|469|Input*0.5") != std::string::npos);
  13670. auto again = lynx::makeRemoteControlPanel (engine, { volume }, true);
  13671. shoot (*again, "global-existing-link");
  13672. engine.setGlobalLink (volume, std::nullopt);
  13673. check ("global_link_removed", ! engine.globalLinkOf (volume));
  13674. }
  13675. // ---- the project file: links with settings come back; a project of an older version loads the same
  13676. {
  13677. lynx::Song song = engine.getSong();
  13678. MidiLink plain { 7, -1, volume };
  13679. MidiLink rich { 74, 2, pan };
  13680. rich.port = 4;
  13681. rich.formula = "Min(Input*1.1,0.5)+Max(Input*1.1,0.6)-0.6";
  13682. rich.smooth = true;
  13683. rich.smoothing = -300;
  13684. rich.omni = true;
  13685. song.midiLinks = { plain, rich };
  13686. juce::String error;
  13687. const auto json = lynx::ProjectFile::toJson (song);
  13688. const auto back = lynx::ProjectFile::fromJson (json, error);
  13689. check ("project_round_trip", back && back->midiLinks == song.midiLinks, error);
  13690. // without settings the file holds only the list older versions wrote
  13691. song.midiLinks = { plain };
  13692. const auto plainJson = lynx::ProjectFile::toJson (song);
  13693. check ("plain_links_write_the_old_form", ! plainJson.contains ("midiLinkSettings") && plainJson.contains ("midiLinks"));
  13694. const auto plainBack = lynx::ProjectFile::fromJson (plainJson, error);
  13695. check ("old_project_loads_the_same", plainBack && plainBack->midiLinks.size() == 1 && plainBack->midiLinks[0] == plain
  13696. && ! plainBack->midiLinks[0].hasSettings());
  13697. // what an older version does with a new file: it reads "midiLinks" alone, so the links stay (plain)
  13698. auto parsed = juce::JSON::parse (json);
  13699. if (auto* o = parsed.getDynamicObject())
  13700. o->removeProperty ("midiLinkSettings");
  13701. const auto stripped = lynx::ProjectFile::fromJson (juce::JSON::toString (parsed), error);
  13702. check ("older_version_keeps_the_links", stripped && stripped->midiLinks.size() == 2 && stripped->midiLinks[1].cc == 74
  13703. && ! stripped->midiLinks[1].hasSettings());
  13704. }
  13705. // ---- round 190cs: FL's live answers (live check 190cq) and the note / button link modes
  13706. {
  13707. const auto state = [] (juce::Component& p) { return lynx::remoteControlPanelState (p); };
  13708. engine.editSong ([] (lynx::Song& s) { s.midiLinks.clear(); });
  13709. // the layout FL shows: no assignment list without a link, no Skip outside Multilink, no internal
  13710. // controller group without a controller in the project; the parameter caption in FL's words
  13711. auto fresh = lynx::makeRemoteControlPanel (engine, { volume }, false);
  13712. shoot (*fresh, "cs-remote-default");
  13713. check ("cs_layout_without_link", state (*fresh).contains ("|" + lynx::tr ("Channel volume") + "|") && state (*fresh).contains ("|shown=POC|"), state (*fresh));
  13714. // Omni: enabled on a mixer track's volume (FL: "Insert 1 - Volume"), greyed on the tempo
  13715. auto onInsert = lynx::makeRemoteControlPanel (engine, { insert }, false);
  13716. auto onTempo = lynx::makeRemoteControlPanel (engine, { AutomationTarget { AutomationTargetKind::tempo, 0 } }, false);
  13717. shoot (*onInsert, "cs-remote-omni-insert");
  13718. check ("cs_omni_mixer_track", state (*onInsert).contains ("|omni=on|") && state (*onTempo).contains ("|omni=off|"),
  13719. state (*onInsert) + " / " + state (*onTempo));
  13720. // the formula compiles on Enter only; FL's messages and colours
  13721. lynx::remoteControlPanelSetFormula (*fresh, "1-Input^2", false);
  13722. check ("cs_no_compile_while_typing", state (*fresh).contains ("|" + lynx::tr ("(default 1:1 mapping)") + "|"), state (*fresh));
  13723. lynx::remoteControlPanelSetFormula (*fresh, "-Input^2");
  13724. shoot (*fresh, "cs-remote-compiled");
  13725. check ("cs_compiled_on_enter", state (*fresh).contains ("|" + lynx::tr ("Compiled ok.") + "|"), state (*fresh));
  13726. const std::pair<const char*, const char*> errors[] { { "Input*", "Syntax error: function or operand" },
  13727. { "foo(Input)", "Invalid identifier: foo" },
  13728. { "Sin(Input", "Unequal brackets" },
  13729. { "Input 2", "input two space limited" } };
  13730. for (const auto& [text, expected] : errors)
  13731. {
  13732. lynx::remoteControlPanelSetFormula (*fresh, text);
  13733. check ("cs_fl_error_text", state (*fresh).contains (expected), state (*fresh));
  13734. }
  13735. lynx::remoteControlPanelSetFormula (*fresh, "foo(Input)");
  13736. shoot (*fresh, "cs-remote-error");
  13737. // Accept with that formula: the link is made, the formula is not kept (FL reopens it as "Input")
  13738. lynx::remoteControlPanelSetController (*fresh, -1, 1, 7);
  13739. lynx::remoteControlPanelPress (*fresh, 2);
  13740. check ("cs_bad_formula_accept_is_input", engine.getSong().midiLinks.size() == 1 && engine.getSong().midiLinks[0].cc == 7
  13741. && engine.getSong().midiLinks[0].formula.empty());
  13742. auto reopened = lynx::makeRemoteControlPanel (engine, { volume }, false);
  13743. shoot (*reopened, "cs-remote-reopened");
  13744. check ("cs_reopened_shows_input_and_link_list", state (*reopened).startsWith ("-1|1|7|Input|" + lynx::tr ("(default 1:1 mapping)") + "|")
  13745. && state (*reopened).contains ("|shown=PAOC|"),
  13746. state (*reopened));
  13747. // the internal controller group appears with a controller in the project, with "Record automation"
  13748. engine.editSong ([] (lynx::Song& s) {
  13749. lynx::EffectSlot peak;
  13750. peak.kind = lynx::EffectKind::peakController;
  13751. s.mixer[0].effects.push_back (peak);
  13752. });
  13753. auto withController = lynx::makeRemoteControlPanel (engine, { volume }, false);
  13754. lynx::remoteControlPanelSetInternal (*withController, 1, true);
  13755. shoot (*withController, "cs-remote-internal");
  13756. check ("cs_internal_group_shown", state (*withController).contains ("|shown=PAIOC|") && state (*withController).startsWith ("-1|1|-1|"),
  13757. state (*withController));
  13758. lynx::remoteControlPanelPress (*withController, 2);
  13759. const auto& autos = engine.getSong().automations;
  13760. check ("cs_record_automation_kept", std::any_of (autos.begin(), autos.end(), [&] (const lynx::Automation& a) {
  13761. return a.isLive() && a.target == volume && a.recordLive;
  13762. }));
  13763. engine.editSong ([] (lynx::Song& s) {
  13764. s.mixer[0].effects.pop_back();
  13765. s.automations.clear();
  13766. s.midiLinks.clear();
  13767. });
  13768. // the global window: no parameter list, Omni, Remove conflicts or Skip; Mode is there
  13769. auto globalPanel = lynx::makeRemoteControlPanel (engine, { volume }, true);
  13770. shoot (*globalPanel, "cs-global-default");
  13771. check ("cs_global_layout", state (*globalPanel).contains ("|shown=|"), state (*globalPanel));
  13772. // a key link in each Mode: note 60 = FL's controller number 256 + 60
  13773. const auto key = lynx::linkNoteBase + 60;
  13774. auto modePanel = lynx::makeRemoteControlPanel (engine, { volume }, false);
  13775. lynx::remoteControlPanelSetController (*modePanel, -1, 1, key);
  13776. lynx::remoteControlPanelSetMode (*modePanel, 2);
  13777. shoot (*modePanel, "cs-remote-note-latch");
  13778. lynx::remoteControlPanelPress (*modePanel, 2);
  13779. check ("cs_note_link_written", engine.getSong().midiLinks.size() == 1 && engine.getSong().midiLinks[0].cc == key
  13780. && engine.getSong().midiLinks[0].mode == 2);
  13781. const auto play = [&engine, key, volume] (int velocity) {
  13782. engine.injectControllerForTest (key, 0, velocity);
  13783. return engine.currentTargetValue (volume);
  13784. };
  13785. const auto setMode = [&engine] (int mode) {
  13786. engine.editSong ([mode] (lynx::Song& s) { s.midiLinks[0].mode = mode; });
  13787. engine.editSong ([] (lynx::Song& s) { s.setTargetValue ({ AutomationTargetKind::channelVolume, 0 }, 0.25f); });
  13788. };
  13789. setMode (2); // Latch: press switches, release does nothing
  13790. const auto l1 = play (100), l1off = play (0), l2 = play (90), l2off = play (0);
  13791. check ("cs_mode_latch", std::abs (l1 - 1.0f) < 1e-4f && std::abs (l1off - 1.0f) < 1e-4f && l2 < 1e-4f && l2off < 1e-4f,
  13792. juce::String (l1) + " " + juce::String (l1off) + " " + juce::String (l2) + " " + juce::String (l2off));
  13793. setMode (1); // Hold: the velocity while held, back to 0 on release
  13794. const auto h1 = play (100), h1off = play (0);
  13795. check ("cs_mode_hold", std::abs (h1 - 100.0f / 127.0f) < 1e-4f && h1off < 1e-4f, juce::String (h1) + " " + juce::String (h1off));
  13796. setMode (0); // Default: as Hold for a key
  13797. const auto d1 = play (64), d1off = play (0);
  13798. check ("cs_mode_default", std::abs (d1 - 64.0f / 127.0f) < 1e-4f && d1off < 1e-4f, juce::String (d1) + " " + juce::String (d1off));
  13799. setMode (3); // Inc: each press adds 1/128
  13800. const auto i1 = play (100), i1off = play (0), i2 = play (20);
  13801. check ("cs_mode_inc", std::abs (i1 - (0.25f + 1.0f / 128.0f)) < 1e-4f && std::abs (i1off - i1) < 1e-6f
  13802. && std::abs (i2 - (0.25f + 2.0f / 128.0f)) < 1e-4f,
  13803. juce::String (i1) + " " + juce::String (i2));
  13804. setMode (4); // Stay: the velocity, kept after the release
  13805. const auto s1 = play (100), s1off = play (0);
  13806. 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));
  13807. // the project file keeps the key link and its mode; an older reader skips it
  13808. lynx::Song song = engine.getSong();
  13809. song.midiLinks[0].mode = 2;
  13810. MidiLink cc7 { 7, 0, pan };
  13811. cc7.mode = 4;
  13812. song.midiLinks.insert (song.midiLinks.begin(), cc7);
  13813. juce::String error;
  13814. const auto json = lynx::ProjectFile::toJson (song);
  13815. const auto back = lynx::ProjectFile::fromJson (json, error);
  13816. check ("cs_note_link_round_trip", back && back->midiLinks == song.midiLinks && json.contains ("midiNoteLinks"), error);
  13817. auto parsed = juce::JSON::parse (json);
  13818. if (auto* o = parsed.getDynamicObject())
  13819. {
  13820. o->removeProperty ("midiNoteLinks");
  13821. o->removeProperty ("midiLinkSettings");
  13822. }
  13823. const auto older = lynx::ProjectFile::fromJson (juce::JSON::toString (parsed), error);
  13824. check ("cs_older_reader_keeps_cc_links_only", older && older->midiLinks.size() == 1 && older->midiLinks[0].cc == 7);
  13825. // "Record automation" of an internal-controller link, saved only when on
  13826. lynx::Automation live;
  13827. live.target = volume;
  13828. live.source.track = 0;
  13829. live.recordLive = true;
  13830. song.automations = { live };
  13831. const auto withLive = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  13832. live.recordLive = false;
  13833. song.automations = { live };
  13834. check ("cs_record_automation_round_trip", withLive && withLive->automations.size() == 1 && withLive->automations[0].recordLive
  13835. && ! lynx::ProjectFile::toJson (song).contains ("recordLive"));
  13836. engine.editSong ([] (lynx::Song& s) { s.midiLinks.clear(); });
  13837. }
  13838. // ---- menus: the control menu, the formula presets, the controller list, the Multilink items
  13839. {
  13840. juce::PopupMenu control;
  13841. lynx::addAutomationItem (control, engine, volume, true);
  13842. engine.setMultilink (true);
  13843. engine.noteTweaked (volume);
  13844. engine.noteTweaked (pan);
  13845. juce::PopupMenu multilink;
  13846. lynx::addMultilinkControlsItems (multilink, engine);
  13847. check ("multilink_queue", engine.multilinkTargets().size() == 2);
  13848. engine.setMultilink (false);
  13849. saveMenus (juce::StringArray { "Control menu", "Formula presets", "Multilink" },
  13850. std::vector<juce::PopupMenu> { control, lynx::remoteControlFormulaMenu ([] (const juce::String&) {}), multilink },
  13851. prefix + "-menus.png");
  13852. saveMenus (juce::StringArray { "Ctrl menu" }, std::vector<juce::PopupMenu> { lynx::remoteControlControllerMenu ([] (int) {}) },
  13853. prefix + "-ctrl-menu.png");
  13854. // the Mode list as its box pops it up (round 190cs)
  13855. juce::PopupMenu modes;
  13856. for (const char* m : { "Default", "Hold", "Latch", "Inc", "Stay" })
  13857. modes.addItem (lynx::tr (m), true, juce::String (m) == "Default", [] {});
  13858. saveMenus (juce::StringArray { "Mode" }, std::vector<juce::PopupMenu> { modes }, prefix + "-mode-menu.png");
  13859. }
  13860. // ---- Settings > MIDI: the input's Port box, the link list with a link's settings
  13861. {
  13862. engine.editSong ([&] (lynx::Song& s) {
  13863. MidiLink l { 74, 2, pan };
  13864. l.port = 4;
  13865. l.formula = "1-Input";
  13866. l.smooth = true;
  13867. s.midiLinks = { MidiLink { 7, 0, volume }, l };
  13868. });
  13869. auto page = lynx::makeMidiPage (engine, {}, false);
  13870. page->setSize (760, 900);
  13871. shoot (*page, "settings-midi");
  13872. }
  13873. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\nresult=" + (allOk ? "OK" : "FAIL") + "\n");
  13874. return allOk;
  13875. }
  13876. // A stand-in hosted plugin for the shot route: three parameters, its state = their values
  13877. struct FlCtlShotPlugin final : juce::AudioPluginInstance
  13878. {
  13879. FlCtlShotPlugin()
  13880. {
  13881. for (const char* n : { "Cutoff", "Resonance", "Drive" })
  13882. addHostedParameter (std::make_unique<juce::AudioParameterFloat> (juce::ParameterID (n, 1), n, 0.0f, 1.0f, 0.5f));
  13883. }
  13884. const juce::String getName() const override { return "Shot plugin"; }
  13885. void prepareToPlay (double, int) override {}
  13886. void releaseResources() override {}
  13887. void processBlock (juce::AudioBuffer<float>&, juce::MidiBuffer&) override {}
  13888. double getTailLengthSeconds() const override { return 0.0; }
  13889. bool acceptsMidi() const override { return false; }
  13890. bool producesMidi() const override { return false; }
  13891. juce::AudioProcessorEditor* createEditor() override { return nullptr; }
  13892. bool hasEditor() const override { return false; }
  13893. int getNumPrograms() override { return 1; }
  13894. int getCurrentProgram() override { return 0; }
  13895. void setCurrentProgram (int) override {}
  13896. const juce::String getProgramName (int) override { return {}; }
  13897. void changeProgramName (int, const juce::String&) override {}
  13898. void getStateInformation (juce::MemoryBlock& b) override
  13899. {
  13900. for (auto* p : getParameters())
  13901. {
  13902. const float v = static_cast<juce::AudioParameterFloat*> (p)->get();
  13903. b.append (&v, sizeof (float));
  13904. }
  13905. }
  13906. void setStateInformation (const void* data, int size) override
  13907. {
  13908. const auto& list = getParameters();
  13909. for (int i = 0; i < list.size() && (i + 1) * (int) sizeof (float) <= size; ++i)
  13910. *static_cast<juce::AudioParameterFloat*> (list[i]) = static_cast<const float*> (data)[i];
  13911. }
  13912. void fillInPluginDescription (juce::PluginDescription& d) const override
  13913. {
  13914. d.name = getName();
  13915. d.pluginFormatName = "Shot";
  13916. d.fileOrIdentifier = "shot";
  13917. }
  13918. };
  13919. static juce::File writeShotSample (const juce::File& file, double hz)
  13920. {
  13921. juce::AudioBuffer<float> buffer (1, 22050);
  13922. for (int i = 0; i < buffer.getNumSamples(); ++i)
  13923. buffer.setSample (0, i, (float) (std::sin (juce::MathConstants<double>::twoPi * hz * i / 44100.0) * std::exp (-i / 6000.0)));
  13924. file.deleteFile();
  13925. juce::WavAudioFormat wav;
  13926. if (auto out = std::unique_ptr<juce::AudioFormatWriter> (wav.createWriterFor (file.createOutputStream().release(), 44100.0, 1, 16, {}, 0)))
  13927. out->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
  13928. return file;
  13929. }
  13930. static bool clickMenuItem (const juce::PopupMenu& menu, const juce::String& text)
  13931. {
  13932. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  13933. if (it.getItem().text == text && it.getItem().isEnabled && it.getItem().action != nullptr)
  13934. {
  13935. it.getItem().action();
  13936. return true;
  13937. }
  13938. return false;
  13939. }
  13940. // --samplerpageshot <prefix> (round 190dh): FL's Sampler page offscreen — the page as FL's shot (dock188a) shows it,
  13941. // the legacy effects, a small window, a zoomed waveform — and its laws turned as a user would; prefix-checks.txt
  13942. bool runSamplerPageShot (const juce::String& prefix)
  13943. {
  13944. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  13945. juce::StringArray report;
  13946. bool allOk = true;
  13947. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  13948. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  13949. allOk = allOk && ok;
  13950. };
  13951. const auto shoot = [&prefix] (juce::Component& c, const char* name) {
  13952. savePng (c.createComponentSnapshot (c.getLocalBounds()), prefix + "-" + name + ".png");
  13953. };
  13954. lynx::AudioEngine engine (false);
  13955. const auto folder = juce::File (prefix).getParentDirectory().getChildFile ("sampler-samples");
  13956. folder.createDirectory();
  13957. // an 808-like kick, 1 s (FL's shot: "Basic 808 Kick.wav")
  13958. const auto kick = folder.getChildFile ("Basic 808 Kick.wav");
  13959. {
  13960. juce::AudioBuffer<float> buffer (1, 44100);
  13961. double phase = 0.0;
  13962. for (int i = 0; i < buffer.getNumSamples(); ++i)
  13963. {
  13964. const auto t = i / 44100.0;
  13965. phase += juce::MathConstants<double>::twoPi * (48.0 + 90.0 * std::exp (-t * 30.0)) / 44100.0;
  13966. buffer.setSample (0, i, (float) (0.9 * std::sin (phase) * std::exp (-t * 3.2)));
  13967. }
  13968. kick.deleteFile();
  13969. juce::WavAudioFormat wav;
  13970. if (auto out = std::unique_ptr<juce::AudioFormatWriter> (wav.createWriterFor (kick.createOutputStream().release(), 44100.0, 1, 16, {}, 0)))
  13971. out->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
  13972. }
  13973. engine.editSong ([&] (lynx::Song& s) {
  13974. if (s.channels.empty())
  13975. s.channels.resize (1);
  13976. lynx::audioclips::loadSampleInto (s.channels[0], kick.getFullPathName().toStdString(), "808 Kick");
  13977. // FL's shot: Resample and Load regions on, Use loop points on, declicking "Out only (no bleeding)"
  13978. s.channels[0].sampler.resampleOnLoad = true;
  13979. });
  13980. const auto sampler = [&engine] { return engine.getSong().channels[0].sampler; };
  13981. auto frame = lynx::makeChannelFrame (engine, 0, 0);
  13982. frame->setSize (frame->getWidth() > 0 ? frame->getWidth() : 700, frame->getHeight() > 0 ? frame->getHeight() : 720);
  13983. frame->createComponentSnapshot (frame->getLocalBounds()); // (starts the waveform's analysis)
  13984. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (8000);
  13985. shoot (*frame, "sampler-page");
  13986. report.add ("page size " + juce::String (frame->getWidth()) + "x" + juce::String (frame->getHeight()));
  13987. // ---- the laws, turned on the page
  13988. auto& f = *frame;
  13989. lynx::samplerPageTurn (f, "pingPong", 1.0);
  13990. check ("ping_pong", sampler().precompute.pingPong);
  13991. lynx::samplerPageTurn (f, "pingPong", 0.0);
  13992. lynx::samplerPageTurn (f, "loopStart", 5000.0);
  13993. check ("loop_start", sampler().loopStart == 5000 && sampler().loopEnd == 5001, juce::String (sampler().loopStart) + "/" + juce::String (sampler().loopEnd));
  13994. lynx::samplerPageTurn (f, "loopEnd", 15000.0);
  13995. check ("loop_end", sampler().loopStart == 5000 && sampler().loopEnd == 15000);
  13996. lynx::samplerPageTurn (f, "loopStart", 20000.0, true); // Shift: the loop moves
  13997. check ("loop_shift_moves", sampler().loopStart == 20000 && sampler().loopEnd == 30000, juce::String (sampler().loopStart) + "/" + juce::String (sampler().loopEnd));
  13998. check ("keep_on_disk_greyed_with_loop", lynx::samplerPageQuery (f, "keepOnDisk") == "0");
  13999. lynx::samplerPageTurn (f, "useLoops", 0.0);
  14000. check ("keep_on_disk_back", lynx::samplerPageQuery (f, "keepOnDisk") == "1" && ! sampler().useLoopPoints);
  14001. check ("not_cut_yet", ! lynx::channelCutsItself (engine.getSong().channels[0]));
  14002. lynx::samplerPageTurn (f, "useLoops", 1.0);
  14003. check ("use_loops_cuts_itself", sampler().useLoopPoints && lynx::channelCutsItself (engine.getSong().channels[0]));
  14004. engine.editSong ([] (lynx::Song& s) {
  14005. lynx::setChannelCutsItself (s.channels[0], 0, false);
  14006. s.channels[0].sampler.useLoopPoints = false;
  14007. });
  14008. lynx::samplerPageTurn (f, "crossfade", 300.0); // (Use loop points off: the crossfade switches it on)
  14009. check ("crossfade_switches_loops_on", sampler().precompute.crossfade == 300 && sampler().useLoopPoints);
  14010. lynx::samplerPageTurn (f, "crossfade", 0.0);
  14011. lynx::samplerPageTurn (f, "pitch", 300.0); // (Resample: FL switches to Auto)
  14012. check ("pitch_resample_to_auto", sampler().keepPitch && sampler().flStretchMode == 5 && sampler().flStretchPitch == 300
  14013. && lynx::samplerPageQuery (f, "mode") == lynx::tr ("General"),
  14014. lynx::samplerPageQuery (f, "mode") + " " + juce::String (sampler().pitch));
  14015. lynx::samplerPageTurn (f, "pitch", 0.0);
  14016. lynx::samplerPageTurn (f, "mode", 1.0); // Resample
  14017. check ("mode_resample", ! sampler().keepPitch && std::abs (sampler().pitch) < 1.0e-4f);
  14018. lynx::samplerPageTurn (f, "time", 4.0);
  14019. lynx::samplerPageTurn (f, "mul", 10000.0);
  14020. check ("time_mul", std::abs (sampler().stretchBeats - 8.0f) < 1.0e-3f && sampler().stretchMul == 10000, juce::String (sampler().stretchBeats));
  14021. lynx::samplerPageTurn (f, "mul", 0.0);
  14022. lynx::samplerPageTurn (f, "time", 0.0);
  14023. lynx::samplerPageTurn (f, "length", 0.5);
  14024. lynx::samplerPageTurn (f, "smpStart", 0.5);
  14025. check ("smp_start_keeps_length", std::abs (sampler().regionStart - 0.5f) < 1.0e-3f && std::abs (sampler().regionEnd - 0.75f) < 1.0e-3f,
  14026. juce::String (sampler().regionStart) + "-" + juce::String (sampler().regionEnd));
  14027. lynx::samplerPageTurn (f, "smpStart", 0.0);
  14028. lynx::samplerPageTurn (f, "length", 1.0);
  14029. lynx::samplerPageTurn (f, "declick", 4.0);
  14030. check ("declick_mode", sampler().declickMode == 4);
  14031. lynx::samplerPageTurn (f, "declick", 0.0);
  14032. // ---- the .lynx keeps what the page set
  14033. {
  14034. lynx::samplerPageTurn (f, "mul", -5000.0);
  14035. lynx::samplerPageTurn (f, "keepOnDisk", 1.0);
  14036. juce::String error;
  14037. const auto json = lynx::ProjectFile::toJson (engine.getSong(), false);
  14038. const auto back = lynx::ProjectFile::fromJson (json, error);
  14039. check ("lynx_round_trip", back.has_value() && back->channels[0].sampler == engine.getSong().channels[0].sampler, error);
  14040. lynx::samplerPageTurn (f, "mul", 0.0);
  14041. lynx::samplerPageTurn (f, "keepOnDisk", 0.0);
  14042. }
  14043. // ---- shots: FL's state again (loop points from the file: none), the legacy panel, a zoom, a small window
  14044. engine.editSong ([] (lynx::Song& s) {
  14045. auto& ch = s.channels[0];
  14046. ch.sampler.loopStart = ch.sampler.loopEnd = -1;
  14047. ch.sampler.useLoopPoints = true;
  14048. ch.sampler.precompute = {};
  14049. });
  14050. lynx::samplerPageTurn (f, "show", 0.0); // (no control: the page shows the channel again)
  14051. frame->createComponentSnapshot (frame->getLocalBounds());
  14052. shoot (*frame, "sampler-page-fl-state");
  14053. lynx::samplerPageTurn (f, "legacy", 1.0);
  14054. check ("legacy_panel", lynx::samplerPageQuery (f, "legacy") == "1");
  14055. shoot (*frame, "sampler-page-legacy");
  14056. lynx::samplerPageTurn (f, "legacy", 0.0);
  14057. lynx::samplerPageTurn (f, "zoom", 0.25);
  14058. check ("zoom_scroll", lynx::samplerPageQuery (f, "scroll") == "0.250", lynx::samplerPageQuery (f, "scroll"));
  14059. shoot (*frame, "sampler-page-zoom");
  14060. lynx::samplerPageTurn (f, "zoom", 1.0);
  14061. frame->setSize (520, 470);
  14062. frame->createComponentSnapshot (frame->getLocalBounds());
  14063. shoot (*frame, "sampler-page-small");
  14064. report.add (juce::String ("result=") + (allOk ? "OK" : "FAIL"));
  14065. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\n");
  14066. return allOk;
  14067. }
  14068. bool runFlCtlShot (const juce::String& prefix)
  14069. {
  14070. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  14071. juce::StringArray report;
  14072. bool allOk = true;
  14073. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  14074. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  14075. allOk = allOk && ok;
  14076. };
  14077. const auto shoot = [&prefix] (juce::Component& c, const char* name) {
  14078. savePng (c.createComponentSnapshot (c.getLocalBounds()), prefix + "-" + name + ".png");
  14079. };
  14080. using lynx::AutomationTarget;
  14081. using lynx::AutomationTargetKind;
  14082. lynx::AudioEngine engine (false);
  14083. engine.editSong ([] (lynx::Song& s) {
  14084. if (s.channels.size() < 3)
  14085. s.channels.resize (3);
  14086. if (s.patterns.empty())
  14087. s.patterns.resize (1);
  14088. s.currentPattern = 0;
  14089. });
  14090. const AutomationTarget volume { AutomationTargetKind::channelVolume, 0 }, pan { AutomationTargetKind::channelPan, 0 };
  14091. // ---- FL's multilink menu: on with two queued controls, off with the last tweaked parameters
  14092. {
  14093. engine.setMultilink (true);
  14094. engine.noteTweaked (volume);
  14095. engine.noteTweaked (pan);
  14096. auto on = lynx::multilinkButtonMenu (engine);
  14097. juce::PopupMenu::MenuItemIterator first (on);
  14098. first.next();
  14099. check ("ml_caption_on", first.getItem().isSectionHeader && first.getItem().text == lynx::tr ("{0} parameters selected", { "2" }), first.getItem().text);
  14100. // Init pattern: the values at the pattern's start; ends multilink
  14101. const auto v0 = engine.currentTargetValue (volume);
  14102. lynx::runMultilinkAction (engine, lynx::mlmenu::Action::initPattern, engine.multilinkTargets(), 0);
  14103. const auto& lanes = engine.getSong().patterns[0].events;
  14104. check ("ml_init_pattern", lanes.size() == 2 && ! lanes[0].events.empty() && lanes[0].events[0].tick == 0
  14105. && std::abs (lanes[0].events[0].value - v0) < 1.0e-6f && ! engine.isMultilinkOn());
  14106. // Randomize keeps multilink on; Humanize moves at most an eighth
  14107. engine.setMultilink (true);
  14108. engine.noteTweaked (volume);
  14109. engine.noteTweaked (pan);
  14110. lynx::runMultilinkAction (engine, lynx::mlmenu::Action::randomize, engine.multilinkTargets(), 1234);
  14111. check ("ml_randomize_keeps_queue", engine.isMultilinkOn() && engine.multilinkTargets().size() == 2);
  14112. const auto before = engine.currentTargetValue (volume);
  14113. lynx::runMultilinkAction (engine, lynx::mlmenu::Action::humanize, engine.multilinkTargets(), 99);
  14114. check ("ml_humanize_small", std::abs (engine.currentTargetValue (volume) - before) <= 0.1251f && engine.isMultilinkOn(),
  14115. juce::String (before) + " -> " + juce::String (engine.currentTargetValue (volume)));
  14116. lynx::runMultilinkAction (engine, lynx::mlmenu::Action::initSong, engine.multilinkTargets(), 0);
  14117. check ("ml_init_song", engine.getSong().findInitialValue (volume) >= 0 && ! engine.isMultilinkOn());
  14118. // off: the last two tweaked parameters, no Cancel
  14119. auto off = lynx::multilinkButtonMenu (engine);
  14120. bool hasCancel = false;
  14121. for (juce::PopupMenu::MenuItemIterator it (off); it.next();)
  14122. hasCancel = hasCancel || it.getItem().text == lynx::tr ("Cancel");
  14123. juce::PopupMenu::MenuItemIterator offFirst (off);
  14124. offFirst.next();
  14125. check ("ml_off_caption", offFirst.getItem().text == lynx::tr ("Last 2 tweaked parameters") && ! hasCancel, offFirst.getItem().text);
  14126. // LYNX's own one-step items stay, after FL's items below a line (greyed while multilink is off)
  14127. juce::String last;
  14128. bool lineBefore = false, prevLine = false;
  14129. for (juce::PopupMenu::MenuItemIterator it (on); it.next();)
  14130. {
  14131. if (it.getItem().text == lynx::tr ("Link to controller"))
  14132. lineBefore = prevLine;
  14133. prevLine = it.getItem().isSeparator;
  14134. last = it.getItem().text;
  14135. }
  14136. check ("ml_lynx_items_after_fl", lineBefore && last == lynx::tr ("Override global links"), last);
  14137. saveMenus (juce::StringArray { "Multilink on (2 queued)", "Multilink off" }, std::vector<juce::PopupMenu> { on, off },
  14138. prefix + "-multilink-menu.png");
  14139. }
  14140. // ---- the plugin menu's spare state and Parameters > Link all parameters...
  14141. {
  14142. FlCtlShotPlugin plugin;
  14143. juce::PopupMenu menu;
  14144. lynx::addPluginWrapperItems (menu, engine, plugin, { AutomationTargetKind::channelParam, 1, 0, 0 });
  14145. saveMenus (juce::StringArray { "Plugin menu: spare state and parameters" }, std::vector<juce::PopupMenu> { menu }, prefix + "-plugin-menu.png");
  14146. const auto targets = lynx::allPluginParameterTargets (plugin, { AutomationTargetKind::channelParam, 1, 0, 0 });
  14147. check ("link_all_parameters", targets.size() == 3 && targets[2].param == 2 && targets[2].index == 1);
  14148. auto* cutoff = static_cast<juce::AudioParameterFloat*> (plugin.getParameters()[0]);
  14149. *cutoff = 0.2f;
  14150. check ("spare_store", clickMenuItem (menu, lynx::tr ("Store in spare state")));
  14151. *cutoff = 0.9f;
  14152. juce::PopupMenu again;
  14153. lynx::addPluginWrapperItems (again, engine, plugin, { AutomationTargetKind::channelParam, 1, 0, 0 });
  14154. check ("spare_flip", clickMenuItem (again, lynx::tr ("Flip with spare state")) && std::abs (cutoff->get() - 0.2f) < 1.0e-6f, juce::String (cutoff->get()));
  14155. 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()));
  14156. lynx::sparestate::shared().forget (&plugin);
  14157. }
  14158. // ---- the sampler's File row: Load (history menu, wheel), Locate, Remove
  14159. {
  14160. const auto folder = juce::File (prefix).getParentDirectory().getChildFile ("flctl-samples");
  14161. folder.createDirectory();
  14162. const auto a = writeShotSample (folder.getChildFile ("Kick 1.wav"), 60.0), b = writeShotSample (folder.getChildFile ("Snare 2.wav"), 200.0),
  14163. c = writeShotSample (folder.getChildFile ("Hat 3.wav"), 900.0);
  14164. lynx::samplehistory::list().clear();
  14165. engine.editSong ([&] (lynx::Song& s) {
  14166. for (const auto& f : { c, b, a }) // (each load goes into the history, newest first)
  14167. lynx::audioclips::loadSampleInto (s.channels[1], f.getFullPathName().toStdString(), f.getFileNameWithoutExtension().toStdString());
  14168. });
  14169. check ("history_order", lynx::samplehistory::list().size() == 3 && lynx::samplehistory::list().front() == a.getFullPathName().toStdString());
  14170. juce::File located;
  14171. lynx::locateInBrowserHandler() = [&located] (const juce::File& f) { located = f; };
  14172. auto frame = lynx::makeChannelFrame (engine, 1, 0);
  14173. frame->setSize (frame->getWidth() > 0 ? frame->getWidth() : 600, frame->getHeight() > 0 ? frame->getHeight() : 820);
  14174. frame->createComponentSnapshot (frame->getLocalBounds()); // (starts the waveform's analysis)
  14175. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (8000);
  14176. shoot (*frame, "sampler-file-row");
  14177. const auto history = lynx::samplerHistoryMenu (*frame);
  14178. check ("history_menu", history.has_value() && history->getNumItems() == 4); // (caption + three samples)
  14179. if (history)
  14180. saveMenus (juce::StringArray { "Load: Sample history" }, std::vector<juce::PopupMenu> { *history }, prefix + "-sample-history.png");
  14181. lynx::samplerFileRowPress (*frame, 0); // wheel down: the next (older) sample
  14182. check ("wheel_down", engine.getSong().channels[1].samplePath == b.getFullPathName().toStdString(), juce::String (engine.getSong().channels[1].samplePath));
  14183. lynx::samplerFileRowPress (*frame, 1); // wheel up: back
  14184. check ("wheel_up", engine.getSong().channels[1].samplePath == a.getFullPathName().toStdString());
  14185. lynx::samplerFileRowPress (*frame, 2);
  14186. check ("locate", located == a, located.getFullPathName());
  14187. lynx::samplerFileRowPress (*frame, 3);
  14188. check ("remove", engine.getSong().channels[1].samplePath.empty());
  14189. engine.undo();
  14190. check ("remove_undo", engine.getSong().channels[1].samplePath == a.getFullPathName().toStdString());
  14191. lynx::locateInBrowserHandler() = nullptr;
  14192. }
  14193. // ---- a sampler running FL's voice: FL's Envelope / instrument page with the tensions, the predelay and presets
  14194. {
  14195. engine.editSong ([] (lynx::Song& s) {
  14196. auto& ch = s.channels[2];
  14197. ch.instrument = lynx::InstrumentKind::sampler;
  14198. ch.name = "FL sampler";
  14199. const auto snap = lynx::flvp::defaultSnapshot();
  14200. ch.sampler.flChannel.assign (90, 0);
  14201. std::memcpy (ch.sampler.flChannel.data(), snap.data(), 85 * 4);
  14202. std::memcpy (&ch.sampler.flChannel[85], snap.data() + 0x15c, 4);
  14203. std::memcpy (&ch.sampler.flChannel[86], snap.data() + 0x160, 4);
  14204. std::memcpy (&ch.sampler.flChannel[87], snap.data() + 0x168, 4);
  14205. ch.sampler.flChannel[88] = 96;
  14206. ch.sampler.flChannel[89] = 0;
  14207. auto& vol = ch.sampler.flChannel; // the volume envelope on, bent
  14208. vol[17 + 1] = -1;
  14209. vol[17 + 2] = 4000; // predelay
  14210. vol[17 + 14] = -70; // attack tension
  14211. vol[17 + 15] = 60; // decay tension
  14212. vol[17 + 16] = -40; // release tension
  14213. });
  14214. auto frame = lynx::makeChannelFrame (engine, 2, 1);
  14215. frame->setSize (frame->getWidth() > 0 ? frame->getWidth() : 600, frame->getHeight() > 0 ? frame->getHeight() : 560);
  14216. shoot (*frame, "sampler-fl-envelope");
  14217. check ("fl_page_shown", lynx::flVoicePresetsMenu (*frame).has_value());
  14218. lynx::flVoicePresetFolder().deleteRecursively();
  14219. check ("preset_save", lynx::flVoiceSavePreset (*frame, "Bent volume")
  14220. && lynx::flVoicePresetFolder().getChildFile ("Bent volume.CHENV").getSize() == 68);
  14221. if (const auto menu = lynx::flVoicePresetsMenu (*frame))
  14222. saveMenus (juce::StringArray { "Channel envelope presets" }, std::vector<juce::PopupMenu> { *menu }, prefix + "-envelope-presets.png");
  14223. // the preset into the pitch target: its record becomes the saved one
  14224. lynx::showFlVoiceTarget (*frame, lynx::flvoice::pitch);
  14225. const auto loaded = lynx::flVoiceLoadPreset (*frame, lynx::flVoicePresetFolder().getChildFile ("Bent volume.CHENV"));
  14226. const auto& fl = engine.getSong().channels[2].sampler.flChannel;
  14227. check ("preset_load", loaded && fl.size() == 90 && fl[68 + 2] == 4000 && fl[68 + 14] == -70 && fl[68 + 16] == -40 && fl[88] == 96);
  14228. engine.undo();
  14229. check ("preset_load_undo", engine.getSong().channels[2].sampler.flChannel[68 + 14] != -70);
  14230. }
  14231. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\nresult=" + (allOk ? "OK" : "FAIL") + "\n");
  14232. return allOk;
  14233. }
  14234. // --flplshot (round 190dx): see the dispatch above
  14235. bool runHdrShot190ft (const juce::String& prefix)
  14236. {
  14237. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  14238. juce::StringArray report;
  14239. bool allOk = true;
  14240. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  14241. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  14242. allOk = allOk && ok;
  14243. };
  14244. const auto list = [] (const std::vector<int>& v) {
  14245. juce::StringArray out;
  14246. for (auto i : v)
  14247. out.add (juce::String (i));
  14248. return out.joinIntoString (",");
  14249. };
  14250. lynx::AudioEngine engine (false);
  14251. lynx::MainComponent ui (engine, false);
  14252. ui.setSize (1600, 900);
  14253. {
  14254. auto song = lynx::Song::makeDefault();
  14255. song.playlist.clear();
  14256. for (int t = 0; t < 6; ++t)
  14257. {
  14258. if ((int) song.playlistTracks.size() <= t)
  14259. song.playlistTracks.resize ((std::size_t) t + 1);
  14260. song.playlistTracks[(std::size_t) t].name = juce::String ("Track " + juce::String (t + 1)).toStdString();
  14261. for (int k = 0; k < 2; ++k)
  14262. {
  14263. lynx::Clip c;
  14264. c.kind = lynx::ClipKind::pattern;
  14265. c.pattern = 0;
  14266. c.track = t;
  14267. c.start = (std::int64_t) (k * 4 + t % 3) * lynx::ppq;
  14268. c.length = 2 * lynx::ppq;
  14269. song.playlist.push_back (c);
  14270. }
  14271. }
  14272. if (song.mixer.size() < 4)
  14273. song.mixer.resize (4);
  14274. song.playlistTracks[2].mode = lynx::PlaylistTrackMode::audio; // an audio track linked to mixer track 3
  14275. song.playlistTracks[2].mixerTrack = 3;
  14276. song.playlistTracks[2].name = "Vox";
  14277. engine.setSong (std::move (song));
  14278. }
  14279. engine.dispatchPendingMessages();
  14280. ui.selectTabForSnapshot (2);
  14281. engine.dispatchPendingMessages();
  14282. auto& pl = ui.getPlaylistForSnapshot();
  14283. pl.setSize (juce::jmax (pl.getWidth(), 900), juce::jmax (pl.getHeight(), 600));
  14284. auto source = juce::Desktop::getInstance().getMainMouseSource();
  14285. const auto now = juce::Time::getCurrentTime();
  14286. const juce::ModifierKeys left (juce::ModifierKeys::leftButtonModifier);
  14287. const int ctrl = juce::ModifierKeys::commandModifier; // (FL's Ctrl: Cmd on a Mac)
  14288. const int shift = juce::ModifierKeys::shiftModifier;
  14289. const int alt = juce::ModifierKeys::altModifier;
  14290. const auto event = [&] (juce::Component& c, juce::Point<int> p, juce::ModifierKeys mods, juce::Point<int> down, int clicks, bool dragged) {
  14291. 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);
  14292. };
  14293. // a press (and release) at p with the modifiers; `to`: a drag there before the release
  14294. const auto press = [&] (juce::Component& c, juce::Point<int> p, juce::ModifierKeys mods, std::optional<juce::Point<int>> to = {}, int clicks = 1) {
  14295. const auto down = mods.withFlags (juce::ModifierKeys::leftButtonModifier);
  14296. c.mouseMove (event (c, p, mods, p, 1, false));
  14297. c.mouseDown (event (c, p, down, p, clicks, false));
  14298. if (to)
  14299. c.mouseDrag (event (c, *to, down, p, clicks, true));
  14300. c.mouseUp (event (c, to ? *to : p, mods, p, clicks, to.has_value()));
  14301. };
  14302. const auto headerPoint = [&] (int track) { const auto r = pl.trackRowForSnapshot (track); return juce::Point<int> (40, r.getY() + juce::jmin (10, r.getHeight() / 3)); };
  14303. const auto bandPoint = [&] (int track) { const auto r = pl.trackRowForSnapshot (track); return juce::Point<int> (40, r.getBottom() - 2); };
  14304. const auto clipsOn = [&] (const std::vector<int>& tracks) {
  14305. std::vector<int> out;
  14306. const auto& song = engine.getSong();
  14307. for (int i = 0; i < (int) song.playlist.size(); ++i)
  14308. if (std::find (tracks.begin(), tracks.end(), song.playlist[(std::size_t) i].track) != tracks.end())
  14309. out.push_back (i);
  14310. return out;
  14311. };
  14312. const auto sortedClips = [&] { auto v = pl.getSelectedClips(); std::sort (v.begin(), v.end()); return v; };
  14313. const auto headerShot = [&] (const juce::String& name, int rows) {
  14314. const auto bottom = pl.trackRowForSnapshot (rows).getY();
  14315. savePng (pl.createComponentSnapshot ({ 0, 0, juce::jmin (pl.getWidth(), 760), juce::jmin (pl.getHeight(), bottom + 12) }), prefix + name);
  14316. };
  14317. // ---- 1. selection (AUTracksPanelMouseDown / FUN_012e83e0)
  14318. press (pl, headerPoint (1), {});
  14319. check ("click_selects_alone", pl.selectedTracksForSnapshot() == std::vector<int> { 1 }, list (pl.selectedTracksForSnapshot()));
  14320. pl.selectClipsForSnapshot ({});
  14321. // LYNX extra (issue #163): Ctrl+click adds / removes one track, its clips follow
  14322. press (pl, headerPoint (3), ctrl);
  14323. check ("ctrl_click_adds_lynx", pl.selectedTracksForSnapshot() == std::vector<int> { 1, 3 } && sortedClips() == clipsOn ({ 3 }),
  14324. list (pl.selectedTracksForSnapshot()) + " clips " + list (sortedClips()));
  14325. press (pl, headerPoint (5), ctrl);
  14326. press (pl, headerPoint (1), ctrl);
  14327. check ("ctrl_click_removes_lynx", pl.selectedTracksForSnapshot() == std::vector<int> { 3, 5 } && sortedClips() == clipsOn ({ 3, 5 }),
  14328. list (pl.selectedTracksForSnapshot()) + " clips " + list (sortedClips()));
  14329. // FL's own toggle: Ctrl+Shift+click (its clips are added)
  14330. press (pl, headerPoint (1), ctrl | shift);
  14331. check ("ctrl_shift_click_adds", pl.selectedTracksForSnapshot() == std::vector<int> { 1, 3, 5 }, list (pl.selectedTracksForSnapshot()));
  14332. check ("ctrl_shift_click_adds_clips", sortedClips() == clipsOn ({ 1, 3, 5 }), list (sortedClips()));
  14333. press (pl, headerPoint (3), ctrl | shift);
  14334. check ("ctrl_shift_click_removes", pl.selectedTracksForSnapshot() == std::vector<int> { 1, 5 }, list (pl.selectedTracksForSnapshot()));
  14335. press (pl, headerPoint (3), ctrl | shift);
  14336. check ("ctrl_shift_click_adds_again", pl.selectedTracksForSnapshot() == std::vector<int> { 1, 3, 5 }, list (pl.selectedTracksForSnapshot()));
  14337. pl.selectClipsForSnapshot ({});
  14338. headerShot ("-ctrl-multiselect.png", 6);
  14339. press (pl, headerPoint (0), ctrl, headerPoint (2));
  14340. check ("ctrl_drag_range_with_clips", pl.selectedTracksForSnapshot() == std::vector<int> { 0, 1, 2 } && sortedClips() == clipsOn ({ 0, 1, 2 }),
  14341. list (pl.selectedTracksForSnapshot()) + " clips " + list (sortedClips()));
  14342. press (pl, headerPoint (1), shift); // LYNX's own Shift+click range (from the last clicked track, 0)
  14343. check ("lynx_shift_range_kept", pl.selectedTracksForSnapshot() == std::vector<int> { 0, 1 }, list (pl.selectedTracksForSnapshot()));
  14344. {
  14345. int linked = -1;
  14346. auto old = pl.onLinkedMixerTrack;
  14347. pl.onLinkedMixerTrack = [&linked] (int insert) { linked = insert; };
  14348. press (pl, headerPoint (2), {});
  14349. check ("audio_track_click_links_mixer_track", linked == 3, juce::String (linked));
  14350. pl.onLinkedMixerTrack = old;
  14351. }
  14352. // ---- 2. the resize band (FUN_00ea93a0, AUTracksPanelMouseMove)
  14353. const auto heightOf = [&] (int t) { return pl.trackRowForSnapshot (t).getHeight(); };
  14354. const auto& tracks = [&]() -> const std::vector<lynx::PlaylistTrack>& { return engine.getSong().playlistTracks; };
  14355. press (pl, headerPoint (4), {}); // (track 4 alone selected)
  14356. {
  14357. const auto start = bandPoint (4);
  14358. press (pl, start, {}, start + juce::Point<int> (0, 41));
  14359. 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)
  14360. headerShot ("-resized.png", 6);
  14361. const auto again = bandPoint (4);
  14362. press (pl, again, {}, again + juce::Point<int> (0, -100)); // (above the row's top, but less than 32 px)
  14363. check ("drag_stops_at_16", heightOf (4) == 16, juce::String (heightOf (4)));
  14364. press (pl, bandPoint (4), alt);
  14365. check ("alt_click_resets", tracks()[4].height == 0 && tracks()[4].lockedHeight == -1 && heightOf (4) == 48, juce::String (heightOf (4)));
  14366. press (pl, bandPoint (4), {}, {}, 2); // the second press of a double click
  14367. check ("double_click_locks_small", tracks()[4].lockedHeight == 1 && heightOf (4) == 16, juce::String (tracks()[4].lockedHeight));
  14368. press (pl, bandPoint (4), {});
  14369. check ("click_on_locked_band_unlocks", tracks()[4].lockedHeight == -1 && heightOf (4) == 48, juce::String (tracks()[4].lockedHeight));
  14370. const auto top = pl.trackRowForSnapshot (4).getY();
  14371. const auto b = bandPoint (4);
  14372. press (pl, b, {}, juce::Point<int> (b.x, top - 40));
  14373. check ("drag_past_the_top_groups", tracks()[4].grouped && tracks()[4].height == 0, juce::String ((int) tracks()[4].grouped));
  14374. const auto b2 = bandPoint (4);
  14375. press (pl, b2, {}, juce::Point<int> (b2.x, pl.trackRowForSnapshot (4).getY() - 40));
  14376. check ("again_ungroups", ! tracks()[4].grouped, juce::String ((int) tracks()[4].grouped));
  14377. }
  14378. {
  14379. // every selected track: the same height, from the first one's top to the mouse
  14380. press (pl, headerPoint (1), {});
  14381. press (pl, headerPoint (2), ctrl | shift);
  14382. press (pl, headerPoint (3), ctrl | shift);
  14383. const auto top = pl.trackRowForSnapshot (1).getY();
  14384. const auto b = bandPoint (2);
  14385. press (pl, b, {}, juce::Point<int> (b.x, top + 2 * 50));
  14386. check ("selected_tracks_share_the_height", tracks()[1].height == 50 && tracks()[2].height == 50 && tracks()[3].height == 50,
  14387. juce::String (tracks()[1].height) + "," + juce::String (tracks()[2].height) + "," + juce::String (tracks()[3].height));
  14388. headerShot ("-selected-resized.png", 6);
  14389. }
  14390. // ---- 3. saved: .lynx round trip and the .flp size factor
  14391. {
  14392. engine.editSong ([] (lynx::Song& s) { s.playlistTracks[5].height = 300; s.playlistTracks[0].lockedHeight = 60; });
  14393. const auto json = lynx::ProjectFile::toJson (engine.getSong());
  14394. juce::String error;
  14395. const auto back = lynx::ProjectFile::fromJson (json, error);
  14396. check ("lynx_round_trip", back && back->playlistTracks.size() > 5 && back->playlistTracks[5].height == 300 && back->playlistTracks[1].height == 50
  14397. && back->playlistTracks[0].lockedHeight == 60, error);
  14398. lynx::flpexport::Options options;
  14399. lynx::flpexport::Report flpReport;
  14400. const auto project = flp::parseProject (lynx::flpexport::exportFlp (engine.getSong(), options, flpReport));
  14401. float size5 = -1.0f, size1 = -1.0f;
  14402. for (const auto& arrangement : project.arrangements)
  14403. for (const auto& t : arrangement.tracks)
  14404. {
  14405. if (t.index == 5) size5 = t.heightScale;
  14406. if (t.index == 1) size1 = t.heightScale;
  14407. }
  14408. 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,
  14409. juce::String (size5) + " " + juce::String (size1));
  14410. }
  14411. // ---- 4. the mixer strips (round 170b's FL rules): Ctrl+click alone, Ctrl+Shift+click adds / removes
  14412. {
  14413. ui.selectTabForSnapshot (3);
  14414. engine.editSong ([] (lynx::Song& s) { if (s.mixer.size() < 9) s.mixer.resize (9); });
  14415. engine.dispatchPendingMessages();
  14416. auto& mixer = ui.getMixerForSnapshot();
  14417. mixer.setSize (1400, 640);
  14418. auto& strips = mixer.getStripsForSnapshot();
  14419. strips.setSize (juce::jmax (strips.getWidth(), 1300), juce::jmax (strips.getHeight(), 560));
  14420. const auto at = [&] (int t) { return juce::Point<int> (strips.stripLeft (t) + 8, strips.getHeight() / 2 + 40); };
  14421. press (strips, at (2), {});
  14422. check ("mixer_click_alone", strips.getSelection() == std::vector<int> { 2 }, list (strips.getSelection()));
  14423. // LYNX extra (issue #163): Ctrl+click adds / removes one insert
  14424. press (strips, at (4), ctrl);
  14425. press (strips, at (6), ctrl);
  14426. check ("mixer_ctrl_click_adds_lynx", strips.getSelection() == std::vector<int> { 2, 4, 6 }, list (strips.getSelection()));
  14427. press (strips, at (4), ctrl);
  14428. check ("mixer_ctrl_click_removes_lynx", strips.getSelection() == std::vector<int> { 2, 6 }, list (strips.getSelection()));
  14429. // FL: Ctrl+Shift+click adds / removes too
  14430. press (strips, at (5), ctrl | shift);
  14431. check ("mixer_ctrl_shift_click_adds", strips.getSelection() == std::vector<int> { 2, 5, 6 }, list (strips.getSelection()));
  14432. savePng (mixer.createComponentSnapshot ({ 0, 0, juce::jmin (mixer.getWidth(), 900), mixer.getHeight() }), prefix + "-mixer-ctrl-multiselect.png");
  14433. // FL: Ctrl+drag across the strips = the range from the press, alone
  14434. press (strips, at (3), ctrl, at (4));
  14435. check ("mixer_ctrl_drag_range", strips.getSelection() == std::vector<int> { 3, 4 }, list (strips.getSelection()));
  14436. }
  14437. // ---- 5. round 190gw (live check 190gu B1): FL's default row, the left lock strip, the right selection strip
  14438. {
  14439. ui.selectTabForSnapshot (2);
  14440. auto song = lynx::Song::makeDefault();
  14441. song.playlist.clear();
  14442. song.playlistTracks.assign (6, {});
  14443. for (int t = 0; t < 6; ++t)
  14444. song.playlistTracks[(std::size_t) t].name = juce::String ("Track " + juce::String (t + 1)).toStdString();
  14445. engine.setSong (std::move (song));
  14446. engine.dispatchPendingMessages();
  14447. pl.setSize (juce::jmax (pl.getWidth(), 900), juce::jmax (pl.getHeight(), 600));
  14448. check ("gw_default_row_48", heightOf (0) == 48 && heightOf (5) == 48, juce::String (heightOf (0)));
  14449. const auto rowMid = [&] (int t) { const auto r = pl.trackRowForSnapshot (t); return r.getY() + r.getHeight() / 2 - 4; };
  14450. const auto stripX = pl.headerWidthForSnapshot() - 4;
  14451. // the left strip (x < 10): the row flips to the smallest size and back; nothing selects
  14452. press (pl, { 2, rowMid (2) }, {});
  14453. check ("gw_left_strip_smallest", heightOf (2) == 16 && tracks()[2].lockedHeight == 1, juce::String (heightOf (2)));
  14454. press (pl, { 2, rowMid (2) }, {});
  14455. check ("gw_left_strip_back", heightOf (2) == 48 && tracks()[2].lockedHeight == -1, juce::String (heightOf (2)));
  14456. // the right strip: click = alone, Shift+click toggles, right-click toggles with no menu
  14457. press (pl, { stripX, rowMid (0) }, {});
  14458. check ("gw_strip_click_alone", pl.selectedTracksForSnapshot() == std::vector<int> { 0 }, list (pl.selectedTracksForSnapshot()));
  14459. press (pl, { stripX, rowMid (1) }, shift);
  14460. check ("gw_strip_shift_click_adds", pl.selectedTracksForSnapshot() == std::vector<int> { 0, 1 }, list (pl.selectedTracksForSnapshot()));
  14461. headerShot ("-gw-strip-two-selected.png", 6);
  14462. press (pl, { stripX, rowMid (0) }, shift);
  14463. check ("gw_strip_shift_click_removes", pl.selectedTracksForSnapshot() == std::vector<int> { 1 }, list (pl.selectedTracksForSnapshot()));
  14464. {
  14465. const juce::Point<int> p { stripX, rowMid (4) };
  14466. const juce::ModifierKeys right (juce::ModifierKeys::rightButtonModifier);
  14467. pl.mouseDown (event (pl, p, right, p, 1, false));
  14468. pl.mouseUp (event (pl, p, {}, p, 1, false));
  14469. }
  14470. check ("gw_strip_right_click_adds", pl.selectedTracksForSnapshot() == std::vector<int> { 1, 4 }, list (pl.selectedTracksForSnapshot()));
  14471. // a drag down the strip: the tracks crossed join (FUN_012e8740)
  14472. press (pl, { stripX, rowMid (0) }, {}, juce::Point<int> (stripX, rowMid (4)));
  14473. check ("gw_strip_drag_range", pl.selectedTracksForSnapshot() == std::vector<int> { 0, 1, 2, 3, 4 }, list (pl.selectedTracksForSnapshot()));
  14474. headerShot ("-gw-strip-range.png", 6);
  14475. // a double click: the track alone <-> every track
  14476. press (pl, { stripX, rowMid (2) }, {});
  14477. press (pl, { stripX, rowMid (2) }, {}, {}, 2);
  14478. check ("gw_strip_double_click_all", (int) pl.selectedTracksForSnapshot().size() == pl.numTracksForSnapshot(), list (pl.selectedTracksForSnapshot()));
  14479. press (pl, { stripX, rowMid (1) }, {});
  14480. // .lynx: the new default row is saved; a project from before (no key) keeps LYNX's old 38 px row
  14481. juce::String error;
  14482. const auto json = lynx::ProjectFile::toJson (engine.getSong());
  14483. const auto back = lynx::ProjectFile::fromJson (json, error);
  14484. check ("gw_lynx_row_saved", back && back->playlistRowHeight == 48, error);
  14485. auto parsed = juce::JSON::parse (json);
  14486. if (auto* o = parsed.getDynamicObject())
  14487. o->removeProperty ("playlistRowHeight");
  14488. const auto old = lynx::ProjectFile::fromJson (juce::JSON::toString (parsed), error);
  14489. check ("gw_old_lynx_keeps_38", old && old->playlistRowHeight == 38, error);
  14490. engine.setSong (*old);
  14491. engine.dispatchPendingMessages();
  14492. check ("gw_old_lynx_rows_38", heightOf (0) == 38, juce::String (heightOf (0)));
  14493. // an automation clip with two target links (Crossfade with) comes back with its links and formulas
  14494. auto linked = lynx::Song::makeDefault();
  14495. linked.channels.resize (2);
  14496. lynx::Automation a;
  14497. a.links = { { { lynx::AutomationTargetKind::channelAdjust, 0, 0, lynx::leveladjust::volume }, lynx::clipops::crossfadeOutFormula },
  14498. { { lynx::AutomationTargetKind::channelAdjust, 1, 0, lynx::leveladjust::volume }, lynx::clipops::crossfadeInFormula } };
  14499. a.target = a.links[0].target;
  14500. a.points = { { 0, 1.0f, 0.0f }, { 384, 0.0f, 0.0f } };
  14501. linked.automations.push_back (a);
  14502. const auto linkedBack = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (linked), error);
  14503. check ("gw_lynx_links_round_trip", linkedBack && linkedBack->automations.size() == linked.automations.size()
  14504. && linkedBack->automations.back().links == a.links && linkedBack->automations.back().target == a.target, error);
  14505. // Sampler › Open in new Fruity Slicer / Slicex channel: named after the sample, " #n" when taken
  14506. const auto wav = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-190gw").getChildFile ("Basic 808 Clap.wav");
  14507. wav.getParentDirectory().createDirectory();
  14508. {
  14509. juce::AudioBuffer<float> b (1, 4410);
  14510. for (int i = 0; i < b.getNumSamples(); ++i)
  14511. b.setSample (0, i, 0.5f * std::sin ((float) i * 0.2f) * (1.0f - (float) i / (float) b.getNumSamples()));
  14512. wav.deleteFile();
  14513. juce::WavAudioFormat format;
  14514. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream());
  14515. if (auto* w = format.createWriterFor (out.get(), 44100.0, 1, 16, {}, 0))
  14516. {
  14517. out.release();
  14518. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  14519. writer->writeFromAudioSampleBuffer (b, 0, b.getNumSamples());
  14520. }
  14521. }
  14522. engine.editSong ([] (lynx::Song& s) {
  14523. s.channels.resize (1);
  14524. s.channels[0] = {};
  14525. s.channels[0].name = "Basic 808 Clap";
  14526. });
  14527. engine.dispatchPendingMessages();
  14528. if (lynx::openInNewChannelHandler())
  14529. {
  14530. lynx::openInNewChannelHandler() (wav, lynx::InstrumentKind::fruityslicer);
  14531. lynx::openInNewChannelHandler() (wav, lynx::InstrumentKind::slicex);
  14532. }
  14533. engine.dispatchPendingMessages();
  14534. const auto& ch = engine.getSong().channels;
  14535. 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"
  14536. && ch[1].instrument == lynx::InstrumentKind::fruityslicer && ch[2].instrument == lynx::InstrumentKind::slicex,
  14537. ch.size() >= 3 ? juce::String::fromUTF8 (ch[1].name.c_str()) + " | " + juce::String::fromUTF8 (ch[2].name.c_str()) : juce::String ((int) ch.size()));
  14538. wav.getParentDirectory().deleteRecursively();
  14539. // the mixer's two boxes (live check 190gu B4): "Insert multiple..." asks "Number of tracks to add" (1),
  14540. // "Add multiple..." "Enter the number of mixer tracks to add" (10)
  14541. for (const auto adding : { false, true })
  14542. {
  14543. auto box = lynx::MixerStrips::makeInsertMultipleBox (adding);
  14544. const auto text = box->getTextEditorContents ("count");
  14545. check (adding ? "gw_add_multiple_box" : "gw_insert_multiple_box", text == (adding ? "10" : "1"), text);
  14546. if (box->getWidth() > 0 && box->getHeight() > 0)
  14547. savePng (box->createComponentSnapshot (box->getLocalBounds()), prefix + (adding ? "-gw-add-multiple-box.png" : "-gw-insert-multiple-box.png"));
  14548. }
  14549. }
  14550. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\nresult=" + (allOk ? "OK" : "FAIL") + "\n");
  14551. return allOk;
  14552. }
  14553. // --userfixshot190ib (round 190ib): see the dispatch above
  14554. bool runUserFixShot190ib (const juce::String& prefix)
  14555. {
  14556. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  14557. juce::StringArray report;
  14558. bool allOk = true;
  14559. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  14560. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  14561. allOk = allOk && ok;
  14562. };
  14563. lynx::AudioEngine engine (false);
  14564. lynx::MainComponent ui (engine, false);
  14565. ui.setSize (1600, 900);
  14566. engine.dispatchPendingMessages();
  14567. // ---- #182: a real JUCE popup menu inside a host component, keys sent to its window as the keyboard would
  14568. juce::Component host;
  14569. host.setSize (560, 900);
  14570. const auto typeInto = [&host] (const juce::String& text) {
  14571. auto* menuWindow = host.getNumChildComponents() > 0 ? host.getChildComponent (host.getNumChildComponents() - 1) : nullptr;
  14572. for (auto c : text)
  14573. if (menuWindow != nullptr)
  14574. menuWindow->keyPressed (juce::KeyPress ((int) juce::CharacterFunctions::toLowerCase (c), 0, c));
  14575. return menuWindow != nullptr;
  14576. };
  14577. const auto shotMenu = [&host, &prefix] (const juce::String& name) {
  14578. savePng (host.createComponentSnapshot (host.getLocalBounds()), prefix + name);
  14579. };
  14580. {
  14581. auto& pl = ui.getPlaylistForSnapshot();
  14582. pl.editMenu().showMenuAsync (juce::PopupMenu::Options().withParentComponent (&host).withTargetScreenArea ({ 8, 8, 1, 1 }));
  14583. check ("menu_shown", host.getNumChildComponents() > 0, juce::String (host.getNumChildComponents()));
  14584. shotMenu ("-menu-0.png");
  14585. typeInto ("d");
  14586. shotMenu ("-menu-d.png"); // the first item starting with D
  14587. typeInto ("d");
  14588. shotMenu ("-menu-dd.png"); // D again: the next one
  14589. juce::Time::waitForMillisecondCounter (juce::Time::getMillisecondCounter() + 1100); // (a pause: a new prefix)
  14590. typeInto ("drop a");
  14591. shotMenu ("-menu-drop-a.png"); // "Drop audio on track headers"
  14592. juce::PopupMenu::dismissAllActiveMenus();
  14593. }
  14594. {
  14595. auto& pr = ui.getPianoRollForSnapshot();
  14596. pr.moreMenuForSnapshot().showMenuAsync (juce::PopupMenu::Options().withParentComponent (&host).withTargetScreenArea ({ 8, 8, 1, 1 }));
  14597. juce::Time::waitForMillisecondCounter (juce::Time::getMillisecondCounter() + 1100);
  14598. typeInto ("preview");
  14599. shotMenu ("-pianoroll-preview.png"); // #183's item, reached by typing its name
  14600. juce::PopupMenu::dismissAllActiveMenus();
  14601. check ("preview_while_playing_off_by_default", ! lynx::PianoRollComponent::previewWhilePlaying);
  14602. }
  14603. // ---- #181: Ctrl+, (Cmd+, on macOS) through the main window's key handling opens Settings, again closes it
  14604. const auto ctrlComma = juce::KeyPress (',', juce::ModifierKeys::commandModifier, ',');
  14605. check ("settings_closed_first", lynx::shownSettingsPage() < 0);
  14606. ui.keyPressed (ctrlComma);
  14607. check ("ctrl_comma_opens_settings", lynx::shownSettingsPage() == (int) lynx::SettingsPage::general, juce::String (lynx::shownSettingsPage()));
  14608. ui.keyPressed (ctrlComma);
  14609. check ("ctrl_comma_again_closes_it", lynx::shownSettingsPage() < 0, juce::String (lynx::shownSettingsPage()));
  14610. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\nresult=" + (allOk ? "OK" : "FAIL") + "\n");
  14611. return allOk;
  14612. }
  14613. // --issuesshot190ht (round 190ht): see the dispatch above
  14614. bool runIssuesShot190ht (const juce::String& prefix)
  14615. {
  14616. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  14617. juce::StringArray report;
  14618. bool allOk = true;
  14619. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  14620. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  14621. allOk = allOk && ok;
  14622. };
  14623. using namespace lynx;
  14624. AudioEngine engine (false);
  14625. MainComponent ui (engine, false);
  14626. ui.setSize (1600, 900);
  14627. const auto bar = (std::int64_t) 4 * ppq;
  14628. {
  14629. // Kick (1 bar), Bass (2 bars, a long note across its second bar), Lead (1 bar), Pad (1 bar): blocks in rows
  14630. auto song = Song::makeDefault();
  14631. song.playlist.clear();
  14632. song.patterns.clear();
  14633. const auto pattern = [&song] (const char* name, std::uint32_t colour, int channel, std::int64_t length) {
  14634. auto& p = song.patterns.emplace_back();
  14635. p.name = name;
  14636. p.colour = colour;
  14637. for (int step : { 0, 4, 8, 12 })
  14638. p.toggleStep (channel, step);
  14639. p.lengthTicks = length;
  14640. return (int) song.patterns.size() - 1;
  14641. };
  14642. pattern ("Kick", 0xFFD85A3C, 0, bar);
  14643. const auto bass = pattern ("Bass", 0xFF3C8DD8, 1, 0);
  14644. Note longNote;
  14645. longNote.channel = 1;
  14646. longNote.start = 6 * ppq;
  14647. longNote.length = 2 * ppq;
  14648. song.patterns[(std::size_t) bass].notes.push_back (longNote);
  14649. song.patterns[(std::size_t) bass].sortNotes();
  14650. pattern ("Lead", 0xFF8A5CD8, 2, bar);
  14651. pattern ("Pad", 0xFF5CB85C, 3, bar);
  14652. song.patternBlocksOn = true;
  14653. for (int b = 0; b < 8; ++b)
  14654. patternblocks::place (song, 0, b * bar);
  14655. patternblocks::place (song, 1, 0);
  14656. patternblocks::place (song, 1, 4 * bar);
  14657. for (int b = 2; b < 6; ++b)
  14658. patternblocks::place (song, 2, b * bar);
  14659. patternblocks::place (song, 3, 0);
  14660. engine.setSong (std::move (song));
  14661. }
  14662. engine.dispatchPendingMessages();
  14663. ui.selectTabForSnapshot (2);
  14664. engine.dispatchPendingMessages();
  14665. auto& pl = ui.getPlaylistForSnapshot();
  14666. pl.setSize (juce::jmax (pl.getWidth(), 1000), juce::jmax (pl.getHeight(), 640));
  14667. pl.setViewForSnapshot (90.0, 0, 0); // (bar 1 at the left edge)
  14668. pl.setBlocksHeight (6 + 5 * 18 + 6);
  14669. engine.dispatchPendingMessages();
  14670. const auto& song = [&]() -> const Song& { return engine.getSong(); };
  14671. auto* blocks = pl.getBlocksViewForSnapshot();
  14672. check ("blocks_view", blocks != nullptr && blocks->isVisible());
  14673. if (blocks == nullptr)
  14674. {
  14675. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\nresult=FAIL\n");
  14676. return false;
  14677. }
  14678. const auto shotBlocks = [&] (const juce::String& name) {
  14679. engine.dispatchPendingMessages();
  14680. const auto area = blocks->getBoundsInParent().withWidth (juce::jmin (pl.getWidth(), 900)).expanded (0, 2).getIntersection (pl.getLocalBounds());
  14681. savePng (pl.createComponentSnapshot (area), prefix + name);
  14682. };
  14683. auto source = juce::Desktop::getInstance().getMainMouseSource();
  14684. const juce::ModifierKeys left (juce::ModifierKeys::leftButtonModifier), right (juce::ModifierKeys::rightButtonModifier);
  14685. juce::Point<float> pressedAt;
  14686. const auto bEvent = [&] (int row, std::int64_t tick, juce::ModifierKeys mods, int clicks = 1) {
  14687. const auto at = blocks->pointForSnapshot (row, tick).toFloat();
  14688. const auto now = juce::Time::getCurrentTime();
  14689. return juce::MouseEvent (source, at, mods, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, blocks, blocks, now, pressedAt, now, clicks, at != pressedAt);
  14690. };
  14691. const auto bPress = [&] (int row, std::int64_t tick, juce::ModifierKeys mods) {
  14692. pressedAt = blocks->pointForSnapshot (row, tick).toFloat();
  14693. blocks->mouseDown (bEvent (row, tick, mods));
  14694. };
  14695. const auto bDrag = [&] (int row, std::int64_t tick, juce::ModifierKeys mods) { blocks->mouseDrag (bEvent (row, tick, mods)); };
  14696. const auto bRelease = [&] (int row, std::int64_t tick, juce::ModifierKeys mods = {}) {
  14697. blocks->mouseUp (bEvent (row, tick, mods));
  14698. engine.dispatchPendingMessages();
  14699. };
  14700. const auto blockOf = [&] (int row, std::int64_t start) -> const PatternBlock* {
  14701. const auto i = patternblocks::indexOf (song(), { row, start });
  14702. return i < 0 ? nullptr : &song().blocks[(std::size_t) i];
  14703. };
  14704. const auto mutedAt = [&] (int row, std::int64_t start) { const auto* x = blockOf (row, start); return x != nullptr && x->muted; };
  14705. const auto playingAt = [&] (int row, std::int64_t start) { const auto* x = blockOf (row, start); return x != nullptr && ! x->muted; };
  14706. const auto mutedCount = [&] {
  14707. int n = 0;
  14708. for (const auto& b : song().blocks)
  14709. n += b.muted ? 1 : 0;
  14710. return n;
  14711. };
  14712. shotBlocks ("-blocks-before.png");
  14713. // ---- #127 Mute: a click mutes the block, a drag down across rows mutes the blocks it crosses (any row)
  14714. pl.setToolForSnapshot (EditTool::mute);
  14715. bPress (0, 2 * bar + 40, left);
  14716. bRelease (0, 2 * bar + 40);
  14717. check ("mute_click", blockOf (0, 2 * bar) != nullptr && mutedAt (0, 2 * bar) && mutedCount() == 1);
  14718. bPress (0, 4 * bar + 40, left);
  14719. bDrag (1, 4 * bar + 60, left);
  14720. bDrag (2, 4 * bar + 80, left);
  14721. bRelease (2, 4 * bar + 80);
  14722. check ("mute_drag_across_rows", mutedAt (0, 4 * bar) && blockOf (1, 4 * bar) != nullptr && mutedAt (1, 4 * bar)
  14723. && mutedAt (2, 4 * bar) && playingAt (3, 0) && mutedCount() == 4,
  14724. juce::String (mutedCount()));
  14725. shotBlocks ("-blocks-mute.png");
  14726. // a sweep that starts on a muted block unmutes
  14727. bPress (0, 2 * bar + 40, left);
  14728. bDrag (0, 3 * bar + 40, left);
  14729. bRelease (0, 3 * bar + 40);
  14730. check ("mute_sweep_from_muted_unmutes", playingAt (0, 2 * bar) && playingAt (0, 3 * bar) && mutedCount() == 3,
  14731. juce::String (mutedCount()));
  14732. // the right button erases, as with every tool but Select / Slice / Zoom
  14733. bPress (3, 40, right);
  14734. bRelease (3, 40);
  14735. check ("mute_right_click_erases", blockOf (3, 0) == nullptr);
  14736. engine.undo();
  14737. engine.dispatchPendingMessages();
  14738. check ("undo_erase", blockOf (3, 0) != nullptr);
  14739. // the muted blocks play nothing: their clips in the playback copy are muted
  14740. {
  14741. auto copy = song();
  14742. patternblocks::expandSong (copy);
  14743. int mutedClips = 0;
  14744. for (const auto& c : copy.playlist)
  14745. mutedClips += c.muted ? 1 : 0;
  14746. check ("muted_blocks_play_muted_clips", mutedClips == 3, juce::String (mutedClips));
  14747. juce::String error;
  14748. const auto back = ProjectFile::fromJson (ProjectFile::toJson (song()), error);
  14749. check ("muted_blocks_saved", back && back->blocks == song().blocks, error);
  14750. }
  14751. // ---- #127 Select: a box over rows 0-2, bars 5-6 selects every block it meets; Pencil moves them together
  14752. pl.setToolForSnapshot (EditTool::lasso);
  14753. bPress (0, 4 * bar + 40, left);
  14754. bDrag (2, 5 * bar + 40, left);
  14755. shotBlocks ("-blocks-select-box.png");
  14756. bRelease (2, 5 * bar + 40);
  14757. const auto selection = blocks->selectionForSnapshot();
  14758. check ("select_box_any_row", selection.size() == 5 && patternblocks::contains (selection, { 0, 4 * bar }) && patternblocks::contains (selection, { 1, 4 * bar })
  14759. && patternblocks::contains (selection, { 2, 5 * bar }),
  14760. juce::String ((int) selection.size()));
  14761. pl.setToolForSnapshot (EditTool::pencil);
  14762. // (Kick's bars 7 and 8 are in the way of a 2-bar move: move the group by 1 bar after clearing them)
  14763. engine.editSong ([bar] (Song& s) { patternblocks::eraseRange (s, 0, 6 * bar, 8 * bar); });
  14764. engine.dispatchPendingMessages();
  14765. bPress (1, 4 * bar + 40, left);
  14766. bDrag (1, 6 * bar + 40, left);
  14767. bRelease (1, 6 * bar + 40);
  14768. check ("pencil_moves_the_selection", blockOf (1, 6 * bar) != nullptr && blockOf (0, 6 * bar) != nullptr && blockOf (0, 7 * bar) != nullptr
  14769. && blockOf (2, 6 * bar) != nullptr && blockOf (2, 7 * bar) != nullptr && blockOf (1, 4 * bar) == nullptr
  14770. && blocks->selectionForSnapshot().size() == 5);
  14771. shotBlocks ("-blocks-select-moved.png");
  14772. // a press on a block outside the selection moves that block alone and drops the selection
  14773. bPress (3, 40, left);
  14774. bDrag (3, bar + 40, left);
  14775. bRelease (3, bar + 40);
  14776. check ("pencil_unselected_block_alone", blockOf (3, bar) != nullptr && blockOf (0, 6 * bar) != nullptr && blocks->selectionForSnapshot().empty());
  14777. // the right button selects too (FL 10: either button)
  14778. pl.setToolForSnapshot (EditTool::lasso);
  14779. bPress (3, bar + 40, right);
  14780. bRelease (3, bar + 40);
  14781. check ("select_click_right_button", blocks->selectionForSnapshot().size() == 1 && blockOf (3, bar) != nullptr);
  14782. // ---- #127 Slice: a click on Bass's first block at bar 2 beat 4 cuts the pattern; a new pattern takes the rest
  14783. pl.setToolForSnapshot (EditTool::knife);
  14784. const auto patternsBefore = song().patterns.size();
  14785. const juce::ModifierKeys freeLeft (juce::ModifierKeys::leftButtonModifier | juce::ModifierKeys::altModifier); // (Alt: no snap)
  14786. bPress (1, bar + 3 * ppq, freeLeft);
  14787. bDrag (2, bar + 3 * ppq, freeLeft); // (a vertical drag: the row under the mouse when released is cut)
  14788. bRelease (1, bar + 3 * ppq);
  14789. check ("slice_adds_a_pattern", song().patterns.size() == patternsBefore + 1 && song().patterns[2].name == "Bass #2",
  14790. juce::String ((int) song().patterns.size()));
  14791. check ("slice_trims_the_long_note", song().patterns[1].notes.back().start == 6 * ppq && song().patterns[1].notes.back().length >= ppq
  14792. && song().patterns[1].notes.back().length < ppq + ppq / 4 && song().patterns[2].notes.empty(),
  14793. juce::String (song().patterns[1].notes.back().length));
  14794. check ("slice_new_blocks_where_bass_ends", blockOf (2, 2 * bar) != nullptr && blockOf (2, 8 * bar) != nullptr);
  14795. shotBlocks ("-blocks-slice.png");
  14796. engine.undo();
  14797. engine.dispatchPendingMessages();
  14798. check ("undo_slice", song().patterns.size() == patternsBefore && song().patterns[2].name == "Lead");
  14799. // ---- #127 Zoom: a drag zooms to the range, a click goes back
  14800. pl.setToolForSnapshot (EditTool::zoom);
  14801. const auto zoomBefore = pl.xOfTickForSnapshot ((double) (4 * bar)) - pl.xOfTickForSnapshot (0.0);
  14802. bPress (0, 2 * bar, left);
  14803. bDrag (0, 4 * bar, left);
  14804. bRelease (0, 4 * bar);
  14805. const auto zoomed = pl.xOfTickForSnapshot ((double) (4 * bar)) - pl.xOfTickForSnapshot (0.0);
  14806. check ("zoom_drag_zooms_in", zoomed > zoomBefore * 1.5, juce::String (zoomed) + " vs " + juce::String (zoomBefore));
  14807. pressedAt = blocks->pointForSnapshot (0, 3 * bar).toFloat();
  14808. blocks->mouseDown (bEvent (0, 3 * bar, right));
  14809. blocks->mouseUp (bEvent (0, 3 * bar, {}));
  14810. const auto back = pl.xOfTickForSnapshot ((double) (4 * bar)) - pl.xOfTickForSnapshot (0.0);
  14811. check ("zoom_click_goes_back", std::abs (back - zoomBefore) < 0.5, juce::String (back));
  14812. // hints name each tool's gesture
  14813. pl.setToolForSnapshot (EditTool::mute);
  14814. check ("hint_mute", blocks->hintAt (blocks->pointForSnapshot (0, 40)).text.contains ("mutes"));
  14815. pl.setToolForSnapshot (EditTool::pencil);
  14816. // ---- #154: linked tracks, then the insert effects list on their headers
  14817. engine.editSong ([bar] (Song& s) {
  14818. s.patternBlocksOn = false;
  14819. s.blocks.clear();
  14820. s.playlist.clear();
  14821. ChannelDef vox;
  14822. vox.name = "Lead vocal";
  14823. vox.instrument = InstrumentKind::audioClip;
  14824. vox.samplePath = "/shots/Lead vocal.wav";
  14825. vox.mixerTrack = 12;
  14826. s.channels.push_back (vox);
  14827. const auto voxChannel = (int) s.channels.size() - 1;
  14828. s.mixer[12].name = "Vox chain";
  14829. for (auto k : { EffectKind::parametricEq, EffectKind::compressor, EffectKind::delay, EffectKind::reverb })
  14830. s.mixer[12].effects.push_back (makeEffectSlot (k));
  14831. s.mixer[12].effects[2].enabled = false;
  14832. s.channels[0].mixerTrack = 3;
  14833. s.mixer[3].name = "Kick";
  14834. s.mixer[3].effects.push_back (makeEffectSlot (EffectKind::compressor));
  14835. const auto clip = [&s, bar] (int track, ClipKind kind, int source, int at, int bars) {
  14836. Clip c;
  14837. c.kind = kind;
  14838. c.track = track;
  14839. c.start = at * bar;
  14840. c.length = bars * bar;
  14841. (kind == ClipKind::pattern ? c.pattern : c.channel) = source;
  14842. s.playlist.push_back (c);
  14843. };
  14844. clip (0, ClipKind::pattern, 0, 0, 4);
  14845. clip (1, ClipKind::audio, voxChannel, 0, 8);
  14846. s.playlistTracks.resize (4);
  14847. s.playlistTracks[1].height = 70;
  14848. });
  14849. engine.dispatchPendingMessages();
  14850. // (rollup 0.1.30: since round 190ib, switching the link on asks first when it moves inserts or routes channels;
  14851. // this run accepts, as the user clicking "Link")
  14852. PlaylistComponent::answerLinkConfirmation = [] (const autolink::Report&) { return true; };
  14853. pl.runAction ("playlist.linkTracks");
  14854. PlaylistComponent::answerLinkConfirmation = nullptr;
  14855. engine.dispatchPendingMessages();
  14856. // (rollup 0.1.30: round 190ib links Playlist track N to insert N, moving the inserts there: the Vox chain and
  14857. // the Kick follow their tracks, so the checks read the inserts the tracks are linked to)
  14858. const auto vox = song().playlistTracks.size() > 1 ? song().playlistTracks[1].mixerTrack : -1;
  14859. const auto kick = song().playlistTracks.size() > 0 ? song().playlistTracks[0].mixerTrack : -1;
  14860. check ("linked", song().linkTracksToMixer && vox > 0 && song().mixer[(std::size_t) vox].name == "Vox chain" && pl.headerWidthForSnapshot() == PlaylistComponent::linkedHeaderWidth,
  14861. juce::String (pl.headerWidthForSnapshot()));
  14862. check ("inserts_off_by_default", ! PlaylistComponent::showTrackInserts && pl.insertsListForSnapshot (1).isEmpty());
  14863. const auto shotRows = [&] (const juce::String& name, int rows) {
  14864. engine.dispatchPendingMessages();
  14865. const auto bottom = pl.trackRowForSnapshot (rows).getY();
  14866. savePng (pl.createComponentSnapshot ({ 0, 0, juce::jmin (pl.getWidth(), 820), juce::jmin (pl.getHeight(), bottom + 12) }), prefix + name);
  14867. };
  14868. shotRows ("-inserts-off.png", 3);
  14869. pl.runAction ("playlist.trackInserts");
  14870. engine.dispatchPendingMessages();
  14871. check ("inserts_on_widens_linked_headers", PlaylistComponent::showTrackInserts
  14872. && pl.headerWidthForSnapshot() == PlaylistComponent::linkedHeaderWidth + PlaylistComponent::insertsColumnWidth,
  14873. juce::String (pl.headerWidthForSnapshot()));
  14874. const auto list = [&] (int t) { return pl.insertsListForSnapshot (t); };
  14875. check ("list_on_linked_tracks_only", ! list (0).isEmpty() && ! list (1).isEmpty() && list (2).isEmpty(),
  14876. list (0).toString() + " / " + list (1).toString());
  14877. shotRows ("-inserts-on.png", 3);
  14878. // a row's hint names the effect
  14879. const auto rowPoint = [&] (int t, int row, bool dot) {
  14880. const auto r = list (t);
  14881. return juce::Point<int> (dot ? r.getX() + 5 : r.getX() + 40, r.getY() + row * 13 + 6);
  14882. };
  14883. const auto hintOf = [&] (juce::Point<int> p) { return pl.hintAt (p); };
  14884. check ("hint_names_the_effect", hintOf (rowPoint (1, 1, false)).value == quickpick::slotName (engine, song().mixer[(std::size_t) vox].effects[1]),
  14885. hintOf (rowPoint (1, 1, false)).value);
  14886. check ("hint_add_row", hintOf (rowPoint (0, 1, false)).text.contains ("add an effect"));
  14887. const auto now = juce::Time::getCurrentTime();
  14888. const int ctrl = juce::ModifierKeys::commandModifier;
  14889. const auto event = [&] (juce::Point<int> p, juce::ModifierKeys mods, juce::Point<int> down, int clicks, bool dragged) {
  14890. 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);
  14891. };
  14892. const auto press = [&] (juce::Point<int> p, juce::ModifierKeys mods, std::optional<juce::Point<int>> to = {}) {
  14893. const auto down = mods.withFlags (juce::ModifierKeys::leftButtonModifier);
  14894. pl.mouseMove (event (p, mods, p, 1, false));
  14895. pl.mouseDown (event (p, down, p, 1, false));
  14896. if (to)
  14897. {
  14898. pl.mouseDrag (event ((p + *to) / 2, down, p, 1, true));
  14899. pl.mouseDrag (event (*to, down, p, 1, true));
  14900. }
  14901. pl.mouseUp (event (to ? *to : p, mods, p, 1, to.has_value()));
  14902. engine.dispatchPendingMessages();
  14903. };
  14904. const auto kinds = [&] (int insert) {
  14905. juce::StringArray k;
  14906. for (const auto& fx : song().mixer[(std::size_t) insert].effects)
  14907. k.add (juce::String ((int) fx.kind) + (fx.enabled ? "" : "-"));
  14908. return k.joinIntoString (",");
  14909. };
  14910. const auto eq = juce::String ((int) EffectKind::parametricEq), comp = juce::String ((int) EffectKind::compressor),
  14911. delay = juce::String ((int) EffectKind::delay), verb = juce::String ((int) EffectKind::reverb);
  14912. // the dot bypasses / un-bypasses, as the Mixer slot's LED (one undo step each)
  14913. press (rowPoint (1, 0, true), {});
  14914. check ("dot_bypasses", ! song().mixer[(std::size_t) vox].effects[0].enabled);
  14915. press (rowPoint (1, 2, true), {});
  14916. check ("dot_switches_on", song().mixer[(std::size_t) vox].effects[2].enabled);
  14917. engine.undo();
  14918. engine.dispatchPendingMessages();
  14919. check ("undo_dot", ! song().mixer[(std::size_t) vox].effects[2].enabled && ! song().mixer[(std::size_t) vox].effects[0].enabled);
  14920. press (rowPoint (1, 0, true), {});
  14921. shotRows ("-inserts-bypass.png", 3);
  14922. // drag the reverb (row 4) above the EQ: the chain order changes, as the Device View's drag
  14923. const auto before = kinds (vox);
  14924. press (rowPoint (1, 3, false), {}, rowPoint (1, 0, false) - juce::Point<int> (0, 4));
  14925. check ("drag_reorders", kinds (vox) == verb + "," + eq + "," + comp + "," + delay + "-", before + " -> " + kinds (vox));
  14926. // Ctrl + drag copies (the compressor, under the delay)
  14927. press (rowPoint (1, 2, false), juce::ModifierKeys (ctrl), rowPoint (1, 4, false) - juce::Point<int> (0, 4));
  14928. check ("ctrl_drag_copies", kinds (vox) == verb + "," + eq + "," + comp + "," + delay + "-," + comp, kinds (vox));
  14929. // onto another linked track's list: it moves to that insert (the Kick's)
  14930. press (rowPoint (1, 1, false), {}, rowPoint (0, 0, false));
  14931. check ("drag_to_another_track_moves", kinds (kick) == comp + "," + eq && kinds (vox) == verb + "," + comp + "," + delay + "-," + comp,
  14932. kinds (kick) + " | " + kinds (vox));
  14933. // the wheel scrolls a list longer than its track (Kick's 4 effects + "add" in a 3-row header)
  14934. engine.editSong ([kick] (Song& s) {
  14935. s.mixer[(std::size_t) kick].effects.push_back (makeEffectSlot (EffectKind::delay));
  14936. s.mixer[(std::size_t) kick].effects.push_back (makeEffectSlot (EffectKind::reverb));
  14937. });
  14938. engine.dispatchPendingMessages();
  14939. const auto firstName = hintOf (rowPoint (0, 0, false)).value;
  14940. const auto rowsShown = list (0).getHeight() / 13;
  14941. pl.mouseWheelMove (event (rowPoint (0, 0, false), {}, rowPoint (0, 0, false), 0, false), juce::MouseWheelDetails { 0.0f, -0.5f, false, false, false });
  14942. const auto afterWheel = hintOf (rowPoint (0, 0, false));
  14943. check ("wheel_scrolls_a_long_list", rowsShown < 5 && afterWheel.value != firstName
  14944. && afterWheel.value == quickpick::slotName (engine, song().mixer[(std::size_t) kick].effects[1]),
  14945. juce::String (rowsShown) + " rows, " + firstName + " -> " + afterWheel.value);
  14946. shotRows ("-inserts-edited.png", 3);
  14947. // a view option: not saved with the project
  14948. check ("option_not_in_project", ! ProjectFile::toJson (song()).contains ("trackInserts"));
  14949. // off again: the linked headers' own width
  14950. pl.runAction ("playlist.trackInserts");
  14951. engine.dispatchPendingMessages();
  14952. check ("inserts_off_again", ! PlaylistComponent::showTrackInserts && pl.headerWidthForSnapshot() == PlaylistComponent::linkedHeaderWidth);
  14953. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\nresult=" + (allOk ? "OK" : "FAIL") + "\n");
  14954. return allOk;
  14955. }
  14956. // --trackautoshot190gz (round 190gz): see the dispatch above
  14957. bool runTrackAutoShot190gz (const juce::String& prefix)
  14958. {
  14959. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  14960. juce::StringArray report;
  14961. bool allOk = true;
  14962. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  14963. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  14964. allOk = allOk && ok;
  14965. };
  14966. lynx::AudioEngine engine (false);
  14967. lynx::MainComponent ui (engine, false);
  14968. ui.setSize (1600, 900);
  14969. {
  14970. // a small song in FL's shape: Kick and Synth patterns, a drum loop, a vocal on its prepared insert, a mixed beat
  14971. using namespace lynx;
  14972. auto song = Song::makeDefault();
  14973. song.playlist.clear();
  14974. song.patterns.clear();
  14975. for (auto& c : song.channels)
  14976. c.mixerTrack = 0; // (FL's new channels play on the Master)
  14977. song.channels[4].mixerTrack = 9; // the Synth on a bus the user made
  14978. song.mixer[9].name = "Synth bus";
  14979. const auto audio = [&song] (const char* name, int mixer) {
  14980. ChannelDef c;
  14981. c.name = name;
  14982. c.instrument = InstrumentKind::audioClip;
  14983. c.samplePath = std::string ("/shots/") + name + ".wav";
  14984. c.mixerTrack = mixer;
  14985. song.channels.push_back (c);
  14986. return (int) song.channels.size() - 1;
  14987. };
  14988. const auto loop = audio ("Drum loop", 0);
  14989. const auto vox = audio ("Lead vocal", 12);
  14990. song.mixer[12].name = "Vox chain";
  14991. song.mixer[12].colour = 0xFF3C8DD8;
  14992. song.mixer[12].effects.push_back (makeEffectSlot (EffectKind::parametricEq));
  14993. const auto pattern = [&song] (const char* name, std::vector<int> channels, std::uint32_t colour) {
  14994. auto& p = song.patterns.emplace_back();
  14995. p.name = name;
  14996. p.colour = colour;
  14997. for (const auto c : channels)
  14998. for (int step : { 0, 4, 8, 12 })
  14999. p.toggleStep (c, step);
  15000. return (int) song.patterns.size() - 1;
  15001. };
  15002. const auto kick = pattern ("Kick", { 0 }, 0xFFD85A3C);
  15003. const auto lead = pattern ("Lead", { 4 }, 0xFF8A5CD8);
  15004. const auto beat = pattern ("Beat", { 1, 2, 3 }, 0xFF5CB85C);
  15005. const auto clip = [&song] (int track, ClipKind kind, int source, int bar, int bars) {
  15006. Clip c;
  15007. c.kind = kind;
  15008. c.track = track;
  15009. c.start = (std::int64_t) bar * 4 * ppq;
  15010. c.length = (std::int64_t) bars * 4 * ppq;
  15011. (kind == ClipKind::pattern ? c.pattern : c.channel) = source;
  15012. song.playlist.push_back (c);
  15013. };
  15014. for (int bar = 0; bar < 8; bar += 2)
  15015. {
  15016. clip (0, ClipKind::pattern, kick, bar, 2);
  15017. clip (2, ClipKind::pattern, beat, bar, 2);
  15018. }
  15019. clip (1, ClipKind::audio, loop, 0, 8);
  15020. clip (3, ClipKind::pattern, lead, 2, 4);
  15021. clip (4, ClipKind::audio, vox, 4, 4);
  15022. clip (6, ClipKind::pattern, kick, 4, 2); // (round 190ib: Track 7 only repeats Track 1's Kick)
  15023. song.playlistTracks.resize (8);
  15024. engine.setSong (std::move (song));
  15025. }
  15026. engine.dispatchPendingMessages();
  15027. ui.selectTabForSnapshot (2);
  15028. engine.dispatchPendingMessages();
  15029. auto& pl = ui.getPlaylistForSnapshot();
  15030. pl.setSize (juce::jmax (pl.getWidth(), 1000), juce::jmax (pl.getHeight(), 640));
  15031. pl.setViewForSnapshot (120.0, 1, 0);
  15032. const auto shotRows = [&] (const juce::String& name, int rows) {
  15033. const auto bottom = pl.trackRowForSnapshot (rows).getY();
  15034. savePng (pl.createComponentSnapshot ({ 0, 0, juce::jmin (pl.getWidth(), 820), juce::jmin (pl.getHeight(), bottom + 12) }), prefix + name);
  15035. };
  15036. const auto& song = [&]() -> const lynx::Song& { return engine.getSong(); };
  15037. const auto mode = [&] (int t) { return t < (int) song().playlistTracks.size() ? song().playlistTracks[(std::size_t) t].mode : lynx::PlaylistTrackMode::unassigned; };
  15038. const auto mixerOf = [&] (int t) { return t < (int) song().playlistTracks.size() ? song().playlistTracks[(std::size_t) t].mixerTrack : -1; };
  15039. // ---- 1. FL's default: tracks and inserts apart, FL's narrow headers
  15040. check ("off_by_default", ! song().linkTracksToMixer && pl.headerWidthForSnapshot() == lynx::PlaylistComponent::flHeaderWidthNow(),
  15041. juce::String (pl.headerWidthForSnapshot()));
  15042. shotRows ("-off.png", 7);
  15043. // ---- 2. the switch (Playlist › Edit, Track mode, Settings › Project): it lists what it changes and asks (round
  15044. // 190ib: inserts move, channels are routed), then it is one undo step
  15045. lynx::autolink::Report plan;
  15046. bool asked = false;
  15047. lynx::PlaylistComponent::answerLinkConfirmation = [&] (const lynx::autolink::Report& r) {
  15048. plan = r;
  15049. asked = true;
  15050. return true;
  15051. };
  15052. {
  15053. const auto text = lynx::PlaylistComponent::describeLinkPlan (song(), lynx::autolink::planOn (song()));
  15054. juce::AlertWindow box (lynx::tr ("Link Playlist tracks to mixer tracks"), text, juce::MessageBoxIconType::QuestionIcon);
  15055. box.addButton (lynx::tr ("Link"), 1);
  15056. box.addButton (lynx::tr ("Cancel"), 0);
  15057. box.sendLookAndFeelChange();
  15058. savePng (lynx::shot::snapshot (box), prefix + "-confirm.png");
  15059. }
  15060. pl.runAction ("playlist.linkTracks");
  15061. engine.dispatchPendingMessages();
  15062. const auto moved = [&plan] (int from, int to) {
  15063. return std::any_of (plan.changes.begin(), plan.changes.end(), [=] (const lynx::autolink::Change& c) {
  15064. return c.kind == lynx::autolink::Change::Kind::moveInsert && c.from == from && c.to == to;
  15065. });
  15066. };
  15067. check ("asked_first_with_the_moves", asked && moved (9, 4) && moved (12, 5) && plan.repeats.size() == 1 && ! plan.changesSound(),
  15068. juce::String ((int) plan.changes.size()));
  15069. check ("switch_on", song().linkTracksToMixer && pl.headerWidthForSnapshot() == lynx::PlaylistComponent::linkedHeaderWidth,
  15070. juce::String (pl.headerWidthForSnapshot()));
  15071. check ("kick_instrument_track_insert_1", mode (0) == lynx::PlaylistTrackMode::instrument && mixerOf (0) == 1 && song().channels[0].mixerTrack == 1,
  15072. juce::String (mixerOf (0)));
  15073. check ("loop_audio_track_insert_2", mode (1) == lynx::PlaylistTrackMode::audio && mixerOf (1) == 2 && song().mixer[2].name == "Drum loop",
  15074. juce::String (mixerOf (1)));
  15075. // (round 190ib: Track N = insert N for every track with content of its own)
  15076. check ("beat_track_insert_3", mode (2) == lynx::PlaylistTrackMode::audio && mixerOf (2) == 3 && song().channels[1].mixerTrack == 3
  15077. && song().channels[2].mixerTrack == 3 && song().channels[3].mixerTrack == 3,
  15078. juce::String (mixerOf (2)));
  15079. check ("synth_bus_moves_to_insert_4", mode (3) == lynx::PlaylistTrackMode::instrument && song().channels[4].mixerTrack == 4
  15080. && song().mixer[4].name == "Synth bus" && song().playlistTracks[3].name == "Synth bus",
  15081. juce::String (song().channels[4].mixerTrack));
  15082. check ("vocal_chain_moves_to_insert_5", mode (4) == lynx::PlaylistTrackMode::audio && mixerOf (4) == 5 && song().mixer[5].effects.size() == 1
  15083. && song().mixer[5].name == "Vox chain",
  15084. juce::String (mixerOf (4)));
  15085. check ("empty_and_repeat_tracks_stay", mode (5) == lynx::PlaylistTrackMode::unassigned && mode (6) == lynx::PlaylistTrackMode::unassigned
  15086. && lynx::autolink::repeatedTracks (song())[6] == 0);
  15087. shotRows ("-on.png", 7);
  15088. // one undo step: Undo brings FL's tracks back, Redo the links
  15089. engine.undo();
  15090. engine.dispatchPendingMessages();
  15091. check ("undo_switch_on", ! song().linkTracksToMixer && mode (0) == lynx::PlaylistTrackMode::unassigned && mode (1) == lynx::PlaylistTrackMode::unassigned
  15092. && song().channels[0].mixerTrack == 0 && pl.headerWidthForSnapshot() == lynx::PlaylistComponent::flHeaderWidthNow());
  15093. engine.redo();
  15094. engine.dispatchPendingMessages();
  15095. check ("redo_switch_on", song().linkTracksToMixer && mixerOf (1) == 2 && pl.headerWidthForSnapshot() == lynx::PlaylistComponent::linkedHeaderWidth);
  15096. auto source = juce::Desktop::getInstance().getMainMouseSource();
  15097. const auto now = juce::Time::getCurrentTime();
  15098. const int ctrl = juce::ModifierKeys::commandModifier;
  15099. const auto event = [&] (juce::Point<int> p, juce::ModifierKeys mods, juce::Point<int> down, int clicks, bool dragged) {
  15100. 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);
  15101. };
  15102. const auto press = [&] (juce::Point<int> p, juce::ModifierKeys mods, std::optional<juce::Point<int>> to = {}) {
  15103. const auto down = mods.withFlags (juce::ModifierKeys::leftButtonModifier);
  15104. pl.mouseMove (event (p, mods, p, 1, false));
  15105. pl.mouseDown (event (p, down, p, 1, false));
  15106. if (to)
  15107. pl.mouseDrag (event (*to, down, p, 1, true));
  15108. pl.mouseUp (event (to ? *to : p, mods, p, 1, to.has_value()));
  15109. engine.flushLevels();
  15110. engine.dispatchPendingMessages();
  15111. };
  15112. const auto doubleClick = [&] (juce::Point<int> p) {
  15113. const auto down = juce::ModifierKeys (juce::ModifierKeys::leftButtonModifier);
  15114. pl.mouseDown (event (p, down, p, 2, false));
  15115. pl.mouseDoubleClick (event (p, down, p, 2, false));
  15116. pl.mouseUp (event (p, {}, p, 2, false));
  15117. engine.flushLevels();
  15118. engine.dispatchPendingMessages();
  15119. };
  15120. // the controls are found where they are drawn: M right of the plate, S left of it, the volume bar and the pan knob
  15121. // under them (the same geometry the header paints with)
  15122. const auto row = [&] (int t) { return pl.trackRowForSnapshot (t); };
  15123. const int w = pl.headerWidthForSnapshot();
  15124. const auto mAt = [&] (int t) { const auto r = row (t); return juce::Point<int> (w - 13 - 9, r.getY() + 11); }; // (meter column 9 px)
  15125. const auto sAt = [&] (int t) { return mAt (t) - juce::Point<int> (20, 0); };
  15126. const auto volumeAt = [&] (int t, float fraction) {
  15127. const auto r = row (t);
  15128. const auto left = 8, width = w - 9 - 2 - 32;
  15129. return juce::Point<int> (left + juce::roundToInt (fraction * (float) width), r.getY() + 26);
  15130. };
  15131. const auto panAt = [&] (int t) { const auto r = row (t); return juce::Point<int> (w - 9 - 6 - 7, r.getY() + 26); };
  15132. const auto& insert2 = [&]() -> const lynx::MixerTrack& { return song().mixer[2]; };
  15133. // ---- 3. the linked headers' controls act on the track's mixer track
  15134. press (mAt (1), {});
  15135. check ("m_mutes_the_insert", insert2().muted, juce::String ((int) insert2().muted));
  15136. press (mAt (1), {});
  15137. check ("m_again_unmutes", ! insert2().muted);
  15138. press (sAt (1), {});
  15139. check ("s_solos_the_insert", insert2().solo);
  15140. press (sAt (1), {});
  15141. press (volumeAt (1, 0.25f), {});
  15142. check ("volume_click_sets_the_level", std::abs (insert2().volume - 0.25f) < 0.03f, juce::String (insert2().volume, 3));
  15143. press (volumeAt (1, 0.25f), {}, volumeAt (1, 0.5f));
  15144. check ("volume_drag", std::abs (insert2().volume - 0.5f) < 0.03f, juce::String (insert2().volume, 3));
  15145. doubleClick (volumeAt (1, 0.5f));
  15146. check ("volume_double_click_0_db", insert2().volume == lynx::unityFader, juce::String (insert2().volume, 3));
  15147. press (panAt (1), {}, panAt (1) - juce::Point<int> (0, 40));
  15148. check ("pan_drag_up", std::abs (insert2().pan - 0.5f) < 0.02f, juce::String (insert2().pan, 3));
  15149. shotRows ("-controls.png", 7);
  15150. doubleClick (panAt (1));
  15151. check ("pan_double_click_centre", insert2().pan == 0.0f, juce::String (insert2().pan, 3));
  15152. // an instrument track's header acts on its channel's insert (Synth: insert 4 since round 190ib)
  15153. press (volumeAt (3, 0.4f), {});
  15154. check ("instrument_track_volume_on_its_insert", std::abs (song().mixer[4].volume - 0.4f) < 0.03f, juce::String (song().mixer[4].volume, 3));
  15155. engine.editSong ([] (lynx::Song& s) { s.mixer[4].volume = lynx::unityFader; });
  15156. // FL's track mute and solo stay on the Playlist track: Ctrl+click on M solos it, a muted track lights M and the
  15157. // first click unmutes it
  15158. press (mAt (1), ctrl);
  15159. check ("ctrl_m_solos_the_playlist_track", song().isTrackMuted (0) && ! song().isTrackMuted (1) && ! insert2().solo);
  15160. press (mAt (1), ctrl);
  15161. engine.editSong ([] (lynx::Song& s) {
  15162. for (auto& t : s.playlistTracks)
  15163. t.muted = false;
  15164. s.playlistTracks[1].muted = true;
  15165. });
  15166. press (mAt (1), {});
  15167. check ("m_unmutes_a_muted_playlist_track_first", ! song().isTrackMuted (1) && ! insert2().muted);
  15168. // a track that only repeats another keeps FL's LED (Track 7, Track 1's Kick): a click mutes the Playlist track
  15169. press (juce::Point<int> (w - 9 - 11, row (6).getCentreY()), {});
  15170. check ("unlinked_led_is_fl", song().isTrackMuted (6));
  15171. engine.editSong ([] (lynx::Song& s) { s.playlistTracks[6].muted = false; });
  15172. // round 190ib: a linked track and its insert keep one name, whichever is renamed
  15173. engine.editSong ([] (lynx::Song& s) { s.mixer[3].name = "Drums"; });
  15174. check ("insert_rename_renames_the_track", song().playlistTracks[2].name == "Drums");
  15175. engine.editSong ([] (lynx::Song& s) { s.playlistTracks[2].name = "Beat"; });
  15176. check ("track_rename_renames_the_insert", song().mixer[3].name == "Beat");
  15177. // ---- 4. new content follows: a sample on empty Track 6 makes it an audio track (insert 6)
  15178. engine.editSong ([] (lynx::Song& s) {
  15179. lynx::ChannelDef c;
  15180. c.name = "Guitar";
  15181. c.instrument = lynx::InstrumentKind::audioClip;
  15182. c.samplePath = "/shots/Guitar.wav";
  15183. s.channels.push_back (c);
  15184. lynx::Clip clip;
  15185. clip.kind = lynx::ClipKind::audio;
  15186. clip.channel = (int) s.channels.size() - 1;
  15187. clip.track = 5;
  15188. clip.start = 4 * 4 * lynx::ppq;
  15189. clip.length = 4 * 4 * lynx::ppq;
  15190. s.playlist.push_back (clip);
  15191. });
  15192. check ("new_sample_links_its_track", mode (5) == lynx::PlaylistTrackMode::audio && mixerOf (5) == 6 && song().channels.back().mixerTrack == 6,
  15193. juce::String (mixerOf (5)));
  15194. engine.undo();
  15195. check ("undo_takes_the_clip_and_the_link", mode (5) == lynx::PlaylistTrackMode::unassigned && song().channels.back().name != "Guitar");
  15196. // ---- 5. row heights (round 190ft): short rows keep M / S; from 34 px the volume and pan; tall rows the input
  15197. const auto heights = [&] (std::vector<std::pair<int, int>> rows) {
  15198. engine.editSong ([rows] (lynx::Song& s) {
  15199. for (const auto& [t, h] : rows)
  15200. s.playlistTracks[(std::size_t) t].height = h;
  15201. });
  15202. engine.dispatchPendingMessages();
  15203. };
  15204. heights ({ { 0, 16 }, { 1, 24 }, { 4, 80 } });
  15205. shotRows ("-heights.png", 7);
  15206. {
  15207. const auto r = row (1);
  15208. const auto before = insert2().volume;
  15209. press (juce::Point<int> (20, r.getY() + 12), {}); // (no volume bar on a 24 px row: the press selects)
  15210. check ("short_row_has_no_volume_bar", insert2().volume == before && pl.selectedTracksForSnapshot() == std::vector<int> { 1 });
  15211. press (juce::Point<int> (w - 22, r.getY() + 12), {});
  15212. check ("short_row_m_still_works", insert2().muted);
  15213. press (juce::Point<int> (w - 22, r.getY() + 12), {});
  15214. }
  15215. heights ({ { 0, 0 }, { 1, 0 }, { 4, 0 } });
  15216. // ---- 6. saved: .lynx keeps the switch; the links themselves are FL track modes
  15217. {
  15218. juce::String error;
  15219. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song()), error);
  15220. check ("lynx_round_trip", back && back->linkTracksToMixer && back->playlistTracks.size() > 4 && back->playlistTracks[1].mixerTrack == 2
  15221. && back->playlistTracks[0].mode == lynx::PlaylistTrackMode::instrument, error);
  15222. auto plain = song();
  15223. plain.linkTracksToMixer = false;
  15224. const auto json = lynx::ProjectFile::toJson (plain);
  15225. check ("off_not_saved", ! json.contains ("linkTracksToMixer"));
  15226. }
  15227. // ---- 7. off: FL's headers again (the links stay)
  15228. lynx::PlaylistComponent::answerLinkConfirmation = nullptr;
  15229. pl.runAction ("playlist.linkTracks");
  15230. engine.dispatchPendingMessages();
  15231. check ("switch_off_fl_headers", ! song().linkTracksToMixer && pl.headerWidthForSnapshot() == lynx::PlaylistComponent::flHeaderWidthNow()
  15232. && mode (1) == lynx::PlaylistTrackMode::audio);
  15233. shotRows ("-off-after.png", 7);
  15234. // ---- 8. Settings › Project's switches
  15235. {
  15236. auto panel = lynx::makeSettingsPanel (engine, lynx::SettingsPage::project);
  15237. panel->setSize (760, 720);
  15238. savePng (lynx::shot::snapshot (*panel), prefix + "-settings-project.png");
  15239. }
  15240. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\nresult=" + (allOk ? "OK" : "FAIL") + "\n");
  15241. return allOk;
  15242. }
  15243. bool runFlPlShot (const juce::String& prefix)
  15244. {
  15245. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  15246. juce::StringArray report;
  15247. bool allOk = true;
  15248. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  15249. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  15250. allOk = allOk && ok;
  15251. };
  15252. const auto plain = [] (juce::String t) {
  15253. // (without the shortcut column and the mnemonic: the mark, or the " (K)" a translation without the letter gets)
  15254. t = t.upToFirstOccurrenceOf ("\t", false, false);
  15255. if (const auto at = t.indexOf (juce::String (" (") + juce::String::charToString (1)); at >= 0)
  15256. t = t.substring (0, at);
  15257. return t.removeCharacters (juce::String ("&_") + juce::String::charToString (1));
  15258. };
  15259. const auto findSub = [&plain] (const juce::PopupMenu& menu, const juce::String& text) -> const juce::PopupMenu* {
  15260. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  15261. if (it.getItem().subMenu != nullptr && plain (it.getItem().text) == plain (text))
  15262. return it.getItem().subMenu.get();
  15263. return nullptr;
  15264. };
  15265. const auto texts = [&plain] (const juce::PopupMenu& menu, int count) {
  15266. juce::StringArray out;
  15267. for (juce::PopupMenu::MenuItemIterator it (menu); it.next() && out.size() < count;)
  15268. out.add (it.getItem().isSeparator ? juce::String ("-") : it.getItem().isSectionHeader ? "[" + plain (it.getItem().text) + "]" : plain (it.getItem().text));
  15269. return out;
  15270. };
  15271. const auto modelTexts = [] (const std::vector<lynx::fltrackmenus::Entry>& model) {
  15272. juce::StringArray out;
  15273. for (const auto& e : model)
  15274. if (e.kind != lynx::fltrackmenus::Entry::Kind::list)
  15275. out.add (e.kind == lynx::fltrackmenus::Entry::Kind::separator ? juce::String ("-")
  15276. : e.kind == lynx::fltrackmenus::Entry::Kind::caption ? "[" + lynx::tr (e.text) + "]"
  15277. : lynx::tr (e.text));
  15278. return out;
  15279. };
  15280. const auto click = [&plain] (const juce::PopupMenu& menu, const juce::String& text) {
  15281. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  15282. if (plain (it.getItem().text) == plain (text) && it.getItem().isEnabled && it.getItem().action != nullptr)
  15283. {
  15284. it.getItem().action();
  15285. return true;
  15286. }
  15287. return false;
  15288. };
  15289. lynx::AudioEngine engine (false);
  15290. lynx::MainComponent ui (engine, false);
  15291. ui.setSize (1600, 900);
  15292. int vox = -1;
  15293. {
  15294. auto song = lynx::Song::makeDefault();
  15295. song.channels.push_back ({});
  15296. song.channels.back().name = "Vox";
  15297. song.channels.back().instrument = lynx::InstrumentKind::audioClip;
  15298. song.channels.back().volume = 0.6f;
  15299. song.channels.back().samplePath = writeShotSample (juce::File (prefix + "-vox.wav"), 330.0).getFullPathName().toStdString();
  15300. vox = (int) song.channels.size() - 1;
  15301. lynx::Clip c;
  15302. c.kind = lynx::ClipKind::audio;
  15303. c.channel = vox;
  15304. c.track = 3;
  15305. c.start = 4 * lynx::ppq;
  15306. c.length = 2 * lynx::ppq;
  15307. song.playlist.push_back (c);
  15308. engine.setSong (std::move (song));
  15309. }
  15310. engine.dispatchPendingMessages();
  15311. auto& playlist = ui.getPlaylistForSnapshot();
  15312. // ---- 1. the audio clip menu: Preview first, Automate › Panning / Volume
  15313. {
  15314. const auto menu = playlist.getClipMenuForSnapshot (0);
  15315. juce::PopupMenu::MenuItemIterator it (menu);
  15316. it.next(); // (the "Audio clip" title band)
  15317. it.next();
  15318. check ("clip_menu_preview_first", plain (it.getItem().text) == lynx::tr ("Preview"), it.getItem().text);
  15319. const auto* automate = findSub (menu, lynx::tr ("Automate"));
  15320. check ("clip_menu_automate", automate != nullptr && texts (*automate, 9) == modelTexts (lynx::fltrackmenus::automate()),
  15321. automate != nullptr ? texts (*automate, 9).joinIntoString ("|") : juce::String ("missing"));
  15322. saveMenus (juce::StringArray { "Audio clip menu", "Automate" }, std::vector<juce::PopupMenu> { menu, automate != nullptr ? *automate : juce::PopupMenu() },
  15323. prefix + "-clip-menu.png");
  15324. const auto before = engine.getSong().automations.size();
  15325. check ("automate_volume_runs", automate != nullptr && click (*automate, lynx::tr ("Volume")));
  15326. const auto& song = engine.getSong();
  15327. // (round 190dz: the Levels adjustment's volume multiplier, neutral = 0.5 of its 0…200 % travel)
  15328. const auto ok = song.automations.size() == before + 1 && song.automations.back().target.kind == lynx::AutomationTargetKind::channelAdjust
  15329. && song.automations.back().target.param == lynx::leveladjust::volume
  15330. && song.automations.back().target.index == vox && song.automations.back().points.size() == 2
  15331. && song.automations.back().points[1].tick == 2 * lynx::ppq && std::abs (song.automations.back().points[0].value - 0.5f) < 1.0e-6f;
  15332. const auto* clip = ok ? &song.playlist.back() : nullptr;
  15333. check ("automate_volume_clip", ok && clip->kind == lynx::ClipKind::automation && clip->track == 3 && clip->start == 4 * lynx::ppq
  15334. && clip->length == 2 * lynx::ppq,
  15335. ok ? juce::String::fromUTF8 (song.automations.back().name.c_str()) : juce::String());
  15336. engine.undo();
  15337. check ("automate_undo", engine.getSong().automations.size() == before);
  15338. // Preview: the clip's own audio (FL plays it through its channel); LYNX renders it for the preview output
  15339. const auto rendered = engine.renderClipAudio (0);
  15340. check ("preview_renders_the_clip", ! rendered.left.empty(), juce::String ((int) rendered.left.size()) + " frames");
  15341. }
  15342. // ---- 2. the Playlist's "+": its menu, a right click's audio track, the corner
  15343. {
  15344. const auto menu = playlist.getAddTrackMenuForSnapshot();
  15345. check ("add_menu_head", texts (menu, 5) == modelTexts (lynx::fltrackmenus::addTrack()), texts (menu, 5).joinIntoString ("|"));
  15346. saveMenus (juce::StringArray { "Playlist +" }, std::vector<juce::PopupMenu> { menu }, prefix + "-add-track-menu.png");
  15347. ui.selectTabForSnapshot (2);
  15348. engine.dispatchPendingMessages();
  15349. auto* button = playlist.getAddTrackButtonForSnapshot();
  15350. check ("add_button_in_corner", button != nullptr && button->isVisible() && button->getX() == 7 && button->getWidth() == 21 && button->getHeight() == 18
  15351. && button->getBottom() <= lynx::PlaylistComponent::headerHeight);
  15352. savePng (playlist.createComponentSnapshot (juce::Rectangle<int> (0, 0, juce::jmin (560, playlist.getWidth()), juce::jmin (260, playlist.getHeight()))),
  15353. prefix + "-playlist-corner.png");
  15354. const auto track = playlist.addAudioTrackNow();
  15355. const auto& song = engine.getSong();
  15356. check ("add_audio_track", track == 0 && song.playlistTracks.size() > 0 && song.playlistTracks[0].mode == lynx::PlaylistTrackMode::audio
  15357. && song.playlistTracks[0].mixerTrack > 0,
  15358. juce::String (track));
  15359. engine.undo();
  15360. }
  15361. // ---- 3. Track mode › Instrument track ›
  15362. {
  15363. const auto menu = playlist.getTrackMenuForSnapshot (5);
  15364. const auto* modes = findSub (menu, lynx::tr ("Track mode"));
  15365. const auto* instrument = modes != nullptr ? findSub (*modes, lynx::tr ("Instrument track")) : nullptr;
  15366. check ("instrument_track_head", instrument != nullptr && texts (*instrument, 4) == modelTexts (lynx::fltrackmenus::instrumentTrack()),
  15367. instrument != nullptr ? texts (*instrument, 4).joinIntoString ("|") : juce::String ("missing"));
  15368. const auto* existing = instrument != nullptr ? findSub (*instrument, lynx::tr ("Use existing channel")) : nullptr;
  15369. check ("use_existing_lists_generators", existing != nullptr && existing->getNumItems() == 5, existing != nullptr ? juce::String (existing->getNumItems()) : juce::String());
  15370. std::vector<juce::PopupMenu> menus { modes != nullptr ? *modes : juce::PopupMenu(), instrument != nullptr ? *instrument : juce::PopupMenu(),
  15371. existing != nullptr ? *existing : juce::PopupMenu() };
  15372. saveMenus (juce::StringArray { "Track mode", "Instrument track", "Use existing channel" }, menus, prefix + "-instrument-track-menu.png");
  15373. lynx::ChannelDef synth;
  15374. synth.name = "Lead";
  15375. synth.instrument = lynx::InstrumentKind::synth;
  15376. const auto channels = engine.getSong().channels.size();
  15377. int made = -1;
  15378. engine.editSong ([&] (lynx::Song& s) { made = lynx::trackmodes::addInstrumentTrack (s, synth, 5); });
  15379. check ("instrument_track_new_channel", made == (int) channels && engine.getSong().playlistTracks.size() > 5
  15380. && engine.getSong().playlistTracks[5].channel == made);
  15381. engine.undo();
  15382. }
  15383. // ---- 4. the Channel rack menu: Assign to new instrument track / Unassign
  15384. {
  15385. auto& rack = ui.getRackForSnapshot();
  15386. const auto menu = rack.getChannelMenuForSnapshot (1);
  15387. saveMenus (juce::StringArray { "Channel menu" }, std::vector<juce::PopupMenu> { menu }, prefix + "-channel-menu.png");
  15388. check ("assign_runs", click (menu, lynx::tr ("Assign to new instrument track")));
  15389. const auto tracks = lynx::trackmodes::instrumentTracksOf (engine.getSong(), 1);
  15390. check ("assign_first_free_track", tracks == std::vector<int> { 0 }, juce::String (tracks.empty() ? -1 : tracks.front()));
  15391. const auto again = rack.getChannelMenuForSnapshot (1);
  15392. check ("unassign_offered", click (again, lynx::tr ("Unassign from instrument track")) && lynx::trackmodes::instrumentTracksOf (engine.getSong(), 1).empty());
  15393. bool greyed = false;
  15394. const auto voxMenu = rack.getChannelMenuForSnapshot (vox);
  15395. for (juce::PopupMenu::MenuItemIterator it (voxMenu); it.next();)
  15396. if (plain (it.getItem().text) == plain (lynx::tr ("Assign to new instrument track")))
  15397. greyed = ! it.getItem().isEnabled;
  15398. check ("assign_greyed_for_audio_clip_channel", greyed);
  15399. }
  15400. // ---- 5. Tools › One-click audio recording
  15401. std::fprintf (stderr, "flplshot: tools\n");
  15402. {
  15403. const auto names = ui.getMenuNamesForSnapshot();
  15404. const auto tools = ui.getMenuForSnapshot (names.indexOf (lynx::tr ("Tools")));
  15405. const auto* oneClick = findSub (tools, lynx::tr ("One-click audio recording"));
  15406. check ("one_click_submenu", oneClick != nullptr && texts (*oneClick, 3) == modelTexts (lynx::fltrackmenus::oneClickRecording()),
  15407. oneClick != nullptr ? texts (*oneClick, 3).joinIntoString ("|") : juce::String ("missing"));
  15408. saveMenus (juce::StringArray { "Tools", "One-click audio recording" }, std::vector<juce::PopupMenu> { tools, oneClick != nullptr ? *oneClick : juce::PopupMenu() },
  15409. prefix + "-tools-one-click.png");
  15410. const auto plan = lynx::oneclick::plan (engine.getSong(), {}, 2, lynx::oneclick::Into::playlist);
  15411. check ("one_click_plan", plan.insert == 2 && plan.armInsert && plan.askInput && plan.songMode);
  15412. }
  15413. // ---- 6. Mixer › Disk recording › Latency compensation
  15414. {
  15415. auto& strips = ui.getMixerForSnapshot().getStripsForSnapshot();
  15416. const auto menu = strips.buildMenu (1);
  15417. const auto* disk = findSub (menu, lynx::tr ("Disk recording"));
  15418. int after = -1, at = -1, i = 0;
  15419. bool ticked = false;
  15420. if (disk != nullptr)
  15421. for (juce::PopupMenu::MenuItemIterator it (*disk); it.next(); ++i)
  15422. {
  15423. if (plain (it.getItem().text) == plain (lynx::tr ("Auto-create audio clip (the rendered files go on the Playlist)")))
  15424. after = i;
  15425. if (plain (it.getItem().text) == plain (lynx::tr ("Latency compensation")))
  15426. {
  15427. at = i;
  15428. ticked = it.getItem().isTicked;
  15429. }
  15430. }
  15431. check ("latency_comp_item", disk != nullptr && after >= 0 && at == after + 1 && ticked && engine.getRecordOptions().latencyCompensation,
  15432. juce::String (after) + " " + juce::String (at));
  15433. saveMenus (juce::StringArray { "Disk recording" }, std::vector<juce::PopupMenu> { disk != nullptr ? *disk : juce::PopupMenu() },
  15434. prefix + "-disk-recording.png");
  15435. check ("latency_comp_toggles", disk != nullptr && click (*disk, lynx::tr ("Latency compensation")) && ! engine.getRecordOptions().latencyCompensation);
  15436. }
  15437. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\nresult=" + (allOk ? "OK" : "FAIL") + "\n");
  15438. return allOk;
  15439. }
  15440. // --flclipshot (round 190dz): see the dispatch above
  15441. // a menu as JUCE lays it out with explicit column breaks (PopupMenu::addColumnBreak): the columns side by side on
  15442. // one menu background; custom items (the title band) are painted by their own component
  15443. static juce::Image columnMenuImage (const juce::PopupMenu& menu)
  15444. {
  15445. auto& lf = juce::LookAndFeel::getDefaultLookAndFeel();
  15446. const auto border = lf.getPopupMenuBorderSize();
  15447. struct Row
  15448. {
  15449. const juce::PopupMenu::Item* item;
  15450. int height;
  15451. };
  15452. std::vector<std::vector<Row>> columns (1);
  15453. std::vector<int> widths (1, 160);
  15454. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  15455. {
  15456. const auto& item = it.getItem();
  15457. int w = 0, h = 0;
  15458. if (item.customComponent != nullptr)
  15459. item.customComponent->getIdealSize (w, h);
  15460. else
  15461. {
  15462. lf.getIdealPopupMenuItemSize (item.text.upToFirstOccurrenceOf ("\t", false, false), item.isSeparator, item.isSectionHeader ? -1 : 0, w, h);
  15463. if (item.isSectionHeader)
  15464. h += h / 2; // as JUCE does
  15465. if (item.text.containsChar ('\t'))
  15466. w += 90;
  15467. }
  15468. columns.back().push_back ({ &item, h });
  15469. widths.back() = juce::jmax (widths.back(), w + 10);
  15470. if (item.shouldBreakAfter)
  15471. {
  15472. columns.emplace_back();
  15473. widths.push_back (160);
  15474. }
  15475. }
  15476. int width = 0, height = 0;
  15477. for (std::size_t c = 0; c < columns.size(); ++c)
  15478. {
  15479. width += widths[c];
  15480. int h = 2 * border;
  15481. for (const auto& row : columns[c])
  15482. h += row.height;
  15483. height = juce::jmax (height, h);
  15484. }
  15485. auto image = lynx::shot::canvas (width, height);
  15486. juce::Graphics g (image);
  15487. lynx::shot::logical (g);
  15488. lf.drawPopupMenuBackground (g, width, height);
  15489. int x = 0;
  15490. for (std::size_t c = 0; c < columns.size(); ++c)
  15491. {
  15492. int y = border;
  15493. for (const auto& row : columns[c])
  15494. {
  15495. const auto& item = *row.item;
  15496. const juce::Rectangle<int> r (x, y, widths[c], row.height);
  15497. if (item.customComponent != nullptr)
  15498. {
  15499. juce::Graphics::ScopedSaveState state (g);
  15500. g.setOrigin (r.getPosition());
  15501. item.customComponent->setSize (r.getWidth(), r.getHeight());
  15502. item.customComponent->paintEntireComponent (g, false);
  15503. }
  15504. else if (item.isSectionHeader)
  15505. lf.drawPopupMenuSectionHeader (g, r, item.text);
  15506. else
  15507. {
  15508. juce::Graphics::ScopedSaveState state (g);
  15509. g.setOrigin (r.getPosition());
  15510. lf.drawPopupMenuItem (g, r.withPosition (0, 0), item.isSeparator, item.isEnabled, false, item.isTicked, item.subMenu != nullptr,
  15511. item.text.upToFirstOccurrenceOf ("\t", false, false), item.text.fromFirstOccurrenceOf ("\t", false, false),
  15512. item.image.get(), nullptr);
  15513. }
  15514. y += row.height;
  15515. }
  15516. x += widths[c];
  15517. if (c + 1 < columns.size()) // (JUCE's column separator)
  15518. {
  15519. g.setColour (lf.findColour (juce::PopupMenu::textColourId).withAlpha (0.15f));
  15520. g.fillRect (x - 1, border, 1, height - 2 * border);
  15521. }
  15522. }
  15523. return image;
  15524. }
  15525. // --genpresetshot (round 190fs): see the dispatch above
  15526. bool runGenPresetShot (const juce::String& prefix)
  15527. {
  15528. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  15529. juce::StringArray report;
  15530. bool allOk = true;
  15531. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  15532. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  15533. allOk = allOk && ok;
  15534. };
  15535. const auto shoot = [&prefix] (juce::Component& c, const char* name) {
  15536. savePng (c.createComponentSnapshot (c.getLocalBounds()), prefix + "-" + name + ".png");
  15537. };
  15538. const auto plain = [] (juce::String t) { return t.upToFirstOccurrenceOf ("\t", false, false).removeCharacters ("&"); };
  15539. const auto texts = [&plain] (const juce::PopupMenu& menu) {
  15540. juce::StringArray out;
  15541. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  15542. out.add (it.getItem().isSeparator ? juce::String ("-") : it.getItem().isSectionHeader ? "[" + plain (it.getItem().text) + "]" : plain (it.getItem().text));
  15543. return out;
  15544. };
  15545. const auto click = [&plain] (const juce::PopupMenu& menu, const juce::String& text) {
  15546. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  15547. if (plain (it.getItem().text) == plain (text) && it.getItem().isEnabled && it.getItem().action != nullptr)
  15548. {
  15549. it.getItem().action();
  15550. return true;
  15551. }
  15552. return false;
  15553. };
  15554. const auto sameSound = [] (const lynx::ChannelDef& a, const lynx::ChannelDef& b) { return lynx::genpresets::sameSound (a, b); };
  15555. lynx::AudioEngine engine (false);
  15556. const auto& fl = lynx::flStudioAccess();
  15557. auto dx = lynx::natives::makeChannel (lynx::InstrumentKind::dx10, fl);
  15558. auto osc = lynx::natives::makeChannel (lynx::InstrumentKind::threeosc, fl);
  15559. check ("channels_made", dx.has_value() && osc.has_value());
  15560. if (! dx || ! osc)
  15561. {
  15562. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\n");
  15563. return false;
  15564. }
  15565. engine.editSong ([&] (lynx::Song& s) {
  15566. s.channels.clear();
  15567. s.channels.push_back (*dx);
  15568. s.channels.back().mixerTrack = 1;
  15569. s.channels.push_back (*osc);
  15570. s.channels.back().mixerTrack = 2;
  15571. lynx::ChannelDef synth;
  15572. synth.instrument = lynx::InstrumentKind::synth;
  15573. synth.name = "Synth";
  15574. synth.mixerTrack = 3;
  15575. s.channels.push_back (synth);
  15576. });
  15577. const auto channel = [&engine] (int i) { return engine.getSong().channels[(std::size_t) i]; };
  15578. // ---- 1. Fruity DX10: the preset box before and after "Save preset..."
  15579. {
  15580. auto frame = lynx::makeChannelFrame (engine, 0, 0);
  15581. frame->setSize (juce::jmax (500, frame->getWidth()), juce::jmax (300, frame->getHeight()));
  15582. auto menu = lynx::channelPresetMenu (*frame);
  15583. check ("dx10_menu", menu.has_value());
  15584. const auto before = menu ? texts (*menu) : juce::StringArray();
  15585. check ("dx10_menu_has_save", before.contains (lynx::tr ("Save preset...")) && before.contains (lynx::tr ("Show the presets folder"))
  15586. && ! before.contains ("[" + lynx::tr ("Your presets") + "]"), before.joinIntoString ("|"));
  15587. if (menu)
  15588. saveMenus (juce::StringArray { "Fruity DX10 presets" }, std::vector<juce::PopupMenu> { *menu }, prefix + "-dx10-menu-before.png");
  15589. // a sound of its own: the bank's 4th preset, then a knob moved (a sound no factory preset has)
  15590. const auto mine = [&] {
  15591. auto c = channel (0);
  15592. if (auto b = lynx::banks::withPreset (c, 3))
  15593. c = *b;
  15594. if (! c.pluginState.empty())
  15595. c.pluginState[c.pluginState.size() / 2] ^= 0x5a;
  15596. return c;
  15597. }();
  15598. engine.editSong ([&] (lynx::Song& s) { s.channels[0] = mine; });
  15599. check ("dx10_saved", lynx::channelPresetSave (*frame, "My FM Bell"));
  15600. const auto file = lynx::genpresetui::folderFor (lynx::InstrumentKind::dx10).getChildFile ("My FM Bell.lynxpreset");
  15601. check ("dx10_file", file.existsAsFile() && lynx::genpresetui::isPresetFile (file), file.getFullPathName());
  15602. check ("dx10_box_shows_it", lynx::channelPresetName (*frame) == "My FM Bell", lynx::channelPresetName (*frame));
  15603. menu = lynx::channelPresetMenu (*frame);
  15604. const auto after = menu ? texts (*menu) : juce::StringArray();
  15605. check ("dx10_menu_your_presets", after.contains ("[" + lynx::tr ("Your presets") + "]") && after.contains ("My FM Bell")
  15606. && after.contains (lynx::tr ("Delete preset \"{0}\"", { "My FM Bell" })), after.joinIntoString ("|"));
  15607. if (menu)
  15608. saveMenus (juce::StringArray { "Fruity DX10 presets" }, std::vector<juce::PopupMenu> { *menu }, prefix + "-dx10-menu.png");
  15609. shoot (*frame, "dx10-window");
  15610. // another sound, then the user's preset from the menu: the saved sound back, one undo step, project changed
  15611. if (auto other = lynx::banks::withPreset (channel (0), 0))
  15612. engine.editSong ([&] (lynx::Song& s) { s.channels[0] = *other; });
  15613. check ("dx10_other_sound", ! sameSound (channel (0), mine));
  15614. engine.markSaved();
  15615. menu = lynx::channelPresetMenu (*frame);
  15616. check ("dx10_load_click", menu.has_value() && click (*menu, "My FM Bell"));
  15617. check ("dx10_loaded_identical", sameSound (channel (0), mine) && channel (0).pluginState == mine.pluginState);
  15618. check ("dx10_loaded_name_and_insert", channel (0).name == "My FM Bell" && channel (0).mixerTrack == 1,
  15619. juce::String::fromUTF8 (channel (0).name.c_str()));
  15620. check ("dx10_project_changed", engine.isModified());
  15621. engine.undo();
  15622. check ("dx10_one_undo_step", ! sameSound (channel (0), mine));
  15623. engine.redo();
  15624. check ("dx10_redo", sameSound (channel (0), mine));
  15625. // the Browser: a new channel with the preset's generator, sound and name
  15626. juce::String error;
  15627. const auto count = engine.getSong().channels.size();
  15628. check ("browser_new_channel", lynx::genpresetui::addChannel (engine, file, error) && engine.getSong().channels.size() == count + 1, error);
  15629. const auto added = engine.getSong().channels.back();
  15630. check ("browser_channel_sound", added.instrument == lynx::InstrumentKind::dx10 && sameSound (added, mine) && added.name == "My FM Bell");
  15631. engine.undo();
  15632. check ("browser_channel_undo", engine.getSong().channels.size() == count);
  15633. }
  15634. // ---- 2. 3x Osc: save, the menu, delete
  15635. {
  15636. auto frame = lynx::makeChannelFrame (engine, 1, 0);
  15637. frame->setSize (juce::jmax (500, frame->getWidth()), juce::jmax (300, frame->getHeight()));
  15638. check ("3xosc_saved", lynx::channelPresetSave (*frame, "Wide Saw Lead") && lynx::channelPresetSave (*frame, "Sub Bass"));
  15639. auto menu = lynx::channelPresetMenu (*frame);
  15640. const auto items = menu ? texts (*menu) : juce::StringArray();
  15641. check ("3xosc_menu", items.contains ("Wide Saw Lead") && items.contains ("Sub Bass") && items.contains (lynx::tr ("Save preset...")),
  15642. items.joinIntoString ("|"));
  15643. if (menu)
  15644. saveMenus (juce::StringArray { "3x Osc presets" }, std::vector<juce::PopupMenu> { *menu }, prefix + "-3xosc-menu.png");
  15645. shoot (*frame, "3xosc-window");
  15646. check ("3xosc_delete", menu.has_value() && click (*menu, lynx::tr ("Delete preset \"{0}\"", { "Sub Bass" })));
  15647. check ("3xosc_deleted", lynx::genpresetui::userPresets (lynx::InstrumentKind::threeosc).size() == 1
  15648. && ! lynx::genpresetui::folderFor (lynx::InstrumentKind::threeosc).getChildFile ("Sub Bass.lynxpreset").exists());
  15649. menu = lynx::channelPresetMenu (*frame);
  15650. const auto left = menu ? texts (*menu) : juce::StringArray();
  15651. check ("3xosc_menu_after_delete", left.contains ("Wide Saw Lead") && ! left.contains ("Sub Bass"), left.joinIntoString ("|"));
  15652. }
  15653. // ---- 3. LYNX's synth: its "Presets..." box
  15654. {
  15655. engine.editSong ([] (lynx::Song& s) { s.channels[2].synth.cutoff = 777.0f; });
  15656. auto frame = lynx::makeChannelFrame (engine, 2, 0);
  15657. frame->setSize (juce::jmax (500, frame->getWidth()), juce::jmax (300, frame->getHeight()));
  15658. check ("synth_saved", lynx::channelPresetSave (*frame, "Dark Pad"));
  15659. const auto menu = lynx::channelPresetMenu (*frame);
  15660. const auto items = menu ? texts (*menu) : juce::StringArray();
  15661. check ("synth_menu", items.contains ("Dark Pad") && items.contains (lynx::tr ("Save preset...")) && items.contains (lynx::tr ("Show the presets folder")),
  15662. items.joinIntoString ("|"));
  15663. if (menu)
  15664. saveMenus (juce::StringArray { "Synth presets" }, std::vector<juce::PopupMenu> { *menu }, prefix + "-synth-menu.png");
  15665. const auto saved = lynx::genpresetui::read (lynx::genpresetui::folderFor (lynx::InstrumentKind::synth).getChildFile ("Dark Pad.lynxpreset"));
  15666. check ("synth_file", saved.has_value() && saved->sound.synth.cutoff == 777.0f);
  15667. }
  15668. // ---- 4. the name box (the hosted plugins' and the effects' "Save preset" box)
  15669. {
  15670. auto box = lynx::genpresetui::makeNameBox ("My FM Bell");
  15671. box->setSize (juce::jmax (360, box->getWidth()), juce::jmax (150, box->getHeight()));
  15672. shoot (*box, "save-name-box");
  15673. check ("name_box", box->getTextEditorContents ("name") == "My FM Bell");
  15674. }
  15675. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\n");
  15676. return allOk;
  15677. }
  15678. // --flfixshot (round 190ey): see the dispatch above
  15679. bool runFlFixShot (const juce::String& prefix)
  15680. {
  15681. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  15682. juce::StringArray report;
  15683. bool allOk = true;
  15684. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  15685. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  15686. allOk = allOk && ok;
  15687. };
  15688. const auto shoot = [&prefix] (juce::Component& c, const char* name) {
  15689. savePng (c.createComponentSnapshot (c.getLocalBounds()), prefix + "-" + name + ".png");
  15690. };
  15691. const auto plain = [] (juce::String t) {
  15692. t = t.upToFirstOccurrenceOf ("\t", false, false);
  15693. if (const auto at = t.indexOf (juce::String (" (") + juce::String::charToString (1)); at >= 0)
  15694. t = t.substring (0, at);
  15695. return t.removeCharacters (juce::String ("&_") + juce::String::charToString (1));
  15696. };
  15697. const auto texts = [&plain] (const juce::PopupMenu& menu) {
  15698. juce::StringArray out;
  15699. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  15700. out.add (it.getItem().isSeparator ? juce::String ("-") : it.getItem().isSectionHeader ? "[" + plain (it.getItem().text) + "]" : plain (it.getItem().text));
  15701. return out;
  15702. };
  15703. const auto findSub = [&plain] (const juce::PopupMenu& menu, const juce::String& text) -> const juce::PopupMenu* {
  15704. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  15705. if (it.getItem().subMenu != nullptr && plain (it.getItem().text) == plain (text))
  15706. return it.getItem().subMenu.get();
  15707. return nullptr;
  15708. };
  15709. const auto click = [&plain] (const juce::PopupMenu& menu, const juce::String& text) {
  15710. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  15711. if (plain (it.getItem().text) == plain (text) && it.getItem().isEnabled && it.getItem().action != nullptr)
  15712. {
  15713. it.getItem().action();
  15714. return true;
  15715. }
  15716. return false;
  15717. };
  15718. const auto folder = juce::File (prefix).getParentDirectory().getChildFile ("flfix-samples");
  15719. folder.createDirectory();
  15720. const auto writeWav = [] (const juce::File& file, double rate, int frames, double hz) {
  15721. juce::AudioBuffer<float> buffer (1, frames);
  15722. for (int i = 0; i < frames; ++i)
  15723. buffer.setSample (0, i, (float) (0.8 * std::sin (juce::MathConstants<double>::twoPi * hz * i / rate) * std::exp (-i / (rate * 0.12))));
  15724. file.deleteFile();
  15725. juce::WavAudioFormat wav;
  15726. if (auto out = std::unique_ptr<juce::AudioFormatWriter> (wav.createWriterFor (file.createOutputStream().release(), rate, 1, 16, {}, 0)))
  15727. out->writeFromAudioSampleBuffer (buffer, 0, frames);
  15728. return file;
  15729. };
  15730. // ---- 1. the Sampler page (SMP-1 / 4 / 5 / 7, CTL-4)
  15731. {
  15732. lynx::AudioEngine engine (false);
  15733. const auto clap = writeWav (folder.getChildFile ("Basic 808 Clap.wav"), 44100.0, 11600, 180.0);
  15734. const auto loop48 = writeWav (folder.getChildFile ("Loop 48k.wav"), 48000.0, 48000, 220.0);
  15735. engine.editSong ([&] (lynx::Song& s) {
  15736. if (s.channels.empty())
  15737. s.channels.resize (1);
  15738. lynx::audioclips::loadSampleInto (s.channels[0], clap.getFullPathName().toStdString(), "808 Clap");
  15739. });
  15740. const auto sampler = [&engine] { return engine.getSong().channels[0].sampler; };
  15741. auto frame = lynx::makeChannelFrame (engine, 0, 0);
  15742. frame->setSize (frame->getWidth() > 0 ? frame->getWidth() : 700, frame->getHeight() > 0 ? frame->getHeight() : 720);
  15743. frame->createComponentSnapshot (frame->getLocalBounds());
  15744. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (8000);
  15745. auto& f = *frame;
  15746. lynx::samplerPageTurn (f, "show", 0.0);
  15747. const auto rate = engine.getTransport().sampleRate.load();
  15748. check ("resample_greyed_at_project_rate", lynx::samplerPageQuery (f, "resample") == (std::abs (rate - 44100.0) < 0.5 ? "0" : "1"), juce::String (rate));
  15749. check ("load_regions_greyed_without_regions", lynx::samplerPageQuery (f, "loadRegions") == "0");
  15750. check ("load_markers_greyed_without_markers", lynx::samplerPageQuery (f, "loadMarkers") == "0");
  15751. check ("bit_depth_16", lynx::samplerPageQuery (f, "corner") == "16", lynx::samplerPageQuery (f, "corner"));
  15752. check ("wave_hint_summary", lynx::samplerPageQuery (f, "waveHint").startsWith ("44100Hz, 16Bit int mono, 0:263"), lynx::samplerPageQuery (f, "waveHint"));
  15753. shoot (f, "sampler-44k");
  15754. // SMP-5: MUL's text
  15755. lynx::samplerPageTurn (f, "mul", 800.0);
  15756. check ("mul_text", lynx::samplerPageQuery (f, "mulText") == "105.70%", lynx::samplerPageQuery (f, "mulText"));
  15757. lynx::samplerPageTurn (f, "mul", 0.0);
  15758. // SMP-4: CROSSFADE on a loopless sample: Use loop points on, the loop = the whole sample, the box reads 32
  15759. engine.editSong ([] (lynx::Song& s) { s.channels[0].sampler.useLoopPoints = false; });
  15760. lynx::samplerPageTurn (f, "crossfade", 120.0);
  15761. check ("crossfade_loops_whole_sample", sampler().useLoopPoints && sampler().loopStart == 0 && sampler().loopEnd == 11599,
  15762. juce::String (sampler().loopStart) + ".." + juce::String (sampler().loopEnd));
  15763. check ("bit_depth_32_precomputed", lynx::samplerPageQuery (f, "corner") == "32", lynx::samplerPageQuery (f, "corner"));
  15764. frame->createComponentSnapshot (frame->getLocalBounds());
  15765. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (8000);
  15766. shoot (f, "sampler-crossfade-red-loop");
  15767. lynx::samplerPageTurn (f, "crossfade", 0.0);
  15768. // SMP-3: a loop set with END alone, drawn red (FL: 0..276)
  15769. engine.editSong ([] (lynx::Song& s) {
  15770. s.channels[0].sampler.loopStart = 0;
  15771. s.channels[0].sampler.loopEnd = 2400;
  15772. });
  15773. lynx::samplerPageTurn (f, "show", 0.0);
  15774. shoot (f, "sampler-end-loop-red");
  15775. // round 190gw (live check 190gu B3): the waveform menu's Spectrum view / Multichannel waveform view, on a stereo
  15776. // clap-like noise burst (left and right differ) with no loop, as FL's shot
  15777. {
  15778. const auto noisy = folder.getChildFile ("Noise Clap.wav");
  15779. juce::AudioBuffer<float> b (2, 44100);
  15780. juce::Random random (190);
  15781. for (int i = 0; i < b.getNumSamples(); ++i)
  15782. for (int c = 0; c < 2; ++c)
  15783. b.setSample (c, i, (float) ((random.nextFloat() * 2.0f - 1.0f) * 0.9 * std::exp (-i / (44100.0 * (c == 0 ? 0.10 : 0.18)))
  15784. * (i > 1500 * c ? 1.0 : 0.15)));
  15785. noisy.deleteFile();
  15786. juce::WavAudioFormat wav;
  15787. if (auto out = std::unique_ptr<juce::AudioFormatWriter> (wav.createWriterFor (noisy.createOutputStream().release(), 44100.0, 2, 16, {}, 0)))
  15788. out->writeFromAudioSampleBuffer (b, 0, b.getNumSamples());
  15789. const auto before = engine.getSong().channels[0];
  15790. engine.editSong ([&] (lynx::Song& s) {
  15791. s.channels[0].samplePath = noisy.getFullPathName().toStdString();
  15792. s.channels[0].sampler.loopStart = s.channels[0].sampler.loopEnd = -1;
  15793. s.channels[0].sampler.useLoopPoints = false;
  15794. });
  15795. lynx::samplerPageTurn (f, "show", 0.0);
  15796. frame->createComponentSnapshot (frame->getLocalBounds()); // (starts the new file's waveform)
  15797. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (8000);
  15798. lynx::samplerpage::waveViews().spectrum = true;
  15799. lynx::samplerPageTurn (f, "show", 0.0);
  15800. shoot (f, "sampler-spectrum-view");
  15801. lynx::samplerpage::waveViews() = { false, true };
  15802. lynx::samplerPageTurn (f, "show", 0.0);
  15803. shoot (f, "sampler-multichannel-view");
  15804. lynx::samplerpage::waveViews() = {};
  15805. engine.editSong ([&before] (lynx::Song& s) { s.channels[0] = before; });
  15806. lynx::samplerPageTurn (f, "show", 0.0);
  15807. frame->createComponentSnapshot (frame->getLocalBounds());
  15808. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (8000);
  15809. }
  15810. // SMP-7: the waveform menu
  15811. const auto waveMenu = lynx::samplerWaveMenu (f);
  15812. juce::StringArray expected { lynx::tr ("Reload"), lynx::tr ("Save as..."), lynx::tr ("Locate file"), lynx::tr ("Copy audio to clipboard"),
  15813. lynx::tr ("Paste audio from clipboard"), "-", lynx::tr ("Edit in audio editor"),
  15814. lynx::tr ("Edit in pitch corrector"), lynx::tr ("Edit in time warper"), "-", // (round 190gw)
  15815. lynx::tr ("Open in new sampler channel"), lynx::tr ("Open in new Fruity Granulizer channel"),
  15816. lynx::tr ("Open in new Fruity Slicer channel"), lynx::tr ("Open in new Slicex channel"), "-", // (round 190gk)
  15817. lynx::tr ("Detect tempo") };
  15818. if (lynx::fileProperties) // (round 190gk: Windows only)
  15819. expected.add (lynx::tr ("Get properties"));
  15820. expected.addArray (juce::StringArray { "-", lynx::tr ("Spectrum view"), lynx::tr ("Multichannel waveform view") }); // (round 190gw)
  15821. check ("wave_menu_items", waveMenu.has_value() && texts (*waveMenu) == expected, waveMenu.has_value() ? texts (*waveMenu).joinIntoString ("|") : juce::String ("none"));
  15822. if (waveMenu.has_value())
  15823. saveMenus (juce::StringArray { "Sampler waveform" }, std::vector<juce::PopupMenu> { *waveMenu }, prefix + "-wave-menu.png");
  15824. check ("copy_audio_to_clipboard", waveMenu.has_value() && click (*waveMenu, lynx::tr ("Copy audio to clipboard"))
  15825. && lynx::audioclipboard::editor().frames() == 11600);
  15826. // SMP-1: a 48 kHz sample in this project: Resample enabled
  15827. lynx::samplerPageTurn (f, "show", 0.0);
  15828. engine.editSong ([&] (lynx::Song& s) { s.channels[0].samplePath = loop48.getFullPathName().toStdString(); });
  15829. lynx::samplerPageTurn (f, "show", 0.0);
  15830. check ("resample_enabled_48k", lynx::samplerPageQuery (f, "resample") == (std::abs (rate - 48000.0) < 0.5 ? "0" : "1"), juce::String (rate));
  15831. frame->createComponentSnapshot (frame->getLocalBounds()); // (starts the new file's waveform)
  15832. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (8000);
  15833. shoot (f, "sampler-48k");
  15834. // CTL-4: Remove sample renames the channel "Sampler"
  15835. lynx::samplerFileRowPress (f, 3);
  15836. check ("remove_sample_renames", engine.getSong().channels[0].name == "Sampler" && engine.getSong().channels[0].samplePath.empty(),
  15837. juce::String::fromUTF8 (engine.getSong().channels[0].name.c_str()));
  15838. lynx::samplerPageTurn (f, "show", 0.0);
  15839. check ("no_sample_content_greyed", lynx::samplerPageQuery (f, "keepOnDisk") == "0" && lynx::samplerPageQuery (f, "resample") == "0");
  15840. shoot (f, "sampler-removed");
  15841. }
  15842. // ---- 2. the Multilink button's menu with multilink off (CTL-1)
  15843. lynx::AudioEngine engine (false);
  15844. lynx::MainComponent ui (engine, false);
  15845. ui.setSize (1600, 900);
  15846. {
  15847. using lynx::AutomationTarget;
  15848. using lynx::AutomationTargetKind;
  15849. engine.editSong ([] (lynx::Song& s) {
  15850. if (s.channels.empty())
  15851. s.channels.resize (1);
  15852. s.channels[0].name = "808 Kick";
  15853. });
  15854. engine.setMultilink (false);
  15855. engine.noteTweaked ({ AutomationTargetKind::channelVolume, 0 });
  15856. engine.noteTweaked ({ AutomationTargetKind::channelPan, 0 });
  15857. const auto menu = ui.getMultilinkMenuForSnapshot();
  15858. juce::PopupMenu::MenuItemIterator first (menu);
  15859. first.next();
  15860. const auto caption = first.getItem().text;
  15861. bool columnBreak = false, lynxLines = false;
  15862. juce::String rightCaption;
  15863. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  15864. {
  15865. if (columnBreak && rightCaption.isEmpty() && it.getItem().isSectionHeader)
  15866. rightCaption = it.getItem().text;
  15867. columnBreak = columnBreak || it.getItem().shouldBreakAfter;
  15868. lynxLines = lynxLines || it.getItem().text == lynx::tr ("Link to controller");
  15869. }
  15870. check ("ml_off_left_column_named", first.getItem().isSectionHeader && caption == lynx::describeAutomationTarget (engine, { AutomationTargetKind::channelPan, 0 }), caption);
  15871. check ("ml_off_two_columns", columnBreak && rightCaption == lynx::tr ("Last 2 tweaked parameters"), rightCaption);
  15872. check ("ml_off_no_lynx_greyed_lines", ! lynxLines);
  15873. savePng (columnMenuImage (menu), prefix + "-multilink-off-menu.png");
  15874. }
  15875. // ---- 3. the Playlist (PL-1 / 2 / 3 / 6 / 7 / 8)
  15876. auto& playlist = ui.getPlaylistForSnapshot();
  15877. {
  15878. auto song = lynx::Song::makeDefault();
  15879. lynx::ChannelDef bass;
  15880. bass.name = "Amount Too - Bass";
  15881. bass.instrument = lynx::InstrumentKind::audioClip;
  15882. bass.samplePath = writeWav (folder.getChildFile ("bass.wav"), 44100.0, 88200, 82.0).getFullPathName().toStdString();
  15883. bass.misc.levels.volume = 1.468f;
  15884. song.channels.push_back (bass);
  15885. lynx::Clip c;
  15886. c.kind = lynx::ClipKind::audio;
  15887. c.channel = (int) song.channels.size() - 1;
  15888. c.track = 3;
  15889. c.start = 4 * lynx::ppq;
  15890. c.length = 2 * lynx::ppq;
  15891. song.playlist.push_back (c);
  15892. engine.setSong (std::move (song));
  15893. }
  15894. engine.dispatchPendingMessages();
  15895. const auto clipIndex = (int) engine.getSong().playlist.size() - 1;
  15896. {
  15897. const auto menu = playlist.getClipMenuForSnapshot (clipIndex);
  15898. const auto* automate = findSub (menu, lynx::tr ("Automate"));
  15899. check ("automate_volume_runs", automate != nullptr && click (*automate, lynx::tr ("Volume")));
  15900. const auto& song = engine.getSong();
  15901. const auto made = (int) song.automations.size() - 1;
  15902. check ("automate_makes_current_clip", made >= 0 && playlist.brush.kind == lynx::ClipKind::automation && playlist.brush.index == made,
  15903. juce::String (playlist.brush.index));
  15904. // (PL-2: Levels VOL 147 %, FL's clip plays unity)
  15905. check ("automate_volume_unity", made >= 0 && song.automations.back().points[0].value == 0.5f
  15906. && lynx::lasttweak::valueText (song, song.automations.back().target, song.automations.back().points[0].value) == "100% 0.0dB 1.00");
  15907. const auto again = playlist.getClipMenuForSnapshot (clipIndex);
  15908. const auto* automate2 = findSub (again, lynx::tr ("Automate"));
  15909. check ("automate_second_is_2", automate2 != nullptr && click (*automate2, lynx::tr ("Volume"))
  15910. && juce::String::fromUTF8 (engine.getSong().automations.back().name.c_str()).endsWith (" #2"),
  15911. juce::String::fromUTF8 (engine.getSong().automations.back().name.c_str()));
  15912. // PL-7: Fade in / out curve
  15913. const auto* fadeIn = findSub (menu, lynx::tr ("Fade in curve"));
  15914. const auto* fadeOut = findSub (menu, lynx::tr ("Fade out curve"));
  15915. const juce::StringArray curve { lynx::tr ("Reset"), lynx::tr ("Normalize"), lynx::tr ("Normalize selection as a group"), lynx::tr ("Create crossfade"),
  15916. lynx::tr ("Manual"), "[" + lynx::tr ("Declicker") + "]", lynx::tr ("Automatic"), lynx::tr ("Disabled"), lynx::tr ("Enabled"),
  15917. "[" + lynx::tr ("Curve shape") + "]", lynx::tr ("Smooth curve"), lynx::tr ("Single curve") };
  15918. check ("fade_curve_submenus", fadeIn != nullptr && fadeOut != nullptr && texts (*fadeIn) == curve && texts (*fadeOut) == curve,
  15919. fadeIn != nullptr ? texts (*fadeIn).joinIntoString ("|") : juce::String ("missing"));
  15920. if (fadeOut != nullptr)
  15921. saveMenus (juce::StringArray { "Audio clip menu", "Fade out curve" }, std::vector<juce::PopupMenu> { menu, *fadeOut }, prefix + "-fade-curve-menu.png");
  15922. // PL-8: Detect tempo is one item now
  15923. bool detectItem = false;
  15924. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  15925. if (plain (it.getItem().text) == plain (lynx::tr ("Detect tempo")))
  15926. detectItem = it.getItem().subMenu == nullptr && it.getItem().action != nullptr;
  15927. check ("detect_tempo_item", detectItem);
  15928. // PL-3: Preview through the channel; transport start ends it
  15929. check ("preview_through_channel", engine.previewClipThroughChannel ((std::size_t) clipIndex) && engine.isClipPreviewing());
  15930. engine.play();
  15931. check ("preview_stops_on_transport", ! engine.isClipPreviewing());
  15932. engine.stop();
  15933. check ("preview_again_then_stop", engine.previewClipThroughChannel ((std::size_t) clipIndex) && engine.isClipPreviewing());
  15934. engine.stop();
  15935. check ("preview_stops_on_stop", ! engine.isClipPreviewing());
  15936. }
  15937. // PL-8: the dialog
  15938. {
  15939. lynx::ui::TempoDetectionRequest r;
  15940. r.name = "Amount Too - Bass";
  15941. // (a drum-like loop at 117.5 BPM, 100 beats as in FL's dialog: clicks on every beat)
  15942. {
  15943. auto beats = std::make_shared<lynx::SampleData>();
  15944. beats->sampleRate = 44100.0;
  15945. const auto period = 44100.0 * 60.0 / 117.5;
  15946. beats->left.assign ((std::size_t) std::llround (period * 100.0), 0.0f);
  15947. for (int b = 0; b < 100; ++b)
  15948. for (int i = 0; i < 2000; ++i)
  15949. if (const auto at = (std::size_t) std::llround (b * period) + (std::size_t) i; at < beats->left.size())
  15950. beats->left[at] = (float) (0.9 * std::sin (i * 0.09) * std::exp (-i / 400.0));
  15951. r.sample = beats;
  15952. }
  15953. r.projectBpm = 100.0;
  15954. double applied = -1.0;
  15955. r.apply = [&applied] (double beats) { applied = beats; };
  15956. auto panel = lynx::ui::makeTempoDetectionPanel (r);
  15957. panel->setSize (panel->getWidth(), panel->getHeight());
  15958. shoot (*panel, "tempo-detection");
  15959. report.add ("tempo dialog title: " + lynx::ui::tempoDetectionTitle (r.name));
  15960. const auto project = lynx::ui::pressTempoDetectionButton (*panel, panel->getNumChildComponents() - 3);
  15961. const auto seconds = (double) r.sample->frames() / r.sample->sampleRate; // (100 beats at 117.5 BPM)
  15962. check ("tempo_project_button", std::abs (applied - seconds * 100.0 / 60.0) < 1.0e-6, project + " -> " + juce::String (applied));
  15963. const auto none = lynx::ui::pressTempoDetectionButton (*panel, panel->getNumChildComponents() - 2);
  15964. check ("tempo_no_tempo_button", applied == 0.0, none);
  15965. }
  15966. // ---- 4. issue #152's question (ISS152-1): FL's message with "Remember my choice"
  15967. {
  15968. auto box = lynx::makeFlMessageDialog ({ lynx::tr ("External input"),
  15969. 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?"),
  15970. { lynx::tr ("Yes"), lynx::tr ("No") }, true });
  15971. shoot (*box, "external-input-question");
  15972. bool listed = false;
  15973. for (const auto& m : lynx::messages::all())
  15974. listed = listed || juce::String (m.id) == "RecAutoSwitchExternalInput";
  15975. check ("external_input_in_manage_messages", listed);
  15976. }
  15977. // ---- 5. round 190gk: FL's Start in the render window; the Sampler's "Open in new Fruity Slicer / Slicex channel";
  15978. // a Gross Beat slot picked by MIDI becomes its parameter
  15979. {
  15980. lynx::AudioEngine engine (false);
  15981. auto panel = lynx::makeClipRenderPanel (engine);
  15982. panel->setSize (panel->getWidth() > 0 ? panel->getWidth() : 640, panel->getHeight() > 0 ? panel->getHeight() : 480);
  15983. juce::String button;
  15984. for (auto* c : panel->getChildren())
  15985. if (auto* b = dynamic_cast<juce::TextButton*> (c); b != nullptr && b->isVisible() && b->getTooltip() == lynx::tr ("Start rendering"))
  15986. button = b->getButtonText();
  15987. check ("render_button_start", button == lynx::trc ("@render button: Start") && button == "Start", button);
  15988. shoot (*panel, "fltails190gk-render-start");
  15989. const auto clap = writeWav (folder.getChildFile ("Slice me.wav"), 44100.0, 44100, 140.0);
  15990. engine.editSong ([] (lynx::Song& s) {
  15991. s.channels.resize (2);
  15992. s.channels[0] = {};
  15993. s.channels[0].instrument = lynx::InstrumentKind::fruityslicer;
  15994. s.channels[0].name = "Fruity Slicer";
  15995. s.channels[1] = {};
  15996. s.channels[1].instrument = lynx::InstrumentKind::slicex;
  15997. s.channels[1].name = "Slicex";
  15998. });
  15999. const auto locate = [] (int index) {
  16000. return [index] (lynx::Song& s) -> lynx::ChannelDef* { return index < (int) s.channels.size() ? &s.channels[(std::size_t) index] : nullptr; };
  16001. };
  16002. lynx::loadSampleWhenOpened (0, clap.getFullPathName());
  16003. auto slicer = lynx::makeFruitySlicerEditor (engine, locate (0), 0);
  16004. const auto& fs = engine.getSong().channels[0];
  16005. check ("open_in_new_fruity_slicer", fs.samplePath == clap.getFullPathName().toStdString() && ! fs.pluginState.empty(), juce::String (fs.samplePath));
  16006. lynx::loadSlicexSampleWhenOpened (1, clap.getFullPathName());
  16007. auto slicex = lynx::makeSlicexEditor (engine, locate (1), 1);
  16008. const auto& sx = engine.getSong().channels[1];
  16009. check ("open_in_new_slicex", sx.samplePath == clap.getFullPathName().toStdString() && ! sx.pluginState.empty(), juce::String (sx.samplePath));
  16010. auto again = lynx::makeSlicexEditor (engine, locate (1), 1); // (the request is used once)
  16011. check ("open_in_new_used_once", engine.getSong().channels[1].samplePath == sx.samplePath);
  16012. // Gross Beat on insert 1: two notes on its MIDI input, one block, the engine's timer step
  16013. engine.editSong ([] (lynx::Song& s) {
  16014. if (s.mixer.size() < 2)
  16015. s.mixer.resize (2);
  16016. s.mixer[1].effects = { lynx::makeEffectSlot (lynx::EffectKind::grossBeat) };
  16017. });
  16018. engine.dispatchPendingMessages();
  16019. auto fx = engine.getEffect (1, 0);
  16020. check ("gb_running", fx != nullptr);
  16021. if (fx != nullptr)
  16022. {
  16023. std::vector<float> l (512, 0.1f), r (512, 0.1f);
  16024. fx->prepare (44100.0);
  16025. fx->setSongPosition (0.0);
  16026. fx->midiNote (60 + 9, 100, 0);
  16027. fx->midiNote (24 + 3, 100, 0);
  16028. fx->process (l.data(), r.data(), 512, engine.getSong().mixer[1].effects[0].params, 120.0);
  16029. engine.pumpGrossBeatPicks();
  16030. const auto& p = engine.getSong().mixer[1].effects[0].params;
  16031. check ("gb_midi_pick_sets_parameters", lynx::grossbeat::rawFromParam (0, p[0]) == 9 && lynx::grossbeat::rawFromParam (1, p[1]) == 3,
  16032. juce::String (lynx::grossbeat::rawFromParam (0, p[0])) + " " + juce::String (lynx::grossbeat::rawFromParam (1, p[1])));
  16033. }
  16034. }
  16035. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\nresult=" + (allOk ? "OK" : "FAIL") + "\n");
  16036. return allOk;
  16037. }
  16038. // --grooveshot190fm (round 190fm): see the dispatch above
  16039. bool runGrooveShot190fm (const juce::String& prefix)
  16040. {
  16041. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  16042. juce::StringArray report;
  16043. bool allOk = true;
  16044. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  16045. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  16046. allOk = allOk && ok;
  16047. };
  16048. const auto plain = [] (juce::String t) {
  16049. t = t.upToFirstOccurrenceOf ("\t", false, false);
  16050. return t.removeCharacters (juce::String ("&_") + juce::String::charToString (1));
  16051. };
  16052. const auto sub = [&plain] (const juce::PopupMenu& menu, const juce::String& start) -> const juce::PopupMenu* {
  16053. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  16054. if (it.getItem().subMenu != nullptr && plain (it.getItem().text).startsWith (start))
  16055. return it.getItem().subMenu.get();
  16056. return nullptr;
  16057. };
  16058. const auto item = [&plain] (const juce::PopupMenu& menu, const juce::String& text) -> const juce::PopupMenu::Item* {
  16059. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  16060. if (plain (it.getItem().text) == text)
  16061. return &it.getItem();
  16062. return nullptr;
  16063. };
  16064. lynx::AudioEngine engine (false);
  16065. lynx::MainComponent ui (engine, false);
  16066. ui.setSize (1600, 900);
  16067. std::uint32_t classic = 0;
  16068. {
  16069. auto song = lynx::Song::makeDefault();
  16070. song.mode = lynx::PlayMode::song;
  16071. song.playlist.push_back ({ 0, 0, 0, 4 * lynx::ppq, 0 });
  16072. song.playlist.push_back ({ 0, 1, 4 * lynx::ppq, 4 * lynx::ppq, 0 });
  16073. for (const auto& e : lynx::groove::factoryBank())
  16074. if (juce::String (e.folder) == "Classic swing" && e.groove.base == lynx::GrooveBase::sixteenth
  16075. && (e.groove.name == "Swing 16ths 54 %" || e.groove.name == "Swing 16ths 58 %" || e.groove.name == "Swing 16ths 62 %"
  16076. || e.groove.name == "Swing 16ths 71 %"))
  16077. {
  16078. const auto id = lynx::groove::add (song.grooves, e.groove);
  16079. if (e.groove.name == "Swing 16ths 58 %")
  16080. classic = id;
  16081. }
  16082. song.playlist[0].groove = classic;
  16083. engine.setSong (std::move (song));
  16084. }
  16085. engine.dispatchPendingMessages();
  16086. auto& playlist = ui.getPlaylistForSnapshot();
  16087. const auto menu = playlist.getClipMenuForSnapshot (0);
  16088. const auto* chooser = sub (menu, lynx::tr ("Groove"));
  16089. check ("groove_chooser_in_clip_menu", chooser != nullptr);
  16090. const auto* add = chooser != nullptr ? sub (*chooser, lynx::tr ("Add a groove")) : nullptr;
  16091. const auto* folder = add != nullptr ? sub (*add, lynx::tr ("Classic swing")) : nullptr;
  16092. check ("classic_swing_folder", folder != nullptr && folder->getNumItems() == 27, folder != nullptr ? juce::String (folder->getNumItems()) : juce::String ("missing"));
  16093. const auto* commit = item (menu, lynx::tr ("Commit groove"));
  16094. check ("commit_enabled_with_a_groove", commit != nullptr && commit->isEnabled);
  16095. check ("extract_present", item (menu, lynx::tr ("Extract groove")) != nullptr);
  16096. {
  16097. juce::StringArray names { "Pattern clip menu" };
  16098. std::vector<juce::PopupMenu> menus { menu };
  16099. if (chooser != nullptr)
  16100. {
  16101. names.add ("Groove");
  16102. menus.push_back (*chooser);
  16103. }
  16104. if (add != nullptr)
  16105. {
  16106. names.add ("Add a groove");
  16107. menus.push_back (*add);
  16108. }
  16109. if (folder != nullptr)
  16110. {
  16111. names.add ("Classic swing");
  16112. menus.push_back (*folder);
  16113. }
  16114. saveMenus (names, menus, prefix + "-playlist-clip-menu.png");
  16115. }
  16116. // the second clip (no groove): Commit is off; choosing a groove from the menu sets it
  16117. {
  16118. const auto other = playlist.getClipMenuForSnapshot (1);
  16119. const auto* c2 = item (other, lynx::tr ("Commit groove"));
  16120. check ("commit_disabled_without_a_groove", c2 != nullptr && ! c2->isEnabled);
  16121. const auto* ch2 = sub (other, lynx::tr ("Groove"));
  16122. const auto* pick = ch2 != nullptr ? item (*ch2, "Swing 16ths 71 %") : nullptr;
  16123. if (pick != nullptr && pick->action != nullptr)
  16124. pick->action();
  16125. const auto& song = engine.getSong();
  16126. check ("chooser_sets_the_clip_groove", song.playlist.size() == 2 && lynx::groove::ofClip (song, song.playlist[1]) != nullptr
  16127. && lynx::groove::ofClip (song, song.playlist[1])->name == "Swing 16ths 71 %");
  16128. }
  16129. // the pool with the classic grooves
  16130. {
  16131. auto pool = lynx::makeGroovePool (engine);
  16132. pool->setSize (900, lynx::groovePoolHeight (engine));
  16133. savePng (pool->createComponentSnapshot (pool->getLocalBounds()), prefix + "-pool.png");
  16134. }
  16135. // .lynx: a Playlist clip's groove comes back; a project without one writes nothing new
  16136. {
  16137. juce::String error;
  16138. const auto& song = engine.getSong();
  16139. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  16140. check ("lynx_round_trip", back && back->playlist.size() == 2 && back->playlist[0].groove == song.playlist[0].groove
  16141. && back->playlist[1].groove == song.playlist[1].groove && back->grooves == song.grooves,
  16142. error);
  16143. auto old = lynx::Song::makeDefault();
  16144. old.playlist.push_back ({ 0, 0, 0, 4 * lynx::ppq, 0 });
  16145. const auto json = lynx::ProjectFile::toJson (old, false);
  16146. const auto reloaded = lynx::ProjectFile::fromJson (json, error);
  16147. check ("old_project_unchanged", reloaded && lynx::ProjectFile::toJson (*reloaded, false) == json && reloaded->playlist[0].groove == 0);
  16148. }
  16149. // Commit from the menu: the clip's pattern (shared with the second clip) is copied, the groove is off
  16150. {
  16151. const auto patterns = engine.getSong().patterns.size();
  16152. const auto again = playlist.getClipMenuForSnapshot (0);
  16153. if (const auto* c = item (again, lynx::tr ("Commit groove")); c != nullptr && c->action != nullptr)
  16154. c->action();
  16155. const auto& song = engine.getSong();
  16156. check ("commit_runs", song.playlist[0].groove == 0 && song.patterns.size() == patterns + 1 && song.playlist[0].pattern == (int) patterns);
  16157. }
  16158. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\n" + (allOk ? "ALL OK" : "SOME FAILED") + "\n");
  16159. return allOk;
  16160. }
  16161. bool runFlClipShot (const juce::String& prefix)
  16162. {
  16163. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  16164. juce::StringArray report;
  16165. bool allOk = true;
  16166. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  16167. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  16168. allOk = allOk && ok;
  16169. };
  16170. const auto plain = [] (juce::String t) {
  16171. t = t.upToFirstOccurrenceOf ("\t", false, false);
  16172. if (const auto at = t.indexOf (juce::String (" (") + juce::String::charToString (1)); at >= 0)
  16173. t = t.substring (0, at);
  16174. return t.removeCharacters (juce::String ("&_") + juce::String::charToString (1));
  16175. };
  16176. const auto find = [&plain] (const juce::PopupMenu& menu, const juce::String& text) -> const juce::PopupMenu::Item* {
  16177. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  16178. if (plain (it.getItem().text) == plain (text))
  16179. return &it.getItem();
  16180. return nullptr;
  16181. };
  16182. const auto click = [&find] (const juce::PopupMenu& menu, const juce::String& text) {
  16183. const auto* item = find (menu, text);
  16184. if (item == nullptr || ! item->isEnabled || item->action == nullptr)
  16185. return false;
  16186. item->action();
  16187. return true;
  16188. };
  16189. lynx::AudioEngine engine (false);
  16190. lynx::MainComponent ui (engine, false);
  16191. ui.setSize (1600, 900);
  16192. int vox = -1;
  16193. {
  16194. auto song = lynx::Song::makeDefault();
  16195. song.channels.push_back ({});
  16196. song.channels.back().name = "Vox";
  16197. song.channels.back().instrument = lynx::InstrumentKind::audioClip;
  16198. song.channels.back().samplePath = writeShotSample (juce::File (prefix + "-vox.wav"), 330.0).getFullPathName().toStdString();
  16199. vox = (int) song.channels.size() - 1;
  16200. lynx::Clip c;
  16201. c.kind = lynx::ClipKind::audio;
  16202. c.channel = vox;
  16203. c.track = 3;
  16204. c.start = 4 * lynx::ppq;
  16205. c.length = 2 * lynx::ppq;
  16206. c.fadeIn = lynx::ppq / 4;
  16207. song.playlist.push_back (c);
  16208. engine.setSong (std::move (song));
  16209. }
  16210. engine.dispatchPendingMessages();
  16211. auto& playlist = ui.getPlaylistForSnapshot();
  16212. // ---- 1. the audio clip menu: FL's order, sections and columns, then LYNX's own items
  16213. {
  16214. const auto menu = playlist.getClipMenuForSnapshot (0);
  16215. juce::StringArray got, want;
  16216. int breakAfter = -1;
  16217. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  16218. {
  16219. const auto& item = it.getItem();
  16220. got.add (item.customComponent != nullptr ? "[" + lynx::tr ("Audio clip") + "]"
  16221. : item.isSeparator ? juce::String ("-")
  16222. : item.isSectionHeader ? "[" + plain (item.text) + "]"
  16223. : plain (item.text));
  16224. if (item.shouldBreakAfter)
  16225. breakAfter = got.size() - 1;
  16226. }
  16227. for (const auto& e : lynx::flclipmenu::shown (true, false))
  16228. if (e.kind != lynx::flclipmenu::Entry::Kind::columnBreak)
  16229. want.add (e.kind == lynx::flclipmenu::Entry::Kind::separator ? juce::String ("-")
  16230. : e.kind == lynx::flclipmenu::Entry::Kind::header ? "[" + lynx::tr (e.text.c_str()) + "]"
  16231. : lynx::tr (e.text.c_str()));
  16232. want.add ("-");
  16233. want.add ("[" + lynx::tr ("LYNX extras") + "]"); // (round 190gi)
  16234. for (const auto& x : lynx::flclipmenu::lynxExtras())
  16235. want.add (lynx::tr (x.c_str()));
  16236. check ("clip_menu_fl_order", got == want, got.joinIntoString ("|"));
  16237. check ("clip_menu_two_columns", breakAfter >= 0 && got[breakAfter] == lynx::tr ("Chop") && got[breakAfter + 1] == "[" + lynx::tr ("Sample") + "]",
  16238. juce::String (breakAfter));
  16239. const auto* crossfade = find (menu, lynx::tr ("Crossfade with"));
  16240. check ("crossfade_with_greyed", crossfade != nullptr && ! crossfade->isEnabled);
  16241. const auto* region = find (menu, lynx::tr ("Select region"));
  16242. const auto* full = region != nullptr && region->subMenu != nullptr ? find (*region->subMenu, lynx::tr ("Full")) : nullptr;
  16243. check ("select_region_full_ticked", full != nullptr && full->isTicked);
  16244. const auto* chop = find (menu, lynx::tr ("Chop"));
  16245. check ("chop_time_based", chop != nullptr && chop->subMenu != nullptr && find (*chop->subMenu, lynx::tr ("Chop in 32nd beats")) != nullptr
  16246. && find (*chop->subMenu, lynx::tr ("Chop to grid")) != nullptr);
  16247. savePng (columnMenuImage (menu), prefix + "-clip-menu.png");
  16248. std::fprintf (stderr, "flclipshot: menu saved\n");
  16249. // Muted is a check; Reset fades clears the fades; Select all similar clips selects
  16250. check ("muted_toggles", click (menu, lynx::tr ("Muted")) && engine.getSong().playlist[0].muted);
  16251. const auto again = playlist.getClipMenuForSnapshot (0);
  16252. const auto* muted = find (again, lynx::tr ("Muted"));
  16253. check ("muted_ticked", muted != nullptr && muted->isTicked);
  16254. check ("reset_fades", click (again, lynx::tr ("Reset fades")) && engine.getSong().playlist[0].fadeIn == 0);
  16255. engine.undo();
  16256. engine.undo();
  16257. engine.dispatchPendingMessages();
  16258. std::fprintf (stderr, "flclipshot: automate\n");
  16259. // Automate › Volume / Panning: the clip channel's Levels adjustment (FL's channel parameters 0x11 / 0x10)
  16260. const auto fresh = playlist.getClipMenuForSnapshot (0);
  16261. const auto* automate = find (fresh, lynx::tr ("Automate"));
  16262. const auto before = engine.getSong().automations.size();
  16263. check ("automate_volume_runs", automate != nullptr && automate->subMenu != nullptr && click (*automate->subMenu, lynx::tr ("Volume")));
  16264. const auto& song = engine.getSong();
  16265. const auto ok = song.automations.size() == before + 1 && song.automations.back().target.kind == lynx::AutomationTargetKind::channelAdjust
  16266. && song.automations.back().target.param == lynx::leveladjust::volume && song.automations.back().target.index == vox
  16267. && std::abs (song.automations.back().points[0].value - 0.5f) < 1.0e-6f;
  16268. check ("automate_volume_is_level_adjust", ok, ok ? juce::String::fromUTF8 (song.automations.back().name.c_str()) : juce::String());
  16269. engine.undo();
  16270. engine.dispatchPendingMessages();
  16271. }
  16272. std::fprintf (stderr, "flclipshot: overlap\n");
  16273. // ---- 2. a second channel's clip overlapping: Crossfade with lists it and makes FL's crossfade clip (round 190gw)
  16274. {
  16275. engine.editSong ([vox] (lynx::Song& s) {
  16276. auto copy = s.playlist[0]; // (another audio clip channel's clip, at the same time)
  16277. s.channels.push_back (s.channels[(std::size_t) vox]);
  16278. s.channels.back().name = "Vox 2";
  16279. copy.channel = (int) s.channels.size() - 1;
  16280. copy.track = 4;
  16281. s.playlist.push_back (copy);
  16282. });
  16283. engine.dispatchPendingMessages();
  16284. const auto overlapped = playlist.getClipMenuForSnapshot (0);
  16285. const auto* with = find (overlapped, lynx::tr ("Crossfade with"));
  16286. check ("crossfade_with_lists_the_overlap", with != nullptr && with->isEnabled && with->subMenu != nullptr && find (*with->subMenu, "Vox 2") != nullptr);
  16287. const auto made = with != nullptr && with->subMenu != nullptr && click (*with->subMenu, "Vox 2");
  16288. engine.dispatchPendingMessages();
  16289. const auto& xsong = engine.getSong();
  16290. const auto xok = made && ! xsong.automations.empty() && xsong.automations.back().links.size() == 2
  16291. && juce::String::fromUTF8 (xsong.automations.back().name.c_str()).endsWith (" to Vox 2 crossfade");
  16292. check ("crossfade_with_makes_the_clip", xok, xok ? juce::String::fromUTF8 (xsong.automations.back().name.c_str()) : juce::String());
  16293. if (made)
  16294. engine.undo();
  16295. engine.undo();
  16296. engine.dispatchPendingMessages();
  16297. }
  16298. std::fprintf (stderr, "flclipshot: misc\n");
  16299. // ---- 3. the channel's Misc tab: Levels adjustment = the offsets (pan 0, volume 100 %, Mod X / Y 0 %)
  16300. {
  16301. engine.editSong ([vox] (lynx::Song& s) {
  16302. s.channels[(std::size_t) vox].misc.levels.volume = 0.5f;
  16303. s.channels[(std::size_t) vox].misc.levels.pan = -0.25f;
  16304. });
  16305. engine.dispatchPendingMessages();
  16306. auto frame = lynx::makeChannelFrame (engine, vox, -1);
  16307. frame->setSize (juce::jmax (frame->getWidth(), 800), juce::jmax (frame->getHeight(), 420));
  16308. savePng (frame->createComponentSnapshot (frame->getLocalBounds()), prefix + "-misc-levels.png");
  16309. auto synthFrame = lynx::makeChannelFrame (engine, 0, -1);
  16310. synthFrame->setSize (juce::jmax (synthFrame->getWidth(), 800), juce::jmax (synthFrame->getHeight(), 420));
  16311. savePng (synthFrame->createComponentSnapshot (synthFrame->getLocalBounds()), prefix + "-misc-levels-ch1.png");
  16312. std::fprintf (stderr, "flclipshot: round trip\n");
  16313. // the .lynx round trip of the adjustment and of an automation of it; an old project writes nothing new
  16314. juce::String error;
  16315. auto song = engine.getSong();
  16316. lynx::Automation a;
  16317. a.target = { lynx::AutomationTargetKind::channelAdjust, vox, 0, lynx::leveladjust::volume };
  16318. a.points = { { 0, 0.25f, 0.0f } };
  16319. song.automations.push_back (a);
  16320. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  16321. check ("lynx_round_trip", back && back->channels[(std::size_t) vox].misc.levels == song.channels[(std::size_t) vox].misc.levels
  16322. && back->automations.back().target == a.target,
  16323. error);
  16324. auto old = lynx::Song::makeDefault();
  16325. const auto json = lynx::ProjectFile::toJson (old, false);
  16326. const auto reloaded = lynx::ProjectFile::fromJson (json, error);
  16327. check ("old_project_unchanged", ! json.contains ("\"levels\"") && reloaded && lynx::ProjectFile::toJson (*reloaded, false) == json
  16328. && std::all_of (reloaded->channels.begin(), reloaded->channels.end(),
  16329. [] (const lynx::ChannelDef& c) { return c.misc.levels.neutral(); }));
  16330. }
  16331. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\nresult=" + (allOk ? "OK" : "FAIL") + "\n");
  16332. return allOk;
  16333. }
  16334. // --bandlabshot <prefix> (round 190ch): the Lyrics / Notes panel (Pattern and Simple layouts, and on its own), the
  16335. // Reference match window measured on a real render and a real file, "Start from", and Clean voice, off-screen; and
  16336. // <prefix>-report.txt with what each route did (ok / FAIL lines)
  16337. void runBandlabShot (const juce::String& prefix)
  16338. {
  16339. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  16340. lynx::AudioEngine offline (false);
  16341. lynx::MainComponent ui (offline, false);
  16342. ui.setSize (1600, 900);
  16343. // (each step is named on stderr as it starts: a run that stops says where)
  16344. const auto note = [] (const juce::String& what) { std::fprintf (stderr, "bandlabshot: %s\n", what.toRawUTF8()); };
  16345. const auto shoot = [&prefix, &note] (juce::Component& c, const char* name) {
  16346. note (name);
  16347. savePng (lynx::shot::snapshot (c), prefix + "-" + name + ".png");
  16348. };
  16349. juce::String report;
  16350. const auto check = [&report, &note] (const juce::String& what, bool ok) {
  16351. note ((ok ? "ok " : "FAIL ") + what);
  16352. report << (ok ? "ok " : "FAIL ") << what << "\n";
  16353. };
  16354. const auto bar = (double) lynx::ppq * 4.0;
  16355. // ---- 1. Lyrics / Notes: the project's Comments
  16356. {
  16357. auto song = lynx::makeShowcaseSong (0);
  16358. song.info.title = "Night Drive";
  16359. 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"
  16360. "I keep driving through the night\n\n[Chorus]\nNight drive, night drive\nNothing but the white line\n\n"
  16361. "Notes: double the chorus vocal, try the second verse an octave down.";
  16362. lynx::Marker chorus;
  16363. chorus.tick = (std::int64_t) (12.0 * bar);
  16364. chorus.name = "Chorus";
  16365. song.addMarker (chorus);
  16366. offline.setSong (std::move (song));
  16367. }
  16368. note ("song set");
  16369. offline.dispatchPendingMessages();
  16370. ui.selectTabForSnapshot (2);
  16371. note ("show lyrics");
  16372. ui.showLyrics (false);
  16373. note ("lyrics shown");
  16374. if (auto* panel = ui.getLyricsPanelForSnapshot())
  16375. {
  16376. panel->showForSnapshot ({}, 6.5 * bar); // the playhead inside bar 7: that line is the one playing
  16377. shoot (ui, "lyrics-pattern");
  16378. shoot (*panel, "lyrics-panel");
  16379. const auto markersBefore = offline.getSong().markers().size();
  16380. panel->setCaretLineForSnapshot (6); // "I keep driving through the night"
  16381. panel->markAtPlayheadForSnapshot (10.0 * bar + 2.0 * lynx::ppq);
  16382. offline.dispatchPendingMessages();
  16383. ui.commitSongNotes();
  16384. const auto& s = offline.getSong();
  16385. check ("Marker at playhead stamps the line [11.3] and adds one marker",
  16386. juce::String::fromUTF8 (s.info.comments.c_str()).contains ("[11.3] I keep driving") && s.markers().size() == markersBefore + 1);
  16387. // (no audio device here: the seek is the request the audio thread takes at its next block)
  16388. const auto& seek = offline.getTransport().seekRequest;
  16389. check ("clicking the stamped line moves the playhead to bar 7", panel->jumpToLineForSnapshot (4) && std::abs (seek.load() - 6.0 * bar) < 1.0);
  16390. check ("clicking [Chorus] (no position) goes to the marker of that name, bar 13",
  16391. panel->jumpToLineForSnapshot (8) && std::abs (seek.load() - 12.0 * bar) < 1.0);
  16392. check ("a line without a position does not jump", ! panel->jumpToLineForSnapshot (9));
  16393. panel->showForSnapshot ("night", 10.5 * bar);
  16394. shoot (*panel, "lyrics-search");
  16395. // the text travels in the project file, and old readers see it as the Comments they always had
  16396. juce::String error;
  16397. const auto json = lynx::ProjectFile::toJson (offline.getSong());
  16398. const auto back = lynx::ProjectFile::fromJson (json, error);
  16399. check ("lyrics round-trip through .lynx (the Comments field)", back.has_value() && back->info.comments == offline.getSong().info.comments);
  16400. const auto text = lynx::lyrics::exportText (offline.getSong(), lynx::lyrics::Stamps::times);
  16401. juce::File (prefix + "-lyrics-export.txt").replaceWithText (juce::String::fromUTF8 (text.c_str()));
  16402. check ("export as text with times", text.find ("[0:") != std::string::npos);
  16403. panel->showForSnapshot ({}, 6.5 * bar);
  16404. }
  16405. else
  16406. check ("the docked Lyrics panel exists", false);
  16407. {
  16408. const auto names = ui.getMenuNamesForSnapshot();
  16409. const auto view = names.indexOf (lynx::tr ("View"));
  16410. saveMenus (juce::StringArray { lynx::tr ("View") }, std::vector<juce::PopupMenu> { ui.getMenuForSnapshot (juce::jmax (0, view)) }, prefix + "-menu-view.png");
  16411. }
  16412. ui.showDesktopForSnapshot (false);
  16413. check ("the panel stays docked beside the Playlist in the default desktop", ui.isLyricsShowing());
  16414. shoot (ui, "lyrics-desktop");
  16415. // ---- the Simple layout: the Lyrics button in its title tools, the chooser's "Start from" link
  16416. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  16417. offline.dispatchPendingMessages();
  16418. ui.selectTabForSnapshot (2); // (the Playlist alone, as --simpleshot shows the layout)
  16419. auto* simple = ui.getSimpleWorkflowForSnapshot();
  16420. check ("the Simple workflow exists", simple != nullptr);
  16421. if (simple != nullptr)
  16422. {
  16423. simple->hideChooser();
  16424. if (! ui.isLyricsShowing())
  16425. ui.showLyrics (false);
  16426. shoot (ui, "lyrics-simple");
  16427. ui.hideLyrics();
  16428. check ("closing the panel keeps the text", juce::String::fromUTF8 (offline.getSong().info.comments.c_str()).contains ("Night drive, night drive"));
  16429. // ---- 4. Clean voice: on a voice track, from the track's menu
  16430. lynx::simpletracks::Result voice;
  16431. offline.editSongStructural ([&voice] (lynx::Song& s) {
  16432. lynx::simpletracks::Request q;
  16433. q.kind = lynx::simpletracks::Kind::voice;
  16434. q.name = "Lead vocal";
  16435. voice = lynx::simpletracks::addTrack (s, q);
  16436. });
  16437. offline.dispatchPendingMessages();
  16438. check ("a voice track was added", voice.insert > 0);
  16439. if (voice.insert > 0)
  16440. {
  16441. auto menu = ui.getPlaylistForSnapshot().getTrackMenuForSnapshot (voice.track);
  16442. juce::StringArray names { "Track" };
  16443. std::vector<juce::PopupMenu> menus { menu };
  16444. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  16445. if (it.getItem().subMenu != nullptr && it.getItem().text == lynx::tr ("Clean voice"))
  16446. {
  16447. names.add (lynx::tr ("Clean voice"));
  16448. menus.push_back (*it.getItem().subMenu);
  16449. }
  16450. check ("the Simple track menu has Clean voice", menus.size() == 2);
  16451. saveMenus (names, menus, prefix + "-cleanvoice-menu.png");
  16452. const auto before = offline.getSong().mixer[(std::size_t) voice.insert].effects.size();
  16453. check ("Clean voice applies", lynx::ui::applyCleanVoice (offline, voice.insert, false));
  16454. offline.dispatchPendingMessages();
  16455. const auto& fx = offline.getSong().mixer[(std::size_t) voice.insert].effects;
  16456. check ("four slots in front of the track's effects", fx.size() == before + 4 && lynx::cleanvoice::slotsOf (offline.getSong(), voice.insert).size() == 4
  16457. && fx[0].kind == lynx::EffectKind::facetEq);
  16458. check ("with noise reduction: five, none doubled", lynx::ui::applyCleanVoice (offline, voice.insert, true)
  16459. && offline.getSong().mixer[(std::size_t) voice.insert].effects.size() == before + 5);
  16460. offline.dispatchPendingMessages();
  16461. juce::String error;
  16462. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (offline.getSong()), error);
  16463. check ("the chain round-trips through .lynx and is still found", back.has_value() && lynx::cleanvoice::slotsOf (*back, voice.insert).size() == 5
  16464. && back->mixer[(std::size_t) voice.insert].effects == offline.getSong().mixer[(std::size_t) voice.insert].effects);
  16465. saveMenus (juce::StringArray { lynx::tr ("Clean voice") }, std::vector<juce::PopupMenu> { lynx::ui::cleanVoiceMenu (offline, voice.insert) },
  16466. prefix + "-cleanvoice-menu-on.png");
  16467. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
  16468. offline.dispatchPendingMessages();
  16469. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::mixer });
  16470. ui.selectMixerTrackForSnapshot (voice.insert);
  16471. shoot (ui, "cleanvoice-mixer");
  16472. offline.undo(); // the second chain
  16473. offline.dispatchPendingMessages();
  16474. check ("undo brings the first chain back", lynx::cleanvoice::slotsOf (offline.getSong(), voice.insert).size() == 4);
  16475. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  16476. offline.dispatchPendingMessages();
  16477. ui.selectTabForSnapshot (2); // (the Playlist alone, as --simpleshot shows the layout)
  16478. simple = ui.getSimpleWorkflowForSnapshot();
  16479. }
  16480. }
  16481. // ---- 2. Reference match: the song's Master render against a file (pink noise with more top, at about -14 LUFS)
  16482. {
  16483. const auto file = juce::File (prefix + "-reference.wav");
  16484. file.deleteFile();
  16485. const auto rate = 44100.0;
  16486. const auto frames = (int) (20.0 * rate);
  16487. juce::AudioBuffer<float> audio (2, frames);
  16488. juce::Random random (190);
  16489. for (int ch = 0; ch < 2; ++ch)
  16490. {
  16491. double b0 = 0, b1 = 0, b2 = 0, hp = 0;
  16492. for (int i = 0; i < frames; ++i)
  16493. {
  16494. const auto w = (double) random.nextFloat() * 2.0 - 1.0;
  16495. b0 = 0.99765 * b0 + w * 0.0990460;
  16496. b1 = 0.96300 * b1 + w * 0.2965164;
  16497. b2 = 0.57000 * b2 + w * 1.0526913;
  16498. const auto pink = (b0 + b1 + b2 + w * 0.1848) * 0.071; // (about -14 LUFS: a streaming master)
  16499. hp += 0.25 * (pink - hp); // a little more top than pink noise has
  16500. audio.setSample (ch, i, (float) (pink + 0.35 * (pink - hp)));
  16501. }
  16502. }
  16503. if (auto out = file.createOutputStream())
  16504. if (auto writer = std::unique_ptr<juce::AudioFormatWriter> (juce::WavAudioFormat().createWriterFor (out.get(), rate, 2, 24, {}, 0)))
  16505. {
  16506. out.release();
  16507. writer->writeFromAudioSampleBuffer (audio, 0, frames);
  16508. }
  16509. note ("measure reference");
  16510. const auto reference = lynx::ReferenceMatchPanel::measureFile (offline, file);
  16511. note ("measure song");
  16512. const auto song = lynx::ReferenceMatchPanel::measureSong (offline.getSong(), false);
  16513. check ("the reference file was measured", reference.valid);
  16514. check ("the song's Master render was measured", song.valid);
  16515. lynx::ReferenceMatchPanel panel (offline, {});
  16516. panel.setSize (lynx::ReferenceMatchPanel::defaultWidth, lynx::ReferenceMatchPanel::defaultHeight);
  16517. panel.showForSnapshot ("Reference.wav", song, reference, nullptr);
  16518. shoot (panel, "refmatch-measured");
  16519. const auto masterBefore = offline.getSong().mixer[0].effects.size();
  16520. check ("Match adds its two slots at the end of the Master", panel.matchForSnapshot() && offline.getSong().mixer[0].effects.size() == masterBefore + 2);
  16521. offline.dispatchPendingMessages();
  16522. const auto first = lynx::ReferenceMatchPanel::measureSong (offline.getSong(), true);
  16523. panel.showForSnapshot ("Reference.wav", song, reference, &first);
  16524. panel.refresh();
  16525. shoot (panel, "refmatch-matched");
  16526. report << " first Match: " << juce::String (first.lufs, 2) << " LUFS, " << juce::String (first.truePeakDb, 2) << " dBTP, EQ output "
  16527. << juce::String (lynx::facet::outputDb (offline.getSong().mixer[0].effects[masterBefore].params[(std::size_t) lynx::facet::outputParam]), 2) << " dB\n";
  16528. // a result more than 0.5 LU from the reference (a limiter that has to hold peaks back): Match again takes
  16529. // what is missing, as the window's note says
  16530. auto after = first;
  16531. const auto secondPass = std::abs (first.lufs - reference.lufs) > 0.5;
  16532. if (secondPass)
  16533. {
  16534. check ("Match again replaces the two slots (level corrected)", panel.matchForSnapshot() && offline.getSong().mixer[0].effects.size() == masterBefore + 2);
  16535. offline.dispatchPendingMessages();
  16536. after = lynx::ReferenceMatchPanel::measureSong (offline.getSong(), true);
  16537. panel.showForSnapshot ("Reference.wav", song, reference, &after);
  16538. panel.refresh();
  16539. shoot (panel, "refmatch-matched-again");
  16540. }
  16541. report << " " << (secondPass ? "a second Match was needed for the level" : "one Match was enough for the level") << "\n";
  16542. const auto& s = panel.suggestionForSnapshot();
  16543. report << " song " << juce::String (song.lufs, 2) << " LUFS, " << juce::String (song.truePeakDb, 2) << " dBTP, width " << juce::String (song.widthPercent(), 1)
  16544. << " % | reference " << juce::String (reference.lufs, 2) << " LUFS, " << juce::String (reference.truePeakDb, 2) << " dBTP, width "
  16545. << juce::String (reference.widthPercent(), 1) << " % | after " << juce::String (after.lufs, 2) << " LUFS, " << juce::String (after.truePeakDb, 2)
  16546. << " dBTP\n next suggestion: gain " << juce::String (s.gainDb, 2) << " dB, EQ fit error " << juce::String (s.fitErrorDb, 2) << " dB\n";
  16547. double before = 0.0, now = 0.0;
  16548. int counted = 0;
  16549. {
  16550. // tone only (each curve around its own mean), over the bands both hold
  16551. double ms = 0, mr = 0, ma = 0;
  16552. const auto used = juce::jmin (song.usedBands, reference.usedBands);
  16553. for (int k = 0; k < used; ++k)
  16554. ms += song.spectrumDb[(std::size_t) k], mr += reference.spectrumDb[(std::size_t) k], ma += after.spectrumDb[(std::size_t) k];
  16555. for (int k = 2; k < used; ++k, ++counted)
  16556. {
  16557. before += std::abs ((song.spectrumDb[(std::size_t) k] - ms / used) - (reference.spectrumDb[(std::size_t) k] - mr / used));
  16558. now += std::abs ((after.spectrumDb[(std::size_t) k] - ma / used) - (reference.spectrumDb[(std::size_t) k] - mr / used));
  16559. }
  16560. }
  16561. report << " mean tone difference to the reference: " << juce::String (before / juce::jmax (1, counted), 2) << " dB before, "
  16562. << juce::String (now / juce::jmax (1, counted), 2) << " dB after one Match (each band moves 6 dB at most)\n";
  16563. check ("after Match the tone is closer to the reference", after.valid && now < before);
  16564. check ("after Match the loudness is within 1 LU of the reference", std::abs (after.lufs - reference.lufs) < 1.0);
  16565. 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);
  16566. juce::String error;
  16567. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (offline.getSong()), error);
  16568. check ("the match round-trips through .lynx as two ordinary Master slots", back.has_value() && lynx::refmatch::present (*back)
  16569. && back->mixer[0].effects == offline.getSong().mixer[0].effects);
  16570. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
  16571. offline.dispatchPendingMessages();
  16572. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::mixer });
  16573. ui.selectMixerTrackForSnapshot (0);
  16574. shoot (ui, "refmatch-mixer");
  16575. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  16576. offline.dispatchPendingMessages();
  16577. ui.selectTabForSnapshot (2); // (the Playlist alone, as --simpleshot shows the layout)
  16578. simple = ui.getSimpleWorkflowForSnapshot();
  16579. if (simple != nullptr)
  16580. {
  16581. simple->hideChooser();
  16582. simple->showFinish();
  16583. shoot (ui, "finish-dock"); // "Match a reference track..." under the saving buttons
  16584. simple->hideFinish();
  16585. }
  16586. file.deleteFile();
  16587. }
  16588. // ---- 3. Start from: the chooser's link, the list, and opening an entry
  16589. if (simple != nullptr)
  16590. {
  16591. simple->showChooser();
  16592. shoot (ui, "chooser");
  16593. simple->hideChooser();
  16594. auto* panel = dynamic_cast<lynx::StartFromPanel*> (simple->startFromForSnapshot());
  16595. check ("the Start from list opens", panel != nullptr && simple->isStartFromShowing());
  16596. if (panel != nullptr)
  16597. {
  16598. shoot (ui, "startfrom");
  16599. auto list = lynx::startfrom::entries();
  16600. check ("it lists the demo song and the templates shipped", list.size() >= 3 && list[0].kind == lynx::startfrom::Entry::Kind::demo
  16601. && (int) list.size() == panel->entryCountForSnapshot());
  16602. for (auto& e : list)
  16603. report << " " << e.name << " | " << juce::String (e.bpm, 0) << " BPM, " << e.channels << " channels, " << e.bars << " bars"
  16604. << (e.playable ? ", preview" : "") << "\n";
  16605. if (const auto demo = lynx::startfrom::songOf (list[0]))
  16606. {
  16607. const auto wav = juce::File (prefix + "-preview.wav");
  16608. const auto ok = lynx::startfrom::renderPreview (*demo, wav);
  16609. check ("the demo's preview renders (" + juce::String (wav.getSize() / 1024) + " kB)", ok && wav.getSize() > 100000);
  16610. wav.deleteFile();
  16611. }
  16612. panel->selectForSnapshot (juce::jmin (2, panel->entryCountForSnapshot() - 1));
  16613. shoot (ui, "startfrom-selected");
  16614. offline.markSaved(); // (a project with changes asks first: Save / Don't save / Cancel)
  16615. const auto opened = panel->openForSnapshot (0);
  16616. offline.dispatchPendingMessages();
  16617. check ("opening the demo starts a new project from it and closes the list",
  16618. opened && ! simple->isStartFromShowing() && offline.getSong().info.comments.empty() && ! offline.getSong().channels.empty());
  16619. shoot (ui, "startfrom-opened");
  16620. }
  16621. }
  16622. juce::File (prefix + "-report.txt").replaceWithText (report);
  16623. }
  16624. void runVersionsShot (const juce::String& prefix)
  16625. {
  16626. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  16627. const auto shoot = [&prefix] (juce::Component& c, const char* name) {
  16628. savePng (lynx::shot::snapshot (c), prefix + "-" + name + ".png");
  16629. };
  16630. // ---- the Versions panel, on files in a temporary folder
  16631. const auto root = juce::File::getSpecialLocation (juce::File::tempDirectory)
  16632. .getChildFile ("lynx-versionsshot-" + juce::String::toHexString (juce::Random::getSystemRandom().nextInt64()));
  16633. const juce::ScopeGuard cleanUp { [&root] { root.deleteRecursively(); } };
  16634. const auto project = root.getChildFile ("Night Drive"), backup = root.getChildFile ("Backup");
  16635. project.createDirectory();
  16636. backup.createDirectory();
  16637. const auto now = juce::Time::getCurrentTime();
  16638. const auto put = [&now] (const juce::File& folder, const juce::String& name, const char* kind, int kilobytes, double hoursAgo) {
  16639. const auto time = now - juce::RelativeTime::hours (hoursAgo);
  16640. const auto file = folder.getChildFile (kind == nullptr ? name + ".lynx" : name + " (" + kind + " on " + time.formatted ("%Y-%m-%d at %Hh%M") + ").lynx");
  16641. juce::MemoryBlock data ((size_t) kilobytes * 1024, true);
  16642. file.replaceWithData (data.getData(), data.getSize());
  16643. file.setLastModificationTime (time);
  16644. };
  16645. put (project, "Night Drive", nullptr, 412, 26.0 * 24.0);
  16646. put (project, "Night Drive_2", nullptr, 688, 9.0 * 24.0);
  16647. put (project, "Night Drive_3", nullptr, 731, 2.0 * 24.0);
  16648. put (project, "Night Drive_4", nullptr, 905, 1.6);
  16649. put (backup, "Night Drive_4", "autosaved", 907, 0.07);
  16650. put (backup, "Night Drive_4", "autosaved", 906, 0.4);
  16651. put (backup, "Night Drive_4", "overwritten", 890, 1.6);
  16652. put (backup, "Night Drive_4", "autosaved", 884, 3.2);
  16653. put (backup, "Night Drive_3", "overwritten", 720, 2.0 * 24.0);
  16654. put (backup, "Night Drive_2", "autosaved", 690, 8.0 * 24.0);
  16655. const lynx::VersionsContext context { project.getChildFile ("Night Drive_4.lynx"), "Night Drive_4", backup, ".lynx" };
  16656. {
  16657. const auto entries = lynx::versionEntries (context);
  16658. const auto label = [&] (const juce::String& startsWith, const char* text) {
  16659. for (const auto& e : entries)
  16660. if (juce::String::fromUTF8 (e.name.c_str()).startsWith (startsWith))
  16661. {
  16662. lynx::setVersionLabel (context, e, text);
  16663. return;
  16664. }
  16665. };
  16666. label ("Night Drive_2", "first full arrangement");
  16667. label ("Night Drive_3", "sent to the singer");
  16668. label ("Night Drive_4 (autosaved", "new bass line");
  16669. }
  16670. {
  16671. lynx::VersionsActions actions;
  16672. actions.context = [context] { return context; };
  16673. auto panel = lynx::makeVersionsPanel (actions);
  16674. shoot (*panel, "versions");
  16675. lynx::VersionsActions fresh;
  16676. fresh.context = [backup] { return lynx::VersionsContext { juce::File(), "Untitled", backup, ".lynx" }; };
  16677. auto empty = lynx::makeVersionsPanel (fresh);
  16678. shoot (*empty, "versions-unsaved");
  16679. }
  16680. // ---- the window
  16681. lynx::AudioEngine offline (false);
  16682. lynx::MainComponent ui (offline, false);
  16683. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  16684. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  16685. const auto saveFileMenu = [&] (const char* name) {
  16686. const auto index = juce::jmax (0, ui.getMenuNamesForSnapshot().indexOf (lynx::tr ("File")));
  16687. saveMenus (juce::StringArray { lynx::tr ("File") }, std::vector<juce::PopupMenu> { ui.getMenuForSnapshot (index) }, prefix + "-" + name + ".png");
  16688. };
  16689. saveFileMenu ("menu-file");
  16690. // ---- a project opened without its third-party plugins (the plugins are not installed: nothing foreign runs)
  16691. {
  16692. const auto ref = [] (const char* id, const char* name) {
  16693. lynx::PluginRef r;
  16694. r.id = id;
  16695. r.name = name;
  16696. r.state = "c2V0dGluZ3M=";
  16697. return r;
  16698. };
  16699. auto song = lynx::Song::makeDefault();
  16700. while (song.channels.size() < 4)
  16701. song.channels.push_back (song.channels.front());
  16702. while (song.mixer.size() < 5)
  16703. song.mixer.push_back (song.mixer.back());
  16704. const char* names[] = { "Lead", "Pad" };
  16705. for (int c = 0; c < 2; ++c)
  16706. {
  16707. auto& channel = song.channels[(std::size_t) (c + 2)];
  16708. channel.instrument = lynx::InstrumentKind::plugin;
  16709. channel.plugin = ref ("VST3-ShotSynth-11111111-aaaaaaaa", "Shot Synth");
  16710. channel.name = names[c];
  16711. channel.mixerTrack = c + 1;
  16712. }
  16713. lynx::EffectSlot fx;
  16714. fx.kind = lynx::EffectKind::plugin;
  16715. fx.plugin = ref ("VST3-ShotVerb-22222222-bbbbbbbb", "Shot Verb");
  16716. song.mixer[1].effects.push_back (fx);
  16717. fx.plugin = ref ("VST3-ShotComp-33333333-cccccccc", "Shot Comp");
  16718. song.mixer[2].effects.push_back (fx);
  16719. song.mixer[0].effects.push_back (fx);
  16720. offline.setSongWithPluginsOff (std::move (song));
  16721. ui.showDesktopForSnapshot (false);
  16722. shoot (ui, "pluginsoff-window");
  16723. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::channelRack, lynx::workspace::Panel::mixer });
  16724. shoot (ui, "pluginsoff-mixer"); // (the rack's and the mixer's "off" tags together)
  16725. saveFileMenu ("menu-file-pluginsoff");
  16726. auto panel = lynx::makePluginsOffPanel (offline);
  16727. shoot (*panel, "pluginsoff-panel");
  16728. offline.switchPluginOn ("VST3-ShotVerb-22222222-bbbbbbbb"); // (not installed: "Did not load")
  16729. auto after = lynx::makePluginsOffPanel (offline);
  16730. shoot (*after, "pluginsoff-panel-one");
  16731. }
  16732. // ---- the Export window: as it opens, and with a preset chosen, sections on and a last export to repeat
  16733. {
  16734. auto song = lynx::Song::makeDefault();
  16735. const auto bar = song.barTicks();
  16736. song.mode = lynx::PlayMode::song;
  16737. song.playlist.clear();
  16738. lynx::Clip clip;
  16739. clip.length = 32 * bar;
  16740. song.playlist.push_back (clip);
  16741. const char* sections[] = { "Intro", "Verse", "Chorus", "Outro" };
  16742. for (int i = 0; i < 4; ++i)
  16743. {
  16744. lynx::Marker m;
  16745. m.tick = i * 8 * bar;
  16746. m.name = sections[i];
  16747. song.addMarker (m);
  16748. }
  16749. offline.setSong (std::move (song)); // (also ends the plugins-off mode)
  16750. auto plain = lynx::makeExportPanel (offline, 0);
  16751. shoot (*plain, "export-default");
  16752. auto additions = lynx::makeExportPanelWithAdditions (offline);
  16753. shoot (*additions, "export");
  16754. }
  16755. }
  16756. void runGamepadShot (const juce::String& prefix)
  16757. {
  16758. juce::String report;
  16759. int failures = 0;
  16760. {
  16761. lynx::AudioEngine engine (false);
  16762. auto hints = lynx::makeGamepadHints();
  16763. savePng (lynx::shot::snapshot (*hints), prefix + "-hints.png");
  16764. auto prefs = engine.getMidiPrefs();
  16765. prefs.gamepad = true;
  16766. engine.setMidiPrefs (prefs, false);
  16767. auto page = lynx::makeMidiPage (engine, {}, false);
  16768. page->setSize (760, 1400);
  16769. savePng (lynx::shot::snapshot (*page), prefix + "-settings.png");
  16770. // the poller with fake states: what the handler gets
  16771. using namespace lynx::gamepad;
  16772. std::vector<std::string> got;
  16773. lynx::GamepadInput input ([&got] (const Changes& c, const State&, double dt) {
  16774. for (int i = 0; i < c.pressedCount; ++i)
  16775. got.push_back (std::string ("press ") + buttonName (c.pressed[(std::size_t) i]));
  16776. for (int i = 0; i < c.releasedCount; ++i)
  16777. got.push_back (std::string ("release ") + buttonName (c.released[(std::size_t) i]));
  16778. for (int i = 0; i < c.controllerCount; ++i)
  16779. got.push_back ("cc " + std::to_string (c.controller[(std::size_t) i]) + "=" + std::to_string (c.value[(std::size_t) i]));
  16780. if (c.connectedChanged)
  16781. got.push_back ("connected changed");
  16782. got.push_back ("dt " + std::to_string ((int) std::lround (dt * 1000)));
  16783. });
  16784. State pad;
  16785. pad.connected = true;
  16786. input.inject (pad, 1.0 / 60.0);
  16787. pad.buttons = mask (Button::a);
  16788. pad.rightTrigger = 255;
  16789. input.inject (pad, 1.0 / 60.0);
  16790. pad.buttons = 0;
  16791. input.inject (pad, 1.0 / 60.0);
  16792. const std::vector<std::string> expected { "connected changed", "dt 17", "press A", "cc 102=127", "cc 21=127", "dt 17",
  16793. "release A", "cc 102=0", "dt 17" };
  16794. for (const auto& line : got)
  16795. report << line << "\n";
  16796. if (got != expected)
  16797. {
  16798. ++failures;
  16799. report << "FAILED: the poller's changes differ from the expected ones\n";
  16800. }
  16801. report << "xinput " << (input.available() ? "loaded" : "not available") << "\n";
  16802. }
  16803. report << (failures == 0 ? "gamepad OK" : "gamepad FAILED") << "\n";
  16804. juce::File (prefix + "-gamepad.txt").replaceWithText (report);
  16805. setApplicationReturnValue (failures == 0 ? 0 : 1);
  16806. quit();
  16807. }
  16808. void runBundleExport (const juce::String& inputPath, const juce::String& folderPath, bool zip, bool mixdown, const juce::String& shotPrefix)
  16809. {
  16810. juce::String error;
  16811. bool ok = false;
  16812. lynx::otherapps::Result result;
  16813. {
  16814. lynx::AudioEngine loader (false);
  16815. const juce::File input (inputPath);
  16816. if (input.hasFileExtension ("flp;als"))
  16817. ok = loader.importFlpFile (input, error);
  16818. else if (auto song = lynx::ProjectFile::load (input, error))
  16819. {
  16820. loader.setSong (std::move (*song));
  16821. ok = true;
  16822. }
  16823. if (ok)
  16824. {
  16825. loader.capturePluginStates();
  16826. lynx::otherapps::Context context;
  16827. context.host = &loader.getPluginHost();
  16828. context.flOptions = lynx::flstudio::optionsFor (context.host, lynx::flpexport::LynxOnly::renderAudio, loader.getSong());
  16829. context.render = [] (const lynx::Song& s, const lynx::exportopts::Options& o, const juce::File& file,
  16830. const std::function<bool (double)>& progress, juce::String& err) {
  16831. lynx::ExportJob job (s, o, file);
  16832. return job.run (progress, err);
  16833. };
  16834. context.onMessageThread = [] (std::function<void()> f) { f(); };
  16835. lynx::exportbundle::Options options;
  16836. options.zip = zip;
  16837. options.mixdown = mixdown;
  16838. const auto name = input.getFileNameWithoutExtension();
  16839. const auto shot = [&shotPrefix] (juce::Component& c, const juce::String& suffix) {
  16840. if (shotPrefix.isNotEmpty())
  16841. savePng (lynx::shot::snapshot (c), shotPrefix + suffix);
  16842. };
  16843. if (auto panel = lynx::makeOtherAppsExportPanel (loader, name))
  16844. shot (*panel, "-panel.png");
  16845. ok = lynx::otherapps::write (loader.getSong(), name, options, juce::File (folderPath), context, result);
  16846. if (auto report = lynx::makeOtherAppsReportPanel (result.folder, result.written, result.failed))
  16847. shot (*report, "-report.png");
  16848. }
  16849. }
  16850. juce::String report;
  16851. report << (ok ? "ok " + result.folder.getFullPathName() : "error=" + error) << "\n";
  16852. for (const auto& w : result.written)
  16853. report << "written " << w << "\n";
  16854. for (const auto& f : result.failed)
  16855. report << "failed " << f << "\n";
  16856. juce::File (folderPath).getChildFile ("export-bundle.txt").replaceWithText (report);
  16857. setApplicationReturnValue (ok && result.failed.isEmpty() ? 0 : 1);
  16858. quit();
  16859. }
  16860. void runFlExport (const juce::String& inputPath, const juce::String& outputPath, bool substitute)
  16861. {
  16862. juce::String error;
  16863. bool ok = false;
  16864. lynx::flstudio::Written written;
  16865. {
  16866. lynx::AudioEngine loader (false);
  16867. const juce::File input (inputPath);
  16868. // a Live set opens through the same import as an .flp (as File › Open does, and --export-als accepts an .flp)
  16869. if (input.hasFileExtension ("flp;als"))
  16870. ok = loader.importFlpFile (input, error);
  16871. else if (auto song = lynx::ProjectFile::load (input, error))
  16872. {
  16873. loader.setSong (std::move (*song));
  16874. ok = true;
  16875. }
  16876. if (ok)
  16877. {
  16878. const juce::File output (outputPath);
  16879. const auto zip = output.hasFileExtension ("zip");
  16880. const auto mode = substitute ? lynx::flpexport::LynxOnly::substitute : lynx::flpexport::LynxOnly::renderAudio;
  16881. loader.capturePluginStates();
  16882. auto options = lynx::flstudio::optionsFor (&loader.getPluginHost(), mode, loader.getSong());
  16883. // --flp-ppq N: the file's PPQ (tests; default: 96 when the notes and clips fit it)
  16884. if (const auto args = juce::JUCEApplication::getCommandLineParameterArray(); args.contains ("--flp-ppq"))
  16885. options.ppq = juce::jlimit (0, 960, args[args.indexOf ("--flp-ppq") + 1].getIntValue());
  16886. const auto renderDir = zip ? juce::File::getSpecialLocation (juce::File::tempDirectory).getNonexistentChildFile ("LYNX FL export", {}, false)
  16887. : output.getSiblingFile (output.getFileNameWithoutExtension() + " audio");
  16888. ok = lynx::flstudio::exportProject (loader.getSong(), options, output, zip, renderDir, 44100.0,
  16889. [] (const lynx::Song& s, const lynx::ExportSettings& settings, const juce::File& wav,
  16890. const std::function<bool (double)>& progress, juce::String& err) {
  16891. lynx::ExportJob job (s, settings, wav);
  16892. return job.run (progress, err);
  16893. },
  16894. {}, written, error);
  16895. if (zip)
  16896. renderDir.deleteRecursively();
  16897. }
  16898. }
  16899. juce::String report;
  16900. report << (ok ? "ok" : "error=" + error) << "\n"
  16901. << "exact=" << (int) written.report.exact.size() << " rendered=" << (int) written.report.rendered.size()
  16902. << " substituted=" << (int) written.report.substituted.size() << " dropped=" << (int) written.report.dropped.size()
  16903. << " samples=" << written.samples << "\n\n"
  16904. << lynx::flstudio::reportText (written) << "\n";
  16905. juce::File (outputPath + ".txt").replaceWithText (report);
  16906. setApplicationReturnValue (ok ? 0 : 1);
  16907. quit();
  16908. }
  16909. // LYNX.exe --export project.(flp|als|lynx) output.(wav|flac|ogg|mp3) [--pattern] [--insert N] [--rate N]
  16910. // Same path as "Export" in the UI: the whole song (or the current pattern) with its tail.
  16911. void runExport (const juce::String& inputPath, const juce::String& outputPath, bool patternOnly, int insert)
  16912. {
  16913. juce::String error, report;
  16914. bool ok = false;
  16915. const auto started = juce::Time::getMillisecondCounterHiRes();
  16916. lynx::loadtrace::begin (inputPath.toStdString()); // phase times (round 112): report lines + load.log
  16917. {
  16918. lynx::AudioEngine loader (false);
  16919. const juce::File input (inputPath);
  16920. // --find-plugins: first the targeted scan opening the project in the app runs (its plugins not known yet)
  16921. if (input.hasFileExtension ("flp") && juce::JUCEApplication::getCommandLineParameters().contains ("--find-plugins"))
  16922. {
  16923. juce::MemoryBlock data;
  16924. if (input.loadFileAsData (data))
  16925. try
  16926. {
  16927. const auto uses = lynx::flpForeignPlugins (flp::parseProject ({ static_cast<const std::uint8_t*> (data.getData()), data.getSize() }));
  16928. auto& host = loader.getPluginHost();
  16929. const auto listed = std::chrono::steady_clock::now();
  16930. const auto files = host.filesToScanFor (uses);
  16931. lynx::loadtrace::add ("plugin_scan_list", lynx::loadtrace::msSince (listed));
  16932. report << "scanned=" << files.joinIntoString (";") << "\n";
  16933. const auto scanned = std::chrono::steady_clock::now();
  16934. host.scanFiles (files, {});
  16935. lynx::loadtrace::add ("plugin_scan", lynx::loadtrace::msSince (scanned), files.size());
  16936. }
  16937. catch (const flp::Error&)
  16938. {
  16939. }
  16940. }
  16941. if (input.hasFileExtension ("flp;als")) // a Live set opens through the same import (round 182b)
  16942. ok = loader.importFlpFile (input, error);
  16943. else if (auto song = lynx::ProjectFile::load (input, error))
  16944. {
  16945. loader.setSong (std::move (*song));
  16946. ok = true;
  16947. }
  16948. if (ok)
  16949. {
  16950. const juce::File output (outputPath);
  16951. lynx::ExportSettings settings;
  16952. settings.wholeSong = ! patternOnly;
  16953. settings.format = output.hasFileExtension ("flac") ? lynx::ExportSettings::Format::flac24
  16954. : output.hasFileExtension ("ogg") ? lynx::ExportSettings::Format::ogg
  16955. : lynx::ExportSettings::Format::wav24;
  16956. // --insert N: only that insert's output (what "Render to audio" records)
  16957. if (juce::JUCEApplication::getCommandLineParameters().contains ("--no-effects")
  16958. || juce::JUCEApplication::getCommandLineParameters().contains ("--sem-efeitos")) // performance diagnostics; --sem-efeitos: legacy alias
  16959. loader.editSong ([] (lynx::Song& s) {
  16960. for (auto& t : s.mixer)
  16961. t.effects.clear();
  16962. }, false);
  16963. if (juce::JUCEApplication::getCommandLineParameters().contains ("--no-automation")
  16964. || juce::JUCEApplication::getCommandLineParameters().contains ("--sem-automacao")) // --sem-automacao: legacy alias
  16965. loader.editSong ([] (lynx::Song& s) { s.automations.clear(); }, false);
  16966. const auto loaded = juce::Time::getMillisecondCounterHiRes();
  16967. // .mp3: the Export window's MP3 (320 kbps); everything else as before
  16968. auto options = settings.toOptions();
  16969. // --save-tempo: FL's "Tempo information" (acid chunk) on (round 167l: compare with FL's AcidBox render; --export)
  16970. if (juce::JUCEApplication::getCommandLineParameters().contains ("--save-tempo"))
  16971. options.saveTempo = true;
  16972. // --no-warmup: the export's plugin warm-up off (round 155: compare the start of the file)
  16973. if (juce::JUCEApplication::getCommandLineParameters().contains ("--no-warmup"))
  16974. options.pluginWarmUp = false;
  16975. // --rate N: render at another sample rate (round 157b: samples resampled as at a 48 kHz device)
  16976. if (const auto args = juce::JUCEApplication::getCommandLineParameterArray(); args.contains ("--rate"))
  16977. if (const auto rate = args[args.indexOf ("--rate") + 1].getDoubleValue(); rate >= 8000.0 && rate <= 384000.0)
  16978. options.sampleRate = rate;
  16979. if (output.hasFileExtension ("mp3"))
  16980. {
  16981. options.format = lynx::exportopts::Format::mp3;
  16982. options.mp3Kbps = 320;
  16983. }
  16984. lynx::ExportJob job (insert > 0 ? lynx::makeBounceSong (loader.getSong(), insert) : loader.getSong(), options, output);
  16985. job.setExtraData (true);
  16986. const auto prepared = juce::Time::getMillisecondCounterHiRes();
  16987. lynx::loadtrace::end();
  16988. int lastPercent = -1;
  16989. ok = job.run ([&lastPercent] (double p) {
  16990. lastPercent = (int) (p * 100.0);
  16991. return true;
  16992. }, error);
  16993. auto joined = [] (const std::map<std::string, int>& items) {
  16994. juce::StringArray names;
  16995. for (const auto& [name, count] : items)
  16996. names.add (juce::String::fromUTF8 (name.c_str()) + "x" + juce::String (count));
  16997. return names.joinIntoString (", ");
  16998. };
  16999. const auto& importReport = loader.getImportReport();
  17000. report << "converted=" << joined (importReport.converted) << "\n"
  17001. << "approximated=" << joined (importReport.approximated) << "\n"
  17002. << "unsupported=" << joined (importReport.unsupported) << "\n"
  17003. << "dropped_effects=" << joined (importReport.droppedEffects) << "\n"
  17004. << "partial_effects=" << joined (importReport.partialEffects) << "\n"
  17005. << "missing_samples=" << importReport.missingSamples << "\n";
  17006. // third-party plugins: how each was found, or what plays in its place (diagnostics for level differences)
  17007. for (const auto& line : loader.getMatchedPlugins())
  17008. report << "plugin_found=" << line << "\n";
  17009. for (const auto& m : loader.getMissingPluginDetails())
  17010. report << "plugin_missing=" << juce::String::fromUTF8 (m.name.c_str()) << " -> "
  17011. << juce::String::fromUTF8 (m.replacement.c_str()).replace ("{0}", juce::String::fromUTF8 (m.replacementArg.c_str())) << "\n";
  17012. {
  17013. const auto& song = loader.getSong();
  17014. for (std::size_t t = 0; t < song.mixer.size(); ++t)
  17015. {
  17016. const auto& track = song.mixer[t];
  17017. if (track.effects.empty() && track.sends.empty())
  17018. continue;
  17019. report << "insert " << (int) t << " vol=" << juce::String (track.volume / lynx::unityFader, 3)
  17020. << (track.muted ? " muted" : "") << (track.toMaster ? "" : " noMaster");
  17021. for (const auto& s : track.sends)
  17022. report << " send>" << s.target << "@" << juce::String (s.level, 3);
  17023. report << " |";
  17024. for (const auto& fx : track.effects)
  17025. report << " [" << (fx.kind == lynx::EffectKind::plugin ? juce::String::fromUTF8 (fx.plugin.name.c_str())
  17026. : juce::String::fromUTF8 (lynx::effectInfo (fx.kind).name))
  17027. << (fx.isSubstitute() ? " (substitute)" : "") << (fx.enabled ? "" : " off")
  17028. << (fx.mix < 0.999f ? " mix=" + juce::String (fx.mix, 2) : juce::String()) << "]";
  17029. report << "\n";
  17030. }
  17031. }
  17032. report << juce::String (lynx::loadtrace::reportLines());
  17033. lynx::PluginHost::settingsFolder().getChildFile ("load.log").replaceWithText (juce::String (lynx::loadtrace::table()));
  17034. report << "open_ms=" << juce::roundToInt (loaded - started) << "\n"
  17035. << "prepare_ms=" << juce::roundToInt (prepared - loaded) << "\n"
  17036. << "render_ms=" << juce::roundToInt (juce::Time::getMillisecondCounterHiRes() - prepared) << "\n"
  17037. << "graph_ms=" << juce::roundToInt (job.getEngine().getLastRenderStats().graphMs) << "\n"
  17038. << "write_ms=" << juce::roundToInt (job.getEngine().getLastRenderStats().writeMs) << "\n"
  17039. << "warmup_blocks=" << job.getEngine().getLastRenderStats().warmUp.blocks << "\n"
  17040. << "warmup_ms=" << juce::roundToInt (job.getEngine().getLastRenderStats().warmUp.wallSeconds * 1000.0) << "\n"
  17041. << "warmup_changes=" << job.getEngine().getLastRenderStats().warmUp.signatureChanges << "\n"
  17042. << "warmup_timed_out=" << (job.getEngine().getLastRenderStats().warmUp.timedOut ? 1 : 0) << "\n"
  17043. << "pdc_trim=" << job.getEngine().getLastRenderStats().trimmedSamples << "\n"
  17044. << "song_seconds=" << job.getMusicSeconds() << "\n"
  17045. << "peak=" << job.getPeak() << "\n"
  17046. << "final_progress=" << lastPercent << "\n"
  17047. << "bytes=" << output.getSize() << "\n";
  17048. ok = ok && job.getPeak() > 0.001f;
  17049. }
  17050. }
  17051. report << "result=" << (ok ? "OK" : "ERROR " + error) << "\n";
  17052. juce::File (outputPath + ".txt").replaceWithText (report);
  17053. setApplicationReturnValue (ok ? 0 : 1);
  17054. quit();
  17055. }
  17056. // LYNX.exe --snapshot prefix [project]: draws the window off-screen and writes
  17057. // prefix-rack.png, -pianoroll.png and -playlist.png (to check the UI without touching the screen).
  17058. // --editorcpu: one editor after another; each phase runs 2 s to settle and 8 s measured
  17059. struct EditorCpuRun final : juce::Timer
  17060. {
  17061. struct Case { lynx::EffectKind kind; const char* name; int type; bool demo; }; // type 0 native, 1 display-first, 2 Facet EQ
  17062. std::vector<Case> cases;
  17063. std::size_t at = 0;
  17064. int phase = 0;
  17065. double t0 = 0.0, c0 = 0.0;
  17066. juce::String report;
  17067. juce::File out;
  17068. std::unique_ptr<lynx::AudioEngine> engine;
  17069. std::unique_ptr<juce::DocumentWindow> window;
  17070. std::function<void()> done;
  17071. void start()
  17072. {
  17073. engine = std::make_unique<lynx::AudioEngine> (false);
  17074. report << "editor\tmode\tcpu % of one core\n";
  17075. open();
  17076. startTimer (250);
  17077. }
  17078. void open()
  17079. {
  17080. window.reset();
  17081. if (at >= cases.size()) { out.replaceWithText (report); stopTimer(); if (done) done(); return; }
  17082. const auto& c = cases[at];
  17083. lynx::Song song;
  17084. song.mixer.resize (2);
  17085. song.mixer[0].name = "Master";
  17086. song.mixer[1].name = "Insert 1";
  17087. song.mixer[1].effects.push_back (lynx::makeEffectSlot (c.kind));
  17088. engine->setSong (std::move (song));
  17089. engine->dispatchPendingMessages();
  17090. lynx::setNativeEditorDemo (c.demo);
  17091. auto editor = c.type == 1 ? lynx::makeProEditor (*engine, 1, 0, c.demo) : c.type == 2 ? lynx::makeFacetEqEditor (*engine, 1, 0, c.demo)
  17092. : lynx::makeNativeEffectEditor (*engine, 1, 0, 1.0f, 0);
  17093. window = std::make_unique<juce::DocumentWindow> (juce::String ("LYNX editor CPU - ") + c.name, lynx::theme::colour::bg1, 0);
  17094. window->setUsingNativeTitleBar (true);
  17095. window->setContentOwned (editor.release(), true);
  17096. const auto area = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea;
  17097. window->setTopLeftPosition (area.getRight() - window->getWidth() - 8, area.getBottom() - window->getHeight() - 8);
  17098. window->setVisible (true);
  17099. phase = 0;
  17100. t0 = juce::Time::getMillisecondCounterHiRes();
  17101. }
  17102. void timerCallback() override
  17103. {
  17104. const auto now = juce::Time::getMillisecondCounterHiRes();
  17105. if (phase == 0 && now - t0 > 2000.0) { phase = 1; t0 = now; c0 = lynx::processCpuSeconds(); return; }
  17106. if (phase == 1 && now - t0 > 8000.0)
  17107. {
  17108. const auto cpu = (lynx::processCpuSeconds() - c0) / ((now - t0) * 0.001) * 100.0;
  17109. const auto& c = cases[at];
  17110. report << c.name << "\t" << (c.demo ? "animating" : "idle") << "\t" << juce::String (cpu, 2) << "\n";
  17111. ++at;
  17112. open();
  17113. }
  17114. }
  17115. };
  17116. std::unique_ptr<EditorCpuRun> editorCpu;
  17117. void runEditorCpu (const juce::String& path)
  17118. {
  17119. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  17120. editorCpu = std::make_unique<EditorCpuRun>();
  17121. editorCpu->out = juce::File (path);
  17122. using K = lynx::EffectKind;
  17123. for (const auto demo : { false, true })
  17124. for (const auto& c : std::vector<EditorCpuRun::Case> { { K::facetEq, "Facet EQ", 2, demo }, { K::crestCompressor, "Crest Compressor", 1, demo },
  17125. { K::apexLimiter, "Apex Limiter", 1, demo }, { K::prismMultiband, "Prism Multiband", 1, demo },
  17126. { K::epochVerb, "Epoch Verb", 0, demo }, { K::glowLeveler, "Glow Leveler", 0, demo },
  17127. { K::fruityLimiter, "Fruity Limiter", 0, demo }, { K::lynxTune, "LYNX Tune", 0, demo } })
  17128. editorCpu->cases.push_back (c);
  17129. editorCpu->done = [this] { juce::MessageManager::callAsync ([this] { editorCpu.reset(); quit(); }); };
  17130. editorCpu->start();
  17131. }
  17132. struct ParityShow
  17133. {
  17134. std::unique_ptr<lynx::AudioEngine> engine;
  17135. std::unique_ptr<juce::Component> editor;
  17136. std::unique_ptr<juce::DocumentWindow> window;
  17137. ~ParityShow() { window.reset(); editor.reset(); engine.reset(); }
  17138. };
  17139. std::shared_ptr<ParityShow> parityShow;
  17140. bool parityShotFailed = false; // --parityshot: the effect name matched no built-in effect
  17141. void runParityShot (const juce::String& path, const juce::String& effectName, const juce::String& paramsFile)
  17142. {
  17143. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  17144. int kindIndex = -1;
  17145. for (int k = 0; k <= (int) lynx::lastEffectKind; ++k)
  17146. if (juce::String::fromUTF8 (lynx::effectInfo ((lynx::EffectKind) k).name).equalsIgnoreCase (effectName))
  17147. kindIndex = k;
  17148. if (kindIndex < 0)
  17149. {
  17150. // round tp172b7: say so and fail (a silent exit 0 hid a split effect name in a launch script)
  17151. std::fprintf (stderr, "unknown effect: %s\n", effectName.toRawUTF8());
  17152. std::fflush (stderr);
  17153. parityShotFailed = true;
  17154. return;
  17155. }
  17156. const auto kind = (lynx::EffectKind) kindIndex;
  17157. auto fx = lynx::makeEffectSlot (kind);
  17158. if (paramsFile.isNotEmpty())
  17159. for (const auto& line : juce::StringArray::fromLines (juce::File (paramsFile).loadFileAsString()))
  17160. {
  17161. const auto t = juce::StringArray::fromTokens (line, " \t", "");
  17162. const auto index = t.size() >= 2 ? t[0].getIntValue() : -1;
  17163. if (index >= 0 && index < lynx::maxEffectParams)
  17164. fx.params[(std::size_t) index] = t[1].getFloatValue();
  17165. }
  17166. auto offlineOwner = std::make_unique<lynx::AudioEngine> (false); // (kept alive by LYNX_PARITYSHOT_SHOW's window)
  17167. auto& offline = *offlineOwner;
  17168. auto song = lynx::Song::makeDefault();
  17169. song.mixer.resize (2);
  17170. song.mixer[0].name = "Master";
  17171. song.mixer[1].name = "Insert 1";
  17172. song.mixer[1].effects.assign (1, fx);
  17173. for (auto& c : song.channels)
  17174. c.mixerTrack = 1;
  17175. offline.setSong (std::move (song));
  17176. offline.dispatchPendingMessages();
  17177. const bool facet = kind == lynx::EffectKind::facetEq;
  17178. // round tp172b4: the originals are pictured idle (nothing playing), so the display-first editors are too: no demo
  17179. // history unless LYNX_PARITYSHOT_DEMO=1 asks for the running display
  17180. const bool demoDisplay = juce::SystemStats::getEnvironmentVariable ("LYNX_PARITYSHOT_DEMO", {}) == "1";
  17181. // (Ember in its Classic voicing: the Classic panel, as the mixer opens it)
  17182. const bool pro = lynx::ProEditorWindows::handles (kind)
  17183. && ! (kind == lynx::EffectKind::ember && fx.params[(std::size_t) lynx::mixsuite::ember::voicing] > 0.5f);
  17184. auto editor = facet ? lynx::makeFacetEqEditor (offline, 1, 0, false)
  17185. : pro ? lynx::makeProEditor (offline, 1, 0, demoDisplay) : lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
  17186. if (editor == nullptr)
  17187. return;
  17188. if (! pro) // the demo song through the effect, the editor ticked 30 times a second of audio as its timer would
  17189. {
  17190. lynx::AudioEngine::RenderOptions o;
  17191. o.seconds = 3.0;
  17192. o.sampleRate = 48000.0;
  17193. o.pluginWarmUp = false;
  17194. int sinceTick = 0;
  17195. o.capture = [&] (const float*, const float*, int n) {
  17196. sinceTick += n;
  17197. if (sinceTick < 1600) return;
  17198. sinceTick = 0;
  17199. if (facet) lynx::tickFacetEqEditor (*editor);
  17200. else lynx::tickNativeEffectEditor (*editor);
  17201. };
  17202. offline.renderOffline (o);
  17203. }
  17204. // round tp172b5: LYNX_PARITYSHOT_CLICKS drives the editor before the picture (the originals' pictures have their
  17205. // panels open), tokens in order: "x,y" a click, then the pointer leaves; "h:x,y" the pointer rests there (a hover);
  17206. // "d:x,y,x2,y2" a drag from there to there, the button still down in the picture
  17207. for (const auto& token : juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_PARITYSHOT_CLICKS", {}), " ", ""))
  17208. {
  17209. const auto hover = token.startsWith ("h:"), drag = token.startsWith ("d:");
  17210. const auto xy = juce::StringArray::fromTokens (hover || drag ? token.substring (2) : token, ",", "");
  17211. if (xy.size() < (drag ? 4 : 2))
  17212. continue;
  17213. const juce::Point<int> at (xy[0].getIntValue(), xy[1].getIntValue());
  17214. editor->setVisible (true); // (getComponentAt finds nothing in a hidden component; it never goes on screen)
  17215. auto* target = editor->getComponentAt (at);
  17216. if (target == nullptr)
  17217. continue;
  17218. const auto local = target->getLocalPoint (editor.get(), at).toFloat();
  17219. const auto now = juce::Time::getCurrentTime();
  17220. auto source = juce::Desktop::getInstance().getMainMouseSource();
  17221. const juce::ModifierKeys left (juce::ModifierKeys::leftButtonModifier);
  17222. const auto event = [&] (juce::Point<float> p, juce::ModifierKeys mods, bool dragged) {
  17223. return juce::MouseEvent (source, p, mods, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, target, target, now, local, now, 1, dragged);
  17224. };
  17225. target->mouseMove (event (local, {}, false));
  17226. if (hover)
  17227. continue;
  17228. target->mouseDown (event (local, left, false));
  17229. if (drag)
  17230. {
  17231. const auto end = target->getLocalPoint (editor.get(), juce::Point<int> (xy[2].getIntValue(), xy[3].getIntValue())).toFloat();
  17232. target->mouseDrag (event (end, left, true));
  17233. continue;
  17234. }
  17235. target->mouseUp (event (local, {}, false));
  17236. target->mouseExit (event ({ -1000.0f, -1000.0f }, {}, false));
  17237. }
  17238. // round tp172b6: LYNX_PARITYSHOT_SHOW=1 puts the same editor in a real window and keeps it open (for a guarded GUI check
  17239. // of its pop-up menus, which the offscreen picture cannot hold); closing the window quits
  17240. if (juce::SystemStats::getEnvironmentVariable ("LYNX_PARITYSHOT_SHOW", {}) == "1")
  17241. {
  17242. struct ShowWindow final : juce::DocumentWindow
  17243. {
  17244. ShowWindow() : juce::DocumentWindow ("LYNX parity check", juce::Colours::black, juce::DocumentWindow::closeButton) {}
  17245. void closeButtonPressed() override { juce::JUCEApplication::getInstance()->systemRequestedQuit(); }
  17246. };
  17247. parityShow = std::make_shared<ParityShow>();
  17248. parityShow->engine = std::move (offlineOwner);
  17249. parityShow->editor = std::move (editor);
  17250. auto window = std::make_unique<ShowWindow>();
  17251. window->setUsingNativeTitleBar (true);
  17252. window->setContentNonOwned (parityShow->editor.get(), true);
  17253. window->setTopLeftPosition (80, 80);
  17254. window->setVisible (true);
  17255. parityShow->window = std::move (window);
  17256. return;
  17257. }
  17258. // round 190ar: LYNX_PARITYSHOT_SCALE=2 draws the same editor at twice the pixel density (as on a 200 % display);
  17259. // round 190bi: the shared shot scale (--shot-scale, LYNX_SHOT_SCALE, LYNX_PARITYSHOT_SCALE as before)
  17260. const auto shotScale = lynx::shot::scale();
  17261. juce::Image image (juce::Image::ARGB, juce::roundToInt ((float) editor->getWidth() * shotScale), juce::roundToInt ((float) editor->getHeight() * shotScale), true);
  17262. {
  17263. juce::Graphics g (image);
  17264. g.fillAll (lynx::theme::panel);
  17265. g.addTransform (juce::AffineTransform::scale (shotScale));
  17266. editor->paintEntireComponent (g, false);
  17267. }
  17268. const auto file = lynx::shot::file (juce::File (path));
  17269. file.deleteFile();
  17270. juce::PNGImageFormat png;
  17271. if (auto stream = file.createOutputStream())
  17272. png.writeImageToStream (image, *stream);
  17273. }
  17274. // an Audio Effect Rack shaped like Live's reference (REA_rodada183c §8): two chains with chain-select zones and fades,
  17275. // four named macros (one on a chain's volume, one on two parameters), two variations, every view open
  17276. static lynx::EffectSlot shotRack()
  17277. {
  17278. auto slot = lynx::rack::makeRackSlot (lynx::RackDoc::Kind::audioEffect);
  17279. auto& doc = slot.patcher;
  17280. doc.rack[0].chains[0].name = "Vocoder";
  17281. lynx::PatchNode vocoder, eq, verb;
  17282. vocoder.effect = lynx::makeEffectSlot (lynx::EffectKind::vocodex);
  17283. eq.effect = lynx::makeEffectSlot (lynx::EffectKind::parametricEq);
  17284. verb.effect = lynx::makeEffectSlot (lynx::EffectKind::reeverb2);
  17285. const auto nVoc = lynx::rack::addDevice (doc, 0, vocoder);
  17286. const auto nEq = lynx::rack::addDevice (doc, 0, eq);
  17287. lynx::rack::addChain (doc, "dry bypass");
  17288. lynx::rack::addDevice (doc, 1, verb);
  17289. doc.rack[0].chains[0].select = { 0, 79, 0, 63 };
  17290. doc.rack[0].chains[1].select = { 32, 127, 48, 127 };
  17291. lynx::rack::setChainVolume (doc, 0, 0.33f);
  17292. lynx::rack::setChainVolume (doc, 1, 0.5f);
  17293. const char* names[] { "Sibilance", "Intensity", "Formant Shift", "Bright Level" };
  17294. for (int m = 0; m < 4; ++m)
  17295. doc.rack[0].macros[(std::size_t) m].name = names[m];
  17296. lynx::RackMapping vol;
  17297. vol.target = lynx::RackMapping::Target::chainVolume, vol.chain = 0, vol.min = 0.0f, vol.max = lynx::rack::unityVolume;
  17298. lynx::rack::map (doc, 0, vol);
  17299. lynx::RackMapping a, b, c, d;
  17300. a.node = nVoc, a.param = 0;
  17301. b.node = nVoc, b.param = 1, b.min = 0.2f, b.max = 0.8f;
  17302. c.node = nEq, c.param = 0, c.min = 0.3f, c.max = 0.9f;
  17303. d.node = nEq, d.param = 1;
  17304. lynx::rack::map (doc, 1, a);
  17305. lynx::rack::map (doc, 2, b);
  17306. lynx::rack::map (doc, 3, c);
  17307. lynx::rack::map (doc, 3, d);
  17308. lynx::rack::setMacro (doc, 0, 60.0f);
  17309. lynx::rack::setMacro (doc, 1, 40.0f);
  17310. lynx::rack::setMacro (doc, 2, 70.0f);
  17311. lynx::rack::setMacro (doc, 3, 86.0f);
  17312. lynx::rack::storeVariation (doc);
  17313. lynx::rack::renameVariation (doc, 0, "Verse");
  17314. lynx::rack::setMacro (doc, 3, 120.0f);
  17315. lynx::rack::storeVariation (doc);
  17316. lynx::rack::renameVariation (doc, 1, "Drop");
  17317. lynx::rack::launchVariation (doc, 0);
  17318. auto& r = doc.rack[0];
  17319. r.showMacros = r.showChains = r.showDevices = r.showVariations = true;
  17320. r.zoneEditor = 2;
  17321. r.selectedChain = 0;
  17322. lynx::rack::setSelector (doc, 56.0f);
  17323. lynx::rack::compile (doc);
  17324. return slot;
  17325. }
  17326. bool runRackShots (const juce::File& out, const juce::String& liveSet = {})
  17327. {
  17328. out.createDirectory();
  17329. lynx::AudioEngine offline (false);
  17330. auto save = [&] (juce::Component& c, const juce::String& name) {
  17331. auto image = lynx::shot::paint (c, lynx::theme::panel);
  17332. const auto f = lynx::shot::file (out.getChildFile (name));
  17333. f.deleteFile();
  17334. juce::PNGImageFormat png;
  17335. if (auto stream = f.createOutputStream())
  17336. return png.writeImageToStream (image, *stream);
  17337. return false;
  17338. };
  17339. auto song = lynx::Song::makeDefault();
  17340. song.mixer.resize (3);
  17341. song.mixer[1].name = "Vocal Main";
  17342. auto slot = shotRack();
  17343. song.mixer[1].effects = { slot };
  17344. // an Instrument Rack: three chains split over the keyboard
  17345. lynx::ChannelDef inst;
  17346. inst.name = "Keys Rack";
  17347. inst.instrument = lynx::InstrumentKind::patcher;
  17348. inst.patcher = lynx::rack::makeRack (lynx::RackDoc::Kind::instrument);
  17349. for (int k = 0; k < 3; ++k)
  17350. {
  17351. if (k > 0)
  17352. lynx::rack::addChain (inst.patcher);
  17353. lynx::PatchNode synth;
  17354. synth.generator = true;
  17355. synth.channel.instrument = lynx::InstrumentKind::synth;
  17356. synth.channel.name = "Synth";
  17357. lynx::rack::addDevice (inst.patcher, k, synth);
  17358. }
  17359. inst.patcher.rack[0].chains[0].key = { 0, 52, 0, 47 };
  17360. inst.patcher.rack[0].chains[1].key = { 48, 76, 53, 71 };
  17361. inst.patcher.rack[0].chains[2].key = { 72, 127, 77, 127 };
  17362. inst.patcher.rack[0].chains[0].name = "Low";
  17363. inst.patcher.rack[0].chains[1].name = "Mid";
  17364. inst.patcher.rack[0].chains[2].name = "High";
  17365. inst.patcher.rack[0].showChains = inst.patcher.rack[0].showDevices = true;
  17366. inst.patcher.rack[0].zoneEditor = 0;
  17367. lynx::rack::compile (inst.patcher);
  17368. song.channels.push_back (inst);
  17369. const auto channel = (int) song.channels.size() - 1;
  17370. offline.setSong (std::move (song));
  17371. offline.dispatchPendingMessages();
  17372. bool ok = true;
  17373. // [set.als]: a Live set's racks as LYNX imports them, the one with the most chains drawn with its title bar (the
  17374. // like-for-like pair with Live's own picture of that set)
  17375. if (liveSet.isNotEmpty())
  17376. {
  17377. juce::MemoryBlock bytes;
  17378. juce::File (liveSet).loadFileAsData (bytes);
  17379. const std::vector<std::uint8_t> data ((const std::uint8_t*) bytes.getData(), (const std::uint8_t*) bytes.getData() + bytes.getSize());
  17380. lynx::AlsImportOptions o;
  17381. o.common.projectFolder = juce::File (liveSet).getParentDirectory().getFullPathName().toStdString();
  17382. std::string error;
  17383. if (auto imported = lynx::importAls (data, o, &error))
  17384. {
  17385. int bestTrack = -1, bestSlot = -1;
  17386. std::size_t most = 0;
  17387. for (int t = 0; t < (int) imported->mixer.size(); ++t)
  17388. for (int s = 0; s < (int) imported->mixer[(std::size_t) t].effects.size(); ++s)
  17389. 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)
  17390. most = fx.patcher.rack[0].chains.size(), bestTrack = t, bestSlot = s;
  17391. if (bestTrack >= 0)
  17392. {
  17393. offline.setSong (std::move (*imported));
  17394. offline.dispatchPendingMessages();
  17395. auto view = lynx::RackWindows::makeSlotView (offline, bestTrack, bestSlot, true);
  17396. view->setSize (view->preferredWidth (228), 228);
  17397. ok = save (*view, "rack-live-import.png") && ok;
  17398. view->setMapMode (true);
  17399. view->setSize (view->preferredWidth (228), 228);
  17400. ok = save (*view, "rack-live-import-map.png") && ok;
  17401. return ok;
  17402. }
  17403. }
  17404. return false;
  17405. }
  17406. {
  17407. auto view = lynx::RackWindows::makeSlotView (offline, 1, 0, false);
  17408. view->setSize (view->preferredWidth (206), 206);
  17409. ok = save (*view, "rack-deviceview.png") && ok;
  17410. }
  17411. {
  17412. auto view = lynx::RackWindows::makeSlotView (offline, 1, 0, true);
  17413. view->setMapMode (true);
  17414. view->setSize (view->preferredWidth (228), 228);
  17415. ok = save (*view, "rack-mapmode.png") && ok;
  17416. }
  17417. {
  17418. auto view = lynx::RackWindows::makeChannelView (offline, channel, true);
  17419. view->setSize (view->preferredWidth (228), 228);
  17420. ok = save (*view, "rack-instrument.png") && ok;
  17421. }
  17422. return ok;
  17423. }
  17424. void runEq166fShots (const juce::String& folder)
  17425. {
  17426. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  17427. const juce::File out (folder);
  17428. out.createDirectory();
  17429. lynx::AudioEngine offline (false);
  17430. auto save = [&] (juce::Component& editor, const juce::String& name) {
  17431. auto image = lynx::shot::paint (editor, lynx::theme::panel);
  17432. const auto f = lynx::shot::file (out.getChildFile (name));
  17433. f.deleteFile();
  17434. juce::PNGImageFormat png;
  17435. if (auto stream = f.createOutputStream())
  17436. png.writeImageToStream (image, *stream);
  17437. };
  17438. // a song whose demo beat plays into insert 1 (the source) and, for Facet's target, its other half into insert 2
  17439. auto songWith = [] (const lynx::EffectSlot& fx, bool split) {
  17440. auto song = lynx::Song::makeDefault();
  17441. song.mixer.resize (3);
  17442. song.mixer[0].name = "Master";
  17443. song.mixer[1].name = "Vocal";
  17444. song.mixer[2].name = "Reference mix";
  17445. song.mixer[1].effects.assign (1, fx);
  17446. for (std::size_t c = 0; c < song.channels.size(); ++c)
  17447. song.channels[c].mixerTrack = split && c % 2 == 1 ? 2 : 1;
  17448. return song;
  17449. };
  17450. auto feed = [&] (juce::Component& editor, bool facet, int frames) {
  17451. // one continuous render of the song, the editor ticked 30 times a second of audio, as its timer would
  17452. lynx::AudioEngine::RenderOptions o;
  17453. o.seconds = frames / 30.0;
  17454. o.sampleRate = 48000.0;
  17455. o.pluginWarmUp = false;
  17456. int sinceTick = 0;
  17457. o.capture = [&] (const float*, const float*, int n) {
  17458. sinceTick += n;
  17459. if (sinceTick < 1600) return;
  17460. sinceTick = 0;
  17461. if (facet) lynx::tickFacetEqEditor (editor);
  17462. else lynx::tickNativeEffectEditor (editor);
  17463. };
  17464. offline.renderOffline (o);
  17465. if (facet) lynx::tickFacetEqEditor (editor);
  17466. else lynx::tickNativeEffectEditor (editor);
  17467. };
  17468. // Parametric EQ 2: spectrum + heatmap (Full), flat / band 4 +12 dB / band 4 -12 dB, then the Top position
  17469. auto& display = lynx::peqview::displaySettings();
  17470. const auto kept = display;
  17471. display.spectrum = display.heatmap = true;
  17472. display.position = 0;
  17473. 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" },
  17474. { 0.0, "peq2-heatmap-top.png" } })
  17475. {
  17476. auto eq = lynx::makeEffectSlot (lynx::EffectKind::parametricEq);
  17477. eq.params[(std::size_t) lynx::peq::param (3, 2)] = lynx::peq::gainValue (gain);
  17478. eq.params[(std::size_t) lynx::peq::param (3, 1)] = lynx::peq::hzValue (900.0);
  17479. display.position = juce::String (name).contains ("top") ? 1 : 0;
  17480. offline.setSong (songWith (eq, false));
  17481. offline.dispatchPendingMessages();
  17482. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.25f, 0);
  17483. feed (*editor, false, 120);
  17484. save (*editor, name);
  17485. }
  17486. display = kept;
  17487. // Facet EQ's comparative EQ: listening to the target (insert 2) with its spectrum over the source's
  17488. {
  17489. using namespace lynx::facet;
  17490. auto eq = lynx::makeEffectSlot (lynx::EffectKind::facetEq);
  17491. eq.params[(std::size_t) param (0, 0)] = shapeValue (Shape::bell);
  17492. eq.params[(std::size_t) param (0, 1)] = hzValue (250.0);
  17493. eq.params[(std::size_t) param (0, 2)] = gainValue (-4.0);
  17494. eq.params[(std::size_t) param (1, 0)] = shapeValue (Shape::highShelf);
  17495. eq.params[(std::size_t) param (1, 1)] = hzValue (6000.0);
  17496. eq.params[(std::size_t) param (1, 2)] = gainValue (3.0);
  17497. eq.params[(std::size_t) analyzerParam] = analyzerValue (Analyzer::both);
  17498. eq.sidechain = 2;
  17499. for (const auto& [l, name] : { std::pair { Listen::target, "facet-compare-target.png" }, { Listen::eq, "facet-compare-eq.png" } })
  17500. {
  17501. eq.params[(std::size_t) listenParam] = listenValue (l);
  17502. offline.setSong (songWith (eq, true));
  17503. offline.dispatchPendingMessages();
  17504. auto editor = lynx::makeFacetEqEditor (offline, 1, 0, false);
  17505. feed (*editor, true, 90);
  17506. save (*editor, name);
  17507. }
  17508. }
  17509. }
  17510. void runDesign168rShots (const juce::String& folder)
  17511. {
  17512. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  17513. const juce::File out (folder);
  17514. out.createDirectory();
  17515. lynx::AudioEngine offline (false);
  17516. using K = lynx::EffectKind;
  17517. for (const auto kind : { K::pitchCorrect, K::lovePhilter, K::peakController, K::spreader, K::fruityFastLP, K::flFrequencyShifter,
  17518. K::flLowLifter, K::distructor, K::flBassBoost, K::flDelay1, K::fl7BandEq, K::flCenter, K::flPhaseInverter,
  17519. K::eq, K::delay, K::reverb, K::limiter, K::filter, K::distortion, K::chorus, K::utility, K::lofi,
  17520. K::crossover, K::pitchShift, K::freqShift, K::rhythmGain, K::volumeGate })
  17521. {
  17522. const auto& bank = lynx::presets::factory (kind);
  17523. // Love Philter / Distructor play FL's state: their second picture is FL's default preset (when installed)
  17524. std::optional<lynx::EffectSlot> flPreset;
  17525. if (kind == K::lovePhilter || kind == K::distructor)
  17526. {
  17527. const auto roots = lynx::findFlStudioRoots();
  17528. const auto file = juce::File (juce::String::fromUTF8 (roots.data.c_str()))
  17529. .getChildFile ("Patches/Plugin presets/Effects")
  17530. .getChildFile (kind == K::lovePhilter ? "Fruity Love Philter/Default.fst" : "Distructor/Default.fst");
  17531. juce::MemoryBlock bytes;
  17532. if (file.loadFileAsData (bytes))
  17533. flPreset = lynx::effectFromFlPreset (std::vector<std::uint8_t> ((const std::uint8_t*) bytes.getData(),
  17534. (const std::uint8_t*) bytes.getData() + bytes.getSize()));
  17535. }
  17536. for (int pass = 0; pass < (bank.empty() && ! flPreset ? 1 : 2); ++pass)
  17537. {
  17538. auto fx = lynx::makeEffectSlot (kind);
  17539. if (pass == 1 && flPreset)
  17540. fx = *flPreset;
  17541. else if (pass == 1)
  17542. {
  17543. fx.params = lynx::presets::apply (kind, bank.front(), 120.0);
  17544. fx.presetName = bank.front().name;
  17545. }
  17546. lynx::Song song;
  17547. song.mixer.resize (2);
  17548. song.mixer[0].name = "Master";
  17549. song.mixer[1].name = "Insert 1";
  17550. song.mixer[1].effects.push_back (fx);
  17551. offline.setSong (std::move (song));
  17552. offline.dispatchPendingMessages();
  17553. const auto pages = juce::jmax (1, (int) lynx::plugui::layoutFor (kind).pages.size());
  17554. for (const auto scale : { 1.0f, 2.0f })
  17555. for (int page = 0; page < pages; ++page)
  17556. {
  17557. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, scale, page);
  17558. if (editor == nullptr)
  17559. continue;
  17560. juce::Image image (juce::Image::ARGB, juce::jmax (1, editor->getWidth()), juce::jmax (1, editor->getHeight()), true);
  17561. {
  17562. juce::Graphics g (image);
  17563. g.fillAll (lynx::theme::panel);
  17564. editor->paintEntireComponent (g, false);
  17565. }
  17566. // (FL's "Frequency Shifter" and LYNX's "Frequency shifter" differ only in case: FL editors get "FL ")
  17567. const auto file = out.getChildFile ((lynx::plugui::hasFlLayout (kind) ? "FL " : "")
  17568. + juce::String (lynx::effectInfo (kind).name).replaceCharacters ("/\\:", "---")
  17569. + (pass == 1 ? "-preset" : "") + (page > 0 ? "-p" + juce::String (page + 1) : juce::String())
  17570. + (scale > 1.5f ? "-200" : "-100") + ".png");
  17571. file.deleteFile();
  17572. juce::PNGImageFormat png;
  17573. if (auto stream = file.createOutputStream())
  17574. png.writeImageToStream (image, *stream);
  17575. }
  17576. }
  17577. }
  17578. }
  17579. bool runInstrumentShots (const juce::File& folder, const juce::String& which, const juce::String& source)
  17580. {
  17581. folder.createDirectory();
  17582. auto key = [] (juce::String n) { return n.toLowerCase().removeCharacters (" -!._"); };
  17583. juce::StringArray wanted;
  17584. wanted.addTokens (which, ",", "");
  17585. auto ok = true;
  17586. struct Shot
  17587. {
  17588. juce::String name;
  17589. std::optional<lynx::ChannelDef> channel;
  17590. };
  17591. std::vector<Shot> shots;
  17592. for (const auto& e : lynx::natives::instrumentEngines())
  17593. {
  17594. const auto name = key (e.name);
  17595. const auto banked = which == "banks" && lynx::banks::hasBank (e.kind);
  17596. if (! banked && ! wanted.contains (name))
  17597. continue;
  17598. auto channel = source == "fl" || source == "flm" ? lynx::natives::makeChannel (e.kind, lynx::flStudioAccess())
  17599. : lynx::banks::defaultChannel (e.kind, e.name);
  17600. // (round 190u) source "flm": the channel as the .flm import makes it (Transistor Bass: FL Studio Mobile's build)
  17601. if (source == "flm" && channel && e.kind == lynx::InstrumentKind::transistorbass)
  17602. {
  17603. 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
  17604. channel->modelParams = { 1.0f };
  17605. channel->samplePath.clear();
  17606. }
  17607. if (! channel)
  17608. {
  17609. std::fprintf (stderr, "%s: no %s channel\n", e.name, source.toRawUTF8());
  17610. ok = false;
  17611. continue;
  17612. }
  17613. shots.push_back ({ name, std::move (channel) });
  17614. }
  17615. // Autogun (round 169h): not in the Add menus (no preset files); FL's own render-test channel, either source
  17616. if (wanted.contains ("autogun"))
  17617. {
  17618. if (auto channel = lynx::natives::autogunShotChannel (lynx::flStudioAccess()))
  17619. shots.push_back ({ "autogun", std::move (channel) });
  17620. else
  17621. {
  17622. std::fprintf (stderr, "Autogun: no channel (FL Studio's Render tests\\Autogun.flp)\n");
  17623. ok = false;
  17624. }
  17625. }
  17626. for (auto& shot : shots)
  17627. {
  17628. const auto& name = shot.name;
  17629. auto& channel = shot.channel;
  17630. lynx::AudioEngine offline (false);
  17631. lynx::Song song;
  17632. song.mixer = lynx::Song::defaultMixer (2);
  17633. song.channels.push_back (*channel);
  17634. song.patterns.emplace_back();
  17635. {
  17636. juce::String error; // the project too, so an older build can picture the same channel (--snapshot)
  17637. lynx::ProjectFile::save (song, folder.getChildFile (name + "-" + source + ".lynx"), error);
  17638. }
  17639. offline.setSong (std::move (song));
  17640. offline.dispatchPendingMessages();
  17641. auto frame = lynx::makeChannelFrame (offline, 0, 0);
  17642. if (frame == nullptr || frame->getWidth() <= 0)
  17643. {
  17644. ok = false;
  17645. continue;
  17646. }
  17647. for (const auto scale : { 1.0f, 1.5f, 2.0f })
  17648. {
  17649. const auto file = folder.getChildFile (name + "-" + source + "-" + juce::String (juce::roundToInt (scale * 100)) + ".png");
  17650. savePng (frame->createComponentSnapshot (frame->getLocalBounds(), true, scale), file.getFullPathName());
  17651. std::printf ("%s %dx%d\n", file.getFullPathName().toRawUTF8(), frame->getWidth(), frame->getHeight());
  17652. }
  17653. // round 169h: the layout's other pages (Toxic's MIDI / Seq …), one shot each at 1.5×
  17654. for (int page = 1; page < lynx::showChannelLayoutPage (*frame, -1); ++page)
  17655. {
  17656. lynx::showChannelLayoutPage (*frame, page);
  17657. const auto file = folder.getChildFile (name + "-" + source + "-page" + juce::String (page) + "-150.png");
  17658. savePng (frame->createComponentSnapshot (frame->getLocalBounds(), true, 1.5f), file.getFullPathName());
  17659. std::printf ("%s\n", file.getFullPathName().toRawUTF8());
  17660. }
  17661. }
  17662. return ok;
  17663. }
  17664. // --- round 170j: the pilot editors with their own art -------------------------------------------------
  17665. struct ArtPilot
  17666. {
  17667. std::string file; // the art's name as a file name: "toxic-biohazard"
  17668. bool instrument;
  17669. lynx::InstrumentKind instrumentKind;
  17670. lynx::EffectKind effectKind;
  17671. lynx::skin::Style before; // the automatic style it had before the Themed style
  17672. };
  17673. static juce::StringArray& artOnly() // --artshot / --artgui: only these (file names), all when empty
  17674. {
  17675. static juce::StringArray only;
  17676. return only;
  17677. }
  17678. // every plugin with art of its own (round 170j/170k): generators first, then effects; built from the art
  17679. // registries, so a new theme is shot without touching this list
  17680. static const std::vector<ArtPilot>& artPilots()
  17681. {
  17682. using I = lynx::InstrumentKind;
  17683. using E = lynx::EffectKind;
  17684. static const std::vector<ArtPilot> list = [] {
  17685. std::vector<ArtPilot> all;
  17686. auto slug = [] (lynx::skin::Art a) {
  17687. return juce::String (lynx::skin::artName (a)).toLowerCase().replaceCharacters (" ", "-").removeCharacters ("!.()'").toStdString();
  17688. };
  17689. for (const auto& e : lynx::natives::instrumentEngines()) // (the engines' order first)
  17690. if (const auto a = lynx::skin::artForInstrument (e.kind); a != lynx::skin::Art::none)
  17691. all.push_back ({ slug (a), true, e.kind, E::reverb, lynx::skin::Style::neon });
  17692. for (int k = 0; k <= (int) I::wavetraveller; ++k) // then every other kind with art (DrumSynth, Autogun, Wasp...)
  17693. if (const auto a = lynx::skin::artForInstrument ((I) k); a != lynx::skin::Art::none)
  17694. all.push_back ({ slug (a), true, (I) k, E::reverb, lynx::skin::Style::neon });
  17695. for (int k = 0; k <= (int) lynx::lastEffectKind; ++k)
  17696. if (const auto a = lynx::skin::artForEffect ((E) k); a != lynx::skin::Art::none)
  17697. all.push_back ({ slug (a), false, I::synth, (E) k, lynx::skin::plainStyleFor (k) });
  17698. std::vector<ArtPilot> kept;
  17699. for (auto& p : all)
  17700. if (artOnly().isEmpty() || artOnly().contains (juce::String (p.file)))
  17701. if (std::none_of (kept.begin(), kept.end(), [&] (const ArtPilot& q) { return q.file == p.file; }))
  17702. kept.push_back (p);
  17703. return kept;
  17704. }();
  17705. return list;
  17706. }
  17707. // the song and the editor of a pilot (an instrument: the channel window on its Plugin tab)
  17708. static std::unique_ptr<juce::Component> makeArtPilot (lynx::AudioEngine& engine, const ArtPilot& p)
  17709. {
  17710. lynx::Song song;
  17711. song.mixer = lynx::Song::defaultMixer (2);
  17712. if (p.instrument)
  17713. {
  17714. for (const auto& e : lynx::natives::instrumentEngines())
  17715. if (e.kind == p.instrumentKind)
  17716. {
  17717. auto channel = lynx::natives::makeChannel (e.kind, lynx::flStudioAccess());
  17718. if (! channel) channel = lynx::banks::defaultChannel (e.kind, e.name);
  17719. if (! channel) return nullptr;
  17720. song.channels.push_back (*channel);
  17721. break;
  17722. }
  17723. if (song.channels.empty()) // a kind without an engine entry: its LYNX default, else an empty channel of that kind
  17724. {
  17725. const std::string name = lynx::skin::artName (lynx::skin::artForInstrument (p.instrumentKind));
  17726. auto channel = lynx::banks::defaultChannel (p.instrumentKind, name);
  17727. if (! channel)
  17728. {
  17729. channel = lynx::ChannelDef {};
  17730. channel->instrument = p.instrumentKind;
  17731. channel->name = name;
  17732. }
  17733. song.channels.push_back (*channel);
  17734. }
  17735. song.patterns.emplace_back();
  17736. }
  17737. else
  17738. {
  17739. song.mixer[1].effects.push_back (lynx::makeEffectSlot (p.effectKind));
  17740. }
  17741. engine.setSong (std::move (song));
  17742. engine.dispatchPendingMessages();
  17743. if (p.instrument) return lynx::makeChannelFrame (engine, 0, 0);
  17744. if (p.effectKind == lynx::EffectKind::facetEq) return lynx::makeFacetEqEditor (engine, 1, 0, true);
  17745. if (lynx::ProEditorWindows::handles (p.effectKind)) return lynx::makeProEditor (engine, 1, 0, true); // display-first editors, demo signal
  17746. return lynx::makeNativeEffectEditor (engine, 1, 0, 1.0f, 0);
  17747. }
  17748. // "before": the style each pilot had (forced for its run); "after": automatic (the pilots are Themed)
  17749. static void artPilotStyle (const ArtPilot& p, const juce::String& mode)
  17750. {
  17751. lynx::skin::setForcedStyle (mode == "before" ? (int) p.before : -1);
  17752. lynx::skin::setArtMotion (mode != "still");
  17753. }
  17754. bool runArtShots (const juce::File& folder, bool before)
  17755. {
  17756. folder.createDirectory();
  17757. auto ok = true;
  17758. juce::String titles ("editor\tsize\twidth\tname width at the style's size\tbox\tsize used\tlines\tresult\n");
  17759. for (const auto& p : artPilots())
  17760. {
  17761. artPilotStyle (p, before ? "before" : "after");
  17762. lynx::AudioEngine offline (false);
  17763. auto editor = makeArtPilot (offline, p);
  17764. if (editor == nullptr || editor->getWidth() <= 0)
  17765. {
  17766. std::fprintf (stderr, "%s: no editor\n", p.file.c_str());
  17767. ok = false;
  17768. continue;
  17769. }
  17770. if (p.effectKind == lynx::EffectKind::facetEq) lynx::tickFacetEqEditor (*editor);
  17771. // round 170k2: titles.tsv, how the header's name fitted (its width at the style's size, the box, the size used)
  17772. auto fit = [&] (const juce::String& at) {
  17773. const auto f = lynx::skin::lastTitleFit();
  17774. if (f.have <= 0.0f) return; // no plugin header drawn (a generator's channel window)
  17775. titles << juce::String (p.file) << "\t" << at << "\t" << editor->getWidth() << "\t" << juce::String (f.need, 1) << "\t" << juce::String (f.have, 1)
  17776. << "\t" << juce::String (f.size, 1) << "\t" << f.lines << "\t" << (f.clipped ? "ELLIPSIS" : "full") << "\n";
  17777. };
  17778. for (const auto scale : { 1.0f, 2.0f })
  17779. {
  17780. const auto file = folder.getChildFile (juce::String (p.file) + "-" + (before ? "before" : "after") + "-" + juce::String (juce::roundToInt (scale * 100)) + ".png");
  17781. lynx::skin::resetTitleFit();
  17782. savePng (editor->createComponentSnapshot (editor->getLocalBounds(), true, scale), file.getFullPathName());
  17783. std::printf ("%s %dx%d\n", file.getFullPathName().toRawUTF8(), editor->getWidth(), editor->getHeight());
  17784. if (scale == 1.0f) fit ("100");
  17785. }
  17786. // ... and at the smallest size its window allows (effect panels; the Pro editors scale as a whole)
  17787. if (const auto smallest = lynx::nativeEditorMinimumSize (*editor); smallest.x > 0)
  17788. {
  17789. editor->setSize (smallest.x, smallest.y);
  17790. const auto file = folder.getChildFile (juce::String (p.file) + "-" + (before ? "before" : "after") + "-min.png");
  17791. lynx::skin::resetTitleFit();
  17792. savePng (lynx::shot::snapshot (*editor), file.getFullPathName());
  17793. fit ("min");
  17794. }
  17795. }
  17796. folder.getChildFile (juce::String ("titles-") + (before ? "before" : "after") + ".tsv").replaceWithText (titles);
  17797. lynx::skin::setForcedStyle (-1);
  17798. return ok;
  17799. }
  17800. struct ArtGuiRun final : juce::Timer
  17801. {
  17802. juce::File folder;
  17803. juce::String mode, report;
  17804. std::size_t at = 0;
  17805. int phase = 0;
  17806. double t0 = 0.0, c0 = 0.0;
  17807. std::unique_ptr<lynx::AudioEngine> engine;
  17808. std::unique_ptr<juce::DocumentWindow> window;
  17809. std::function<void()> done;
  17810. void start()
  17811. {
  17812. engine = std::make_unique<lynx::AudioEngine> (false);
  17813. report << "editor\tmode\tcpu % of one core\tart layer animating\n";
  17814. open();
  17815. startTimer (100);
  17816. }
  17817. void open()
  17818. {
  17819. window.reset();
  17820. const auto& pilots = artPilots();
  17821. if (at >= pilots.size())
  17822. {
  17823. folder.getChildFile ("cpu-" + mode + ".txt").replaceWithText (report);
  17824. stopTimer();
  17825. lynx::skin::setForcedStyle (-1);
  17826. lynx::skin::setArtMotion (true);
  17827. if (done) done();
  17828. return;
  17829. }
  17830. const auto& p = pilots[at];
  17831. artPilotStyle (p, mode);
  17832. auto editor = makeArtPilot (*engine, p);
  17833. if (editor == nullptr) { ++at; open(); return; }
  17834. window = std::make_unique<juce::DocumentWindow> (juce::String ("LYNX art - ") + juce::String (p.file), lynx::theme::colour::bg1, 0);
  17835. window->setUsingNativeTitleBar (true);
  17836. window->setContentOwned (editor.release(), true);
  17837. const auto area = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea;
  17838. window->setTopLeftPosition (area.getX() + 24, area.getY() + 24);
  17839. window->setAlwaysOnTop (true);
  17840. window->setVisible (true);
  17841. phase = 0;
  17842. t0 = juce::Time::getMillisecondCounterHiRes();
  17843. }
  17844. bool animating() const
  17845. {
  17846. if (window == nullptr || window->getContentComponent() == nullptr) return false;
  17847. std::function<bool (juce::Component&)> find = [&] (juce::Component& c) {
  17848. if (auto* l = dynamic_cast<lynx::skin::ArtLayer*> (&c); l != nullptr && l->animating()) return true;
  17849. for (auto* child : c.getChildren())
  17850. if (find (*child)) return true;
  17851. return false;
  17852. };
  17853. return find (*window->getContentComponent());
  17854. }
  17855. void timerCallback() override
  17856. {
  17857. const auto now = juce::Time::getMillisecondCounterHiRes();
  17858. const auto& p = artPilots()[at];
  17859. const auto ready = folder.getChildFile (juce::String (p.file) + "-" + mode + ".ready");
  17860. const auto shotDone = folder.getChildFile (juce::String (p.file) + "-" + mode + ".done");
  17861. if (phase == 0 && now - t0 > 1500.0)
  17862. {
  17863. // the window's content on screen, in physical pixels, for the outside screenshot to crop
  17864. auto* c = window->getContentComponent();
  17865. const auto scale = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->scale;
  17866. const auto b = c->getScreenBounds();
  17867. shotDone.deleteFile();
  17868. ready.replaceWithText (juce::String (juce::roundToInt (b.getX() * scale)) + " " + juce::String (juce::roundToInt (b.getY() * scale)) + " "
  17869. + juce::String (juce::roundToInt (b.getWidth() * scale)) + " " + juce::String (juce::roundToInt (b.getHeight() * scale)));
  17870. phase = 1;
  17871. t0 = now;
  17872. return;
  17873. }
  17874. if (phase == 1 && (shotDone.existsAsFile() || now - t0 > 10000.0))
  17875. {
  17876. ready.deleteFile();
  17877. shotDone.deleteFile();
  17878. phase = 2;
  17879. t0 = now;
  17880. c0 = lynx::processCpuSeconds();
  17881. return;
  17882. }
  17883. if (phase == 2 && now - t0 > 6000.0)
  17884. {
  17885. const auto cpu = (lynx::processCpuSeconds() - c0) / ((now - t0) * 0.001) * 100.0;
  17886. report << juce::String (p.file) << "\t" << mode << "\t" << juce::String (cpu, 2) << "\t" << (animating() ? "yes" : "no") << "\n";
  17887. ++at;
  17888. open();
  17889. }
  17890. }
  17891. };
  17892. std::unique_ptr<ArtGuiRun> artGui;
  17893. void runArtGui (const juce::File& folder, const juce::String& mode)
  17894. {
  17895. folder.createDirectory();
  17896. artGui = std::make_unique<ArtGuiRun>();
  17897. artGui->folder = folder;
  17898. artGui->mode = mode;
  17899. artGui->done = [this] { juce::MessageManager::callAsync ([this] { artGui.reset(); quit(); }); };
  17900. artGui->start();
  17901. }
  17902. void runDesign190inShot (const juce::String& prefix, const juce::String& project)
  17903. {
  17904. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  17905. juce::String report;
  17906. {
  17907. lynx::AudioEngine engine (false);
  17908. juce::String error;
  17909. if (const juce::File input (project); input.existsAsFile() && input.hasFileExtension ("flp"))
  17910. report << "import: " << (engine.importFlpFile (input, error) ? "ok" : "failed " + error) << "\n";
  17911. engine.dispatchPendingMessages();
  17912. // a native FL generator with FL's presets (FL's capture: FLEX's "Piano Dark"), on a mixer track of its own
  17913. const auto& fl = lynx::flStudioAccess();
  17914. auto osc = lynx::natives::makeChannel (lynx::InstrumentKind::threeosc, fl);
  17915. int generator = -1, sampler = -1;
  17916. engine.editSong ([&] (lynx::Song& s) {
  17917. if (osc)
  17918. {
  17919. osc->mixerTrack = s.claimFreeInsert();
  17920. s.channels.push_back (*osc);
  17921. generator = (int) s.channels.size() - 1;
  17922. }
  17923. if (const juce::File kick (juce::String::fromUTF8 (fl.roots.data.c_str()) + "/Patches/Packs/Drums/Kicks/808 Kick.wav"); kick.existsAsFile())
  17924. {
  17925. lynx::ChannelDef d; // FL's Sampler with a kick, as FL's default channel (the Sample, Envelope and Misc tabs)
  17926. d.instrument = lynx::InstrumentKind::sampler;
  17927. lynx::audioclips::loadSampleInto (d, kick.getFullPathName().toStdString(), "808 Kick");
  17928. d.mixerTrack = s.claimFreeInsert();
  17929. s.channels.push_back (d);
  17930. sampler = (int) s.channels.size() - 1;
  17931. }
  17932. for (const auto withSample : { true, false }) // (a sampler with its sample first, else any)
  17933. for (int c = 0; c < (int) s.channels.size() && sampler < 0; ++c)
  17934. if (s.channels[(std::size_t) c].instrument == lynx::InstrumentKind::sampler && (! withSample || ! s.channels[(std::size_t) c].samplePath.empty()))
  17935. sampler = c;
  17936. });
  17937. engine.dispatchPendingMessages();
  17938. lynx::MainComponent ui (engine, false); // (sets the Channel rack's wrapper-menu items)
  17939. ui.setSize (1920, 1080);
  17940. report << "generator " << generator << ", sampler " << sampler << "\n";
  17941. auto shoot = [&] (juce::Component& c, const juce::String& name) {
  17942. savePng (lynx::shot::snapshot (c), prefix + name);
  17943. report << name << " " << c.getWidth() << "x" << c.getHeight() << "\n";
  17944. };
  17945. auto window = [&] (int channel, int tab, const juce::String& name) {
  17946. if (channel < 0)
  17947. return;
  17948. if (auto w = lynx::makeChannelWindowForShot (engine, channel, tab))
  17949. shoot (*w, name);
  17950. };
  17951. window (generator, 0, "-cw-plugin.png");
  17952. window (generator, -1, "-cw-plugin-misc.png");
  17953. window (sampler, 0, "-cw-sample.png");
  17954. window (sampler, 1, "-cw-envelope.png");
  17955. window (sampler, -1, "-cw-misc.png");
  17956. // the strip of a window with the system's title bar (docking off): ▸ and the presets stay in it
  17957. if (generator >= 0)
  17958. if (auto frame = lynx::makeChannelFrame (engine, generator, 0))
  17959. {
  17960. shoot (*frame, "-frame-floating.png");
  17961. if (auto menu = lynx::channelWrapperMenu (*frame))
  17962. {
  17963. // FL's two columns: the plugin's items, then the Channel column (split at the column break)
  17964. juce::PopupMenu left, right;
  17965. auto* to = &left;
  17966. for (juce::PopupMenu::MenuItemIterator it (*menu); it.next();)
  17967. {
  17968. to->addItem (it.getItem());
  17969. if (it.getItem().shouldBreakAfter)
  17970. to = &right;
  17971. }
  17972. saveMenus (juce::StringArray { "Plugin", "Channel" }, std::vector<juce::PopupMenu> { left, right }, prefix + "-menu-channel.png");
  17973. report << "menu items " << left.getNumItems() << " + " << right.getNumItems() << "\n";
  17974. }
  17975. }
  17976. }
  17977. {
  17978. // FW-8: LYNX engines standing in for FL plugins of an imported project (the import's flOrigin) are titled
  17979. // with FL's name; LYNX's own Delay (no FL origin) keeps its own
  17980. lynx::AudioEngine offline (false);
  17981. lynx::Song song;
  17982. song.mixer.resize (2);
  17983. song.mixer[0].name = "Master";
  17984. song.mixer[1].name = "Insert 1";
  17985. const std::vector<std::pair<lynx::EffectKind, const char*>> standIns { { lynx::EffectKind::limiter, "Fruity Limiter" },
  17986. { lynx::EffectKind::utility, "Fruity Stereo Shaper" }, { lynx::EffectKind::delay, "Fruity Delay 3" },
  17987. { lynx::EffectKind::reverb, "Fruity Reeverb 2" }, { lynx::EffectKind::delay, "" } };
  17988. for (const auto& [kind, origin] : standIns)
  17989. {
  17990. auto fx = lynx::makeEffectSlot (kind);
  17991. fx.flOrigin.plugin = origin;
  17992. song.mixer[1].effects.push_back (fx);
  17993. }
  17994. offline.setSong (std::move (song));
  17995. offline.dispatchPendingMessages();
  17996. std::vector<juce::Image> strips;
  17997. int width = 0, height = 0;
  17998. for (int k = 0; k < (int) standIns.size(); ++k)
  17999. if (auto editor = lynx::makeNativeEffectEditor (offline, 1, k, 1.0f, 0))
  18000. {
  18001. auto image = lynx::shot::paint (*editor, lynx::theme::panel); // (as --plugui draws the editors)
  18002. const auto h = juce::jmin (image.getHeight(), (int) std::ceil (30.0f * lynx::shot::scale()));
  18003. juce::Image strip (juce::Image::ARGB, image.getWidth(), h, true);
  18004. juce::Graphics (strip).drawImageAt (image, 0, 0);
  18005. strips.push_back (strip);
  18006. width = juce::jmax (width, image.getWidth());
  18007. height += h + 4;
  18008. }
  18009. if (! strips.empty())
  18010. {
  18011. juce::Image all (juce::Image::RGB, width, height, true);
  18012. {
  18013. juce::Graphics g (all); // (flushed when it goes: a native image's context draws on its release)
  18014. g.fillAll (juce::Colours::black);
  18015. int y = 0;
  18016. for (auto& strip : strips)
  18017. {
  18018. g.drawImageAt (strip, 0, y);
  18019. y += strip.getHeight() + 4;
  18020. }
  18021. }
  18022. savePng (all, prefix + "-names.png");
  18023. report << "names " << (int) strips.size() << "\n";
  18024. }
  18025. }
  18026. juce::File (prefix + "-report.txt").replaceWithText (report);
  18027. }
  18028. void runPluginEditorSnapshots (const juce::String& folder)
  18029. {
  18030. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  18031. {
  18032. const juce::File out (folder);
  18033. out.createDirectory();
  18034. lynx::AudioEngine offline (false);
  18035. const auto roots = lynx::findFlStudioRoots();
  18036. const auto presets = juce::File (juce::String::fromUTF8 (roots.data.c_str())).getChildFile ("Patches/Plugin presets/Effects");
  18037. auto kinds = lynx::plugui::flLayoutKinds();
  18038. kinds.push_back (lynx::EffectKind::maximus); // Soundgoodizer (below)
  18039. for (const auto own : lynx::plugui::ownLayoutKinds()) // LYNX's own panels (mixing suite, round 96)
  18040. kinds.push_back (own);
  18041. kinds.push_back (lynx::EffectKind::apexLimiter); // round 114: display-first editor
  18042. kinds.push_back (lynx::EffectKind::ridgeStrip); // round 145: the second pass shows the Vocal strip voicing
  18043. kinds.push_back (lynx::EffectKind::ridgeStrip); // round 165: the third pass shows the E console voicing
  18044. kinds.push_back (lynx::EffectKind::compressor); // round 152: the RComp role's panel (vintage voicing, RComp ranges)
  18045. const auto database = juce::File (juce::String::fromUTF8 (roots.data.c_str())).getChildFile ("Patches/Plugin database/Effects");
  18046. auto maximusPasses = 0; // Maximus has its own page (first pass); the second pass shows Soundgoodizer
  18047. auto ridgePasses = 0;
  18048. // round 173d3: the parity pictures of one editor — LYNX_PLUGUI_ONLY=<effect name>, LYNX_PLUGUI_PRESET=<.fst>,
  18049. // LYNX_PLUGUI_PAGES=<page,page,…> (the page numbers as the editor encodes them)
  18050. const auto only = juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGUI_ONLY", {});
  18051. const auto onlyPreset = juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGUI_PRESET", {});
  18052. const auto onlyPages = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGUI_PAGES", {}), ",", "");
  18053. for (const auto kind : kinds)
  18054. {
  18055. if (only.isNotEmpty() && only != lynx::effectInfo (kind).name)
  18056. continue;
  18057. auto fx = lynx::makeEffectSlot (kind);
  18058. juce::String name (lynx::effectInfo (kind).name);
  18059. for (const auto& plugin : lynx::flPluginsForEffect (kind))
  18060. {
  18061. const auto dir = presets.getChildFile (juce::String::fromUTF8 (plugin.c_str()));
  18062. auto file = dir.getChildFile ("Default.fst");
  18063. if (! file.existsAsFile()) // plugins without presets: their entry of FL's plugin database
  18064. for (const auto& f : database.findChildFiles (juce::File::findFiles, true, juce::String::fromUTF8 (plugin.c_str()) + ".fst"))
  18065. file = f;
  18066. if (only.isNotEmpty() && onlyPreset.isNotEmpty())
  18067. file = juce::File (onlyPreset);
  18068. if (! file.existsAsFile())
  18069. {
  18070. auto files = dir.findChildFiles (juce::File::findFiles, true, "*.fst");
  18071. std::sort (files.begin(), files.end(), [] (const juce::File& a, const juce::File& b) { return a.getFullPathName().compareNatural (b.getFullPathName()) < 0; });
  18072. file = files.isEmpty() ? juce::File() : files[0];
  18073. }
  18074. juce::MemoryBlock data;
  18075. if (file.existsAsFile() && file.loadFileAsData (data))
  18076. {
  18077. const auto* bytes = static_cast<const std::uint8_t*> (data.getData());
  18078. 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)
  18079. {
  18080. fx = *loaded;
  18081. // round 190in (FW-8): a LYNX engine loaded with an FL plugin's preset stands in for that
  18082. // plugin as an imported slot does (its header shows FL's name)
  18083. if (fx.flOrigin.empty() && ! lynx::plugui::hasFlLayout (kind))
  18084. fx.flOrigin.plugin = plugin;
  18085. }
  18086. }
  18087. name = juce::String::fromUTF8 (plugin.c_str());
  18088. break;
  18089. }
  18090. if (kind == lynx::EffectKind::maximus && ++maximusPasses == 2) // Soundgoodizer: preset A of the installation, Amount 60 %
  18091. {
  18092. juce::MemoryBlock data;
  18093. juce::File (juce::String::fromUTF8 (roots.factoryData.c_str())).getChildFile ("Plugins/Fruity/Effects/Soundgoodizer/Data/Presets/a.dat").loadFileAsData (data);
  18094. lynx::maximusfx::Blob blob;
  18095. blob.build = lynx::hlfx::MaximusBuild::soundgoodizer;
  18096. blob.mix = 600;
  18097. const auto* b = static_cast<const std::uint8_t*> (data.getData());
  18098. blob.state.assign (b, b + data.getSize());
  18099. fx = lynx::makeEffectSlot (kind);
  18100. fx.state = lynx::maximusfx::pack (blob);
  18101. name = "Soundgoodizer";
  18102. }
  18103. if (kind == lynx::EffectKind::ridgeStrip && ++ridgePasses == 2) // round 145: her Vocalstrip 2 setting
  18104. {
  18105. for (const auto& [param, value] : { std::pair<const char*, float> { "Vocal strip", 1.0f }, { "Compander", 1.0f },
  18106. { "Compander threshold", 0.3083f }, { "Compander ratio", 0.6929f }, { "Compander attack", 0.2543f },
  18107. { "Compander release", 0.5316f }, { "Make-up", 0.2917f }, { "Soft knee", 1.0f },
  18108. { "Expander threshold", 0.2198f }, { "Vocal input", 0.6792f }, { "Vocal output", 0.3938f },
  18109. { "Process order", 0.4783f }, { "De-esser", 1.0f } })
  18110. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, param)] = value;
  18111. name = "Ridge Strip (Vocal strip)";
  18112. }
  18113. else if (kind == lynx::EffectKind::ridgeStrip && ridgePasses == 3) // round 165: the E console, EQ to the side chain
  18114. {
  18115. for (const auto& [param, value] : { std::pair<const char*, float> { "Voicing", 1.0f }, { "HPF", 0.3f }, { "HF gain", 0.8f },
  18116. { "HF bell", 1.0f }, { "Ratio", 0.5f }, { "Comp. threshold", 0.4f }, { "EQ to SC", 1.0f },
  18117. { "Filter split", 1.0f }, { "Expander", 1.0f } })
  18118. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, param)] = value;
  18119. name = "Ridge Strip (E console)";
  18120. }
  18121. else if (kind == lynx::EffectKind::ridgeStrip) // a vocal setting, so the graphs show something
  18122. for (const auto& [param, value] : { std::pair<const char*, float> { "HPF", 0.3f }, { "LMF gain", 0.35f }, { "HF gain", 0.7f },
  18123. { "Ratio", 0.3f }, { "Comp. threshold", 0.55f } })
  18124. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, param)] = value;
  18125. if (kind == lynx::EffectKind::compressor) // round 152: the vintage voicing with the reference's ranges and meter
  18126. {
  18127. for (const auto& [param, value] : { std::pair<const char*, float> { "Voicing", 1.0f }, { "Ranges", 1.0f }, { "Limiter", 1.0f },
  18128. { "Threshold", 0.6f }, { "RC ratio", 0.4f } })
  18129. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, param)] = value;
  18130. name = "Compressor (RComp role)";
  18131. }
  18132. if (kind == lynx::EffectKind::apexLimiter) // round 114: gain into the ceiling, so the display shows reduction
  18133. fx.params[0] = 0.33f;
  18134. if (kind == lynx::EffectKind::ember)
  18135. {
  18136. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, "Drive")] = 0.5f;
  18137. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, "Bands")] = 1.0f; // round 108: the band rows
  18138. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, "B3 drive")] = 0.6f;
  18139. }
  18140. if (kind == lynx::EffectKind::crestCompressor) // round 108: a curve with a knee and a side-chain low cut
  18141. for (const auto& [param, value] : { std::pair<const char*, float> { "Threshold", 0.55f }, { "Knee", 0.15f },
  18142. { "SC1 shape", 0.5f }, { "SC1 freq.", 0.3f } })
  18143. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, param)] = value;
  18144. lynx::Song song;
  18145. song.mixer.resize (2);
  18146. song.mixer[0].name = "Master";
  18147. song.mixer[1].name = "Insert 1";
  18148. song.mixer[1].effects.push_back (fx);
  18149. offline.setSong (std::move (song));
  18150. offline.dispatchPendingMessages();
  18151. if (lynx::ProEditorWindows::handles (kind)) // round 114: the display-first editors, with a demo signal
  18152. {
  18153. auto editor = lynx::makeProEditor (offline, 1, 0, true);
  18154. auto image = lynx::shot::paint (*editor);
  18155. const auto file = lynx::shot::file (out.getChildFile (name + ".png"));
  18156. file.deleteFile();
  18157. juce::PNGImageFormat png;
  18158. if (auto stream = file.createOutputStream())
  18159. png.writeImageToStream (image, *stream);
  18160. continue;
  18161. }
  18162. const auto pages = name == "Soundgoodizer" ? 1 : juce::jmax (1, (int) lynx::plugui::layoutFor (kind).pages.size());
  18163. std::vector<int> pageList;
  18164. for (int page = 0; page < pages; ++page)
  18165. pageList.push_back (page);
  18166. if (only.isNotEmpty() && ! onlyPages.isEmpty())
  18167. {
  18168. pageList.clear();
  18169. for (const auto& p : onlyPages)
  18170. pageList.push_back (p.getIntValue());
  18171. }
  18172. for (const auto page : pageList)
  18173. {
  18174. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, page);
  18175. auto image = lynx::shot::paint (*editor, lynx::theme::panel);
  18176. const auto file = lynx::shot::file (out.getChildFile (name + (page > 0 ? "-p" + juce::String (page + 1) : juce::String()) + ".png"));
  18177. file.deleteFile();
  18178. juce::PNGImageFormat png;
  18179. if (auto stream = file.createOutputStream())
  18180. png.writeImageToStream (image, *stream);
  18181. }
  18182. }
  18183. // round 137: Echoform in its Rhythm mode (EchoBoy's role) with the Present era
  18184. {
  18185. namespace ef = lynx::echosuite::echoform;
  18186. auto fx = lynx::makeEffectSlot (lynx::EffectKind::echoform);
  18187. fx.params[ef::rhythm] = 1.0f;
  18188. fx.params[ef::rhythmRepeats] = 5.0f / 15.0f;
  18189. fx.params[ef::rhythmDecay] = 0.25f;
  18190. fx.params[ef::rhythmTap1 + 2] = 0.45f;
  18191. fx.params[ef::feedback] = 0.25f;
  18192. fx.params[ef::era] = 0.5f;
  18193. for (const auto& [param, value] : ef::rhythmPresetEdits (0)) // round 144: a pattern in the rhythm editor (Grid)
  18194. fx.params[(std::size_t) param] = value;
  18195. fx.params[ef::rhythmShape] = 0.5f; // swell
  18196. lynx::Song song;
  18197. song.mixer.resize (2);
  18198. song.mixer[0].name = "Master";
  18199. song.mixer[1].name = "Insert 1";
  18200. song.mixer[1].effects.push_back (fx);
  18201. offline.setSong (std::move (song));
  18202. offline.dispatchPendingMessages();
  18203. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
  18204. auto image = lynx::shot::paint (*editor, lynx::theme::panel);
  18205. const auto file = lynx::shot::file (out.getChildFile ("Echoform-rhythm.png"));
  18206. file.deleteFile();
  18207. juce::PNGImageFormat png;
  18208. if (auto stream = file.createOutputStream())
  18209. png.writeImageToStream (image, *stream);
  18210. }
  18211. // round 150: Echoform with a voicing (the Stereo / L/R offset controls on the Rhythm row)
  18212. {
  18213. namespace ef = lynx::echosuite::echoform;
  18214. auto fx = lynx::makeEffectSlot (lynx::EffectKind::echoform);
  18215. fx.params[ef::voicing] = ef::voicingValue (ef::voicingForEchoBoyStyle (19));
  18216. fx.params[ef::style] = ef::styleValue (ef::Style::dual);
  18217. lynx::Song song;
  18218. song.mixer.resize (2);
  18219. song.mixer[0].name = "Master";
  18220. song.mixer[1].name = "Insert 1";
  18221. song.mixer[1].effects.push_back (fx);
  18222. offline.setSong (std::move (song));
  18223. offline.dispatchPendingMessages();
  18224. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
  18225. auto image = lynx::shot::paint (*editor, lynx::theme::panel);
  18226. const auto file = lynx::shot::file (out.getChildFile ("Echoform-voicing.png"));
  18227. file.deleteFile();
  18228. juce::PNGImageFormat png;
  18229. if (auto stream = file.createOutputStream())
  18230. png.writeImageToStream (image, *stream);
  18231. }
  18232. // round 150: Auto-pan's Rhythm voicing with its Tweak row (PanMan's role)
  18233. {
  18234. auto fx = lynx::makeEffectSlot (lynx::EffectKind::autoPan);
  18235. fx.params[lynx::autopan::count] = 1.0f; // the Rhythm voicing
  18236. fx.params[lynx::autopan::count + 13] = 0.75f; // offset mod +90°
  18237. lynx::Song song;
  18238. song.mixer.resize (2);
  18239. song.mixer[0].name = "Master";
  18240. song.mixer[1].name = "Insert 1";
  18241. song.mixer[1].effects.push_back (fx);
  18242. offline.setSong (std::move (song));
  18243. offline.dispatchPendingMessages();
  18244. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
  18245. auto image = lynx::shot::paint (*editor, lynx::theme::panel);
  18246. const auto file = lynx::shot::file (out.getChildFile ("Auto-pan-tweak.png"));
  18247. file.deleteFile();
  18248. juce::PNGImageFormat png;
  18249. if (auto stream = file.createOutputStream())
  18250. png.writeImageToStream (image, *stream);
  18251. }
  18252. // round 165: Ember's Classic voicing (the Decapitator role) in its one-screen panel
  18253. {
  18254. namespace em = lynx::mixsuite::ember;
  18255. auto fx = lynx::makeEffectSlot (lynx::EffectKind::ember);
  18256. fx.params[em::voicing] = 1.0f;
  18257. fx.params[em::classicDrive] = 0.35f;
  18258. lynx::Song song;
  18259. song.mixer.resize (2);
  18260. song.mixer[0].name = "Master";
  18261. song.mixer[1].name = "Insert 1";
  18262. song.mixer[1].effects.push_back (fx);
  18263. offline.setSong (std::move (song));
  18264. offline.dispatchPendingMessages();
  18265. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
  18266. auto image = lynx::shot::paint (*editor, lynx::theme::panel);
  18267. const auto file = lynx::shot::file (out.getChildFile ("Ember Saturator-classic.png"));
  18268. file.deleteFile();
  18269. juce::PNGImageFormat png;
  18270. if (auto stream = file.createOutputStream())
  18271. png.writeImageToStream (image, *stream);
  18272. }
  18273. // round 152: Foil Plate's one-knob Plate view (the Little Plate role)
  18274. {
  18275. auto fx = lynx::makeEffectSlot (lynx::EffectKind::foilPlate);
  18276. fx.params[14] = 1.0f; // the measured plate voicing
  18277. fx.params[15] = 1.0f; // View = Plate
  18278. lynx::Song song;
  18279. song.mixer.resize (2);
  18280. song.mixer[0].name = "Master";
  18281. song.mixer[1].name = "Insert 1";
  18282. song.mixer[1].effects.push_back (fx);
  18283. offline.setSong (std::move (song));
  18284. offline.dispatchPendingMessages();
  18285. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
  18286. auto image = lynx::shot::paint (*editor, lynx::theme::panel);
  18287. const auto file = lynx::shot::file (out.getChildFile ("Foil Plate-plate.png"));
  18288. file.deleteFile();
  18289. juce::PNGImageFormat png;
  18290. if (auto stream = file.createOutputStream())
  18291. png.writeImageToStream (image, *stream);
  18292. }
  18293. // LYNX's own editors with live displays (round 103): Facet EQ (a mixing curve, one dynamic band, demo analyser)
  18294. // and LYNX Tune (demo pitch phrase)
  18295. {
  18296. lynx::setNativeEditorDemo (true);
  18297. using namespace lynx::facet;
  18298. auto eq = lynx::makeEffectSlot (lynx::EffectKind::facetEq);
  18299. const struct { Shape s; double f, g, q; int slope; double range; } bandsDemo[] = {
  18300. { Shape::lowCut, 32, 0, 1, 24, 0 }, { Shape::bell, 110, 3, 1.2, 12, 0 }, { Shape::bell, 380, -3.5, 1.6, 12, 0 },
  18301. { Shape::bell, 3200, 0, 2.5, 12, -6 }, { Shape::highShelf, 9000, 2.5, 0.8, 12, 0 }
  18302. };
  18303. for (int b = 0; b < 5; ++b)
  18304. {
  18305. eq.params[(std::size_t) param (b, 0)] = shapeValue (bandsDemo[b].s);
  18306. eq.params[(std::size_t) param (b, 1)] = hzValue (bandsDemo[b].f);
  18307. eq.params[(std::size_t) param (b, 2)] = gainValue (bandsDemo[b].g);
  18308. eq.params[(std::size_t) param (b, 3)] = qValue (bandsDemo[b].q);
  18309. eq.params[(std::size_t) param (b, 4)] = slopeValue (bandsDemo[b].slope);
  18310. eq.params[(std::size_t) (rangeParam0 + b)] = rangeValue (bandsDemo[b].range);
  18311. }
  18312. eq.params[(std::size_t) phaseParam] = phaseValue (Phase::natural);
  18313. const auto own = [&] (const lynx::EffectSlot& fx, const juce::String& file, bool facetEditor, int page = 0) {
  18314. lynx::Song song;
  18315. song.mixer.resize (2);
  18316. song.mixer[0].name = "Master";
  18317. song.mixer[1].name = "Vocal";
  18318. song.mixer[1].effects.push_back (fx);
  18319. offline.setSong (std::move (song));
  18320. offline.dispatchPendingMessages();
  18321. auto editor = facetEditor ? lynx::makeFacetEqEditor (offline, 1, 0, true) : lynx::makeNativeEffectEditor (offline, 1, 0, 1.25f, page);
  18322. auto image = lynx::shot::paint (*editor, lynx::theme::panel);
  18323. const auto f = lynx::shot::file (out.getChildFile (file));
  18324. f.deleteFile();
  18325. juce::PNGImageFormat png;
  18326. if (auto stream = f.createOutputStream())
  18327. png.writeImageToStream (image, *stream);
  18328. };
  18329. own (eq, "Facet EQ.png", true);
  18330. own (lynx::makeEffectSlot (lynx::EffectKind::lynxTune), "LYNX Tune.png", false);
  18331. {
  18332. // round 128: the ADVANCED page, with E bypassed and A removed on the keyboard and a created vibrato
  18333. auto tune = lynx::makeEffectSlot (lynx::EffectKind::lynxTune);
  18334. tune.params[(std::size_t) (lynx::lynxtune::bypassC + 4)] = 1.0f;
  18335. tune.params[(std::size_t) (lynx::lynxtune::noteC + 9)] = 0.0f;
  18336. tune.params[lynx::lynxtune::vibratoShape] = 1.0f / 3.0f;
  18337. // round 166c: the created vibrato's amplitude / formant / variation, a short throat, In scale +2
  18338. tune.params[lynx::lynxtune::vibratoAmplitude] = 1.0f / 3.0f;
  18339. tune.params[lynx::lynxtune::vibratoFormant] = 0.7f;
  18340. tune.params[lynx::lynxtune::vibratoVariation] = 0.2f;
  18341. tune.params[lynx::lynxtune::throatLength] = lynx::lynxtune::throatValue (80.0);
  18342. tune.params[lynx::lynxtune::transposeInScale] = 1.0f;
  18343. tune.params[lynx::lynxtune::scaleTranspose] = lynx::lynxtune::scaleTransposeValue (2);
  18344. own (tune, "LYNX Tune-p2.png", false, 1);
  18345. }
  18346. own (lynx::makeEffectSlot (lynx::EffectKind::lynxTune), "LYNX Tune-p3.png", false, 2); // round 135w: Real-time
  18347. lynx::setNativeEditorDemo (false);
  18348. }
  18349. // generators in FL's arrangement: the channel's plugin page with the FL preset's settings
  18350. const auto generators = juce::File (juce::String::fromUTF8 (roots.data.c_str())).getChildFile ("Patches/Plugin presets/Generators");
  18351. 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" } })
  18352. {
  18353. juce::MemoryBlock data;
  18354. if (juce::String (folder) == "Harmor") // the first preset whose state the engine reads
  18355. {
  18356. auto files = generators.getChildFile (folder).findChildFiles (juce::File::findFiles, true, "*.fst");
  18357. files.sort();
  18358. for (const auto& f : files)
  18359. {
  18360. juce::MemoryBlock block;
  18361. if (! f.loadFileAsData (block))
  18362. continue;
  18363. const auto* b = static_cast<const std::uint8_t*> (block.getData());
  18364. try
  18365. {
  18366. const auto p = flp::parseProject (std::vector<std::uint8_t> (b, b + block.getSize()), true);
  18367. if (! p.channels.empty() && lynx::harmorStateUsable (p.channels.front().pluginState))
  18368. {
  18369. preset = nullptr;
  18370. data = block;
  18371. break;
  18372. }
  18373. }
  18374. catch (const std::exception&)
  18375. {
  18376. }
  18377. }
  18378. }
  18379. auto file = preset == nullptr ? juce::File() : juce::String (preset).isEmpty() ? database.getSiblingFile ("Generators").getChildFile ("Misc").getChildFile (juce::String (folder) + ".fst")
  18380. : generators.getChildFile (folder).getChildFile (preset);
  18381. if (! file.existsAsFile())
  18382. {
  18383. auto files = generators.getChildFile (folder).findChildFiles (juce::File::findFiles, true, "*.fst");
  18384. files.sort();
  18385. file = files.isEmpty() ? juce::File() : files[0];
  18386. }
  18387. if (data.isEmpty() && ! file.loadFileAsData (data))
  18388. continue;
  18389. try
  18390. {
  18391. const auto* bytes = static_cast<const std::uint8_t*> (data.getData());
  18392. auto project = flp::parseProject (std::vector<std::uint8_t> (bytes, bytes + data.getSize()), true);
  18393. if (project.channels.empty())
  18394. continue;
  18395. project.channels.front().type = flp::ChannelType::native;
  18396. lynx::FlpImportOptions options;
  18397. options.roots = roots;
  18398. options.fileExists = [] (const std::string& path) { return lynx::platform::localFile (path).existsAsFile(); };
  18399. options.readFile = [] (const std::string& path) {
  18400. juce::MemoryBlock block;
  18401. lynx::platform::localFile (path).loadFileAsData (block);
  18402. const auto* b = static_cast<const std::uint8_t*> (block.getData());
  18403. return std::vector<std::uint8_t> (b, b + block.getSize());
  18404. };
  18405. options.saveEmbedded = [out] (const std::vector<std::uint8_t>& wav, const std::string& name) {
  18406. const auto f = out.getChildFile ("samples").getNonexistentChildFile (juce::String::fromUTF8 (name.c_str()), ".wav");
  18407. f.getParentDirectory().createDirectory();
  18408. f.replaceWithData (wav.data(), wav.size());
  18409. return f.getFullPathName().toStdString();
  18410. };
  18411. auto song = lynx::importFlp (project, options);
  18412. // the page only needs the plugin's saved state (FL Keys' sample zones need the installed wavetables)
  18413. if (! song.channels.empty() && project.channels.front().pluginName == "BooBass" && song.channels.front().instrument != lynx::InstrumentKind::boobass)
  18414. {
  18415. song.channels.front().instrument = lynx::InstrumentKind::boobass; // (its sound needs the engine DLL; the page does not)
  18416. song.channels.front().modelParams.assign (3, 32768.0f);
  18417. }
  18418. if (! song.channels.empty() && project.channels.front().pluginName == "FL Keys")
  18419. {
  18420. song.channels.front().instrument = lynx::InstrumentKind::flkeys;
  18421. song.channels.front().pluginState = project.channels.front().pluginState;
  18422. }
  18423. offline.setSong (std::move (song));
  18424. offline.dispatchPendingMessages();
  18425. if (offline.getSong().channels.empty())
  18426. continue;
  18427. auto panel = lynx::makeChannelSettingsPanel (offline, 0);
  18428. auto image = lynx::shot::paint (*panel, lynx::theme::panel);
  18429. const auto out2 = lynx::shot::file (out.getChildFile (juce::String (folder) + ".png"));
  18430. out2.deleteFile();
  18431. juce::PNGImageFormat png;
  18432. if (auto stream = out2.createOutputStream())
  18433. png.writeImageToStream (image, *stream);
  18434. }
  18435. catch (const std::exception&)
  18436. {
  18437. }
  18438. }
  18439. }
  18440. quit();
  18441. }
  18442. void runVideoShot (const juce::String& prefix, const juce::String& videoPath)
  18443. {
  18444. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  18445. // the message loop runs while the frames decode (modal loops are off): a timer takes one snapshot per step
  18446. struct VideoShot final : juce::Timer
  18447. {
  18448. lynx::AudioEngine offline { false };
  18449. std::unique_ptr<juce::Component> editor;
  18450. juce::String prefix, report;
  18451. int step = 0;
  18452. std::function<void()> done;
  18453. void moveTo (double seconds)
  18454. {
  18455. offline.getTransport().positionTicks.store (seconds * offline.getSong().bpm / 60.0 * lynx::ppq);
  18456. }
  18457. void timerCallback() override
  18458. {
  18459. static constexpr double times[] = { 0.0, 1.5, 3.25 };
  18460. constexpr int typeInStep = (int) std::size (times) + 1;
  18461. if (step > 0 && step < typeInStep && editor != nullptr)
  18462. savePng (lynx::shot::snapshot (*editor), prefix + "-" + juce::String (step - 1) + ".png");
  18463. if (editor != nullptr && step == (int) std::size (times))
  18464. {
  18465. // round 174d: FL's in-place type-in of the current time (a right click on it)
  18466. lynx::videoview::openTypeIn (*editor, 2);
  18467. ++step;
  18468. return;
  18469. }
  18470. if (editor != nullptr && step == typeInStep)
  18471. savePng (lynx::shot::snapshot (*editor), prefix + "-typein.png");
  18472. if (editor == nullptr || step >= typeInStep)
  18473. {
  18474. stopTimer();
  18475. juce::File (prefix + "-report.txt").replaceWithText (report);
  18476. if (done)
  18477. done();
  18478. return;
  18479. }
  18480. moveTo (times[step++]);
  18481. }
  18482. };
  18483. static std::unique_ptr<VideoShot> shot;
  18484. shot = std::make_unique<VideoShot>();
  18485. shot->prefix = prefix;
  18486. auto& offline = shot->offline;
  18487. lynx::videoview::install (offline);
  18488. lynx::Song song;
  18489. song.mixer = lynx::Song::defaultMixer (2);
  18490. lynx::ChannelDef c;
  18491. c.name = "Fruity Video Player";
  18492. c.instrument = lynx::InstrumentKind::videoplayer;
  18493. lynx::video::Settings vs;
  18494. vs.path = juce::File (videoPath).getFullPathName().toStdString();
  18495. vs.delay = lynx::video::unitsPerSecond / 2; // the video starts at 0.5 s
  18496. c.pluginState = lynx::video::write (vs);
  18497. song.channels.push_back (c);
  18498. song.patterns.emplace_back();
  18499. {
  18500. // round 174d (A3): the same Video Player in a song whose tempo drops from 120 to 60 BPM at bar 5, for FL
  18501. // (LYNX.exe --export-flp <prefix>-tempo.lynx <prefix>-tempo.flp), to compare FL's video clock with LYNX's
  18502. auto fl = song;
  18503. fl.bpm = 120.0;
  18504. fl.mode = lynx::PlayMode::song;
  18505. auto settings = vs;
  18506. settings.delay = 0;
  18507. settings.timeDisplay = lynx::video::Settings {}.timeDisplay;
  18508. fl.channels[0].pluginState = lynx::video::write (settings);
  18509. fl.patterns[0].name = "Pattern 1";
  18510. lynx::Automation tempo;
  18511. tempo.name = "Tempo";
  18512. tempo.target = { lynx::AutomationTargetKind::tempo, 0, 0, 0 };
  18513. const auto bar = (std::int64_t) lynx::ppq * 4;
  18514. tempo.points = { { 0, lynx::valueFromTempo (120.0), 0.0f }, { bar * 4 - 1, lynx::valueFromTempo (120.0), 0.0f },
  18515. { bar * 4, lynx::valueFromTempo (60.0), 0.0f }, { bar * 8, lynx::valueFromTempo (60.0), 0.0f } };
  18516. fl.automations.push_back (tempo);
  18517. lynx::Clip at;
  18518. at.kind = lynx::ClipKind::automation;
  18519. at.automation = 0;
  18520. at.track = 1;
  18521. at.start = 0;
  18522. at.length = bar * 8;
  18523. fl.playlist.push_back (at);
  18524. lynx::Clip pc;
  18525. pc.pattern = 0;
  18526. pc.track = 0;
  18527. pc.start = 0;
  18528. pc.length = bar * 8;
  18529. fl.playlist.push_back (pc);
  18530. juce::String error;
  18531. lynx::ProjectFile::save (fl, juce::File (prefix + "-tempo.lynx"), error);
  18532. }
  18533. offline.setSong (std::move (song));
  18534. offline.dispatchPendingMessages();
  18535. auto& report = shot->report;
  18536. report << "ffmpeg: " << lynx::findFfmpeg().getFullPathName() << "\n";
  18537. report << lynx::videoview::report (vs.path).fromFirstOccurrenceOf ("Input #0", true, false).upToFirstOccurrenceOf ("At least", false, false) << "\n";
  18538. shot->editor = lynx::makeChannelSettingsPanel (offline, 0);
  18539. if (shot->editor != nullptr)
  18540. shot->editor->setVisible (true);
  18541. shot->done = [this] { juce::MessageManager::callAsync ([this] { shot.reset(); quit(); }); };
  18542. shot->startTimer (1500);
  18543. }
  18544. void runVideoTrackShot (const juce::String& prefix, const juce::String& videoPath, const juce::String& secondPath)
  18545. {
  18546. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  18547. struct TrackShot final : juce::Timer
  18548. {
  18549. lynx::AudioEngine offline { false };
  18550. std::unique_ptr<lynx::PlaylistComponent> playlist;
  18551. std::unique_ptr<lynx::media::FrameDecoder> decoder;
  18552. juce::String prefix, report, path;
  18553. double fps = 25.0;
  18554. int step = 0, waits = 0, adrStep = 0;
  18555. std::unique_ptr<juce::Component> adrPanel;
  18556. std::function<void()> done;
  18557. // song times (s): before, inside the first clip (on and between frame edges), across the second clip
  18558. std::vector<double> times { 0.0, 1.0, 2.0 + 1.0 / 25.0, 2.5, 4.0, 7.3 };
  18559. void timerCallback() override
  18560. {
  18561. if (step > 0 && adrStep == 0)
  18562. {
  18563. // the frame the decoder shows for the wanted file time (the clip starts at song 1.0 s, offset 0)
  18564. const auto want = times[(std::size_t) step - 1] - 1.0;
  18565. double ft = -1.0;
  18566. const auto img = decoder->frame (ft);
  18567. const auto expected = std::floor (want * fps + 1e-6) / fps;
  18568. if (want >= 0.0 && ft < expected - 1e-3 && ++waits < 20)
  18569. return; // (still decoding)
  18570. waits = 0;
  18571. report << "song " << juce::String (times[(std::size_t) step - 1], 3) << " s: wanted file time " << juce::String (want, 4)
  18572. << ", frame shown at " << juce::String (ft, 4) << " (expected " << juce::String (expected, 4) << ")"
  18573. << (want < 0.0 ? " [before the clip]" : std::abs (ft - expected) < 1e-3 ? " OK" : " MISMATCH") << "\n";
  18574. savePng (lynx::shot::snapshot (*playlist), prefix + "-playlist-" + juce::String (step - 1) + ".png");
  18575. if (img.isValid())
  18576. savePng (img, prefix + "-frame-" + juce::String (step - 1) + ".png");
  18577. for (int w = 0; w < juce::Desktop::getInstance().getNumComponents(); ++w)
  18578. if (auto* c = juce::Desktop::getInstance().getComponent (w); c != nullptr && c->getName().startsWith ("Picture"))
  18579. savePng (lynx::shot::snapshot (*c), prefix + "-window-" + juce::String (step - 1) + ".png");
  18580. }
  18581. if (step >= (int) times.size() && adrStep == 0)
  18582. {
  18583. // the ADR window: two cues, takes on the first; the play position inside the streamer before the in
  18584. // point (4.0 s), so the video window shows the streamer and the line
  18585. adrStep = 1;
  18586. offline.editSong ([] (lynx::Song& s) {
  18587. lynx::AdrCue a, b;
  18588. a.id = "SC1-01";
  18589. a.in = 4.0;
  18590. a.out = 6.4;
  18591. a.character = "Dr. Silva";
  18592. a.line = "We have to leave before the storm reaches the coast.";
  18593. a.notes = "softer, out of breath";
  18594. a.status = lynx::AdrCue::Status::recorded;
  18595. for (int n = 1; n <= 3; ++n)
  18596. {
  18597. lynx::AdrTake t;
  18598. t.number = n;
  18599. t.name = lynx::adr::takeName (a, n);
  18600. t.rating = n == 2 ? 4 : n;
  18601. t.circled = n == 2;
  18602. a.takes.push_back (t);
  18603. }
  18604. a.selected = 2;
  18605. lynx::adr::setCompRange (a, 4.0, 5.1, 2);
  18606. lynx::adr::setCompRange (a, 5.1, 6.4, 3);
  18607. b.id = "SC1-02";
  18608. b.in = 8.0;
  18609. b.out = 9.5;
  18610. b.character = "Marta";
  18611. b.line = "Then we go now.";
  18612. s.adr.cues = { a, b };
  18613. s.adr.current = 0;
  18614. });
  18615. adrPanel = lynx::adrwindow::makePanel (offline);
  18616. adrPanel->setSize (1200, 640);
  18617. adrPanel->setVisible (true);
  18618. offline.getTransport().positionTicks.store (3.0 * offline.getSong().bpm / 60.0 * lynx::ppq);
  18619. decoder->request (2.0, false);
  18620. return;
  18621. }
  18622. if (adrStep == 1)
  18623. {
  18624. adrStep = 2;
  18625. savePng (lynx::shot::snapshot (*adrPanel), prefix + "-adr.png");
  18626. for (int w = 0; w < juce::Desktop::getInstance().getNumComponents(); ++w)
  18627. if (auto* c = juce::Desktop::getInstance().getComponent (w); c != nullptr && c->getName().startsWith ("Picture"))
  18628. savePng (lynx::shot::snapshot (*c), prefix + "-adr-window.png");
  18629. offline.getTransport().positionTicks.store (4.5 * offline.getSong().bpm / 60.0 * lynx::ppq);
  18630. decoder->request (3.5, false);
  18631. return;
  18632. }
  18633. if (adrStep == 2)
  18634. {
  18635. for (int w = 0; w < juce::Desktop::getInstance().getNumComponents(); ++w)
  18636. if (auto* c = juce::Desktop::getInstance().getComponent (w); c != nullptr && c->getName().startsWith ("Picture"))
  18637. savePng (lynx::shot::snapshot (*c), prefix + "-adr-window-line.png");
  18638. adrPanel.reset();
  18639. // export with video: a 3 s mix under the picture, re-encoded (the clip starts at 1 s) and copied (from 1 s)
  18640. {
  18641. const juce::File wav (prefix + "-mix.wav");
  18642. wav.deleteFile();
  18643. juce::WavAudioFormat format;
  18644. if (std::unique_ptr<juce::OutputStream> os (wav.createOutputStream().release()); os != nullptr)
  18645. if (std::unique_ptr<juce::AudioFormatWriter> w (format.createWriterFor (os.get(), 48000.0, 2, 16, {}, 0)); w != nullptr)
  18646. {
  18647. os.release();
  18648. juce::AudioBuffer<float> b (2, 48000 * 3);
  18649. for (int k = 0; k < b.getNumSamples(); ++k)
  18650. 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));
  18651. w->writeFromAudioSampleBuffer (b, 0, b.getNumSamples());
  18652. }
  18653. for (const auto origin : { 0.0, 1.0 })
  18654. {
  18655. const juce::File out (prefix + "-mux-" + juce::String ((int) origin) + ".mp4");
  18656. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  18657. const auto error = lynx::videotracks::muxWithVideo (offline.getSong(), origin, wav, out);
  18658. report << "export with video from " << origin << " s: " << (error.isEmpty() ? "OK " + juce::String (out.getSize()) + " bytes" : "FAILED " + error)
  18659. << " (" << juce::String ((juce::Time::getMillisecondCounterHiRes() - t0) / 1000.0, 2) << " s)\n";
  18660. }
  18661. }
  18662. stopTimer();
  18663. report << "frames decoded " << decoder->frameCount() << ", dropped " << decoder->droppedCount() << "\n";
  18664. juce::File (prefix + "-report.txt").replaceWithText (report);
  18665. if (done)
  18666. done();
  18667. return;
  18668. }
  18669. const auto t = times[(std::size_t) step++];
  18670. offline.getTransport().positionTicks.store (t * offline.getSong().bpm / 60.0 * lynx::ppq);
  18671. decoder->request (std::max (0.0, t - 1.0), false);
  18672. }
  18673. };
  18674. static std::unique_ptr<TrackShot> shot;
  18675. shot = std::make_unique<TrackShot>();
  18676. shot->prefix = prefix;
  18677. auto& offline = shot->offline;
  18678. lynx::Song song;
  18679. song.mixer = lynx::Song::defaultMixer (2);
  18680. song.patterns.emplace_back();
  18681. song.mode = lynx::PlayMode::song;
  18682. song.bpm = 120.0;
  18683. offline.setSong (std::move (song));
  18684. offline.dispatchPendingMessages();
  18685. const juce::File video (videoPath);
  18686. const auto pr = lynx::media::probe (video.getFullPathName());
  18687. auto& report = shot->report;
  18688. report << "decoder: " << (pr.backend.isEmpty() ? juce::String ("none") : pr.backend) << " (system: " << lynx::media::nativeBackendName()
  18689. << ", ffmpeg: " << lynx::findFfmpeg().getFullPathName() << ")\n";
  18690. report << "video: " << pr.info.width << "x" << pr.info.height << " " << juce::String (pr.info.fps, 3) << " fps " << juce::String (pr.info.duration, 3)
  18691. << " s, sound " << (pr.info.hasAudio ? "yes" : "no") << "\n";
  18692. shot->fps = pr.info.fps > 1.0 ? pr.info.fps : 25.0;
  18693. shot->times[2] = 2.0 + 1.0 / shot->fps; // (exactly on a frame edge)
  18694. lynx::videotracks::importVideo (offline, video, 1.0, -1);
  18695. if (secondPath.isNotEmpty())
  18696. lynx::videotracks::importVideo (offline, juce::File (secondPath), 3.0, 1);
  18697. offline.editSong ([] (lynx::Song& s) {
  18698. s.video.startTimecode = 3600.0;
  18699. s.video.burnIn = true;
  18700. if (s.videoTracks.size() < 2)
  18701. s.videoTracks.push_back ({});
  18702. s.videoTracks[0].name = "Picture";
  18703. s.videoTracks[1].name = "Reference";
  18704. });
  18705. report << "project rate: " << lynx::vtime::rateName (offline.getSong().video.rate) << ", clip 1: "
  18706. << juce::String (offline.getSong().videoTracks[0].clips.empty() ? -1.0 : offline.getSong().videoTracks[0].clips[0].length, 3) << " s\n";
  18707. // the project round trip
  18708. {
  18709. const juce::File file (prefix + "-project.lynx");
  18710. juce::String error;
  18711. lynx::ProjectFile::save (offline.getSong(), file, error);
  18712. const auto back = lynx::ProjectFile::load (file, error);
  18713. report << "project file round trip: " << (back && back->videoTracks == offline.getSong().videoTracks && back->video == offline.getSong().video ? "OK" : "MISMATCH " + error) << "\n";
  18714. }
  18715. shot->playlist = std::make_unique<lynx::PlaylistComponent> (offline);
  18716. shot->playlist->setSize (1400, 640);
  18717. shot->playlist->setVisible (true);
  18718. shot->decoder = std::make_unique<lynx::media::FrameDecoder>();
  18719. shot->decoder->setSource (video.getFullPathName(), pr.info);
  18720. shot->decoder->setSize (pr.info.width, pr.info.height);
  18721. shot->decoder->startThread (juce::Thread::Priority::low);
  18722. lynx::videotracks::showWindow (offline, 0);
  18723. shot->done = [this] { juce::MessageManager::callAsync ([this] { shot.reset(); quit(); }); };
  18724. shot->startTimer (700);
  18725. }
  18726. void runDanceShot (const juce::String& prefix)
  18727. {
  18728. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  18729. // the moves: one row each, eight moments of a cycle (both facings for Spinning; Pose ends the sheet)
  18730. {
  18731. constexpr int cell = 120, cols = 8;
  18732. auto sheet = lynx::shot::canvas (130 + cols * cell, lynx::dance::moveCount * cell + 10);
  18733. {
  18734. // (the picture is complete when its Graphics is gone: round 190ba, the file was blank on Windows)
  18735. juce::Graphics g (sheet);
  18736. lynx::shot::logical (g);
  18737. g.fillAll (lynx::theme::colour::bg0);
  18738. for (int m = 0; m < lynx::dance::moveCount; ++m)
  18739. {
  18740. g.setColour (lynx::theme::colour::textSecondary);
  18741. g.setFont (14.0f);
  18742. g.drawText (lynx::dance::moveName (m), 8, m * cell + 5, 118, cell, juce::Justification::centredLeft);
  18743. for (int k = 0; k < cols; ++k)
  18744. {
  18745. const auto pose = lynx::dance::pose (m, k / (double) cols + (m == lynx::dance::freestyle ? k * 2 : 0), 1);
  18746. lynx::dancer::draw (g, { 130.0f + (k + 0.5f) * cell, (float) (m + 1) * cell - 6.0f }, 92.0f, pose, false, juce::Colour (0xffff3048));
  18747. }
  18748. }
  18749. }
  18750. savePng (sheet, prefix + "-moves.png");
  18751. }
  18752. lynx::AudioEngine offline (false);
  18753. lynx::Song song;
  18754. song.mixer = lynx::Song::defaultMixer (2);
  18755. for (int d = 0; d < 2; ++d)
  18756. {
  18757. lynx::ChannelDef c;
  18758. c.name = d == 0 ? "Fruity Dance" : "Fruity Dance #2";
  18759. c.instrument = lynx::InstrumentKind::fruitydance;
  18760. lynx::dance::Settings s;
  18761. s.move = d == 0 ? lynx::dance::stepping : lynx::dance::waving;
  18762. s.x = d == 0 ? 520 : 760;
  18763. s.y = 560;
  18764. s.colour = d == 0 ? 0xffff3048 : 0xff30a8ff;
  18765. s.mirrored = d == 1;
  18766. c.pluginState = lynx::dance::toState (s);
  18767. song.channels.push_back (c);
  18768. }
  18769. // Issue #121 (round 190ba): a sprite sheet in FL's Fruity Dance format (8 frames across, a row per move, a names
  18770. // file beside it), made here from LYNX's own poses, loaded back as a user's sheet would be
  18771. juce::String sheetReport;
  18772. {
  18773. constexpr int fw = 120, fh = 150;
  18774. const std::vector<std::pair<const char*, int>> rows { { "Idle", lynx::dance::waiting }, { "Step", lynx::dance::stepping },
  18775. { "Jump", lynx::dance::jumping }, { "Wave", lynx::dance::waving },
  18776. { "Windmill", lynx::dance::windmill }, { "Held", lynx::dance::held } };
  18777. juce::Image sheet (juce::Image::ARGB, fw * lynx::dance::sheetColumns, fh * (int) rows.size(), true);
  18778. {
  18779. juce::Graphics g (sheet);
  18780. for (int r = 0; r < (int) rows.size(); ++r)
  18781. for (int k = 0; k < lynx::dance::sheetColumns; ++k)
  18782. {
  18783. juce::Graphics::ScopedSaveState save (g);
  18784. g.reduceClipRegion (k * fw, r * fh, fw, fh);
  18785. lynx::dancer::draw (g, { (k + 0.5f) * fw, (float) (r + 1) * fh - 8.0f }, 96.0f,
  18786. lynx::dance::pose (rows[(std::size_t) r].second, k / (double) lynx::dance::sheetColumns, 1), false, juce::Colour (0xff35c46a));
  18787. }
  18788. }
  18789. const juce::File picture (prefix + "-sheet.png");
  18790. savePng (sheet, picture.getFullPathName());
  18791. juce::String names;
  18792. for (const auto& [name, move] : rows)
  18793. names << (names.isEmpty() ? "" : "\r\n") << name;
  18794. picture.withFileExtension ("txt").replaceWithText (names, false, false, nullptr);
  18795. // a picture that is not a whole number of frames: FL's "Bitmap size is incorrect."
  18796. const juce::File wrong (prefix + "-sheet-wrong.png");
  18797. savePng (sheet.getClippedImage ({ 0, 0, sheet.getWidth() - 3, sheet.getHeight() }), wrong.getFullPathName());
  18798. wrong.withFileExtension ("txt").replaceWithText (names, false, false, nullptr);
  18799. auto error = lynx::dancer::SheetError::none;
  18800. const auto loaded = lynx::dancer::sheetFor (picture.getFullPathName().toStdString(), &error);
  18801. auto wrongError = lynx::dancer::SheetError::none;
  18802. const auto refused = lynx::dancer::sheetFor (wrong.getFullPathName().toStdString(), &wrongError);
  18803. auto missingError = lynx::dancer::SheetError::none;
  18804. const auto missing = lynx::dancer::sheetFor (juce::File (prefix + "-sheet-none.png").getFullPathName().toStdString(), &missingError);
  18805. sheetReport << "sheet_loaded=" << (loaded != nullptr ? 1 : 0) << "\n"
  18806. << "sheet_wrong_size_refused=" << (refused == nullptr && wrongError == lynx::dancer::SheetError::size ? 1 : 0) << "\n"
  18807. << "sheet_missing_refused=" << (missing == nullptr && missingError == lynx::dancer::SheetError::missing ? 1 : 0) << "\n";
  18808. bool ok = loaded != nullptr && refused == nullptr && missing == nullptr;
  18809. if (loaded != nullptr)
  18810. {
  18811. sheetReport << "sheet_rows=" << loaded->layout.rows << "\nsheet_frame=" << loaded->layout.frameWidth << "x" << loaded->layout.frameHeight
  18812. << "\nsheet_moves=" << loaded->moves() << "\nsheet_names=";
  18813. for (const auto& n : loaded->names)
  18814. sheetReport << juce::String::fromUTF8 (n.c_str()) << ";";
  18815. sheetReport << "\n";
  18816. ok = ok && loaded->layout.rows == (int) rows.size() && loaded->layout.frameWidth == fw && loaded->layout.frameHeight == fh;
  18817. // the animation as the stage draws it: a row of moments of the move "Wave" (blending on), then mirrored,
  18818. // then the row shown while the dancer is held
  18819. auto strip = lynx::shot::canvas (fw * 12, fh * 3 + 20);
  18820. int solid = 0;
  18821. {
  18822. juce::Graphics g (strip);
  18823. lynx::shot::logical (g);
  18824. g.fillAll (lynx::theme::colour::bg0);
  18825. for (int line = 0; line < 3; ++line)
  18826. {
  18827. lynx::dance::SheetAnimator animator (3);
  18828. for (int k = 0; k < 12; ++k)
  18829. {
  18830. const auto frame = animator.advance (k / 12.0 + 0.001, loaded->layout.rows, 4, line == 1, true, 0.5f, line == 2);
  18831. const juce::Point<float> feet ((k + 0.5f) * fw, (float) (line + 1) * fh + 5.0f);
  18832. lynx::dancer::drawSheet (g, *loaded, feet, 1.0f, frame);
  18833. solid += lynx::dancer::sheetSolidAt (*loaded, feet, 1.0f, frame, feet.translated (0.0f, -70.0f)) ? 1 : 0;
  18834. ok = ok && ! lynx::dancer::sheetSolidAt (*loaded, feet, 1.0f, frame, feet.translated (-(float) fw * 0.5f + 1.0f, -(float) fh + 1.0f));
  18835. }
  18836. }
  18837. }
  18838. // mirrored = the same frame flipped left-right, on whatever renderer this build draws with
  18839. {
  18840. lynx::dance::SheetFrame plain;
  18841. plain.row = 3;
  18842. plain.column = 2;
  18843. auto turned = plain;
  18844. turned.mirrored = true;
  18845. juce::Image a (juce::Image::ARGB, fw, fh, true), b (juce::Image::ARGB, fw, fh, true);
  18846. {
  18847. juce::Graphics ga (a);
  18848. lynx::dancer::drawSheet (ga, *loaded, { fw * 0.5f, (float) fh }, 1.0f, plain);
  18849. }
  18850. {
  18851. juce::Graphics gb (b);
  18852. lynx::dancer::drawSheet (gb, *loaded, { fw * 0.5f, (float) fh }, 1.0f, turned);
  18853. }
  18854. int same = 0, flippedSame = 0, solidPixels = 0;
  18855. for (int y = 0; y < fh; ++y)
  18856. for (int x = 0; x < fw; ++x)
  18857. {
  18858. const auto pa = a.getPixelAt (x, y);
  18859. if (pa.getAlpha() < 200)
  18860. continue;
  18861. ++solidPixels;
  18862. auto alike = [pa] (juce::Colour c) {
  18863. return std::abs ((int) c.getRed() - (int) pa.getRed()) + std::abs ((int) c.getGreen() - (int) pa.getGreen())
  18864. + std::abs ((int) c.getBlue() - (int) pa.getBlue()) + std::abs ((int) c.getAlpha() - (int) pa.getAlpha()) < 12;
  18865. };
  18866. same += alike (b.getPixelAt (x, y)) ? 1 : 0;
  18867. flippedSame += alike (b.getPixelAt (fw - 1 - x, y)) ? 1 : 0;
  18868. }
  18869. const auto flips = solidPixels > 500 && flippedSame >= solidPixels * 98 / 100 && same < solidPixels * 95 / 100;
  18870. sheetReport << "sheet_mirror_flips=" << (flips ? 1 : 0) << " (" << flippedSame << " of " << solidPixels << " solid pixels match flipped, " << same
  18871. << " unflipped)\n";
  18872. ok = ok && flips;
  18873. }
  18874. sheetReport << "sheet_body_solid=" << solid << "/36\n";
  18875. ok = ok && solid >= 18;
  18876. savePng (strip, prefix + "-sheet-frames.png");
  18877. }
  18878. sheetReport << "sheet_result=" << (ok ? "OK" : "ERROR") << "\n";
  18879. lynx::ChannelDef c;
  18880. c.name = "Fruity Dance #3";
  18881. c.instrument = lynx::InstrumentKind::fruitydance;
  18882. lynx::dance::Settings s;
  18883. s.move = 2; // (the sheet's second row: "Step")
  18884. s.x = 1000;
  18885. s.y = 560;
  18886. s.sheet = picture.getFullPathName().toStdString();
  18887. c.pluginState = lynx::dance::toState (s);
  18888. song.channels.push_back (c);
  18889. }
  18890. song.patterns.emplace_back();
  18891. {
  18892. const juce::File demo (prefix + "-demo.lynx");
  18893. juce::String error;
  18894. lynx::ProjectFile::save (song, demo, error);
  18895. }
  18896. offline.setSong (std::move (song));
  18897. offline.dispatchPendingMessages();
  18898. if (auto editor = lynx::makeChannelSettingsPanel (offline, 0))
  18899. savePng (lynx::shot::snapshot (*editor), prefix + "-editor.png");
  18900. if (auto frame = lynx::makeChannelFrame (offline, 1, 0))
  18901. savePng (lynx::shot::snapshot (*frame), prefix + "-frame.png");
  18902. if (auto editor = lynx::makeChannelSettingsPanel (offline, 2))
  18903. savePng (lynx::shot::snapshot (*editor), prefix + "-sheet-editor.png");
  18904. {
  18905. // the stage with the three dancers (the third from the sheet)
  18906. lynx::DanceStage stage (offline);
  18907. stage.setSize (1280, 640);
  18908. stage.update();
  18909. sheetReport << "stage_dancers=" << stage.dancerCount() << "\n";
  18910. auto picture = lynx::shot::canvas (1280, 640);
  18911. {
  18912. juce::Graphics g (picture);
  18913. lynx::shot::logical (g);
  18914. g.fillAll (lynx::theme::colour::bg0);
  18915. stage.paintEntireComponent (g, true);
  18916. }
  18917. savePng (picture, prefix + "-sheet-stage.png");
  18918. }
  18919. juce::File (prefix + "-sheetreport.txt").replaceWithText (sheetReport);
  18920. }
  18921. void runControllerShot (const juce::String& prefix)
  18922. {
  18923. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  18924. lynx::AudioEngine offline (false);
  18925. lynx::Song song;
  18926. song.mixer = lynx::Song::defaultMixer (2);
  18927. song.mixer[1].name = "Insert 1";
  18928. auto fx = lynx::makeEffectSlot (lynx::EffectKind::formulaController);
  18929. lynx::formula::State formula;
  18930. formula.formula = "a*Sin(SongTime*Pi*b*4)+c";
  18931. fx.state = lynx::formula::writeState (formula);
  18932. fx.params[0] = 0.5f;
  18933. fx.params[1] = 0.25f;
  18934. fx.params[2] = 0.5f;
  18935. song.mixer[1].effects.push_back (fx);
  18936. // round 164: X-Y (slot 2), X-Y-Z (slot 3) and a Control Surface (slot 4)
  18937. {
  18938. auto xyFx = lynx::makeEffectSlot (lynx::EffectKind::xyController);
  18939. xyFx.params[(std::size_t) lynx::xy::level (0)] = 0.3f;
  18940. xyFx.params[(std::size_t) lynx::xy::level (1)] = 0.7f;
  18941. xyFx.params[(std::size_t) lynx::xy::tension (0)] = 0.8f;
  18942. song.mixer[1].effects.push_back (xyFx);
  18943. auto xyzFx = lynx::makeEffectSlot (lynx::EffectKind::xyzController);
  18944. xyzFx.params[(std::size_t) lynx::xy::level (2)] = 0.8f;
  18945. song.mixer[1].effects.push_back (xyzFx);
  18946. // round 165: an X-Y-Z whose X curve is FL's "Stairs" (tension +40 %) and Y a bent single curve
  18947. xyzFx.params[(std::size_t) lynx::xy::curveMode (0)] = lynx::xy::curveModeValue (lynx::flcurve::stairs);
  18948. xyzFx.params[(std::size_t) lynx::xy::tension (0)] = 0.7f;
  18949. xyzFx.params[(std::size_t) lynx::xy::level (0)] = 0.62f;
  18950. xyzFx.params[(std::size_t) lynx::xy::tension (1)] = 0.825f;
  18951. song.mixer[1].effects.push_back (xyzFx);
  18952. auto panel = lynx::makeEffectSlot (lynx::EffectKind::controlSurface);
  18953. lynx::SurfaceControl c;
  18954. for (const auto& [kind, name, v, x, y] : std::vector<std::tuple<lynx::SurfaceControl::Kind, const char*, float, float, float>> {
  18955. { lynx::SurfaceControl::Kind::knob, "Cutoff", 0.65f, 20.0f, 20.0f },
  18956. { lynx::SurfaceControl::Kind::knob, "Reso", 0.3f, 90.0f, 20.0f },
  18957. { lynx::SurfaceControl::Kind::slider, "Mix", 0.8f, 170.0f, 20.0f },
  18958. { lynx::SurfaceControl::Kind::xy, "Space", 0.4f, 230.0f, 20.0f },
  18959. { lynx::SurfaceControl::Kind::button, "Drop", 0.0f, 20.0f, 110.0f },
  18960. { lynx::SurfaceControl::Kind::checkBox, "Bypass", 1.0f, 20.0f, 160.0f } })
  18961. {
  18962. c.kind = kind;
  18963. c.name = name;
  18964. c.value = v;
  18965. c.valueY = 0.6f;
  18966. c.x = x;
  18967. c.y = y;
  18968. lynx::surface::add (panel, c);
  18969. }
  18970. song.mixer[1].effects.push_back (panel);
  18971. }
  18972. lynx::ChannelDef env;
  18973. env.name = "Envelope Controller";
  18974. env.instrument = lynx::InstrumentKind::controller;
  18975. auto ecData = lynx::defaultEnvelopeController();
  18976. ecData[0].lfoOn = true;
  18977. ecData[0].lfoTempo = true;
  18978. ecData[0].lfoSpeed = 40898;
  18979. ecData[0].maps[lynx::mapKeyboard].count = 2;
  18980. ecData[0].maps[lynx::mapKeyboard].time = { 0.2f, 0.8f };
  18981. ecData[0].maps[lynx::mapKeyboard].level = { 0.0f, 1.0f };
  18982. ecData[0].maps[lynx::mapModX] = ecData[0].maps[lynx::mapKeyboard];
  18983. env.controllerState = lynx::writeEnvelopeController (ecData);
  18984. song.channels.push_back (env);
  18985. lynx::ChannelDef out;
  18986. out.name = "MIDI Out";
  18987. out.instrument = lynx::InstrumentKind::midiOut;
  18988. lynx::midictl::MidiOutSettings settings;
  18989. settings.port = 1;
  18990. lynx::midictl::writeMidiOut (out.pluginState, settings);
  18991. song.channels.push_back (out);
  18992. // a Layer (round 164) over three synths split across the keyboard, crossfading
  18993. for (const auto* name : { "Bass", "Pad", "Lead" })
  18994. {
  18995. lynx::ChannelDef c;
  18996. c.name = name;
  18997. c.instrument = lynx::InstrumentKind::synth;
  18998. song.channels.push_back (c);
  18999. }
  19000. {
  19001. lynx::ChannelDef layer;
  19002. layer.name = "Layer";
  19003. layer.instrument = lynx::InstrumentKind::layer;
  19004. song.channels.push_back (layer);
  19005. const auto self = (int) song.channels.size() - 1;
  19006. lynx::layer::setChildren (song, self, { 2, 3, 4 });
  19007. song.channels[2].keyLow = 0, song.channels[2].keyHigh = 47;
  19008. song.channels[3].keyLow = 36, song.channels[3].keyHigh = 83;
  19009. song.channels[4].keyLow = 72, song.channels[4].keyHigh = 127;
  19010. song.channels[(std::size_t) self].layer.crossfade = true;
  19011. song.channels[(std::size_t) self].layer.fade = 0.35f;
  19012. }
  19013. {
  19014. lynx::ChannelDef dash; // channel 6
  19015. dash.name = "Dashboard";
  19016. dash.instrument = lynx::InstrumentKind::dashboard;
  19017. dash.patcher.surface = lynx::surface::starterControls();
  19018. song.channels.push_back (dash);
  19019. }
  19020. {
  19021. lynx::ChannelDef volt; // channel 7: FL's render-test settings (main L pitch, R gate × 0.5) with Out 2 on insert 3
  19022. volt.name = "Voltage Controller";
  19023. volt.instrument = lynx::InstrumentKind::voltage;
  19024. lynx::voltage::Settings v;
  19025. v.enabled = true;
  19026. v.params[9] = 49152;
  19027. v.unipolar[2] = true;
  19028. v.tracks = { 3, 0, 0 };
  19029. v.source[6] = lynx::voltage::Source::clock;
  19030. volt.pluginState = lynx::voltage::write (v);
  19031. song.channels.push_back (volt);
  19032. }
  19033. song.patterns.emplace_back();
  19034. offline.setSong (std::move (song));
  19035. offline.dispatchPendingMessages();
  19036. auto shoot = [&] (std::unique_ptr<juce::Component> c, const juce::String& name) {
  19037. if (c == nullptr)
  19038. return;
  19039. savePng (lynx::shot::snapshot (*c), prefix + name);
  19040. };
  19041. shoot (lynx::makeChannelSettingsPanel (offline, 0), "-envelope-controller.png");
  19042. shoot (lynx::makeChannelSettingsPanel (offline, 1), "-midi-out.png");
  19043. shoot (lynx::makeChannelSettingsPanel (offline, 5), "-layer.png");
  19044. shoot (lynx::makeChannelFrame (offline, 3, -1), "-layer-child-misc.png"); // (the key-region ruler over the root keyboard)
  19045. {
  19046. const auto slotOf = [] (int k) -> lynx::SlotLocator {
  19047. return [k] (lynx::Song& s) { return &s.mixer[1].effects[(std::size_t) k]; };
  19048. };
  19049. const lynx::AutomationTarget target { lynx::AutomationTargetKind::effectParam, 1, 1, 0 };
  19050. shoot (lynx::makeXyControllerEditor (offline, slotOf (1), nullptr, target), "-xy-controller.png");
  19051. shoot (lynx::makeXyControllerEditor (offline, slotOf (2), nullptr, target), "-xyz-controller.png");
  19052. shoot (lynx::makeXyControllerEditor (offline, slotOf (3), nullptr, target), "-xyz-controller-stairs.png");
  19053. shoot (lynx::makeControlSurfaceEditor (offline, slotOf (4), target), "-control-surface.png");
  19054. shoot (lynx::makeChannelSettingsPanel (offline, 6), "-dashboard.png");
  19055. shoot (lynx::makeChannelSettingsPanel (offline, 7), "-voltage-controller.png");
  19056. }
  19057. // FL's Dashboard presets of this PC's FL Studio, imported (round 164f): one PNG each
  19058. if (const auto fl = lynx::findFlStudio(); fl.installDir.isDirectory())
  19059. for (const auto& file : fl.installDir.getChildFile ("Data/Patches/Plugin presets/Generators/Dashboard").findChildFiles (juce::File::findFiles, false, "*.fst"))
  19060. {
  19061. juce::MemoryBlock bytes;
  19062. if (! file.loadFileAsData (bytes))
  19063. continue;
  19064. const auto preset = flp::parseProject ({ (const std::uint8_t*) bytes.getData(), bytes.getSize() }, true);
  19065. const auto dash = preset.channels.empty() ? std::nullopt : lynx::surface::parseFlDashboard (preset.channels[0].pluginState);
  19066. if (! dash || dash->controls.empty())
  19067. continue;
  19068. offline.editSong ([&] (lynx::Song& s) {
  19069. s.channels[6].name = file.getFileNameWithoutExtension().toStdString();
  19070. s.channels[6].patcher.surface = dash->controls;
  19071. s.channels[6].pluginState = preset.channels[0].pluginState; // (its MIDI port, channel, program)
  19072. });
  19073. offline.dispatchPendingMessages();
  19074. const auto name = file.getFileNameWithoutExtension().replaceCharacter (' ', '-');
  19075. shoot (lynx::makeChannelSettingsPanel (offline, 6), "-dashboard-fl-" + name + ".png");
  19076. // edit mode (round 165): each control's output number and the MIDI it sends ("1 CC74")
  19077. if (auto panel = lynx::makeChannelSettingsPanel (offline, 6))
  19078. {
  19079. std::function<void (juce::Component&)> pressEdit = [&] (juce::Component& c) {
  19080. for (auto* child : c.getChildren())
  19081. {
  19082. if (auto* b = dynamic_cast<juce::TextButton*> (child); b != nullptr && b->getButtonText() == lynx::tr ("Edit"))
  19083. b->setToggleState (true, juce::sendNotificationSync);
  19084. pressEdit (*child);
  19085. }
  19086. };
  19087. pressEdit (*panel);
  19088. shoot (std::move (panel), "-dashboard-fl-" + name + "-edit.png");
  19089. }
  19090. }
  19091. // the Envelope Controller's pages (issue #7): one PNG per part of the dropdown
  19092. if (auto ec = lynx::makeEnvelopeControllerEditor (offline, 0))
  19093. for (int part = 0; part < 7; ++part)
  19094. {
  19095. for (auto* child : ec->getChildren())
  19096. if (auto* box = dynamic_cast<juce::ComboBox*> (child))
  19097. box->setSelectedItemIndex (part, juce::sendNotificationSync);
  19098. savePng (lynx::shot::snapshot (*ec), prefix + "-ec-part" + juce::String (part) + ".png");
  19099. }
  19100. lynx::FormulaControllerWindows::open (offline, 1, 0);
  19101. for (int k = 0; k < juce::TopLevelWindow::getNumTopLevelWindows(); ++k)
  19102. if (auto* w = dynamic_cast<juce::DocumentWindow*> (juce::TopLevelWindow::getTopLevelWindow (k)))
  19103. if (w->getName().startsWith ("Formula") && w->getContentComponent() != nullptr)
  19104. savePng (lynx::shot::snapshot (*w->getContentComponent()), prefix + "-formula-controller.png");
  19105. lynx::FormulaControllerWindows::closeAll();
  19106. }
  19107. bool runEdisonSlotTest (const juce::String& folderPath, const juce::String& flp)
  19108. {
  19109. namespace ae = lynx::audioedit;
  19110. namespace ef = lynx::edisonfx;
  19111. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  19112. const juce::File folder (folderPath);
  19113. folder.createDirectory();
  19114. juce::String report;
  19115. bool all = true;
  19116. auto check = [&] (const juce::String& name, bool ok, const juce::String& note = {}) {
  19117. report << name << "=" << (ok ? "ok" : "FAIL") << (note.isNotEmpty() ? " (" + note + ")" : juce::String()) << "\n";
  19118. all = all && ok;
  19119. };
  19120. auto shot = [&folder] (juce::Component& c, const juce::String& name) {
  19121. savePng (lynx::shot::paint (c, lynx::theme::panel), folder.getChildFile (name).getFullPathName());
  19122. };
  19123. auto findSlot = [] (const lynx::Song& song, int& track, int& slot) {
  19124. for (track = 0; track < (int) song.mixer.size(); ++track)
  19125. for (slot = 0; slot < (int) song.mixer[(std::size_t) track].effects.size(); ++slot)
  19126. if (song.mixer[(std::size_t) track].effects[(std::size_t) slot].kind == lynx::EffectKind::edison)
  19127. return true;
  19128. return false;
  19129. };
  19130. {
  19131. lynx::AudioEngine engine (false);
  19132. engine.setRecordingTarget (folder.getChildFile ("Audio").getChildFile ("Recorded"), "Test");
  19133. // a project without the plugin is written as before: nothing of it in the file, and it reads back the same
  19134. const auto before = lynx::ProjectFile::toJson (engine.getSong(), false);
  19135. juce::String error;
  19136. const auto same = lynx::ProjectFile::fromJson (before, error);
  19137. check ("old_project_text_has_no_trace", ! before.containsIgnoreCase ("edison"));
  19138. check ("old_project_round_trip_stable", same.has_value() && lynx::ProjectFile::toJson (*same, false) == before);
  19139. const auto at = lynx::addEdisonSlot (engine, 1);
  19140. engine.dispatchPendingMessages();
  19141. check ("slot_added_to_first_empty_slot", at == 0 && engine.getSong().mixer[1].effects.size() == 1
  19142. && engine.getSong().mixer[1].effects[0].kind == lynx::EffectKind::edison);
  19143. if (at < 0)
  19144. {
  19145. folder.getChildFile ("report.txt").replaceWithText (report);
  19146. return false;
  19147. }
  19148. const auto second = lynx::addEdisonSlot (engine, 1); // several instances on a track
  19149. engine.dispatchPendingMessages();
  19150. check ("second_instance_on_the_same_track", second == 1);
  19151. engine.editSong ([at] (lynx::Song& s) {
  19152. s.mixer[1].effects[(std::size_t) at].params[ef::recordMode] = ef::modeValue (ef::Mode::now);
  19153. });
  19154. engine.dispatchPendingMessages();
  19155. const auto slotOf = [&engine, at] { return engine.getSong().mixer[1].effects[(std::size_t) at]; };
  19156. const auto fx = engine.getEffect (1, at);
  19157. const auto p = std::dynamic_pointer_cast<ef::Processor> (fx);
  19158. const auto session = ef::findSession (slotOf().instance.id);
  19159. check ("engine_built_the_effect_with_its_session", p != nullptr && session != nullptr);
  19160. const auto other = ef::findSession (engine.getSong().mixer[1].effects[1].instance.id);
  19161. check ("instances_have_their_own_audio", other != nullptr && other != session);
  19162. if (p == nullptr || session == nullptr)
  19163. {
  19164. folder.getChildFile ("report.txt").replaceWithText (report);
  19165. return false;
  19166. }
  19167. // idle: the audio passes through bit for bit
  19168. const auto rate = p->sampleRate();
  19169. std::vector<float> l (512), r (512);
  19170. auto fill = [&] (int block) {
  19171. for (int k = 0; k < 512; ++k)
  19172. {
  19173. const auto t = (double) (block * 512 + k) / rate;
  19174. l[(std::size_t) k] = 0.6f * (float) std::sin (2.0 * 3.141592653589793 * 220.0 * t);
  19175. r[(std::size_t) k] = 0.4f * (float) std::sin (2.0 * 3.141592653589793 * 330.0 * t);
  19176. }
  19177. };
  19178. fill (0);
  19179. auto inL = l, inR = r;
  19180. p->process (l.data(), r.data(), 512, slotOf().params, 120.0);
  19181. check ("idle_pass_through_bit_exact", l == inL && r == inR);
  19182. // a take through the slot (Now), then the flush that makes it a file of the project
  19183. std::vector<float> wantL, wantR;
  19184. check ("record_starts", session->start (p, true));
  19185. for (int block = 0; block < 60; ++block)
  19186. {
  19187. fill (block);
  19188. wantL.insert (wantL.end(), l.begin(), l.end());
  19189. wantR.insert (wantR.end(), r.begin(), r.end());
  19190. p->process (l.data(), r.data(), 512, slotOf().params, 120.0);
  19191. }
  19192. session->stop();
  19193. check ("take_is_the_input", session->document().audio.numChannels() == 2 && session->document().audio.channels[0] == wantL
  19194. && session->document().audio.channels[1] == wantR);
  19195. ae::Document withMarkers = session->document();
  19196. ae::addMarker (withMarkers, 4000, "Verse");
  19197. ae::addMarker (withMarkers, 12000);
  19198. ae::setLoop (withMarkers, { 2000, 20000 });
  19199. session->setDocument (withMarkers);
  19200. engine.flushEdisonAudio();
  19201. engine.dispatchPendingMessages();
  19202. const juce::File file (juce::String::fromUTF8 (slotOf().samplePath.c_str()));
  19203. check ("audio_written_to_the_project_folder", file.existsAsFile() && file.isAChildOf (folder.getChildFile ("Audio").getChildFile ("Recorded")),
  19204. file.getFullPathName());
  19205. check ("file_listed_with_the_session_recordings", std::find (engine.getSessionRecordings().begin(), engine.getSessionRecordings().end(), file)
  19206. != engine.getSessionRecordings().end());
  19207. check ("effect_kept_running_through_the_flush", engine.getEffect (1, at) == fx);
  19208. check ("nothing_unsaved_after_the_flush", ! session->dirty());
  19209. engine.flushEdisonAudio(); // (a second flush writes nothing new)
  19210. check ("second_flush_keeps_the_file", juce::File (juce::String::fromUTF8 (slotOf().samplePath.c_str())) == file);
  19211. // the project file: saved, loaded, the same slot with the same audio
  19212. engine.editSong ([at] (lynx::Song& s) {
  19213. auto& params = s.mixer[1].effects[(std::size_t) at].params;
  19214. params[ef::recordMode] = ef::modeValue (ef::Mode::onPlay);
  19215. params[ef::append] = 0.0f;
  19216. params[ef::muteInput] = 1.0f;
  19217. params[ef::slave] = 1.0f;
  19218. params[ef::maxTime] = 5.0f / 6.0f;
  19219. });
  19220. engine.capturePluginStates();
  19221. const auto project = folder.getChildFile ("edison-slot.lynx");
  19222. check ("project_saved", lynx::ProjectFile::save (engine.getSong(), project, error), error);
  19223. auto loaded = lynx::ProjectFile::load (project, error);
  19224. check ("project_loaded", loaded.has_value(), error);
  19225. if (loaded)
  19226. {
  19227. const auto& a = slotOf();
  19228. const auto& b = loaded->mixer[1].effects[(std::size_t) at];
  19229. check ("slot_kind_kept", b.kind == lynx::EffectKind::edison && loaded->mixer[1].effects.size() == 2);
  19230. check ("slot_settings_kept", ef::modeOf (b.params) == ef::Mode::onPlay && b.params[ef::append] < 0.5f && b.params[ef::muteInput] >= 0.5f
  19231. && b.params[ef::slave] >= 0.5f && ef::maxTimeIndexOf (b.params) == 5
  19232. && std::abs (b.params[ef::noiseThreshold] - a.params[ef::noiseThreshold]) < 1.0e-6f);
  19233. check ("slot_audio_path_kept", b.samplePath == a.samplePath);
  19234. check ("project_text_round_trip_stable", lynx::ProjectFile::toJson (*loaded, false) == lynx::ProjectFile::toJson (engine.getSong(), false));
  19235. lynx::AudioEngine second (false);
  19236. second.setSong (std::move (*loaded));
  19237. second.dispatchPendingMessages();
  19238. const auto reopened = ef::findSession (second.getSong().mixer[1].effects[(std::size_t) at].instance.id);
  19239. check ("reopened_project_has_the_audio", reopened != nullptr && reopened != session
  19240. && reopened->document().audio.channels == withMarkers.audio.channels
  19241. && reopened->document().audio.sampleRate == withMarkers.audio.sampleRate);
  19242. check ("reopened_project_has_markers_and_loop", reopened != nullptr && reopened->document().markers.size() == 2
  19243. && reopened->document().markers[0].name == "Verse"
  19244. && reopened->document().loopStart == 2000 && reopened->document().loopEnd == 20000);
  19245. check ("reopened_empty_instance_is_empty", ef::findSession (second.getSong().mixer[1].effects[1].instance.id) != nullptr
  19246. && ef::findSession (second.getSong().mixer[1].effects[1].instance.id)->document().audio.empty());
  19247. if (auto editor = lynx::makeEdisonSlotEditor (second, 1, at))
  19248. {
  19249. editor->setSize (1120, 600);
  19250. second.dispatchPendingMessages();
  19251. shot (*editor, "slot-editor-reopened.png");
  19252. }
  19253. }
  19254. // the plugin's window: the audio editor on the slot (empty instance, then the one with the take)
  19255. if (auto editor = lynx::makeEdisonSlotEditor (engine, 1, 1))
  19256. {
  19257. editor->setSize (1120, 600);
  19258. engine.dispatchPendingMessages();
  19259. shot (*editor, "slot-editor-empty.png");
  19260. }
  19261. auto editor = lynx::makeEdisonSlotEditor (engine, 1, at);
  19262. check ("slot_window_is_the_audio_editor", editor != nullptr);
  19263. if (editor != nullptr)
  19264. {
  19265. editor->setSize (1120, 600);
  19266. engine.dispatchPendingMessages();
  19267. shot (*editor, "slot-editor.png");
  19268. juce::File (folder.getChildFile ("slot-menu.txt")).replaceWithText (lynx::audioEditorMenuForSnapshot (*editor).joinIntoString ("\n") + "\n");
  19269. }
  19270. check ("no_editor_for_other_slots", lynx::makeEdisonSlotEditor (engine, 0, 0) == nullptr);
  19271. editor.reset();
  19272. // deleting the slot leaves the song without it (the file stays for the unused-recordings prompt)
  19273. engine.editSong ([at] (lynx::Song& s) { s.mixer[1].effects.erase (s.mixer[1].effects.begin() + at); });
  19274. engine.dispatchPendingMessages();
  19275. check ("deleted_slot_is_gone", engine.getSong().mixer[1].effects.size() == 1 && file.existsAsFile());
  19276. }
  19277. if (flp.isNotEmpty())
  19278. {
  19279. lynx::AudioEngine engine (false);
  19280. juce::String error;
  19281. const auto imported = engine.importFlpFile (juce::File (flp), error);
  19282. engine.dispatchPendingMessages();
  19283. check ("flp_imported", imported, error);
  19284. int count = 0, withAudio = 0;
  19285. const auto& song = engine.getSong();
  19286. for (int t = 0; t < (int) song.mixer.size(); ++t)
  19287. for (int s = 0; s < (int) song.mixer[(std::size_t) t].effects.size(); ++s)
  19288. {
  19289. const auto& fx = song.mixer[(std::size_t) t].effects[(std::size_t) s];
  19290. if (fx.kind != lynx::EffectKind::edison)
  19291. continue;
  19292. ++count;
  19293. const auto session = ef::findSession (fx.instance.id);
  19294. const auto frames = session != nullptr ? session->document().audio.frames() : -1;
  19295. withAudio += frames > 0 ? 1 : 0;
  19296. report << "flp_slot track " << t << " slot " << s << ": mode " << ef::modeName (ef::modeOf (fx.params))
  19297. << ", append " << (fx.params[ef::append] >= 0.5f ? "on" : "off") << ", mute input " << (fx.params[ef::muteInput] >= 0.5f ? "on" : "off")
  19298. << ", slave " << (fx.params[ef::slave] >= 0.5f ? "on" : "off") << ", loop " << (fx.params[ef::loopPlay] >= 0.5f ? "on" : "off")
  19299. << ", max time index " << ef::maxTimeIndexOf (fx.params) << ", threshold " << juce::String (fx.params[ef::noiseThreshold], 4)
  19300. << ", state " << (int) fx.state.size() << " bytes, audio " << (juce::int64) frames << " frames"
  19301. << (session != nullptr && frames > 0 ? " at " + juce::String (session->document().audio.sampleRate, 0) + " Hz, "
  19302. + juce::String (session->document().audio.numChannels()) + " ch, "
  19303. + juce::String ((int) session->document().markers.size()) + " markers"
  19304. : juce::String())
  19305. << "\n";
  19306. if (count == 1 || (frames > 0 && withAudio == 1))
  19307. if (auto editor = lynx::makeEdisonSlotEditor (engine, t, s))
  19308. {
  19309. editor->setSize (1120, 600);
  19310. engine.dispatchPendingMessages();
  19311. shot (*editor, frames > 0 ? "slot-editor-flp-audio.png" : "slot-editor-flp.png");
  19312. }
  19313. }
  19314. check ("flp_edison_slots_kept_as_the_plugin", count > 0, juce::String (count) + " slots, " + juce::String (withAudio) + " with audio");
  19315. // saved as .lynx and read again: still the plugin, FL's state (the audio) with it
  19316. int t = 0, s = 0;
  19317. if (findSlot (song, t, s))
  19318. {
  19319. const auto project = folder.getChildFile ("edison-flp.lynx");
  19320. const auto saved = lynx::ProjectFile::save (song, project, error);
  19321. std::optional<lynx::Song> loaded;
  19322. if (saved)
  19323. loaded = lynx::ProjectFile::load (project, error);
  19324. check ("flp_slot_survives_the_project_file", loaded.has_value() && t < (int) loaded->mixer.size()
  19325. && s < (int) loaded->mixer[(std::size_t) t].effects.size()
  19326. && loaded->mixer[(std::size_t) t].effects[(std::size_t) s].kind == lynx::EffectKind::edison
  19327. && loaded->mixer[(std::size_t) t].effects[(std::size_t) s].state == song.mixer[(std::size_t) t].effects[(std::size_t) s].state
  19328. && loaded->mixer[(std::size_t) t].effects[(std::size_t) s].params == song.mixer[(std::size_t) t].effects[(std::size_t) s].params,
  19329. error);
  19330. }
  19331. }
  19332. // round 190ct (live FL check 190cq): the open-and-record preset, the fresh defaults and the question before
  19333. // "Remove all Edison instances", in the app
  19334. {
  19335. lynx::AudioEngine engine (false);
  19336. lynx::MainComponent ui (engine, false);
  19337. ui.setSize (1600, 900);
  19338. engine.dispatchPendingMessages();
  19339. const auto toolsMenu = [&ui] {
  19340. const auto names = ui.getMenuNamesForSnapshot();
  19341. for (int m = 0; m < names.size(); ++m)
  19342. if (names[m] == lynx::tr ("Tools"))
  19343. return ui.getMenuForSnapshot (m);
  19344. return juce::PopupMenu();
  19345. };
  19346. const auto removeItem = [&toolsMenu] (bool& found, bool& enabled) {
  19347. found = enabled = false;
  19348. const auto menu = toolsMenu(); // (the iterator keeps a reference)
  19349. for (juce::PopupMenu::MenuItemIterator it (menu, true); it.next();)
  19350. if (it.getItem().text == lynx::tr ("Remove all Edison instances"))
  19351. {
  19352. found = true;
  19353. enabled = it.getItem().isEnabled;
  19354. if (enabled && it.getItem().action)
  19355. it.getItem().action(); // asks: nothing may go before the answer
  19356. return;
  19357. }
  19358. };
  19359. const auto count = [&engine] {
  19360. int n = 0;
  19361. for (const auto& track : engine.getSong().mixer)
  19362. for (const auto& fx : track.effects)
  19363. n += fx.kind == lynx::EffectKind::edison ? 1 : 0;
  19364. return n;
  19365. };
  19366. bool found = false, enabled = false;
  19367. removeItem (found, enabled);
  19368. check ("remove_all_edison_enabled_with_none", found && enabled && count() == 0);
  19369. const auto plain = lynx::addEdisonSlot (engine, 1);
  19370. const auto armed = lynx::addEdisonSlot (engine, 2, true);
  19371. engine.dispatchPendingMessages();
  19372. if (plain >= 0 && armed >= 0)
  19373. {
  19374. const auto& a = engine.getSong().mixer[1].effects[(std::size_t) plain].params;
  19375. const auto& b = engine.getSong().mixer[2].effects[(std::size_t) armed].params;
  19376. check ("open_audio_editor_fresh_defaults", ef::modeOf (a) == ef::Mode::onInput && ef::maxTimeIndexOf (a) == 5 && a[ef::append] >= 0.5f
  19377. && a[ef::slave] < 0.5f);
  19378. check ("open_audio_editor_and_record_preset", ef::modeOf (b) == ef::Mode::onPlay && ef::maxTimeIndexOf (b) == 3 && b[ef::append] < 0.5f
  19379. && b[ef::slave] >= 0.5f);
  19380. }
  19381. else
  19382. check ("open_audio_editor_slots_added", false);
  19383. removeItem (found, enabled);
  19384. engine.dispatchPendingMessages();
  19385. check ("remove_all_edison_asks_first", found && enabled && count() == 2);
  19386. const auto question = lynx::removeAllEdisonInstancesQuestion();
  19387. check ("remove_all_edison_question_is_fls", question.getTitle() == lynx::tr ("Remove Edison instances")
  19388. && question.getMessage() == lynx::tr ("Are you sure you want to remove all Edison instances from the project ?")
  19389. && question.getNumButtons() == 2 && question.getButtonText (0) == lynx::tr ("Yes")
  19390. && question.getButtonText (1) == lynx::tr ("No"));
  19391. // LYNX keeps an undo for the removal (rollup 190cv), so the question may not promise "(No undo)" in any
  19392. // language, and the Yes action must come back with one undo
  19393. {
  19394. bool noUndoLine = false;
  19395. for (const auto& line : juce::StringArray::fromLines (question.getMessage()))
  19396. noUndoLine = noUndoLine || line.trim().startsWithChar ('(');
  19397. check ("remove_all_edison_question_has_no_no_undo_line", ! noUndoLine && ! question.getMessage().contains ("No undo"));
  19398. const int before = count();
  19399. lynx::removeAllEdisonInstances (engine);
  19400. engine.dispatchPendingMessages();
  19401. const int removed = count();
  19402. engine.undo();
  19403. engine.dispatchPendingMessages();
  19404. check ("remove_all_edison_yes_removes_and_undo_restores", before == 2 && removed == 0 && count() == 2);
  19405. }
  19406. {
  19407. juce::AlertWindow box (question.getTitle(), question.getMessage(), question.getIconType());
  19408. box.addButton (question.getButtonText (0), 1);
  19409. box.addButton (question.getButtonText (1), 0);
  19410. box.setSize (box.getWidth(), box.getHeight());
  19411. savePng (lynx::shot::paint (box, lynx::theme::panel), folder.getChildFile ("remove-all-edison-question.png").getFullPathName());
  19412. }
  19413. {
  19414. lynx::EffectSlot slot = lynx::makeEffectSlot (lynx::EffectKind::edison);
  19415. lynx::edisonfx::setOpenAndRecord (slot.params);
  19416. engine.editSong ([&slot] (lynx::Song& s) { s.mixer[3].effects.push_back (slot); });
  19417. engine.dispatchPendingMessages();
  19418. if (const auto editor = lynx::makeEdisonSlotEditor (engine, 3, 0))
  19419. {
  19420. editor->setSize (1120, 600);
  19421. engine.dispatchPendingMessages();
  19422. shot (*editor, "slot-editor-open-and-record.png");
  19423. }
  19424. if (const auto editor = lynx::makeEdisonSlotEditor (engine, 1, plain))
  19425. {
  19426. editor->setSize (1120, 600);
  19427. engine.dispatchPendingMessages();
  19428. shot (*editor, "slot-editor-fresh-defaults.png");
  19429. }
  19430. }
  19431. }
  19432. report << (all ? "ALL OK\n" : "FAILURES\n");
  19433. folder.getChildFile ("report.txt").replaceWithText (report);
  19434. return all;
  19435. }
  19436. void runEdisonShot (const juce::String& prefix, const juce::String& file)
  19437. {
  19438. namespace ae = lynx::audioedit;
  19439. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  19440. lynx::AudioEngine offline (false);
  19441. ae::Document d;
  19442. if (file.isNotEmpty())
  19443. {
  19444. juce::MemoryBlock bytes;
  19445. if (! juce::File (file).loadFileAsData (bytes) || ! ae::decodeWav (static_cast<const std::uint8_t*> (bytes.getData()), bytes.getSize(), d))
  19446. {
  19447. std::fprintf (stderr, "edisonshot: cannot read %s\n", file.toRawUTF8());
  19448. return;
  19449. }
  19450. }
  19451. else
  19452. {
  19453. // a drum loop with a hum and hiss under it (something for the denoiser and the EQ to show)
  19454. d.title = "Drum loop";
  19455. d.audio.sampleRate = 44100.0;
  19456. const auto frames = (std::size_t) (44100 * 2);
  19457. d.audio.channels.assign (2, std::vector<float> (frames, 0.0f));
  19458. std::uint32_t seed = 7;
  19459. for (std::size_t i = 0; i < frames; ++i)
  19460. {
  19461. seed = seed * 1664525u + 1013904223u;
  19462. const auto hiss = ((float) (seed >> 8) / 16777216.0f - 0.5f) * 0.02f;
  19463. const auto hum = 0.01f * (float) std::sin (2.0 * 3.141592653589793 * 50.0 * (double) i / 44100.0);
  19464. d.audio.channels[0][i] = hiss + hum;
  19465. d.audio.channels[1][i] = hiss * 0.9f + hum;
  19466. }
  19467. for (int hit = 0; hit < 8; ++hit)
  19468. {
  19469. const auto at = (std::size_t) hit * frames / 8;
  19470. const auto kick = hit % 2 == 0;
  19471. double phase = 0.0;
  19472. for (std::size_t i = 0; i < 12000 && at + i < frames; ++i)
  19473. {
  19474. seed = seed * 1664525u + 1013904223u;
  19475. const auto noise = (float) (seed >> 8) / 16777216.0f - 0.5f;
  19476. const auto t = (double) i / 44100.0;
  19477. phase += 2.0 * 3.141592653589793 * (kick ? 45.0 + 160.0 * std::exp (-t * 30.0) : 190.0) / 44100.0;
  19478. const auto body = (float) std::sin (phase) * (float) std::exp (-t * (kick ? 9.0 : 22.0));
  19479. const auto v = kick ? 0.85f * body : 0.35f * body + 0.6f * noise * (float) std::exp (-t * 18.0);
  19480. d.audio.channels[0][at + i] += v;
  19481. d.audio.channels[1][at + i] += kick ? v : v * 0.8f;
  19482. }
  19483. }
  19484. for (int hit = 1; hit < 8; ++hit)
  19485. ae::addMarker (d, (std::int64_t) (hit * frames / 8));
  19486. ae::setLoop (d, { 0, (std::int64_t) frames });
  19487. }
  19488. // a volume envelope (a fade-in and a dip) to show the envelope mode and the envelope tools
  19489. 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 } };
  19490. auto editor = lynx::makeAudioEditorForSnapshot (offline, d, false);
  19491. auto shot = [&prefix] (juce::Component& c, const juce::String& name) {
  19492. auto image = lynx::shot::paint (c, lynx::theme::panel);
  19493. savePng (image, prefix + name);
  19494. };
  19495. editor->setSize (1120, 600);
  19496. lynx::setAudioEditorEnvelopeModeForSnapshot (*editor, 1);
  19497. shot (*editor, "-editor-volume-envelope.png");
  19498. lynx::setAudioEditorEnvelopeModeForSnapshot (*editor, 0);
  19499. juce::File (prefix + "-menu.txt").replaceWithText (lynx::audioEditorMenuForSnapshot (*editor).joinIntoString ("\n") + "\n");
  19500. // round 190ee: the first marker's menu (Trigger note) and FL's four snap modes on a probe frame
  19501. if (! d.markers.empty())
  19502. juce::File (prefix + "-marker-menu.txt").replaceWithText (lynx::audioEditorMarkerMenuForSnapshot (*editor, 0).joinIntoString ("\n") + "\n");
  19503. {
  19504. juce::StringArray snaps;
  19505. const auto probe = (std::int64_t) (d.audio.frames() * 3 / 8) + 777;
  19506. for (int mode = 0; mode < 4; ++mode)
  19507. snaps.add (lynx::setAudioEditorSnapForSnapshot (*editor, mode, probe));
  19508. juce::File (prefix + "-snap.txt").replaceWithText (snaps.joinIntoString ("\n") + "\n");
  19509. shot (*editor, "-editor-snap-on.png");
  19510. }
  19511. for (int t = 0; lynx::audioToolNameForSnapshot (t) != nullptr; ++t)
  19512. {
  19513. const auto envelopeTool = t >= 10 && t <= 14; // Scale levels .. Create sequence work on the volume envelope
  19514. if (auto panel = lynx::makeAudioToolPanelForSnapshot (*editor, t, envelopeTool ? 1 : 0))
  19515. {
  19516. offline.dispatchPendingMessages();
  19517. const auto name = juce::String (lynx::audioToolNameForSnapshot (t)).toLowerCase().retainCharacters ("abcdefghijklmnopqrstuvwxyz ").trim().replaceCharacter (' ', '-');
  19518. shot (*panel, "-tool-" + juce::String (t).paddedLeft ('0', 2) + "-" + name + ".png");
  19519. if (envelopeTool)
  19520. shot (*editor, "-tool-" + juce::String (t).paddedLeft ('0', 2) + "-" + name + "-editor.png");
  19521. panel.reset(); // (puts the envelope back)
  19522. }
  19523. }
  19524. }
  19525. static juce::TextButton* findButton (juce::Component& root, const juce::String& text)
  19526. {
  19527. if (auto* b = dynamic_cast<juce::TextButton*> (&root); b != nullptr && b->getButtonText() == text)
  19528. return b;
  19529. for (auto* child : root.getChildren())
  19530. if (auto* b = findButton (*child, text))
  19531. return b;
  19532. return nullptr;
  19533. }
  19534. // a VFX Script editor's Script / Log / API reference tabs, then the Script tab of a script with an error
  19535. void shootScriptTabs (juce::Component& panel, lynx::AudioEngine& engine, int index, const juce::String& name)
  19536. {
  19537. const std::pair<const char*, const char*> tabs[] = { { "Script", "script" }, { "Log", "log" }, { "API reference", "api" } };
  19538. for (const auto& [tab, file] : tabs)
  19539. if (auto* b = findButton (panel, lynx::tr (tab)); b != nullptr && b->onClick)
  19540. {
  19541. b->onClick();
  19542. savePng (lynx::shot::snapshot (panel), name + "-tab-" + file + ".png");
  19543. }
  19544. engine.editSong ([&] (lynx::Song& s) {
  19545. auto st = *lynx::vfx::readState (s.channels[(std::size_t) index].pluginState);
  19546. auto settings = lynx::vfx::parseScript (st.fl).value_or (lynx::vfx::defaultScript());
  19547. settings.setSource ("import flvfx as vfx\n\ndef onTriggerVoice(incomingVoice):\n v = vfx.Voice(incomingVoice)\n"
  19548. " v.note += 7\n v.trigger(\n\ndef onReleaseVoice(incomingVoice):\n pass\n");
  19549. st.fl = lynx::vfx::writeScript (settings);
  19550. s.channels[(std::size_t) index].pluginState = lynx::vfx::writeState (st);
  19551. });
  19552. engine.dispatchPendingMessages();
  19553. if (auto broken = lynx::makeChannelSettingsPanel (engine, index))
  19554. {
  19555. engine.dispatchPendingMessages();
  19556. if (auto* b = findButton (*broken, lynx::tr ("Script")); b != nullptr && b->onClick)
  19557. b->onClick();
  19558. savePng (lynx::shot::snapshot (*broken), name + "-error.png");
  19559. }
  19560. }
  19561. void runVfxShot (const juce::String& prefix)
  19562. {
  19563. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  19564. lynx::AudioEngine offline (false);
  19565. lynx::MainComponent ui (offline, false);
  19566. ui.setSize (1280, 720);
  19567. auto song = lynx::Song::makeDefault();
  19568. song.channels.clear();
  19569. for (const auto kind : lynx::vfx::allKinds)
  19570. {
  19571. lynx::ChannelDef c;
  19572. lynx::vfx::makeChannel (c, kind);
  19573. if (kind == lynx::vfx::Kind::keyMapper) // a chord on every key: something to see in the grid
  19574. for (const auto& p : lynx::vfx::builtInPresets (kind))
  19575. if (p.name == "Major triad")
  19576. {
  19577. auto st = *lynx::vfx::readState (c.pluginState);
  19578. st.fl = p.fl;
  19579. c.pluginState = lynx::vfx::writeState (st);
  19580. }
  19581. song.channels.push_back (c);
  19582. }
  19583. // a Patcher: its notes through a Color Mapper to three synths
  19584. lynx::ChannelDef patcher;
  19585. patcher.name = "Patcher";
  19586. patcher.instrument = lynx::InstrumentKind::patcher;
  19587. lynx::PatchNode mapper;
  19588. mapper.generator = true;
  19589. lynx::vfx::makeChannel (mapper.channel, lynx::vfx::Kind::colorMapper);
  19590. mapper.x = 260.0f;
  19591. patcher.patcher.nodes.push_back (mapper);
  19592. lynx::PatchWire notes;
  19593. notes.kind = lynx::PatchWire::Kind::midi, notes.to = 0;
  19594. patcher.patcher.wires.push_back (notes);
  19595. for (int k = 0; k < 3; ++k)
  19596. {
  19597. lynx::PatchNode synth;
  19598. synth.generator = true;
  19599. synth.channel.instrument = lynx::InstrumentKind::synth;
  19600. synth.channel.name = "Synth " + std::to_string (k + 1);
  19601. synth.x = 520.0f, synth.y = (float) k * 90.0f;
  19602. patcher.patcher.nodes.push_back (synth);
  19603. lynx::PatchWire in, out;
  19604. in.kind = lynx::PatchWire::Kind::midi, in.from = 0, in.fromPort = k, in.to = 1 + k;
  19605. out.from = 1 + k, out.to = lynx::patchToHost;
  19606. patcher.patcher.wires.push_back (in);
  19607. patcher.patcher.wires.push_back (out);
  19608. }
  19609. patcher.patcher.outputX = 760.0f;
  19610. song.channels.push_back (patcher);
  19611. offline.setSong (std::move (song));
  19612. offline.dispatchPendingMessages();
  19613. for (int c = 0; c < lynx::vfx::kindCount; ++c)
  19614. if (auto panel = lynx::makeChannelSettingsPanel (offline, c))
  19615. {
  19616. offline.dispatchPendingMessages();
  19617. savePng (lynx::shot::snapshot (*panel),
  19618. prefix + "-" + juce::String (lynx::vfx::flName (*lynx::vfx::kindOf (offline.getSong().channels[(std::size_t) c]))).replaceCharacter (' ', '-').toLowerCase() + ".png");
  19619. }
  19620. // with FL Studio installed: the Sequencer with FL's factory bank (to compare with FL's own editor) and
  19621. // a Script with FL's "Snap To Scale"
  19622. if (const auto roots = lynx::findFlStudioRoots(); ! roots.data.empty())
  19623. {
  19624. const auto data = juce::File (juce::String::fromUTF8 (roots.data.c_str()));
  19625. const std::pair<lynx::vfx::Kind, juce::String> extra[] = {
  19626. { lynx::vfx::Kind::sequencer, "Patches/Plugin database/Effects/Patcher/VFX Sequencer.fst" },
  19627. { lynx::vfx::Kind::script, "Patches/Plugin presets/Effects/VFX Script/Snap To Scale.fst" },
  19628. };
  19629. for (const auto& [kind, path] : extra)
  19630. {
  19631. juce::MemoryBlock bytes;
  19632. if (! data.getChildFile (path).loadFileAsData (bytes))
  19633. continue;
  19634. const auto* b = static_cast<const std::uint8_t*> (bytes.getData());
  19635. const auto fl = lynx::vfx::stateFromFlPreset (std::vector<std::uint8_t> (b, b + bytes.getSize()), kind);
  19636. int index = -1;
  19637. for (int c = 0; c < lynx::vfx::kindCount; ++c)
  19638. if (lynx::vfx::kindOf (offline.getSong().channels[(std::size_t) c]) == kind)
  19639. index = c;
  19640. if (! fl || index < 0)
  19641. continue;
  19642. offline.editSong ([&] (lynx::Song& s) {
  19643. auto st = *lynx::vfx::readState (s.channels[(std::size_t) index].pluginState);
  19644. st.fl = *fl;
  19645. s.channels[(std::size_t) index].pluginState = lynx::vfx::writeState (st);
  19646. });
  19647. offline.dispatchPendingMessages();
  19648. if (auto panel = lynx::makeChannelSettingsPanel (offline, index))
  19649. {
  19650. offline.dispatchPendingMessages();
  19651. const auto name = prefix + "-" + juce::String (lynx::vfx::flName (kind)).replaceCharacter (' ', '-').toLowerCase();
  19652. savePng (lynx::shot::snapshot (*panel), name + "-fl.png");
  19653. if (kind == lynx::vfx::Kind::script) // the editor's other tabs (round 165d)
  19654. shootScriptTabs (*panel, offline, index, name);
  19655. }
  19656. }
  19657. }
  19658. lynx::PatcherWindows::openChannel (offline, lynx::vfx::kindCount);
  19659. for (int k = 0; k < juce::TopLevelWindow::getNumTopLevelWindows(); ++k)
  19660. if (auto* w = dynamic_cast<juce::DocumentWindow*> (juce::TopLevelWindow::getTopLevelWindow (k)))
  19661. if (w->getName().startsWith (lynx::tr ("Patcher")) && w->getContentComponent() != nullptr)
  19662. {
  19663. auto* content = w->getContentComponent();
  19664. savePng (lynx::shot::snapshot (*content), prefix + "-patcher.png");
  19665. delete w;
  19666. break;
  19667. }
  19668. lynx::PatcherWindows::shootMenus (offline, true, lynx::vfx::kindCount, 0, [&] (const juce::Image& image, const juce::String& name) {
  19669. savePng (image, prefix + "-patcher-menu-" + name + ".png");
  19670. });
  19671. // a plugin renamed in the Plugin database ("1_EQ", FL): the Quick-add palette and the mixer slot show the new name
  19672. if (juce::SystemStats::getEnvironmentVariable ("LYNX_TEST_MODE", {}).isNotEmpty())
  19673. {
  19674. const auto key = std::string ("lynx:fx:") + lynx::effectInfo (lynx::EffectKind::parametricEq).name;
  19675. offline.getPluginHost().setPluginName (key, "1_EQ");
  19676. offline.editSong ([] (lynx::Song& s) {
  19677. if (s.mixer.size() > 1)
  19678. {
  19679. lynx::EffectSlot slot;
  19680. slot.kind = lynx::EffectKind::parametricEq;
  19681. s.mixer[1].effects.push_back (slot);
  19682. }
  19683. });
  19684. offline.dispatchPendingMessages();
  19685. {
  19686. lynx::QuickAddTargets targets;
  19687. targets.addInstrument = [] (lynx::ChannelDef) {};
  19688. targets.addEffect = [] (lynx::EffectSlot) {};
  19689. auto palette = lynx::makeQuickAddPalette (offline, std::move (targets));
  19690. savePng (lynx::shot::snapshot (*palette), prefix + "-quickadd-renamed.png");
  19691. }
  19692. ui.selectTabForSnapshot (3);
  19693. ui.getMixerForSnapshot().selectTrack (1);
  19694. offline.dispatchPendingMessages();
  19695. savePng (lynx::shot::snapshot (ui), prefix + "-mixer-renamed.png");
  19696. offline.getPluginHost().setPluginName (key, "");
  19697. }
  19698. }
  19699. void runAudioXShot (const juce::String& prefix)
  19700. {
  19701. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  19702. lynx::AudioEngine offline (false);
  19703. {
  19704. lynx::MainComponent ui (offline, false);
  19705. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  19706. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  19707. offline.dispatchPendingMessages();
  19708. // 1. sends: insert 1 feeds insert 3 pre-fader and insert 4 post-fader (FL's way)
  19709. offline.editSong ([] (lynx::Song& s) {
  19710. if (s.mixer.size() < 5)
  19711. return;
  19712. s.mixer[1].name = "Vocal";
  19713. s.mixer[3].name = "Reverb";
  19714. s.mixer[4].name = "Delay";
  19715. s.setRoute (1, 3, true);
  19716. s.setRoute (1, 4, true);
  19717. s.setRouteLevel (1, 3, 0.6f);
  19718. s.setRouteLevel (1, 4, 0.4f);
  19719. s.setSendPre (1, 3, true);
  19720. });
  19721. offline.dispatchPendingMessages();
  19722. ui.selectTabForSnapshot (3);
  19723. ui.getMixerForSnapshot().selectTrack (1);
  19724. offline.dispatchPendingMessages();
  19725. saveSnapshot (ui, prefix + "-send-pre.png");
  19726. auto& strips = ui.getMixerForSnapshot().getStripsForSnapshot();
  19727. saveMenus (juce::StringArray { "Send to Reverb (pre-fader)", "Send to Delay (post-fader)" },
  19728. std::vector<juce::PopupMenu> { strips.buildSendMenu (3), strips.buildSendMenu (4) }, prefix + "-send-menu.png");
  19729. // 2. low latency while recording: the monitored track's look-ahead limiter is bypassed, the EQ stays
  19730. offline.editSong ([] (lynx::Song& s) {
  19731. s.mixer[1].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::parametricEq));
  19732. s.mixer[1].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::limiter));
  19733. s.mixer[1].inputChannel = 0;
  19734. s.mixer[1].monitor = lynx::InputMonitor::on;
  19735. });
  19736. offline.dispatchPendingMessages();
  19737. saveSnapshot (ui, prefix + "-lowlat-off.png");
  19738. auto options = offline.getRecordOptions();
  19739. options.lowLatencyRecording = true;
  19740. offline.setRecordOptions (options);
  19741. offline.dispatchPendingMessages();
  19742. ui.getMixerForSnapshot().selectTrack (1);
  19743. offline.dispatchPendingMessages();
  19744. saveSnapshot (ui, prefix + "-lowlat-on.png");
  19745. saveMenus (juce::StringArray { "Record" }, std::vector<juce::PopupMenu> { ui.getFullRecordMenuForSnapshot() }, prefix + "-lowlat-menu.png");
  19746. juce::String report;
  19747. report << "latency_with_option=" << offline.getLatencySamples() << " bypassed_slots=" << offline.lowLatencyBypassedCount() << "\n";
  19748. options.lowLatencyRecording = false;
  19749. offline.setRecordOptions (options);
  19750. offline.dispatchPendingMessages();
  19751. report << "latency_without_option=" << offline.getLatencySamples() << "\n";
  19752. // 3. the Browser's "Preview in time": a 120 BPM loop previewed in a 140 BPM project
  19753. const auto dir = juce::File (prefix).getParentDirectory().getChildFile ("audiox-preview");
  19754. dir.createDirectory();
  19755. const auto wav = dir.getChildFile ("Drum loop 120 bpm.wav");
  19756. {
  19757. const int frames = 44100 * 4;
  19758. juce::AudioBuffer<float> audio (1, frames);
  19759. for (int i = 0; i < frames; ++i)
  19760. {
  19761. const auto t = (double) (i % 22050) / 44100.0;
  19762. 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)));
  19763. }
  19764. wav.deleteFile();
  19765. juce::WavAudioFormat format;
  19766. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  19767. if (auto* w = format.createWriterFor (out.get(), 44100.0, 1, 16, {}, 0))
  19768. {
  19769. out.release();
  19770. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  19771. writer->writeFromAudioSampleBuffer (audio, 0, frames);
  19772. }
  19773. }
  19774. offline.getTransport().bpm.store (140.0);
  19775. offline.setPreviewInTime (true);
  19776. ui.showDesktopForSnapshot (false);
  19777. offline.previewFile (wav);
  19778. offline.finishPreviewJobs();
  19779. ui.getBrowserForSnapshot().showPreviewForSnapshot (wav);
  19780. offline.dispatchPendingMessages();
  19781. saveSnapshot (ui, prefix + "-preview-in-time.png");
  19782. saveMenus (juce::StringArray { "Browser options" }, std::vector<juce::PopupMenu> { ui.getBrowserForSnapshot().buildViewMenu() }, prefix + "-preview-menu.png");
  19783. const auto& timing = offline.getPreviewTiming();
  19784. report << "preview file_bpm=" << timing.fileBpm << " project_bpm=" << timing.projectBpm << " ratio=" << timing.ratio
  19785. << " prepare_ms=" << juce::String (offline.getLastPreviewPrepareMs(), 1) << "\n";
  19786. offline.previewFile ({});
  19787. offline.setPreviewInTime (false);
  19788. juce::File (prefix + "-report.txt").replaceWithText (report);
  19789. }
  19790. }
  19791. void runComp177Shot (const juce::String& prefix, const juce::String& projectPath)
  19792. {
  19793. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  19794. lynx::AudioEngine offline (false);
  19795. {
  19796. lynx::MainComponent ui (offline, false);
  19797. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  19798. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  19799. ui.openFile (juce::File (projectPath));
  19800. offline.dispatchPendingMessages();
  19801. ui.selectTabForSnapshot (2);
  19802. offline.dispatchPendingMessages();
  19803. auto& playlist = ui.getPlaylistForSnapshot();
  19804. std::int64_t last = 0;
  19805. for (const auto& c : offline.getSong().playlist)
  19806. last = std::max (last, c.end());
  19807. const auto bars = juce::jmax (1, (int) (last / (4 * lynx::ppq)) + 1);
  19808. playlist.setViewForSnapshot (juce::jmax (60.0, (ui.getWidth() - 300.0) / bars), 0, 0);
  19809. // (the first paint asks for the clips' waveforms, a worker thread loads them)
  19810. saveSnapshot (ui, prefix + "-opened.png");
  19811. juce::Thread::sleep (3000);
  19812. offline.dispatchPendingMessages();
  19813. saveSnapshot (ui, prefix + "-opened.png");
  19814. // a muted clip selected
  19815. for (int c = 0; c < (int) offline.getSong().playlist.size(); ++c)
  19816. if (offline.getSong().playlist[(std::size_t) c].muted)
  19817. {
  19818. playlist.selectClipsForSnapshot ({ c });
  19819. offline.dispatchPendingMessages();
  19820. saveSnapshot (ui, prefix + "-selected.png");
  19821. playlist.selectClipsForSnapshot ({});
  19822. break;
  19823. }
  19824. juce::String report;
  19825. const auto listTracks = [&offline, &report] (const juce::String& title) {
  19826. const auto& s = offline.getSong();
  19827. report << title << "\n";
  19828. for (int t = 0; t < (int) s.playlistTracks.size(); ++t)
  19829. {
  19830. int clips = 0, muted = 0;
  19831. for (const auto& c : s.playlist)
  19832. if (c.track == t)
  19833. ++clips, muted += c.muted ? 1 : 0;
  19834. const auto& pt = s.playlistTracks[(std::size_t) t];
  19835. if (clips > 0 || pt.grouped || ! pt.name.empty())
  19836. report << "track " << (t + 1) << " '" << juce::String::fromUTF8 (pt.name.c_str()) << "' grouped=" << (pt.grouped ? 1 : 0) << " collapsed=" << (pt.collapsed ? 1 : 0)
  19837. << " comp=" << (pt.compTrack ? 1 : 0) << " clips=" << clips << " muted=" << muted << "\n";
  19838. }
  19839. };
  19840. listTracks ("opened");
  19841. // the first group's header (a member's menu holds "Comp these takes" too)
  19842. int firstGroup = -1;
  19843. for (int t = 0; t < (int) offline.getSong().playlistTracks.size() && firstGroup < 0; ++t)
  19844. if (lynx::comp::canComp (offline.getSong(), t))
  19845. firstGroup = t;
  19846. report << "first group with takes: track " << (firstGroup + 1) << "\n";
  19847. if (firstGroup >= 0)
  19848. {
  19849. saveMenus (juce::StringArray { "Playlist track" }, std::vector<juce::PopupMenu> { playlist.getTrackMenuForSnapshot (firstGroup) }, prefix + "-trackmenu.png");
  19850. int comp = -1;
  19851. offline.editSong ([firstGroup, &comp] (lynx::Song& s) { comp = lynx::comp::compTakes (s, firstGroup); });
  19852. offline.dispatchPendingMessages();
  19853. saveSnapshot (ui, prefix + "-comped.png");
  19854. listTracks ("after Comp these takes");
  19855. const auto g = lynx::comp::groupOf (offline.getSong(), comp);
  19856. std::int64_t from = -1, to = 0;
  19857. for (const auto& c : offline.getSong().playlist)
  19858. if (c.track == g.first)
  19859. from = from < 0 ? c.start : std::min (from, c.start), to = std::max (to, c.end());
  19860. if (g.valid() && to > from)
  19861. {
  19862. offline.editSong ([&g, from, to] (lynx::Song& s) { lynx::comp::swipe (s, g.first, from + (to - from) / 4, from + (to - from) / 2); });
  19863. offline.dispatchPendingMessages();
  19864. saveSnapshot (ui, prefix + "-swiped.png");
  19865. listTracks ("after a swipe of the middle of the first lane");
  19866. // a lane auditioned; the crossfade close up; the comp flattened
  19867. offline.editSong ([&g] (lynx::Song& s) { lynx::comp::setAudition (s, g.first); }, false);
  19868. offline.dispatchPendingMessages();
  19869. saveSnapshot (ui, prefix + "-audition.png");
  19870. offline.editSong ([] (lynx::Song& s) { lynx::comp::setAudition (s, -1); }, false);
  19871. const auto switchAt = from + (to - from) / 4;
  19872. playlist.setViewForSnapshot (4.0 * 4.0 * lynx::ppq, 0, 0);
  19873. playlist.setScrollTickForSnapshot ((double) (switchAt - 100));
  19874. juce::Thread::sleep (1500);
  19875. offline.dispatchPendingMessages();
  19876. saveSnapshot (ui, prefix + "-crossfade.png");
  19877. playlist.setViewForSnapshot (juce::jmax (60.0, (ui.getWidth() - 300.0) / bars), 0, 0);
  19878. offline.editSong ([comp] (lynx::Song& s) { lynx::comp::flatten (s, comp); });
  19879. offline.dispatchPendingMessages();
  19880. saveSnapshot (ui, prefix + "-flattened.png");
  19881. listTracks ("after Flatten comp");
  19882. }
  19883. }
  19884. saveMenus (juce::StringArray { "Record" }, std::vector<juce::PopupMenu> { ui.getRecordMenuForSnapshot() }, prefix + "-recordmenu.png");
  19885. juce::File (prefix + "-tracks.txt").replaceWithText (report);
  19886. }
  19887. }
  19888. // Round 190bx: the Settings pages alone (the full --snapshot takes minutes). prefix-settings-<page>.png at the
  19889. // window's size, -small.png at 390 x 390 (rows must scroll, never be cut off or squeezed) and -whole.png tall
  19890. // enough to show every row of the page.
  19891. void runSettingsShot (const juce::String& prefix)
  19892. {
  19893. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  19894. {
  19895. lynx::AudioEngine offline (false);
  19896. offline.editSong ([] (lynx::Song& s) {
  19897. s.info = { "Night Drive", "LYNX SHARE demo", "Synthwave", "https://lynx-share.com",
  19898. "Made with LYNX SHARE.\nDrums and bass from the Channel Rack, pads from the Browser.", false };
  19899. }, false);
  19900. auto shoot = [&] (lynx::SettingsPage page, const juce::String& name, int width, int height) {
  19901. auto panel = lynx::makeSettingsPanel (offline, page);
  19902. if (width > 0)
  19903. panel->setSize (width, height);
  19904. juce::Component frame;
  19905. frame.setSize (panel->getWidth(), panel->getHeight());
  19906. frame.addAndMakeVisible (*panel);
  19907. panel->setTopLeftPosition (0, 0);
  19908. juce::Image image (juce::Image::ARGB, frame.getWidth(), frame.getHeight(), true);
  19909. {
  19910. juce::Graphics g (image);
  19911. g.fillAll (lynx::theme::panel);
  19912. frame.paintEntireComponent (g, false);
  19913. }
  19914. savePng (image, prefix + "-settings-" + name + ".png");
  19915. };
  19916. const std::pair<lynx::SettingsPage, const char*> pages[] = { { lynx::SettingsPage::audio, "audio" }, { lynx::SettingsPage::midi, "midi" },
  19917. { lynx::SettingsPage::general, "general" }, { lynx::SettingsPage::theme, "theme" },
  19918. { lynx::SettingsPage::files, "files" }, { lynx::SettingsPage::extras, "extras" },
  19919. { lynx::SettingsPage::project, "project" }, { lynx::SettingsPage::info, "info" } };
  19920. for (const auto& [page, name] : pages)
  19921. {
  19922. shoot (page, name, 0, 0);
  19923. shoot (page, juce::String (name) + "-small", 390, 390);
  19924. }
  19925. shoot (lynx::SettingsPage::audio, "audio-whole", 680, 1500);
  19926. shoot (lynx::SettingsPage::general, "general-whole", 680, 2400); // (round 190gh: + the Updates section's previous-version row)
  19927. }
  19928. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  19929. }
  19930. // round 190bw: FL's 13 curve modes of an automation clip's points (see --curveshot)
  19931. bool runPickerDropShot (const juce::String& prefix)
  19932. {
  19933. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  19934. lynx::AudioEngine offline (false);
  19935. juce::StringArray checks;
  19936. bool all = true;
  19937. const auto check = [&checks, &all] (bool ok, const juce::String& what) {
  19938. checks.add ((ok ? "OK " : "FAIL ") + what);
  19939. all = all && ok;
  19940. };
  19941. {
  19942. lynx::MainComponent ui (offline, false);
  19943. ui.setSize (1600, 900);
  19944. offline.dispatchPendingMessages();
  19945. const auto bar = (std::int64_t) lynx::ppq * 4;
  19946. offline.editSong ([bar] (lynx::Song& s) {
  19947. s.patterns.resize (3);
  19948. const char* names[] = { "Pattern 1", "Pattern 2", "Pattern 3" };
  19949. for (int p = 0; p < 3; ++p)
  19950. {
  19951. auto& pattern = s.patterns[(std::size_t) p];
  19952. pattern.name = names[p];
  19953. pattern.notes.clear();
  19954. for (int n = 0; n < 4 * (p + 1); ++n)
  19955. {
  19956. lynx::Note note;
  19957. note.start = (std::int64_t) n * lynx::ppq / 2;
  19958. note.length = lynx::ppq / 4;
  19959. note.key = 60 + (n * 5 + p * 3) % 12;
  19960. pattern.notes.push_back (note);
  19961. }
  19962. }
  19963. s.patterns[1].lengthTicks = bar * 2; // (Pattern 2 is two bars long)
  19964. s.currentPattern = 0;
  19965. s.playlist.clear();
  19966. }, false);
  19967. offline.dispatchPendingMessages();
  19968. ui.selectTabForSnapshot (2);
  19969. offline.dispatchPendingMessages();
  19970. auto& playlist = ui.getPlaylistForSnapshot();
  19971. playlist.setViewForSnapshot (120.0, 0, 0);
  19972. offline.dispatchPendingMessages();
  19973. // the drag's description survives the trip
  19974. {
  19975. auto kind = lynx::ClipKind::audio;
  19976. std::vector<int> entries;
  19977. const auto text = lynx::PlaylistComponent::pickerDragDescription (lynx::ClipKind::pattern, { 2, 0 });
  19978. check (lynx::PlaylistComponent::pickerDrag (text, kind, entries) && kind == lynx::ClipKind::pattern && entries == std::vector<int> ({ 2, 0 }),
  19979. "drag description " + text);
  19980. }
  19981. const auto at = [&playlist] (int track, double ticks) {
  19982. return juce::Point<int> (juce::roundToInt (playlist.xOfTickForSnapshot (ticks)), playlist.trackRowForSnapshot (track).getCentreY());
  19983. };
  19984. const auto find = [&offline] (int track, int pattern) -> const lynx::Clip* {
  19985. for (const auto& c : offline.getSong().playlist)
  19986. if (c.track == track && c.kind == lynx::ClipKind::pattern && c.pattern == pattern)
  19987. return &c;
  19988. return nullptr;
  19989. };
  19990. // 1. Pattern 1 dropped on track 1 a little after bar 2's line: it starts on that line
  19991. playlist.dropFromPicker (lynx::ClipKind::pattern, { 0 }, at (0, (double) bar + lynx::ppq * 0.2), false);
  19992. offline.dispatchPendingMessages();
  19993. const auto* one = find (0, 0);
  19994. check (one != nullptr && one->start == bar && one->length == bar, "plain drop: Pattern 1 on track 1 at bar 2");
  19995. // 2. Pattern 2 + Pattern 3 (picked together) dropped on track 3 at bar 3: tracks 3 and 4, same time
  19996. playlist.dropFromPicker (lynx::ClipKind::pattern, { 1, 2 }, at (2, (double) bar * 2), false);
  19997. offline.dispatchPendingMessages();
  19998. const auto* two = find (2, 1);
  19999. const auto* three = find (3, 2);
  20000. check (two != nullptr && three != nullptr && two->start == bar * 2 && three->start == bar * 2,
  20001. "two picked patterns: Pattern 2 on track 3, Pattern 3 on track 4, both at bar 3");
  20002. check (offline.getSong().currentPattern == 2, "the current pattern is the last dropped one (Pattern 3)");
  20003. const auto selectedAre = [&playlist, &offline] (int track, std::size_t count) {
  20004. const auto& sel = playlist.getSelectedClips();
  20005. if (sel.size() != count)
  20006. return false;
  20007. for (const auto i : sel)
  20008. if (i < 0 || i >= (int) offline.getSong().playlist.size() || offline.getSong().playlist[(std::size_t) i].start != (track < 0 ? 2 * (std::int64_t) lynx::ppq * 4 : offline.getSong().playlist[(std::size_t) i].start)
  20009. || (track >= 0 && offline.getSong().playlist[(std::size_t) i].track != track))
  20010. return false;
  20011. return true;
  20012. };
  20013. check (selectedAre (-1, 2), "the two dropped clips are the selection (FL), Pattern 1's clip is not");
  20014. saveSnapshot (ui, prefix + "-plain.png");
  20015. // 3. Shift: all three on track 6 from bar 1, one after the other
  20016. playlist.dropFromPicker (lynx::ClipKind::pattern, { 0, 1, 2 }, at (5, 0.0), true);
  20017. offline.dispatchPendingMessages();
  20018. const auto* a = find (5, 0);
  20019. const auto* b = find (5, 1);
  20020. const auto* c = find (5, 2);
  20021. check (a != nullptr && b != nullptr && c != nullptr && a->start == 0 && b->start == a->end() && c->start == b->end(),
  20022. "Shift drop: Pattern 1, 2, 3 one after the other on track 6");
  20023. check (offline.getSong().currentPattern == 2, "Shift keeps the current pattern");
  20024. check (selectedAre (5, 3), "the three chained clips are the selection");
  20025. saveSnapshot (ui, prefix + "-shift.png");
  20026. }
  20027. checks.add (all ? "ALL OK" : "FAILURES");
  20028. juce::File (prefix + "-checks.txt").replaceWithText (checks.joinIntoString ("\n") + "\n");
  20029. return all;
  20030. }
  20031. bool runTrackModeShot (const juce::String& prefix)
  20032. {
  20033. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  20034. lynx::AudioEngine offline (false);
  20035. bool all = true;
  20036. juce::String report;
  20037. {
  20038. lynx::MainComponent ui (offline, false);
  20039. ui.setSize (1600, 900);
  20040. offline.dispatchPendingMessages();
  20041. auto& playlist = ui.getPlaylistForSnapshot();
  20042. // the track's menu, Track mode and Audio track side by side; the Audio track entries as FL writes them
  20043. // ("-" in front = greyed, "v" = ticked)
  20044. const auto shoot = [&] (int track, const juce::String& name, const juce::StringArray& fl) {
  20045. const auto menu = playlist.getTrackMenuForSnapshot (track);
  20046. juce::StringArray names { "Track " + juce::String (track + 1) };
  20047. std::vector<juce::PopupMenu> menus { menu };
  20048. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  20049. if (it.getItem().subMenu != nullptr && it.getItem().text == lynx::theme::mnemonic (lynx::tr ("Track mode"), 'T'))
  20050. {
  20051. names.add (lynx::tr ("Track mode"));
  20052. menus.push_back (*it.getItem().subMenu);
  20053. }
  20054. if (menus.size() == 2)
  20055. for (juce::PopupMenu::MenuItemIterator it (menus[1]); it.next();)
  20056. if (it.getItem().subMenu != nullptr && it.getItem().text == lynx::theme::mnemonic (lynx::tr ("Audio track"), 'A'))
  20057. {
  20058. names.add (lynx::tr ("Audio track"));
  20059. menus.push_back (*it.getItem().subMenu);
  20060. }
  20061. juce::StringArray lynxList;
  20062. if (menus.size() == 3)
  20063. for (juce::PopupMenu::MenuItemIterator it (menus[2]); it.next();)
  20064. lynxList.add (it.getItem().isSeparator ? juce::String ("|")
  20065. : (it.getItem().isTicked ? "v " : "") + juce::String (it.getItem().isEnabled ? "" : "- ") + it.getItem().text);
  20066. saveMenus (names, menus, prefix + "-" + name + ".png");
  20067. const auto same = menus.size() == 3 && lynxList == fl;
  20068. all = all && same;
  20069. report << name << ": " << (same ? "SAME AS FL" : "DIFFERENT") << "\n LYNX: " << lynxList.joinIntoString (" / ")
  20070. << "\n FL: " << fl.joinIntoString (" / ") << "\n";
  20071. };
  20072. const auto flList = [] (int inserts, std::map<int, juce::String> named, std::set<int> greyed) {
  20073. juce::StringArray l { "New mixer track(s)", "|" };
  20074. for (int i = 1; i <= inserts; ++i)
  20075. l.add ((greyed.count (i) ? "- " : "") + juce::String (i) + ". " + (named.count (i) ? named[i] : "Insert " + juce::String (i)));
  20076. return l;
  20077. };
  20078. // q1-01: a fresh project, Track 1 unassigned
  20079. shoot (0, "fresh", flList (16, {}, {}));
  20080. // q1-02: Track 1 linked to insert 6, insert 7 renamed "Vox chain"; Track 2's menu
  20081. offline.editSong ([] (lynx::Song& s) {
  20082. lynx::trackmodes::assignAudioTracks (s, { 0 }, 6);
  20083. s.mixer[7].name = "Vox chain";
  20084. });
  20085. offline.dispatchPendingMessages();
  20086. shoot (1, "linked-renamed", flList (16, { { 7, "Vox chain" } }, { 6 }));
  20087. // q1-07: the rest of FL's session (live 190cu Q2): Track 3 → 7; Track 4 → New mixer track (17), insert 9
  20088. // renamed "Vox chain", Track 4 → 9; Track 5 "Lead" → 11, insert 12 "Vox chain", Track 5 → 12; Track 6 "Lead"
  20089. // (unassigned), insert 13 "Vox chain", Track 6 → 13. Track 7's menu
  20090. offline.editSong ([] (lynx::Song& s) {
  20091. namespace tm = lynx::trackmodes;
  20092. if (s.playlistTracks.size() < 8)
  20093. s.playlistTracks.resize (8);
  20094. tm::assignAudioTracks (s, { 2 }, 7);
  20095. tm::assignAudioTracks (s, { 3 }, tm::newMixerTrack);
  20096. s.mixer[9].name = "Vox chain";
  20097. tm::assignAudioTracks (s, { 3 }, 9);
  20098. s.playlistTracks[4].name = "Lead";
  20099. tm::assignAudioTracks (s, { 4 }, 11);
  20100. s.mixer[12].name = "Vox chain";
  20101. tm::assignAudioTracks (s, { 4 }, 12);
  20102. s.playlistTracks[5].name = "Lead";
  20103. s.mixer[13].name = "Vox chain";
  20104. tm::assignAudioTracks (s, { 5 }, 13);
  20105. });
  20106. offline.dispatchPendingMessages();
  20107. shoot (6, "full-state", flList (17, { { 7, "Vox chain" }, { 9, "Insert 17" }, { 12, "Lead" }, { 13, "Vox chain" } }, { 6, 7, 9, 12, 13 }));
  20108. }
  20109. report << (all ? "ALL SAME AS FL\n" : "FAILURES\n");
  20110. juce::File (prefix + "-report.txt").replaceWithText (report);
  20111. return all;
  20112. }
  20113. void runCurveShot (const juce::String& prefix)
  20114. {
  20115. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  20116. lynx::AudioEngine offline (false);
  20117. {
  20118. lynx::MainComponent ui (offline, false);
  20119. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  20120. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  20121. offline.dispatchPendingMessages();
  20122. // FL's menu order, one bar per mode, the levels going up and down; a tension where the mode needs one to show
  20123. static const int order[] = { lynx::flcurve::smooth, lynx::flcurve::hold, lynx::flcurve::singleCurve, lynx::flcurve::singleCurve2,
  20124. lynx::flcurve::singleCurve3, lynx::flcurve::doubleCurve, lynx::flcurve::doubleCurve2, lynx::flcurve::doubleCurve3,
  20125. lynx::flcurve::halfSine, lynx::flcurve::stairs, lynx::flcurve::smoothStairs, lynx::flcurve::pulse, lynx::flcurve::wave };
  20126. const auto bar = (std::int64_t) lynx::ppq * 4;
  20127. offline.editSong ([bar] (lynx::Song& song) {
  20128. song.mode = lynx::PlayMode::song;
  20129. lynx::Automation a;
  20130. a.name = "Curve modes";
  20131. a.target = { lynx::AutomationTargetKind::mixerVolume, 1 };
  20132. a.points.push_back ({ 0, 0.15f, 0.0f });
  20133. int k = 0;
  20134. for (const auto mode : order)
  20135. {
  20136. const auto stepped = mode == lynx::flcurve::stairs || mode == lynx::flcurve::smoothStairs || mode == lynx::flcurve::pulse || mode == lynx::flcurve::wave;
  20137. a.points.back().mode = (std::uint8_t) mode;
  20138. a.points.back().tension = mode == lynx::flcurve::smooth || mode == lynx::flcurve::hold ? 0.0f : stepped ? -0.72f : (k % 2 == 0 ? 0.55f : -0.55f);
  20139. ++k;
  20140. a.points.push_back ({ bar * k, k % 2 == 1 ? 0.85f : 0.15f, 0.0f });
  20141. }
  20142. song.automations.insert (song.automations.begin(), a);
  20143. for (auto& c : song.playlist)
  20144. if (c.kind == lynx::ClipKind::automation)
  20145. ++c.automation;
  20146. lynx::Clip clip;
  20147. clip.kind = lynx::ClipKind::automation;
  20148. clip.automation = 0;
  20149. clip.track = 3;
  20150. clip.length = bar * 13;
  20151. song.playlist.push_back (clip);
  20152. if (song.playlistTracks.size() < 4)
  20153. song.playlistTracks.resize (4);
  20154. song.playlistTracks[3].height = 150;
  20155. }, false);
  20156. offline.dispatchPendingMessages();
  20157. ui.selectTabForSnapshot (2);
  20158. offline.dispatchPendingMessages();
  20159. auto& playlist = ui.getPlaylistForSnapshot();
  20160. saveSnapshot (ui, prefix + "-playlist.png");
  20161. const auto clipIndex = (int) offline.getSong().playlist.size() - 1;
  20162. // the point menu of the point that ends the "Stairs" segment (point 10), and of the first point
  20163. saveMenus (juce::StringArray { "Automation point (ends a Stairs segment)", "First point" },
  20164. std::vector<juce::PopupMenu> { playlist.getAutomationPointMenuForSnapshot (clipIndex, 10), playlist.getAutomationPointMenuForSnapshot (clipIndex, 0) },
  20165. prefix + "-point-menu.png");
  20166. auto editor = lynx::makeAutomationEditor (offline, 0);
  20167. editor->setSize (1500, 420);
  20168. savePng (editor->createComponentSnapshot (editor->getLocalBounds()), prefix + "-editor.png");
  20169. editor.reset();
  20170. // the project itself, for --export-flp and a look at the same clip in FL
  20171. {
  20172. juce::String saveError;
  20173. lynx::ProjectFile::save (offline.getSong(), juce::File (prefix + "-modes.lynx"), saveError);
  20174. }
  20175. // part 2: the Piano roll tools that gained FL's options (they preview on the pattern and put the notes back)
  20176. ui.selectTabForSnapshot (1);
  20177. offline.dispatchPendingMessages();
  20178. auto& roll = ui.getPianoRollForSnapshot();
  20179. const std::pair<lynx::NoteTool, const char*> tools[] = { { lynx::NoteTool::flip, "-tool-flip.png" },
  20180. { lynx::NoteTool::limit, "-tool-limit.png" },
  20181. { lynx::NoteTool::scaleLevels, "-tool-scalelevels.png" },
  20182. { lynx::NoteTool::randomise, "-tool-randomise.png" },
  20183. { lynx::NoteTool::lfo, "-tool-lfo.png" } };
  20184. // round 190ct: checks of the FL-live fixes, one line each in <prefix>-checks.txt (OK / FAIL)
  20185. juce::StringArray checks;
  20186. const auto check = [&checks] (bool ok, const juce::String& what) { checks.add ((ok ? "OK " : "FAIL ") + what); };
  20187. {
  20188. juce::String header;
  20189. const auto pointMenu = playlist.getAutomationPointMenuForSnapshot (clipIndex, 10); // (the iterator keeps a reference)
  20190. for (juce::PopupMenu::MenuItemIterator it (pointMenu); it.next();)
  20191. {
  20192. header = it.getItem().text;
  20193. break;
  20194. }
  20195. check (header == "Point 11/14", "point menu header \"" + header + "\" (FL: \"Point n/N\")");
  20196. }
  20197. for (const auto& [tool, name] : tools)
  20198. {
  20199. auto panel = lynx::makeNoteToolPanel (offline, tool, roll.noteIndicesForSnapshot(), roll.gridForSnapshot());
  20200. offline.dispatchPendingMessages();
  20201. savePng (panel->createComponentSnapshot (panel->getLocalBounds()), prefix + name);
  20202. if (tool == lynx::NoteTool::flip)
  20203. {
  20204. std::vector<juce::ToggleButton*> toggles;
  20205. for (auto* child : panel->getChildren())
  20206. if (auto* t = dynamic_cast<juce::ToggleButton*> (child))
  20207. toggles.push_back (t);
  20208. check (toggles.size() == 3 && toggles[0]->getToggleState() && toggles[1]->getToggleState() && ! toggles[2]->getToggleState(),
  20209. "flip opens with Flip horizontally on, Preserve start times on, Flip vertically off");
  20210. if (toggles.size() == 3)
  20211. {
  20212. toggles[2]->setToggleState (true, juce::sendNotificationSync);
  20213. check (! toggles[0]->getToggleState() && toggles[2]->getToggleState(), "flip: vertically turns horizontally off (radios)");
  20214. toggles[0]->setToggleState (true, juce::sendNotificationSync);
  20215. check (toggles[0]->getToggleState() && ! toggles[2]->getToggleState(), "flip: horizontally turns vertically off (radios)");
  20216. }
  20217. }
  20218. if (tool == lynx::NoteTool::limit)
  20219. {
  20220. auto* list = lynx::noteToolLongestChoiceForSnapshot (*panel);
  20221. juce::ComboBox* key = nullptr;
  20222. for (auto* child : panel->getChildren())
  20223. if (auto* box = dynamic_cast<juce::ComboBox*> (child); box != nullptr && box->getNumItems() == 12)
  20224. key = box;
  20225. check (list != nullptr && list->getNumItems() == 89, "limit list has (none) + 66 chords + 22 scales: "
  20226. + juce::String (list != nullptr ? list->getNumItems() : 0));
  20227. check (list != nullptr && key != nullptr && list->getY() == key->getY() && list->getX() > key->getRight(),
  20228. "limit: Key and the chord / scale list share one row");
  20229. if (list != nullptr)
  20230. saveMenus (juce::StringArray { "Limit: Key / scale list" }, std::vector<juce::PopupMenu> { *list->getRootMenu() },
  20231. prefix + "-tool-limit-list.png");
  20232. }
  20233. if (tool == lynx::NoteTool::lfo)
  20234. saveMenus (juce::StringArray { "LFO tool: right-click on a Period slider" },
  20235. std::vector<juce::PopupMenu> { lynx::noteToolPresetMenuForSnapshot (*panel) }, prefix + "-tool-lfo-steps.png");
  20236. }
  20237. juce::File (prefix + "-checks.txt").replaceWithText (checks.joinIntoString ("\n") + "\n");
  20238. }
  20239. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  20240. }
  20241. bool runEvPaneShot (const juce::String& prefix, const juce::String& projectPath)
  20242. {
  20243. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  20244. lynx::AudioEngine offline (false);
  20245. juce::StringArray report;
  20246. bool ok = true;
  20247. {
  20248. lynx::MainComponent ui (offline, false);
  20249. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  20250. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  20251. if (projectPath.isNotEmpty())
  20252. ui.openFile (juce::File (projectPath));
  20253. offline.dispatchPendingMessages();
  20254. ui.selectTabForSnapshot (1); // the Piano Roll
  20255. offline.dispatchPendingMessages();
  20256. auto& roll = ui.getPianoRollForSnapshot();
  20257. roll.scrollToNotes();
  20258. const auto area = ui.getLocalArea (&roll, roll.getLocalBounds());
  20259. const auto file = lynx::platform::settingsFile ("piano-roll-event-pane.txt");
  20260. auto source = juce::Desktop::getInstance().getMainMouseSource();
  20261. const auto now = juce::Time::getCurrentTime();
  20262. auto event = [&] (juce::Point<int> p, juce::Point<int> down, juce::ModifierKeys mods, int clicks, bool dragged) {
  20263. 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);
  20264. };
  20265. auto barCentre = [&roll] { return roll.eventPaneBarArea().getCentre(); };
  20266. const juce::ModifierKeys left (juce::ModifierKeys::leftButtonModifier), right (juce::ModifierKeys::rightButtonModifier),
  20267. middle (juce::ModifierKeys::middleButtonModifier);
  20268. auto click = [&] (juce::ModifierKeys button, int clicks) {
  20269. const auto at = barCentre();
  20270. roll.mouseDown (event (at, at, button, clicks, false));
  20271. roll.mouseUp (event (at, at, {}, clicks, false));
  20272. offline.dispatchPendingMessages();
  20273. };
  20274. auto dragTo = [&] (int y) {
  20275. const auto at = barCentre();
  20276. roll.mouseDown (event (at, at, left, 1, false));
  20277. for (int step = 1; step <= 8; ++step) // (a few moves, as a hand does)
  20278. roll.mouseDrag (event ({ at.x, at.y + (y - at.y) * step / 8 }, at, left, 1, true));
  20279. roll.mouseUp (event ({ at.x, y }, at, {}, 1, true));
  20280. offline.dispatchPendingMessages();
  20281. };
  20282. auto state = [&] (const juce::String& name) {
  20283. const auto grid = roll.getHeight() - lynx::PianoRollComponent::headerHeight - roll.velocityHeight - lynx::evpane::barThickness;
  20284. const auto& st = lynx::PianoRollComponent::eventPaneState();
  20285. report.add (name + ": roll " + juce::String (roll.getHeight()) + " px, grid " + juce::String (juce::jmax (0, grid)) + " px, bar top "
  20286. + juce::String (roll.eventPaneBarTopForTests()) + ", event editor " + juce::String (roll.velocityHeight) + " px, aspect "
  20287. + juce::String (st.aspect, 4) + ", spare " + juce::String (st.spare, 4) + ", file \"" + file.loadFileAsString().trim().replace ("\n", " ") + "\"");
  20288. saveArea (ui, area, prefix + "-" + name + ".png");
  20289. };
  20290. auto expect = [&] (bool condition, const juce::String& what) {
  20291. report.add ((condition ? "PASS " : "FAIL ") + what);
  20292. ok = ok && condition;
  20293. };
  20294. state ("1-default");
  20295. const auto defaultLane = roll.velocityHeight;
  20296. expect (std::abs (lynx::PianoRollComponent::eventPaneState().aspect - 0.8f) < 1e-6f, "default place is FL's 0.8");
  20297. ui.setHintForSnapshot (roll.hintAt (barCentre()));
  20298. saveSnapshot (ui, prefix + "-2-hover-hint.png");
  20299. ui.setHintForSnapshot ({});
  20300. const auto travelTop = lynx::PianoRollComponent::headerHeight, travelBottom = roll.getHeight() - lynx::evpane::barThickness;
  20301. dragTo (travelTop + (travelBottom - travelTop) * 45 / 100);
  20302. state ("3-dragged-larger");
  20303. const auto largeLane = roll.velocityHeight;
  20304. expect (largeLane > defaultLane * 2, "drag up makes the event editor taller");
  20305. expect (lynx::evpane::fromText (file.loadFileAsString().toStdString()) == lynx::PianoRollComponent::eventPaneState(),
  20306. "the place is written to the settings file on release");
  20307. click (right, 1);
  20308. state ("4-right-click-alternate");
  20309. expect (roll.velocityHeight == 0, "right-click: the alternate size (FL's spare 1.0) folds the event editor away");
  20310. click (right, 1);
  20311. state ("5-right-click-back");
  20312. expect (roll.velocityHeight == largeLane, "right-click again: back to the dragged size");
  20313. roll.runAction ("pianoRoll.eventPaneAlternate");
  20314. offline.dispatchPendingMessages();
  20315. expect (roll.velocityHeight == 0, "Shift+Enter (pianoRoll.eventPaneAlternate) swaps too");
  20316. roll.runAction ("pianoRoll.eventPaneAlternate");
  20317. offline.dispatchPendingMessages();
  20318. dragTo (travelTop + 10);
  20319. state ("6-grid-folded");
  20320. expect (roll.eventPaneBarTopForTests() == travelTop, "a drag within 23 px of the top folds the note grid away");
  20321. click (middle, 1);
  20322. state ("7-middle-click-default");
  20323. expect (roll.velocityHeight == defaultLane, "middle-click: back to the default place");
  20324. // a taller window keeps the proportion (the place is a fraction of the travel)
  20325. dragTo (travelTop + (travelBottom - travelTop) * 60 / 100);
  20326. const auto before = lynx::PianoRollComponent::eventPaneState().aspect;
  20327. roll.setSize (roll.getWidth(), roll.getHeight() + 200);
  20328. offline.dispatchPendingMessages();
  20329. const auto newTravel = roll.getHeight() - lynx::evpane::barThickness - travelTop;
  20330. expect (std::abs (roll.eventPaneBarTopForTests() - (travelTop + juce::roundToInt (before * (float) newTravel))) <= 1,
  20331. "a taller window keeps the proportion");
  20332. roll.setSize (roll.getWidth(), roll.getHeight() - 200);
  20333. offline.dispatchPendingMessages();
  20334. click (middle, 1); // leave FL's default behind
  20335. }
  20336. report.add (ok ? "RESULT OK" : "RESULT FAIL");
  20337. juce::File (prefix + "-report.txt").replaceWithText (report.joinIntoString ("\n") + "\n");
  20338. return ok;
  20339. }
  20340. void runFeat166Shot (const juce::String& prefix, const juce::String& projectPath)
  20341. {
  20342. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  20343. lynx::AudioEngine offline (false);
  20344. {
  20345. lynx::MainComponent ui (offline, false);
  20346. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  20347. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  20348. if (projectPath.isNotEmpty())
  20349. ui.openFile (juce::File (projectPath));
  20350. offline.dispatchPendingMessages();
  20351. ui.selectTabForSnapshot (1); // the Piano Roll, on the channel with the most notes
  20352. offline.dispatchPendingMessages();
  20353. // the scale the pattern's notes fit best (major / minor, any root)
  20354. const auto& song = offline.getSong();
  20355. const auto& notes = song.patterns[(std::size_t) song.currentPattern].notes;
  20356. int bestRoot = 0, bestScale = 1, bestHits = -1;
  20357. for (int sc = 1; sc < (int) lynx::notetools::scales().size(); ++sc)
  20358. {
  20359. const juce::String name (lynx::notetools::scales()[(std::size_t) sc].name);
  20360. if (name != "Major" && name != "Minor")
  20361. continue;
  20362. for (int root = 0; root < 12; ++root)
  20363. {
  20364. int hits = 0;
  20365. for (const auto& n : notes)
  20366. hits += lynx::notetools::inScale (n.key, root, sc) ? 1 : 0;
  20367. if (hits > bestHits)
  20368. bestHits = hits, bestRoot = root, bestScale = sc;
  20369. }
  20370. }
  20371. auto& roll = ui.getPianoRollForSnapshot();
  20372. roll.setScaleForSnapshot (bestRoot, bestScale);
  20373. roll.scrollToNotes();
  20374. offline.dispatchPendingMessages();
  20375. saveSnapshot (ui, prefix + "-pr-scale.png");
  20376. roll.setFoldToScale (true);
  20377. offline.dispatchPendingMessages();
  20378. saveSnapshot (ui, prefix + "-pr-folded.png");
  20379. roll.setFoldToScale (false);
  20380. // ghost channels: only the first other channel with notes stays a ghost
  20381. const auto selected = offline.getSelectedChannel();
  20382. int keep = -1;
  20383. for (const auto& n : notes)
  20384. if (n.channel != selected && keep < 0)
  20385. keep = n.channel;
  20386. offline.editSong ([keep] (lynx::Song& s) {
  20387. for (int c = 0; c < (int) s.channels.size(); ++c)
  20388. s.channels[(std::size_t) c].ghostHidden = c != keep;
  20389. }, false);
  20390. offline.dispatchPendingMessages();
  20391. saveSnapshot (ui, prefix + "-pr-ghost-one.png");
  20392. saveMenus (juce::StringArray { "Ghost channels" }, { roll.ghostChannelsMenu() }, prefix + "-ghostmenu.png");
  20393. offline.editSong ([] (lynx::Song& s) {
  20394. for (auto& c : s.channels)
  20395. c.ghostHidden = false;
  20396. }, false);
  20397. // the Mixer at 500 inserts
  20398. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  20399. offline.editSong ([] (lynx::Song& s) { lynx::mixerops::insertTracks (s, (int) s.mixer.size(), lynx::mixerops::roomForInserts (s)); }, false);
  20400. const auto t1 = juce::Time::getMillisecondCounterHiRes();
  20401. offline.dispatchPendingMessages();
  20402. ui.selectTabForSnapshot (3);
  20403. offline.dispatchPendingMessages();
  20404. auto& mixer = ui.getMixerForSnapshot();
  20405. const auto t2 = juce::Time::getMillisecondCounterHiRes();
  20406. saveSnapshot (ui, prefix + "-mixer500-start.png");
  20407. const auto t3 = juce::Time::getMillisecondCounterHiRes();
  20408. mixer.selectTrack ((int) offline.getSong().mixer.size() - 1);
  20409. offline.dispatchPendingMessages();
  20410. saveSnapshot (ui, prefix + "-mixer500-end.png");
  20411. juce::File (prefix + "-mixer500.txt")
  20412. .replaceWithText ("inserts=" + juce::String ((int) offline.getSong().mixer.size() - 1) + "\nfill_ms=" + juce::String (t1 - t0, 2)
  20413. + "\nsnapshot_ms=" + juce::String (t3 - t2, 2) + "\n");
  20414. }
  20415. }
  20416. // Round 190ay, Freeze, end to end with the real engine, files and export (LYNX.exe --freezetest prefix [project]).
  20417. // The project (.lynx / .flp / .als; without one, a small demo song) is rendered live, every channel that can be
  20418. // frozen is frozen, and the same render is made again: the two mixes must null. Written to prefix-report.txt: the
  20419. // null residual, the process memory and the render time before / frozen / unfrozen, what a save holds, whether
  20420. // Unfreeze gives the channels back as they were, the out-of-date and missing-audio states. Shots: the Channel Rack
  20421. // (live, frozen, out of date), the channel menus, the Piano roll of a frozen channel. The frozen audio goes to
  20422. // prefix-data (never next to the project). True = every check passed.
  20423. bool runFreezeTest (const juce::String& prefix, const juce::String& projectPath, const juce::String& mode = {})
  20424. {
  20425. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  20426. lynx::AudioEngine offline (false);
  20427. lynx::MainComponent ui (offline, false);
  20428. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  20429. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  20430. const auto write = [&prefix, &ui] (const char* name) {
  20431. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  20432. file.deleteFile();
  20433. juce::FileOutputStream out (file);
  20434. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (ui), out);
  20435. };
  20436. juce::String report;
  20437. int failures = 0;
  20438. const auto check = [&] (bool ok, const juce::String& what) {
  20439. report << (ok ? "ok " : "FAIL ") << what << "\n";
  20440. failures += ok ? 0 : 1;
  20441. };
  20442. const auto flush = [&] { juce::File (prefix + "-report.txt").replaceWithText (report + "failures=" + juce::String (failures) + "\n"); };
  20443. if (projectPath.isNotEmpty())
  20444. {
  20445. ui.openFile (juce::File (projectPath));
  20446. offline.dispatchPendingMessages();
  20447. }
  20448. else
  20449. offline.editSong ([] (lynx::Song& s) {
  20450. s.channels.clear();
  20451. s.patterns.clear();
  20452. s.playlist.clear();
  20453. s.bpm = 120.0;
  20454. const char* names[] = { "Lead", "Bass", "Pad", "Kick" };
  20455. for (int c = 0; c < 4; ++c)
  20456. {
  20457. lynx::ChannelDef d;
  20458. d.name = names[c];
  20459. d.instrument = c == 3 ? lynx::InstrumentKind::kick : lynx::InstrumentKind::synth;
  20460. d.synth.release = 0.3f + 0.3f * (float) c;
  20461. d.synth.cutoff = 1500.0f + 900.0f * (float) c;
  20462. d.mixerTrack = c + 1;
  20463. s.channels.push_back (d);
  20464. }
  20465. for (int p = 0; p < 2; ++p)
  20466. {
  20467. auto& pattern = s.patterns.emplace_back();
  20468. pattern.name = p == 0 ? "Verse" : "Break";
  20469. pattern.lengthTicks = 4 * lynx::ppq * 4;
  20470. for (int c = 0; c < 4; ++c)
  20471. for (int step = 0; step < (p == 0 ? 8 : 2); ++step)
  20472. {
  20473. lynx::Note n;
  20474. n.channel = c;
  20475. n.start = (std::int64_t) step * lynx::ppq * (p == 0 ? 2 : 1) + (c == 2 ? lynx::ppq / 2 : 0);
  20476. n.length = c == 3 ? lynx::ppq / 4 : lynx::ppq;
  20477. n.key = c == 3 ? 36 : 48 + c * 7 + (step * 5) % 12;
  20478. pattern.notes.push_back (n);
  20479. }
  20480. pattern.sortNotes();
  20481. }
  20482. const int order[] = { 0, 0, 1, 0 };
  20483. for (int i = 0; i < 4; ++i)
  20484. {
  20485. lynx::Clip clip;
  20486. clip.pattern = order[i];
  20487. clip.start = (std::int64_t) i * 16 * lynx::ppq;
  20488. clip.length = 16 * lynx::ppq;
  20489. s.playlist.push_back (clip);
  20490. }
  20491. s.mode = lynx::PlayMode::song;
  20492. });
  20493. offline.dispatchPendingMessages();
  20494. // the case Freeze exists for, a heavy hosted plugin: LYNX_FREEZETEST_PLUGIN = a plugin file whose first
  20495. // instrument plays the demo song's Lead (tools/testplugin/lynx_test_heavy_vst3.cpp: memory, CPU, latency, a
  20496. // state, and with LYNX_TEST_HEAVY_LOG the instances alive)
  20497. int hostedChannel = -1;
  20498. const auto hostedLog = juce::SystemStats::getEnvironmentVariable ("LYNX_TEST_HEAVY_LOG", {});
  20499. const auto hostedAlive = [&hostedLog] {
  20500. int alive = 0;
  20501. juce::StringArray lines;
  20502. juce::File (hostedLog).readLines (lines);
  20503. for (const auto& l : lines)
  20504. alive += l.startsWith ("create") ? 1 : l.startsWith ("destroy") ? -1 : 0;
  20505. return alive;
  20506. };
  20507. if (const auto pluginPath = juce::SystemStats::getEnvironmentVariable ("LYNX_FREEZETEST_PLUGIN", {}); pluginPath.isNotEmpty() && projectPath.isEmpty())
  20508. {
  20509. auto& host = offline.getPluginHost();
  20510. const auto added = host.addPluginFile (juce::File (pluginPath));
  20511. report << "hosted plugin file: " << pluginPath << " (" << added << " plugins)\n";
  20512. for (const auto& type : host.getKnownPlugins().getTypes())
  20513. if (type.isInstrument && juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginPath).getFileName())
  20514. {
  20515. offline.editSong ([&type] (lynx::Song& s) {
  20516. auto& c = s.channels[0];
  20517. c.instrument = lynx::InstrumentKind::plugin;
  20518. c.plugin.id = type.createIdentifierString().toStdString();
  20519. c.plugin.name = type.name.toStdString();
  20520. });
  20521. hostedChannel = 0;
  20522. break;
  20523. }
  20524. offline.dispatchPendingMessages();
  20525. auto* instance = dynamic_cast<lynx::PluginInstrument*> (offline.getChannelInstrument (0).get());
  20526. check (hostedChannel == 0 && instance != nullptr, "the hosted plugin is loaded on channel 1");
  20527. report << "hosted plugin: " << juce::String::fromUTF8 (offline.getSong().channels[0].plugin.name.c_str())
  20528. << ", engine latency " << offline.getLatencySamples() << " frames, instances alive " << hostedAlive() << "\n";
  20529. }
  20530. const auto hostedLine = [&] (const char* stage) {
  20531. if (hostedChannel < 0)
  20532. return;
  20533. offline.freeRetiredRacks();
  20534. report << "hosted, " << stage << ": instance on the channel "
  20535. << (dynamic_cast<lynx::PluginInstrument*> (offline.getChannelInstrument (hostedChannel).get()) != nullptr ? "yes" : "no")
  20536. << ", plugin instances alive in the process " << (hostedLog.isNotEmpty() ? juce::String (hostedAlive()) : juce::String ("(no log)")) << "\n";
  20537. };
  20538. const juce::File data (prefix + "-data");
  20539. data.deleteRecursively();
  20540. offline.setRecordingTarget (data.getChildFile ("Audio").getChildFile ("Recorded"), "freezetest");
  20541. report << "project=" << (projectPath.isNotEmpty() ? projectPath : juce::String ("(demo song)")) << "\n"
  20542. << "frozen_audio_folder=" << offline.getFreezeFolder().getFullPathName() << "\n";
  20543. const auto megabytes = [] (std::int64_t bytes) { return juce::String ((double) bytes / 1048576.0, 1); };
  20544. struct Mix
  20545. {
  20546. juce::AudioBuffer<float> audio;
  20547. double renderSeconds = 0.0, audioSeconds = 0.0;
  20548. std::int64_t workingSet = 0, privateBytes = 0;
  20549. };
  20550. // the song as it stands, rendered by an export (its own engine: frozen channels play their audio there too)
  20551. const auto renderMix = [&] (const char* name, const lynx::Song* other = nullptr, std::vector<int>* renderedLive = nullptr, int range = 0) {
  20552. Mix m;
  20553. offline.dispatchPendingMessages();
  20554. offline.freeRetiredRacks(); // (what the message loop does in the app: this mode runs without one)
  20555. m.workingSet = lynx::toolbar::PerformanceMeter::processMemoryBytes();
  20556. m.privateBytes = lynx::toolbar::PerformanceMeter::processPrivateBytes();
  20557. const juce::File file (prefix + "-" + name + ".wav");
  20558. lynx::ExportSettings settings;
  20559. settings.format = lynx::ExportSettings::Format::wav32Float;
  20560. settings.sampleRate = offline.getTransport().sampleRate.load();
  20561. settings.tailSeconds = 2.0;
  20562. juce::String error;
  20563. {
  20564. auto options = settings.toOptions();
  20565. options.hqAllPlugins = false; // the quality heard while playing: what a frozen channel's audio is made at
  20566. options.disableMaxPolyphony = false; // (and each channel's Max polyphony, as while playing)
  20567. if (range == 1)
  20568. options.range = lynx::exportopts::Range::selection;
  20569. if (range == 2)
  20570. {
  20571. options.range = lynx::exportopts::Range::pattern;
  20572. options.loops = 2;
  20573. }
  20574. lynx::ExportJob job (other != nullptr ? *other : offline.getSong(), options, file);
  20575. if (renderedLive != nullptr)
  20576. *renderedLive = job.channelsRenderedLive();
  20577. const auto started = juce::Time::getMillisecondCounterHiRes();
  20578. const auto ok = job.run ([] (double) { return true; }, error);
  20579. m.renderSeconds = (juce::Time::getMillisecondCounterHiRes() - started) / 1000.0;
  20580. check (ok, juce::String ("render ") + name + (ok ? juce::String() : ": " + error));
  20581. }
  20582. juce::WavAudioFormat wav;
  20583. if (std::unique_ptr<juce::AudioFormatReader> reader { wav.createReaderFor (file.createInputStream().release(), true) })
  20584. {
  20585. m.audio.setSize (2, (int) reader->lengthInSamples);
  20586. reader->read (&m.audio, 0, (int) reader->lengthInSamples, 0, true, true);
  20587. m.audioSeconds = (double) reader->lengthInSamples / reader->sampleRate;
  20588. }
  20589. file.deleteFile();
  20590. return m;
  20591. };
  20592. // the worst sample difference, in dB below the first mix's peak
  20593. const auto residual = [] (const Mix& a, const Mix& b, float& peak) {
  20594. float worst = 0.0f;
  20595. peak = 0.0f;
  20596. const auto n = juce::jmin (a.audio.getNumSamples(), b.audio.getNumSamples());
  20597. for (int ch = 0; ch < 2; ++ch)
  20598. for (int i = 0; i < n; ++i)
  20599. {
  20600. worst = juce::jmax (worst, std::abs (a.audio.getSample (ch, i) - b.audio.getSample (ch, i)));
  20601. peak = juce::jmax (peak, std::abs (a.audio.getSample (ch, i)));
  20602. }
  20603. return worst <= 0.0f ? -200.0 : 20.0 * std::log10 ((double) worst / (double) juce::jmax (peak, 1.0e-12f));
  20604. };
  20605. const auto line = [&] (const char* name, const Mix& m) {
  20606. report << name << ": working set " << megabytes (m.workingSet) << " MB, private " << megabytes (m.privateBytes) << " MB, render "
  20607. << juce::String (m.renderSeconds, 2) << " s for " << juce::String (m.audioSeconds, 2) << " s of audio ("
  20608. << juce::String (m.audioSeconds > 0.0 ? 100.0 * m.renderSeconds / m.audioSeconds : 0.0, 1) << " % of real time)\n";
  20609. };
  20610. if (mode == "measure")
  20611. {
  20612. // a process that only loaded this project and renders it: its memory with the project loaded, and after
  20613. int frozenCount = 0, hosted = 0;
  20614. for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
  20615. {
  20616. frozenCount += offline.getSong().channels[(std::size_t) c].freeze.on();
  20617. hosted += dynamic_cast<lynx::PluginInstrument*> (offline.getChannelInstrument (c).get()) != nullptr;
  20618. }
  20619. report << "channels " << (int) offline.getSong().channels.size() << ", frozen " << frozenCount << ", hosted plugin instances " << hosted << "\n";
  20620. const auto m = renderMix ("measure");
  20621. line ("loaded ", m);
  20622. report << "after the render: working set " << megabytes (lynx::toolbar::PerformanceMeter::processMemoryBytes()) << " MB, private "
  20623. << megabytes (lynx::toolbar::PerformanceMeter::processPrivateBytes()) << " MB\n";
  20624. flush();
  20625. return failures == 0;
  20626. }
  20627. // --- live ---
  20628. offline.capturePluginStates();
  20629. offline.editSong ([] (lynx::Song&) {}, false); // (whatever any edit settles — ids of new objects... — settled first)
  20630. const auto before = offline.getSong();
  20631. // (the project's working-time counter runs on while the test does: not part of what is compared)
  20632. const auto savedJson = [] (lynx::Song song) {
  20633. song.info.workSeconds = 0.0;
  20634. return lynx::ProjectFile::toJson (song, false);
  20635. };
  20636. const auto jsonBefore = savedJson (before);
  20637. std::vector<int> targets;
  20638. for (int c = 0; c < (int) before.channels.size(); ++c)
  20639. {
  20640. const auto* why = lynx::freeze::whyNot (before, c);
  20641. const auto plays = std::any_of (before.patterns.begin(), before.patterns.end(), [c] (const lynx::Pattern& p) {
  20642. return std::any_of (p.notes.begin(), p.notes.end(), [c] (const lynx::Note& n) { return n.channel == c; });
  20643. });
  20644. report << "channel " << (c + 1) << " '" << juce::String::fromUTF8 (before.channels[(std::size_t) c].name.c_str()) << "': "
  20645. << (why != nullptr ? juce::String ("not frozen (") + why + ")" : plays ? juce::String ("freeze") : juce::String ("no notes, left alone")) << "\n";
  20646. if (why == nullptr && plays)
  20647. {
  20648. targets.push_back (c);
  20649. // what could make a stem differ from the live channel, for the record
  20650. const auto& def = before.channels[(std::size_t) c];
  20651. int volPan = 0, params = 0, live = 0, lanes = 0, routes = 0;
  20652. for (const auto& a : before.automations)
  20653. if (a.target.index == c)
  20654. {
  20655. volPan += a.target.kind == lynx::AutomationTargetKind::channelVolume || a.target.kind == lynx::AutomationTargetKind::channelPan;
  20656. params += a.target.kind == lynx::AutomationTargetKind::channelParam;
  20657. live += a.isLive() && (a.target.kind == lynx::AutomationTargetKind::channelVolume || a.target.kind == lynx::AutomationTargetKind::channelPan
  20658. || a.target.kind == lynx::AutomationTargetKind::channelParam);
  20659. }
  20660. for (const auto& p : before.patterns)
  20661. for (const auto& lane : p.events)
  20662. lanes += lane.target.index == c && (lane.target.kind == lynx::AutomationTargetKind::channelVolume
  20663. || lane.target.kind == lynx::AutomationTargetKind::channelPan
  20664. || lane.target.kind == lynx::AutomationTargetKind::channelParam);
  20665. for (const auto& m : before.modulators)
  20666. for (const auto& r : m.routes)
  20667. routes += r.target.index == c && (r.target.kind == lynx::AutomationTargetKind::channelVolume
  20668. || r.target.kind == lynx::AutomationTargetKind::channelPan
  20669. || r.target.kind == lynx::AutomationTargetKind::channelParam);
  20670. report << " instrument kind " << (int) def.instrument << ", insert " << def.mixerTrack << ", automation: volume/pan " << volPan
  20671. << ", parameters " << params << ", live links " << live << ", event lanes " << lanes << ", modulator routes " << routes << "\n";
  20672. }
  20673. }
  20674. check (! targets.empty(), "the project has channels to freeze (" + juce::String ((int) targets.size()) + ")");
  20675. if (targets.empty())
  20676. {
  20677. flush();
  20678. return false;
  20679. }
  20680. const auto first = targets.front();
  20681. offline.setSelectedChannel (first);
  20682. ui.selectTabForSnapshot (0);
  20683. write ("rack-live");
  20684. saveMenus (juce::StringArray { "Channel (live)" }, std::vector<juce::PopupMenu> { ui.getRackForSnapshot().getChannelMenuForSnapshot (first) }, prefix + "-menu-live.png");
  20685. const auto live = renderMix ("live");
  20686. line ("live ", live);
  20687. hostedLine ("live");
  20688. const auto hostedState = hostedChannel >= 0 ? before.channels[(std::size_t) hostedChannel].plugin.state : std::string();
  20689. if (hostedChannel >= 0)
  20690. check (! hostedState.empty(), "the hosted plugin's state is in the project (" + juce::String ((int) hostedState.size()) + " characters)");
  20691. flush();
  20692. // --- frozen ---
  20693. const auto freezeStarted = juce::Time::getMillisecondCounterHiRes();
  20694. for (const auto c : targets)
  20695. {
  20696. const auto error = lynx::freezeChannelNow (offline, c);
  20697. check (error.isEmpty(), "freeze channel " + juce::String (c + 1) + (error.isEmpty() ? juce::String() : ": " + error));
  20698. }
  20699. const auto freezeSeconds = (juce::Time::getMillisecondCounterHiRes() - freezeStarted) / 1000.0;
  20700. offline.dispatchPendingMessages();
  20701. std::int64_t stemBytes = 0;
  20702. int stemFiles = 0;
  20703. bool pluginsGone = true, allFrozen = true;
  20704. for (const auto c : targets)
  20705. {
  20706. const auto& ch = offline.getSong().channels[(std::size_t) c];
  20707. allFrozen = allFrozen && ch.freeze.on() && ! offline.frozenAudioMissing (c) && ! offline.freezeOutOfDate (c);
  20708. for (const auto& stem : ch.freeze.stems)
  20709. {
  20710. stemBytes += juce::File (juce::String::fromUTF8 (stem.path.c_str())).getSize();
  20711. ++stemFiles;
  20712. }
  20713. pluginsGone = pluginsGone && dynamic_cast<lynx::PluginInstrument*> (offline.getChannelInstrument (c).get()) == nullptr;
  20714. auto thawed = ch;
  20715. thawed.freeze = {};
  20716. check (thawed == before.channels[(std::size_t) c], "channel " + juce::String (c + 1) + " keeps its instrument and settings as they were while frozen");
  20717. }
  20718. check (allFrozen, "every target is frozen, its audio on disk and up to date");
  20719. check (pluginsGone, "no hosted plugin instance is left on a frozen channel");
  20720. report << "freeze: " << juce::String (freezeSeconds, 2) << " s for " << (int) targets.size() << " channels, " << stemFiles << " files, "
  20721. << megabytes (stemBytes) << " MB on disk\n";
  20722. if (mode == "keep")
  20723. {
  20724. juce::String error;
  20725. check (lynx::ProjectFile::save (offline.getSong(), juce::File (prefix + "-frozen.lynx"), error), "the frozen project is saved" + (error.isEmpty() ? juce::String() : ": " + error));
  20726. flush();
  20727. return failures == 0;
  20728. }
  20729. const auto frozen = renderMix ("frozen");
  20730. line ("frozen ", frozen);
  20731. hostedLine ("frozen");
  20732. if (hostedChannel >= 0 && hostedLog.isNotEmpty())
  20733. check (hostedAlive() == 0, "while frozen no instance of the hosted plugin is alive in the process");
  20734. float peak = 0.0f;
  20735. const auto nullFrozen = residual (live, frozen, peak);
  20736. report << "null frozen vs live: " << juce::String (nullFrozen, 1) << " dB (peak " << juce::String (peak, 4) << ", "
  20737. << live.audio.getNumSamples() << " / " << frozen.audio.getNumSamples() << " samples)\n";
  20738. check (peak > 0.001f && nullFrozen < -90.0 && live.audio.getNumSamples() == frozen.audio.getNumSamples(), "the frozen mix nulls against the live mix (below -90 dB)");
  20739. ui.selectTabForSnapshot (0);
  20740. ui.setHintForSnapshot (ui.getRackForSnapshot().getChannelHintForSnapshot (first));
  20741. write ("rack-frozen");
  20742. saveMenus (juce::StringArray { "Channel (frozen)" }, std::vector<juce::PopupMenu> { ui.getRackForSnapshot().getChannelMenuForSnapshot (first) }, prefix + "-menu-frozen.png");
  20743. report << "hint frozen: " << ui.getRackForSnapshot().getChannelHintForSnapshot (first).text << "\n";
  20744. offline.setSelectedChannel (first);
  20745. ui.selectTabForSnapshot (1);
  20746. offline.setSelectedChannel (first);
  20747. offline.dispatchPendingMessages();
  20748. ui.setHintForSnapshot ({ lynx::tr ("{0} is frozen: Unfreeze to edit ([RMB] on the channel, Unfreeze)",
  20749. { juce::String::fromUTF8 (offline.getSong().channels[(std::size_t) first].name.c_str()) }), {} });
  20750. write ("pianoroll-frozen");
  20751. // --- exports that do not play the song's timeline once: a selection, one pattern twice ---
  20752. // (the frozen audio is the whole song from its start: those renders play the instruments, never a wrong part of it)
  20753. if (projectPath.isEmpty())
  20754. {
  20755. auto part = offline.getSong();
  20756. part.loopStart = 16 * lynx::ppq;
  20757. part.loopEnd = 40 * lynx::ppq;
  20758. const auto partLive = lynx::freeze::thawed (part);
  20759. for (int range = 1; range <= 2; ++range)
  20760. {
  20761. std::vector<int> renderedLive;
  20762. const auto a = renderMix (range == 1 ? "selection-live" : "pattern-live", &partLive, nullptr, range);
  20763. const auto b = renderMix (range == 1 ? "selection-frozen" : "pattern-frozen", &part, &renderedLive, range);
  20764. float partPeak = 0.0f;
  20765. const auto null = residual (a, b, partPeak);
  20766. report << (range == 1 ? "export of a selection (bars 5-10)" : "export of the current pattern, twice") << ", frozen vs live: " << juce::String (null, 1)
  20767. << " dB (peak " << juce::String (partPeak, 4) << ", " << juce::String (b.audioSeconds, 2) << " s), channels rendered live: " << (int) renderedLive.size() << "\n";
  20768. check (partPeak > 0.001f && null < -90.0 && a.audio.getNumSamples() == b.audio.getNumSamples(),
  20769. 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");
  20770. }
  20771. }
  20772. // --- what a save holds ---
  20773. {
  20774. const auto json = lynx::ProjectFile::toJson (offline.getSong(), false);
  20775. juce::String error;
  20776. const auto loaded = lynx::ProjectFile::fromJson (json, error);
  20777. check (json.contains ("\"freeze\""), "the saved project holds the frozen state");
  20778. check (loaded.has_value() && loaded->channels.size() == offline.getSong().channels.size()
  20779. && loaded->channels[(std::size_t) first].freeze == offline.getSong().channels[(std::size_t) first].freeze,
  20780. "a frozen project loads frozen, with the same audio files");
  20781. check (savedJson (lynx::freeze::thawed (offline.getSong())) == jsonBefore,
  20782. "without the frozen state the saved project is byte for byte what it was before the freeze");
  20783. check (! jsonBefore.contains ("\"freeze\""), "a project with nothing frozen has no freeze field");
  20784. }
  20785. // --- out of date: the tempo, a note of the frozen channel; not another channel's notes ---
  20786. {
  20787. offline.editSong ([] (lynx::Song& s) { s.bpm += 4.0; });
  20788. check (offline.freezeOutOfDate (first), "a tempo change marks the freeze out of date");
  20789. ui.selectTabForSnapshot (0);
  20790. ui.setHintForSnapshot (ui.getRackForSnapshot().getChannelHintForSnapshot (first));
  20791. write ("rack-out-of-date");
  20792. report << "hint out of date: " << ui.getRackForSnapshot().getChannelHintForSnapshot (first).text << "\n";
  20793. offline.editSong ([] (lynx::Song& s) { s.bpm -= 4.0; });
  20794. check (! offline.freezeOutOfDate (first), "the tempo back: up to date again");
  20795. int pattern = -1;
  20796. for (int p = 0; p < (int) before.patterns.size() && pattern < 0; ++p)
  20797. for (const auto& n : before.patterns[(std::size_t) p].notes)
  20798. if (n.channel == first)
  20799. {
  20800. pattern = p;
  20801. break;
  20802. }
  20803. if (pattern >= 0)
  20804. {
  20805. offline.editSong ([pattern, first] (lynx::Song& s) {
  20806. lynx::Note n;
  20807. n.channel = first;
  20808. n.start = 0;
  20809. n.key = 71;
  20810. s.patterns[(std::size_t) pattern].notes.push_back (n);
  20811. s.patterns[(std::size_t) pattern].sortNotes();
  20812. });
  20813. check (offline.freezeOutOfDate (first), "a note edit on the frozen channel marks it out of date");
  20814. bool othersFresh = true;
  20815. for (const auto c : targets)
  20816. othersFresh = othersFresh && (c == first || ! offline.freezeOutOfDate (c));
  20817. check (othersFresh, "the other frozen channels stay up to date");
  20818. // an export of the project in that state: the out-of-date channel renders live (never the old audio),
  20819. // the others keep their frozen audio — the same mix as the edited project with nothing frozen
  20820. {
  20821. std::vector<int> renderedLive;
  20822. const auto stale = renderMix ("stale", nullptr, &renderedLive);
  20823. const auto edited = lynx::freeze::thawed (offline.getSong());
  20824. const auto reference = renderMix ("stale-reference", &edited);
  20825. float stalePeak = 0.0f;
  20826. const auto nullStale = residual (reference, stale, stalePeak);
  20827. const auto nullOld = residual (frozen, stale, stalePeak);
  20828. report << "export with channel " << (first + 1) << " out of date: " << juce::String (nullStale, 1) << " dB vs the edited project live, "
  20829. << juce::String (nullOld, 1) << " dB vs the old frozen mix; channels rendered live: " << (int) renderedLive.size() << "\n";
  20830. check (renderedLive == std::vector<int> { first }, "an export renders the out-of-date frozen channel live, and only that one");
  20831. check (nullStale < -90.0 && nullOld > -60.0, "an export of an out-of-date freeze holds the edited notes, not the old audio");
  20832. }
  20833. offline.editSong ([&before] (lynx::Song& s) { s.patterns = before.patterns; });
  20834. check (! offline.freezeOutOfDate (first), "the notes back: up to date again");
  20835. }
  20836. }
  20837. // --- the audio gone: the instrument plays, never silence ---
  20838. {
  20839. const auto stems = offline.getSong().channels[(std::size_t) first].freeze.stems;
  20840. std::vector<std::pair<juce::File, juce::File>> moved;
  20841. for (const auto& stem : stems)
  20842. {
  20843. const juce::File file (juce::String::fromUTF8 (stem.path.c_str()));
  20844. const auto away = file.getSiblingFile (file.getFileName() + ".away");
  20845. if (file.moveFileTo (away))
  20846. moved.emplace_back (file, away);
  20847. }
  20848. offline.editSong ([] (lynx::Song&) {}, false);
  20849. check (offline.frozenAudioMissing (first), "frozen audio that is not on disk is noticed");
  20850. report << "hint audio missing: " << ui.getRackForSnapshot().getChannelHintForSnapshot (first).text << "\n";
  20851. const auto fallback = renderMix ("missing");
  20852. const auto nullMissing = residual (live, fallback, peak);
  20853. report << "null with the first channel's audio missing vs live: " << juce::String (nullMissing, 1) << " dB\n";
  20854. check (nullMissing < -90.0, "with its audio missing the channel plays its instrument");
  20855. for (const auto& [file, away] : moved)
  20856. away.moveFileTo (file);
  20857. offline.editSong ([] (lynx::Song&) {}, false);
  20858. check (! offline.frozenAudioMissing (first), "the audio back: frozen again");
  20859. // the frozen mix did not null and the first channel is not (alone) why: which one is, each thawed in turn
  20860. if (nullFrozen >= -90.0 && nullMissing >= -90.0)
  20861. for (const auto c : targets)
  20862. {
  20863. if (c == first)
  20864. continue;
  20865. std::vector<std::pair<juce::File, juce::File>> aside;
  20866. for (const auto& stem : offline.getSong().channels[(std::size_t) c].freeze.stems)
  20867. {
  20868. const juce::File file (juce::String::fromUTF8 (stem.path.c_str()));
  20869. const auto away = file.getSiblingFile (file.getFileName() + ".away");
  20870. if (file.moveFileTo (away))
  20871. aside.emplace_back (file, away);
  20872. }
  20873. offline.editSong ([] (lynx::Song&) {}, false);
  20874. const auto one = renderMix ("thawed");
  20875. report << "null with channel " << (c + 1) << " thawed vs live: " << juce::String (residual (live, one, peak), 1) << " dB\n";
  20876. for (const auto& [file, away] : aside)
  20877. away.moveFileTo (file);
  20878. offline.editSong ([] (lynx::Song&) {}, false);
  20879. }
  20880. }
  20881. // --- unfrozen ---
  20882. std::vector<juce::File> stemPaths;
  20883. for (const auto c : targets)
  20884. for (const auto& stem : offline.getSong().channels[(std::size_t) c].freeze.stems)
  20885. stemPaths.emplace_back (juce::String::fromUTF8 (stem.path.c_str()));
  20886. for (const auto c : targets)
  20887. lynx::unfreezeChannel (offline, c);
  20888. offline.dispatchPendingMessages();
  20889. check (offline.getSong().channels == before.channels, "Unfreeze gives every channel back exactly as it was (instrument, plugin state, settings)");
  20890. {
  20891. const auto jsonAfter = savedJson (offline.getSong());
  20892. check (jsonAfter == jsonBefore, "the unfrozen project saves byte for byte as before the freeze");
  20893. if (jsonAfter != jsonBefore)
  20894. {
  20895. juce::File (prefix + "-before.json").replaceWithText (jsonBefore);
  20896. juce::File (prefix + "-after.json").replaceWithText (jsonAfter);
  20897. }
  20898. }
  20899. int left = 0;
  20900. for (const auto& f : stemPaths)
  20901. left += f.existsAsFile() ? 1 : 0;
  20902. check (left == 0, "Unfreeze deletes the frozen audio (" + juce::String (left) + " of " + juce::String ((int) stemPaths.size()) + " files left)");
  20903. if (hostedChannel >= 0)
  20904. {
  20905. // the new instance (it starts with another tuning than the first one had) took the saved state
  20906. offline.capturePluginStates();
  20907. check (dynamic_cast<lynx::PluginInstrument*> (offline.getChannelInstrument (hostedChannel).get()) != nullptr, "Unfreeze loads the hosted plugin again");
  20908. check (offline.getSong().channels[(std::size_t) hostedChannel].plugin.state == hostedState,
  20909. "the hosted plugin's state, read back from the new instance, is the state it had before the freeze");
  20910. }
  20911. const auto unfrozen = renderMix ("unfrozen");
  20912. line ("unfrozen ", unfrozen);
  20913. hostedLine ("unfrozen");
  20914. const auto nullUnfrozen = residual (live, unfrozen, peak);
  20915. report << "null unfrozen vs live: " << juce::String (nullUnfrozen, 1) << " dB\n";
  20916. check (nullUnfrozen < -90.0, "the unfrozen mix nulls against the live mix");
  20917. ui.selectTabForSnapshot (0);
  20918. flush();
  20919. data.deleteRecursively();
  20920. return failures == 0;
  20921. }
  20922. // Round 190ff, the Clip-launch workflow's track commands end to end with the real engine, files and export
  20923. // (LYNX --trackfreezetest prefix). A demo song of three tracks (Lead through a delay and a reverb whose mix is
  20924. // automated, Bass through a delay, Drums on a bare insert; each insert's fader, pan and EQ set) is rendered live; then
  20925. // Freeze Track on every track (the instrument with its volume and pan through its insert's effects), the same render
  20926. // again (must null), the effects and instruments unloaded, the render time (the CPU while frozen), what a save holds;
  20927. // Flatten (Bounce Track in Place on a frozen track) with its undo; Bounce Track in Place of a live track; Bounce to New
  20928. // Track of a track's clips against that track's device output; Consolidate of pattern clips; Unfreeze. Written to
  20929. // prefix-report.txt; shots of the grid, the column menus, the Detail View's frozen devices and the Playlist's clip
  20930. // menu. True = every check passed.
  20931. bool runTrackFreezeTest (const juce::String& prefix)
  20932. {
  20933. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  20934. lynx::AudioEngine offline (false);
  20935. lynx::MainComponent ui (offline, false);
  20936. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  20937. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  20938. const auto write = [&prefix, &ui] (const char* name) {
  20939. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  20940. file.deleteFile();
  20941. juce::FileOutputStream out (file);
  20942. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (ui), out);
  20943. };
  20944. juce::String report;
  20945. int failures = 0;
  20946. const auto check = [&] (bool ok, const juce::String& what) {
  20947. report << (ok ? "ok " : "FAIL ") << what << "\n";
  20948. failures += ok ? 0 : 1;
  20949. };
  20950. const auto flush = [&] { juce::File (prefix + "-report.txt").replaceWithText (report + "failures=" + juce::String (failures) + "\n"); };
  20951. const juce::File data (prefix + "-data");
  20952. data.deleteRecursively();
  20953. offline.setRecordingTarget (data.getChildFile ("Audio").getChildFile ("Recorded"), "trackfreezetest");
  20954. ui.setVisible (true);
  20955. lynx::DetailView::shownSetting = lynx::DetailView::devicesPage = true;
  20956. ui.setClipLaunchWorkflow (true);
  20957. offline.editSong ([] (lynx::Song& s) {
  20958. s.channels.clear();
  20959. s.patterns.clear();
  20960. s.playlist.clear();
  20961. s.automations.clear();
  20962. s.bpm = 120.0;
  20963. s.mode = lynx::PlayMode::song;
  20964. const char* names[] = { "Lead", "Bass", "Drums" };
  20965. for (int c = 0; c < 3; ++c)
  20966. {
  20967. lynx::ChannelDef d;
  20968. d.name = names[c];
  20969. d.instrument = c == 2 ? lynx::InstrumentKind::kick : lynx::InstrumentKind::synth;
  20970. d.synth.release = c == 0 ? 0.6f : 0.2f;
  20971. d.synth.cutoff = c == 0 ? 2400.0f : 900.0f;
  20972. d.volume = c == 0 ? 0.65f : 0.78f;
  20973. d.pan = c == 0 ? 0.25f : 0.0f;
  20974. d.mixerTrack = c + 1;
  20975. s.channels.push_back (d);
  20976. }
  20977. if (s.mixer.size() < 5)
  20978. s.mixer.resize (5);
  20979. s.mixer[1].effects = { lynx::makeEffectSlot (lynx::EffectKind::delay), lynx::makeEffectSlot (lynx::EffectKind::reverb) };
  20980. s.mixer[2].effects = { lynx::makeEffectSlot (lynx::EffectKind::delay) };
  20981. s.mixer[3].effects.clear();
  20982. for (int t = 1; t <= 3; ++t)
  20983. {
  20984. s.mixer[(std::size_t) t].name = names[t - 1];
  20985. s.mixer[(std::size_t) t].volume = 0.7f;
  20986. s.mixer[(std::size_t) t].pan = t == 1 ? -0.3f : 0.1f;
  20987. s.mixer[(std::size_t) t].eq.gainDb[1] = 3.0f;
  20988. }
  20989. for (int p = 0; p < 3; ++p)
  20990. {
  20991. auto& pattern = s.patterns.emplace_back();
  20992. pattern.name = names[p];
  20993. pattern.lengthTicks = 4 * lynx::ppq * 2;
  20994. for (int step = 0; step < 8; ++step)
  20995. {
  20996. lynx::Note n;
  20997. n.channel = p;
  20998. n.start = (std::int64_t) step * lynx::ppq;
  20999. n.length = p == 2 ? lynx::ppq / 4 : lynx::ppq / 2;
  21000. n.key = p == 2 ? 36 : (p == 0 ? 60 : 36) + (step * 5) % 12;
  21001. pattern.notes.push_back (n);
  21002. }
  21003. }
  21004. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 4));
  21005. for (int t = 0; t < 3; ++t)
  21006. {
  21007. s.playlistTracks[(std::size_t) t].name = names[t];
  21008. for (int k = 0; k < 3; ++k)
  21009. {
  21010. if (t == 0 && k == 1)
  21011. continue; // (a gap in the Lead: its tail rings into it)
  21012. lynx::Clip clip;
  21013. clip.pattern = t;
  21014. clip.track = t;
  21015. clip.start = (std::int64_t) k * 8 * lynx::ppq;
  21016. clip.length = 8 * lynx::ppq;
  21017. s.playlist.push_back (clip);
  21018. }
  21019. }
  21020. // the Lead's reverb mix rises over the song (automation the freeze takes into its audio)
  21021. lynx::Automation a;
  21022. a.name = "Lead reverb mix";
  21023. a.target = { lynx::AutomationTargetKind::effectMix, 1, 1, 0 };
  21024. a.points = { { 0, 0.2f }, { 24 * lynx::ppq, 0.9f } };
  21025. s.automations.push_back (a);
  21026. lynx::Clip lane;
  21027. lane.kind = lynx::ClipKind::automation;
  21028. lane.automation = 0;
  21029. lane.track = 3;
  21030. lane.length = 24 * lynx::ppq;
  21031. s.playlist.push_back (lane);
  21032. std::stable_sort (s.playlist.begin(), s.playlist.end(), [] (const lynx::Clip& x, const lynx::Clip& y) { return x.start < y.start; });
  21033. });
  21034. offline.dispatchPendingMessages();
  21035. const auto megabytes = [] (std::int64_t bytes) { return juce::String ((double) bytes / 1048576.0, 1); };
  21036. struct Mix
  21037. {
  21038. juce::AudioBuffer<float> audio;
  21039. double renderSeconds = 0.0, audioSeconds = 0.0;
  21040. };
  21041. const auto renderMix = [&] (const char* name, const lynx::Song* other = nullptr) {
  21042. Mix m;
  21043. offline.dispatchPendingMessages();
  21044. offline.freeRetiredRacks();
  21045. const juce::File file (prefix + "-" + name + ".wav");
  21046. lynx::ExportSettings settings;
  21047. settings.format = lynx::ExportSettings::Format::wav32Float;
  21048. settings.sampleRate = offline.getTransport().sampleRate.load();
  21049. settings.tailSeconds = 2.0;
  21050. juce::String error;
  21051. auto options = settings.toOptions();
  21052. options.hqAllPlugins = false;
  21053. options.disableMaxPolyphony = false;
  21054. {
  21055. lynx::ExportJob job (other != nullptr ? *other : offline.getSong(), options, file);
  21056. const auto started = juce::Time::getMillisecondCounterHiRes();
  21057. const auto ok = job.run ([] (double) { return true; }, error);
  21058. m.renderSeconds = (juce::Time::getMillisecondCounterHiRes() - started) / 1000.0;
  21059. check (ok, juce::String ("render ") + name + (ok ? juce::String() : ": " + error));
  21060. }
  21061. juce::WavAudioFormat wav;
  21062. if (std::unique_ptr<juce::AudioFormatReader> reader { wav.createReaderFor (file.createInputStream().release(), true) })
  21063. {
  21064. m.audio.setSize (2, (int) reader->lengthInSamples);
  21065. reader->read (&m.audio, 0, (int) reader->lengthInSamples, 0, true, true);
  21066. m.audioSeconds = (double) reader->lengthInSamples / reader->sampleRate;
  21067. }
  21068. if (juce::SystemStats::getEnvironmentVariable ("LYNX_TRACKFREEZE_KEEP", {}).isEmpty()) // (kept: to look at a residual)
  21069. file.deleteFile();
  21070. return m;
  21071. };
  21072. const auto residual = [] (const Mix& a, const Mix& b, float& peak) {
  21073. float worst = 0.0f;
  21074. peak = 0.0f;
  21075. const auto n = juce::jmin (a.audio.getNumSamples(), b.audio.getNumSamples());
  21076. for (int ch = 0; ch < 2; ++ch)
  21077. for (int i = 0; i < n; ++i)
  21078. {
  21079. worst = juce::jmax (worst, std::abs (a.audio.getSample (ch, i) - b.audio.getSample (ch, i)));
  21080. peak = juce::jmax (peak, std::abs (a.audio.getSample (ch, i)));
  21081. }
  21082. return worst <= 0.0f ? -200.0 : 20.0 * std::log10 ((double) worst / (double) juce::jmax (peak, 1.0e-12f));
  21083. };
  21084. const auto nullLine = [&] (const char* what, const Mix& a, const Mix& b, double limit) {
  21085. float peak = 0.0f;
  21086. const auto r = residual (a, b, peak);
  21087. report << what << ": " << juce::String (r, 1) << " dB (peak " << juce::String (peak, 4) << ", " << a.audio.getNumSamples() << " / "
  21088. << b.audio.getNumSamples() << " samples)\n";
  21089. check (peak > 0.001f && r < limit && a.audio.getNumSamples() == b.audio.getNumSamples(), juce::String (what) + " below " + juce::String (limit, 0) + " dB");
  21090. return r;
  21091. };
  21092. const auto savedJson = [] (lynx::Song song) {
  21093. song.info.workSeconds = 0.0;
  21094. return lynx::ProjectFile::toJson (song, false);
  21095. };
  21096. // --- live ---
  21097. offline.capturePluginStates();
  21098. offline.editSong ([] (lynx::Song&) {}, false);
  21099. const auto before = offline.getSong();
  21100. const auto jsonBefore = savedJson (before);
  21101. auto* grid = ui.getClipGridForSnapshot();
  21102. check (grid != nullptr, "the Clip-launch workflow's grid is there");
  21103. if (grid == nullptr)
  21104. {
  21105. flush();
  21106. return false;
  21107. }
  21108. ui.setClipGridView (lynx::PlaylistArea::GridView::beside);
  21109. write ("live");
  21110. saveMenus (juce::StringArray { "Track title (live)" }, std::vector<juce::PopupMenu> { lynx::clipGridHeaderMenu (*grid, 0) }, prefix + "-menu-track-live.png");
  21111. int leadClip = -1;
  21112. for (int i = 0; i < (int) before.playlist.size() && leadClip < 0; ++i)
  21113. if (before.playlist[(std::size_t) i].track == 0 && before.playlist[(std::size_t) i].kind == lynx::ClipKind::pattern)
  21114. leadClip = i;
  21115. ui.getPlaylistForSnapshot().selectForSnapshot ({ leadClip });
  21116. saveMenus (juce::StringArray { "Playlist clip (Clip-launch workflow)" }, std::vector<juce::PopupMenu> { ui.getPlaylistForSnapshot().getClipMenuForSnapshot (leadClip) },
  21117. prefix + "-menu-clip.png");
  21118. const auto live = renderMix ("live");
  21119. report << "live: render " << juce::String (live.renderSeconds, 2) << " s for " << juce::String (live.audioSeconds, 2) << " s of audio\n";
  21120. // --- Freeze Track on every track ---
  21121. std::vector<int> channels;
  21122. for (int t = 0; t < 3; ++t)
  21123. {
  21124. const auto c = lynx::detailchain::forTrack (before, t).channel;
  21125. check (c == t, "track " + juce::String (t + 1) + " shows channel " + juce::String (t + 1));
  21126. const auto* why = lynx::freeze::whyNotTrack (before, c);
  21127. check (why == nullptr, "track " + juce::String (t + 1) + " can be frozen" + (why != nullptr ? juce::String (": ") + why : juce::String()));
  21128. const auto error = lynx::freezeTrackNow (offline, c);
  21129. check (error.isEmpty(), "Freeze Track " + juce::String (t + 1) + (error.isEmpty() ? juce::String() : ": " + error));
  21130. channels.push_back (c);
  21131. }
  21132. offline.dispatchPendingMessages();
  21133. offline.freeRetiredRacks();
  21134. int loadedEffects = 0;
  21135. for (int t = 1; t <= 3; ++t)
  21136. for (int slot = 0; slot < (int) offline.getSong().mixer[(std::size_t) t].effects.size(); ++slot)
  21137. loadedEffects += offline.getEffect (t, slot) != nullptr ? 1 : 0;
  21138. check (loadedEffects == 0, "no effect of a frozen track is loaded (" + juce::String (loadedEffects) + " left)");
  21139. bool fresh = true;
  21140. for (const auto c : channels)
  21141. {
  21142. const auto& f = offline.getSong().channels[(std::size_t) c].freeze;
  21143. fresh = fresh && f.on() && f.insert == c + 1 && lynx::freeze::trackFreezeHolds (offline.getSong(), c) && ! offline.freezeOutOfDate (c)
  21144. && ! offline.frozenAudioMissing (c);
  21145. }
  21146. check (fresh, "every track is frozen with its insert, its audio on disk and up to date");
  21147. check (offline.getSong().mixer == before.mixer, "the project keeps every effect as it was (Unfreeze brings them back)");
  21148. const auto frozenSong = offline.getSong();
  21149. const auto frozen = renderMix ("frozen");
  21150. report << "frozen: render " << juce::String (frozen.renderSeconds, 2) << " s (" << juce::String (100.0 * frozen.renderSeconds / juce::jmax (0.001, live.renderSeconds), 0)
  21151. << " % of the live render's time)\n";
  21152. nullLine ("frozen vs live", live, frozen, -90.0);
  21153. write ("frozen");
  21154. saveMenus (juce::StringArray { "Track title (frozen)" }, std::vector<juce::PopupMenu> { lynx::clipGridHeaderMenu (*grid, 0) }, prefix + "-menu-track-frozen.png");
  21155. if (auto* detail = ui.getDetailViewForSnapshot())
  21156. {
  21157. detail->showSelection (0, 0);
  21158. detail->setPage (lynx::DetailView::Page::devices);
  21159. write ("detail-frozen");
  21160. }
  21161. // the insert's fader is live: moved, the frozen and the live song change alike
  21162. {
  21163. auto liveLouder = before, frozenLouder = frozenSong;
  21164. liveLouder.mixer[1].volume = frozenLouder.mixer[1].volume = 0.8f;
  21165. nullLine ("frozen vs live, the Lead's fader moved afterwards", renderMix ("live-louder", &liveLouder), renderMix ("frozen-louder", &frozenLouder), -90.0);
  21166. }
  21167. // --- what a save holds ---
  21168. {
  21169. const auto json = lynx::ProjectFile::toJson (offline.getSong(), false);
  21170. juce::String error;
  21171. const auto loaded = lynx::ProjectFile::fromJson (json, error);
  21172. check (json.contains ("\"trackFreeze\"") && ! json.contains ("\"freeze\""), "a track freeze is saved under its own key (older versions play it live)");
  21173. check (loaded.has_value() && loaded->channels.size() == frozenSong.channels.size() && loaded->channels[0].freeze == frozenSong.channels[0].freeze,
  21174. "a track-frozen project loads frozen, with its insert and audio files");
  21175. check (savedJson (lynx::freeze::thawed (offline.getSong())) == jsonBefore, "without the frozen state the project saves as before the freeze");
  21176. }
  21177. // --- an edit of a frozen device's insert routing: the freeze stops holding, the track plays live ---
  21178. {
  21179. offline.editSong ([] (lynx::Song& s) { s.channels[1].mixerTrack = 1; }); // (the Bass into the Lead's insert)
  21180. check (! lynx::freeze::trackFreezeHolds (offline.getSong(), 0) && offline.freezeOutOfDate (0), "another channel routed into a frozen insert: out of date, plays live");
  21181. offline.undo();
  21182. offline.dispatchPendingMessages();
  21183. check (lynx::freeze::trackFreezeHolds (offline.getSong(), 0) && ! offline.freezeOutOfDate (0), "undo: frozen again");
  21184. }
  21185. // --- Flatten: Bounce Track in Place on the frozen Lead, and its undo ---
  21186. {
  21187. const auto error = lynx::flattenChannelNow (offline, 0);
  21188. check (error.isEmpty(), "Bounce Track in Place of the frozen Lead (Flatten)" + (error.isEmpty() ? juce::String() : ": " + error));
  21189. const auto& song = offline.getSong();
  21190. check (song.channels[0].instrument == lynx::InstrumentKind::audioClip && song.mixer[1].effects.empty() && song.mixer[1].volume == before.mixer[1].volume
  21191. && song.channels[0].name == "Lead (Bounce)",
  21192. "the Lead is audio now (\"Lead (Bounce)\"), its insert's effects removed, its fader kept");
  21193. int audioClips = 0;
  21194. for (const auto& c : song.playlist)
  21195. audioClips += c.kind == lynx::ClipKind::audio && c.channel == 0;
  21196. report << "flattened Lead: " << audioClips << " audio clips\n";
  21197. write ("flattened");
  21198. // over the song (the flattened clips end where the arrangement ends, as a frozen track plays; an export's
  21199. // ring-out after the song's end is not in them)
  21200. const auto span = (int) std::llround (before.secondsForTicks (24 * lynx::ppq) * offline.getTransport().sampleRate.load());
  21201. auto flatMix = renderMix ("flattened");
  21202. auto reference = live;
  21203. reference.audio.setSize (2, juce::jmin (span, reference.audio.getNumSamples()), true);
  21204. flatMix.audio.setSize (2, reference.audio.getNumSamples(), true);
  21205. nullLine ("flattened (Lead) + frozen (others) vs live, over the song", reference, flatMix, -90.0);
  21206. offline.undo();
  21207. offline.dispatchPendingMessages();
  21208. check (savedJson (offline.getSong()) == savedJson (frozenSong), "undo of the Flatten: the frozen project exactly as before");
  21209. }
  21210. // --- Unfreeze every track ---
  21211. for (const auto c : channels)
  21212. lynx::unfreezeChannel (offline, c);
  21213. offline.dispatchPendingMessages();
  21214. check (savedJson (offline.getSong()) == jsonBefore, "Unfreeze: the project saves byte for byte as before the freeze");
  21215. nullLine ("unfrozen vs live", live, renderMix ("unfrozen"), -90.0);
  21216. // --- Bounce Track in Place of a live track (render and flatten in one step, one undo) ---
  21217. {
  21218. const auto error = lynx::freezeTrackNow (offline, 1, true);
  21219. check (error.isEmpty(), "Bounce Track in Place of the live Bass" + (error.isEmpty() ? juce::String() : ": " + error));
  21220. check (offline.getSong().channels[1].instrument == lynx::InstrumentKind::audioClip && ! offline.getSong().channels[1].freeze.on(),
  21221. "the Bass is audio, not frozen");
  21222. auto bouncedMix = renderMix ("bounced");
  21223. auto reference = live;
  21224. const auto span = (int) std::llround (before.secondsForTicks (24 * lynx::ppq) * offline.getTransport().sampleRate.load());
  21225. reference.audio.setSize (2, juce::jmin (span, reference.audio.getNumSamples()), true);
  21226. bouncedMix.audio.setSize (2, reference.audio.getNumSamples(), true);
  21227. nullLine ("Bass bounced in place vs live, over the song", reference, bouncedMix, -90.0);
  21228. offline.undo();
  21229. offline.dispatchPendingMessages();
  21230. check (savedJson (offline.getSong()) == jsonBefore, "undo of Bounce Track in Place: the project as before");
  21231. }
  21232. // --- Bounce to New Track: the Lead's clips onto a new track (the clips muted, the new track with the Lead's mixer) ---
  21233. {
  21234. std::vector<int> leadClips;
  21235. for (int i = 0; i < (int) offline.getSong().playlist.size(); ++i)
  21236. if (offline.getSong().playlist[(std::size_t) i].track == 0 && offline.getSong().playlist[(std::size_t) i].kind == lynx::ClipKind::pattern)
  21237. leadClips.push_back (i);
  21238. const auto channelsBefore = offline.getSong().channels.size();
  21239. const auto error = lynx::bounceToNewTrack (offline, leadClips, true);
  21240. check (error.isEmpty(), "Bounce to New Track of the Lead's clips" + (error.isEmpty() ? juce::String() : ": " + error));
  21241. const auto& song = offline.getSong();
  21242. check (song.channels.size() == channelsBefore + 1 && song.channels.back().instrument == lynx::InstrumentKind::audioClip
  21243. && song.channels.back().mixerTrack > 3 && song.mixer[(std::size_t) song.channels.back().mixerTrack].volume == before.mixer[1].volume,
  21244. "a new audio channel holds the bounce, on an insert with the Lead's mixer");
  21245. // the song's span (the bounce stops at the last clip's end, the live render rings on after it)
  21246. auto bounced = renderMix ("bounced-new-track");
  21247. auto reference = live;
  21248. const auto span = (int) std::llround (before.secondsForTicks (24 * lynx::ppq) * offline.getTransport().sampleRate.load());
  21249. reference.audio.setSize (2, juce::jmin (span, reference.audio.getNumSamples()), true);
  21250. bounced.audio.setSize (2, reference.audio.getNumSamples(), true);
  21251. nullLine ("Bounce to New Track (Lead's clips muted) vs live, over the song", reference, bounced, -90.0);
  21252. write ("bounced-new-track");
  21253. offline.undo();
  21254. offline.dispatchPendingMessages();
  21255. check (savedJson (offline.getSong()) == jsonBefore, "undo of Bounce to New Track: the project as before");
  21256. }
  21257. // --- Consolidate: the Bass's three pattern clips become one ---
  21258. {
  21259. std::vector<int> bassClips;
  21260. for (int i = 0; i < (int) offline.getSong().playlist.size(); ++i)
  21261. if (offline.getSong().playlist[(std::size_t) i].track == 1 && offline.getSong().playlist[(std::size_t) i].kind == lynx::ClipKind::pattern)
  21262. bassClips.push_back (i);
  21263. const auto error = lynx::consolidateClips (offline, bassClips, true);
  21264. check (error.isEmpty(), "Consolidate of the Bass's clips" + (error.isEmpty() ? juce::String() : ": " + error));
  21265. int left = 0;
  21266. for (const auto& c : offline.getSong().playlist)
  21267. left += c.track == 1 && c.kind == lynx::ClipKind::pattern;
  21268. check (left == 1, "one clip on the Bass track (" + juce::String (left) + ")");
  21269. nullLine ("consolidated vs live", live, renderMix ("consolidated"), -90.0);
  21270. offline.undo();
  21271. offline.dispatchPendingMessages();
  21272. check (savedJson (offline.getSong()) == jsonBefore, "undo of Consolidate: the project as before");
  21273. }
  21274. report << "frozen audio folder: " << offline.getFreezeFolder().getFullPathName() << "\n";
  21275. flush();
  21276. data.deleteRecursively();
  21277. (void) megabytes;
  21278. return failures == 0;
  21279. }
  21280. // --paintbench (round 190ge): the paint cost of every main view, off screen. Each view is shown maximised in a
  21281. // LYNX_SNAPSHOT_SIZE window (default 1920x1080) and drawn whole into a picture `frames` times (after a repaint of
  21282. // all of it, so no cached picture is reused: the cost of a frame after an edit), then `frames` times without the
  21283. // repaint (what a view's own caches leave of a frame). The report gives the median and the 90th percentile of
  21284. // the message thread's CPU per frame.
  21285. void runPaintBench (const juce::File& project, const juce::File& report)
  21286. {
  21287. // LYNX_PROFILE_MAIN=<file> (round 190gr): the message thread sampled while it paints (Windows; one view at a time
  21288. // with LYNX_PAINTBENCH_VIEWS)
  21289. const auto profile = juce::SystemStats::getEnvironmentVariable ("LYNX_PROFILE_MAIN", {});
  21290. if (profile.isNotEmpty())
  21291. lynx::crashguard::startMainProfiler (profile.toStdString(), 1000, 2);
  21292. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  21293. lynx::AudioEngine offline (false);
  21294. lynx::MainComponent ui (offline, false);
  21295. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1920x1080"), "x", "");
  21296. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  21297. juce::String text;
  21298. text << "project: " << project.getFullPathName() << "\nLYNX " << getApplicationVersion() << ", " << juce::SystemStats::getCpuModel()
  21299. << ", window " << ui.getWidth() << "x" << ui.getHeight() << "\n";
  21300. if (project.existsAsFile())
  21301. {
  21302. // (round perfgate190id) the time to open it headless, and the memory after
  21303. const auto open0 = juce::Time::getMillisecondCounterHiRes();
  21304. const auto cpu0 = lynx::threadCpuSeconds();
  21305. ui.openFile (project);
  21306. offline.dispatchPendingMessages();
  21307. text << "open: " << juce::String (juce::Time::getMillisecondCounterHiRes() - open0, 1) << " ms wall, "
  21308. << juce::String (1000.0 * (lynx::threadCpuSeconds() - cpu0), 1) << " ms message thread CPU, working set "
  21309. << juce::String ((double) lynx::toolbar::PerformanceMeter::processMemoryBytes() / 1048576.0, 0) << " MB\n";
  21310. }
  21311. const auto& song = offline.getSong();
  21312. text << "channels " << (int) song.channels.size() << ", patterns " << (int) song.patterns.size() << ", playlist clips " << (int) song.playlist.size()
  21313. << ", inserts " << (int) song.mixer.size() << "\n";
  21314. // the playhead a third into the song (song mode) so the views draw it as when playing
  21315. offline.getTransport().songMode = true;
  21316. offline.getTransport().positionTicks.store ((double) song.songLength() / 3.0);
  21317. const auto frames = juce::jlimit (3, 500, juce::SystemStats::getEnvironmentVariable ("LYNX_PAINTBENCH_FRAMES", "40").getIntValue());
  21318. juce::Image image (juce::Image::ARGB, ui.getWidth(), ui.getHeight(), true);
  21319. {
  21320. // (round 190gr) which renderer draws the frames: the software one (Linux), Direct2D (Windows), Core Graphics
  21321. juce::Graphics g (image);
  21322. auto& context = g.getInternalContext();
  21323. text << "renderer: " << (dynamic_cast<juce::LowLevelGraphicsSoftwareRenderer*> (&context) != nullptr ? "software" : typeid (context).name())
  21324. << ", paint caches " << (lynx::ui::paintCache() ? "on" : "off (LYNX_PAINT_CACHE=0)") << ", paint savings "
  21325. << (lynx::ui::paintSavings() ? "on" : "off (LYNX_PAINT_SAVINGS=0)") << "\n";
  21326. }
  21327. // LYNX_PAINTBENCH_VIEWS="mixer,channel rack" (round 190gr): only those views
  21328. const auto onlyViews = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_PAINTBENCH_VIEWS", {}), ",", "");
  21329. const auto wanted = [&onlyViews] (const juce::String& name) { return onlyViews.isEmpty() || onlyViews.contains (name); };
  21330. // the picture's pixels as one number: the same before and after a change = the same drawing
  21331. auto pixelHash = [&image] {
  21332. const juce::Image::BitmapData data (image, juce::Image::BitmapData::readOnly);
  21333. std::uint64_t h = 1469598103934665603ull;
  21334. for (int y = 0; y < data.height; ++y)
  21335. for (int x = 0; x < data.width; ++x)
  21336. h = (h ^ data.getPixelColour (x, y).getARGB()) * 1099511628211ull;
  21337. return juce::String::toHexString ((juce::int64) h);
  21338. };
  21339. // mode 0: whole frames after a repaint of everything; 1: whole frames, the views' own caches kept; 2: a 14-pixel
  21340. // column of the whole height at 40 places (what a moving playhead repaints each frame)
  21341. auto measure = [&] (const juce::String& name, int mode) {
  21342. offline.dispatchPendingMessages();
  21343. std::vector<double> ms, wall;
  21344. juce::String hash;
  21345. for (int f = -3; f < frames; ++f) // (3 frames to warm the caches up)
  21346. {
  21347. if (mode == 0)
  21348. ui.repaint();
  21349. const auto column = juce::Rectangle<int> ((juce::jmax (0, f) * 97) % juce::jmax (1, ui.getWidth() - 14), 0, 14, ui.getHeight());
  21350. const auto t0 = lynx::threadCpuSeconds();
  21351. const auto w0 = juce::Time::getMillisecondCounterHiRes();
  21352. {
  21353. juce::Graphics g (image);
  21354. if (mode == 2)
  21355. g.reduceClipRegion (column);
  21356. ui.paintEntireComponent (g, true);
  21357. }
  21358. if (f >= 0)
  21359. {
  21360. ms.push_back (1000.0 * (lynx::threadCpuSeconds() - t0));
  21361. wall.push_back (juce::Time::getMillisecondCounterHiRes() - w0); // (round 190gr: Direct2D's work ends with the frame)
  21362. }
  21363. if (f == 0 && mode == 0)
  21364. {
  21365. hash = pixelHash();
  21366. // LYNX_PAINTBENCH_PNG=<prefix> (round 190gr): the whole frame as <prefix>-<view>.png, to compare pixels
  21367. if (const auto png = juce::SystemStats::getEnvironmentVariable ("LYNX_PAINTBENCH_PNG", {}); png.isNotEmpty())
  21368. {
  21369. const juce::File file (png + "-" + name.replaceCharacter (' ', '-') + ".png");
  21370. file.deleteFile();
  21371. juce::FileOutputStream out (file);
  21372. juce::PNGImageFormat().writeImageToStream (image, out);
  21373. }
  21374. }
  21375. }
  21376. std::sort (ms.begin(), ms.end());
  21377. std::sort (wall.begin(), wall.end());
  21378. text << name << (mode == 0 ? ", whole frame" : mode == 1 ? ", cached frame" : ", playhead column") << ": median "
  21379. << juce::String (ms[ms.size() / 2], 3) << " ms, p90 " << juce::String (ms[(ms.size() * 9) / 10], 3) << " ms, wall median "
  21380. << juce::String (wall[wall.size() / 2], 3) << " ms"
  21381. << (hash.isNotEmpty() ? ", pixels " + hash : juce::String()) << "\n";
  21382. report.replaceWithText (text);
  21383. };
  21384. auto measureAll = [&] (const juce::String& name) {
  21385. if (! wanted (name))
  21386. return;
  21387. measure (name, 0);
  21388. measure (name, 1);
  21389. measure (name, 2);
  21390. // the columns' pixels too (painted over the whole frame: culling must not change a pixel)
  21391. ui.repaint();
  21392. {
  21393. juce::Graphics g (image);
  21394. ui.paintEntireComponent (g, true);
  21395. for (int x = 3; x < ui.getWidth() - 14; x += 211)
  21396. {
  21397. juce::Graphics::ScopedSaveState state (g);
  21398. g.reduceClipRegion (x, 0, 14, ui.getHeight());
  21399. ui.paintEntireComponent (g, true);
  21400. }
  21401. }
  21402. text << name << ", columns over the whole frame: pixels " << pixelHash() << "\n";
  21403. };
  21404. const char* views[] { "channel rack", "piano roll", "playlist", "mixer" };
  21405. for (int v = 0; v < 4; ++v)
  21406. {
  21407. ui.selectTabForSnapshot (v);
  21408. measureAll (views[v]);
  21409. }
  21410. ui.showDesktopForSnapshot (false);
  21411. measureAll ("desktop");
  21412. ui.selectTabForSnapshot (2);
  21413. ui.setClipLaunchWorkflow (true);
  21414. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  21415. measureAll ("clip grid");
  21416. ui.setClipLaunchWorkflow (false);
  21417. text << "result=OK\n";
  21418. report.replaceWithText (text);
  21419. if (profile.isNotEmpty())
  21420. lynx::crashguard::stopMainProfiler();
  21421. }
  21422. void runGridShot (const juce::String& prefix, const juce::String& projectPath = {})
  21423. {
  21424. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  21425. lynx::AudioEngine offline (false);
  21426. lynx::MainComponent ui (offline, false);
  21427. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  21428. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  21429. const auto write = [&prefix, &ui] (const char* name) {
  21430. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  21431. file.deleteFile();
  21432. juce::FileOutputStream out (file);
  21433. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (ui), out);
  21434. };
  21435. ui.selectTabForSnapshot (2); // the Playlist panel, maximized
  21436. if (projectPath.isNotEmpty())
  21437. {
  21438. ui.openFile (juce::File (projectPath));
  21439. offline.dispatchPendingMessages();
  21440. ui.setClipLaunchWorkflow (true);
  21441. offline.dispatchPendingMessages();
  21442. write ("file-both");
  21443. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  21444. write ("file-grid");
  21445. const auto& song = offline.getSong();
  21446. juce::String info;
  21447. info << "grid " << (song.clipGrid ? "yes" : "no") << ", clips " << (song.clipGrid ? (int) song.clipGrid->clips.size() : 0)
  21448. << ", scenes " << (song.clipGrid ? (int) song.clipGrid->scenes.size() : 0) << ", playlist clips " << (int) song.playlist.size() << "\n";
  21449. juce::File (prefix + "-file.txt").replaceWithText (info);
  21450. ui.setClipLaunchWorkflow (false);
  21451. return;
  21452. }
  21453. write ("pattern"); // Pattern workflow: nothing of the grid exists yet
  21454. const auto madeBefore = lynx::launcher::Runtime::instances.load();
  21455. offline.editSong ([] (lynx::Song& s) {
  21456. while (s.patterns.size() < 6)
  21457. s.patterns.emplace_back();
  21458. for (int p = 0; p < 6; ++p)
  21459. {
  21460. auto& pattern = s.patterns[(std::size_t) p];
  21461. const char* names[] { "Drums A", "Drums B", "Bass", "Chords", "Lead", "Pad" };
  21462. pattern.name = names[p];
  21463. pattern.lengthTicks = 4 * lynx::ppq;
  21464. }
  21465. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 6));
  21466. const char* tracks[] { "Drums", "Bass", "Chords", "Lead", "Vocals", "FX" };
  21467. for (int t = 0; t < 6; ++t)
  21468. s.playlistTracks[(std::size_t) t].name = tracks[t];
  21469. 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 } };
  21470. for (const auto& c : placed)
  21471. {
  21472. lynx::Clip clip;
  21473. clip.pattern = c[2];
  21474. clip.length = 4 * lynx::ppq;
  21475. lynx::launcher::setClip (s, c[0], c[1], clip);
  21476. }
  21477. auto& grid = lynx::launcher::ensureGrid (s);
  21478. const char* scenes[] { "Intro", "Verse", "Drop", "Break" };
  21479. grid.scenes.resize (6);
  21480. for (int r = 0; r < 4; ++r)
  21481. grid.scenes[(std::size_t) r].name = scenes[r];
  21482. }, false);
  21483. offline.dispatchPendingMessages();
  21484. write ("pattern-edited"); // the same song as -pattern-after: the workflow must leave no trace
  21485. ui.setClipLaunchWorkflow (true);
  21486. offline.dispatchPendingMessages();
  21487. if (auto* runtime = offline.launcherStateForSnapshot())
  21488. {
  21489. runtime->tracks[0].playing.store (2);
  21490. runtime->tracks[0].progress.store (0.4f);
  21491. runtime->tracks[0].taken.store (true);
  21492. runtime->tracks[1].playing.store (2);
  21493. runtime->tracks[1].progress.store (0.4f);
  21494. runtime->tracks[1].taken.store (true);
  21495. runtime->tracks[2].pending.store (2);
  21496. runtime->tracks[3].taken.store (true);
  21497. }
  21498. write ("both");
  21499. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  21500. write ("grid");
  21501. // round 190bv: recording into slots and the Groove Pool. Two tracks armed (round record buttons in their empty
  21502. // slots, their arm buttons lit), one of them recording and one waiting for its start; then a clip through a
  21503. // groove with the pool shown, and the slot menus
  21504. if (auto* gridView = ui.getClipGridForSnapshot())
  21505. {
  21506. offline.setGridTrackArmed (4, true);
  21507. offline.setGridTrackArmed (5, true, false);
  21508. offline.dispatchPendingMessages();
  21509. write ("rec-armed");
  21510. if (auto* runtime = offline.launcherStateForSnapshot())
  21511. {
  21512. runtime->tracks[4].recording.store (1);
  21513. runtime->tracks[4].recordFrom.store (0.0); // (round 190cy: one beat recorded, the counter reads 0.1.0)
  21514. runtime->clockNow.store ((double) lynx::ppq);
  21515. runtime->tracks[5].recordPending.store (1);
  21516. }
  21517. write ("rec-recording");
  21518. if (auto* runtime = offline.launcherStateForSnapshot())
  21519. {
  21520. runtime->tracks[4].recording.store (-1);
  21521. runtime->tracks[5].recordPending.store (-1);
  21522. }
  21523. offline.editSong ([] (lynx::Song& s) {
  21524. const auto& bank = lynx::groove::factoryBank();
  21525. std::uint32_t first = 0;
  21526. for (const auto index : { std::size_t (9), std::size_t (20), std::size_t (27) })
  21527. if (index < bank.size())
  21528. {
  21529. const auto id = lynx::groove::add (s.grooves, bank[index].groove);
  21530. first = first == 0 ? id : first;
  21531. }
  21532. lynx::groove::setClipGroove (s, 0, 0, first);
  21533. }, false);
  21534. offline.dispatchPendingMessages();
  21535. lynx::setClipGridGroovePoolShown (*gridView, true);
  21536. write ("groove-pool");
  21537. saveMenus ({ "Clip slot", "Groove", "Empty slot" },
  21538. { lynx::clipGridSlotMenu (*gridView, 0, 0), [&] {
  21539. juce::PopupMenu found;
  21540. const auto menu = lynx::clipGridSlotMenu (*gridView, 0, 0);
  21541. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  21542. if (it.getItem().subMenu != nullptr && it.getItem().text == lynx::tr ("Groove"))
  21543. found = *it.getItem().subMenu;
  21544. return found;
  21545. }(), lynx::clipGridSlotMenu (*gridView, 4, 1) },
  21546. prefix + "-rec-menus.png");
  21547. lynx::setClipGridGroovePoolShown (*gridView, false);
  21548. // round 190cy: a second record button pressed while recording: the first take ("Vocals 1") plays on, the
  21549. // clicked slot records "Vocals 2" with its counter at 2.0.2 (as Live 12.4.16, live check 190cw shot 03b)
  21550. {
  21551. const auto name = offline.slotRecordingName (4);
  21552. offline.editSong ([&name] (lynx::Song& s) { lynx::session::placeRecordedPattern (s, 4, 0, {}, 8 * lynx::ppq, name); }, false);
  21553. offline.dispatchPendingMessages();
  21554. if (auto* runtime = offline.launcherStateForSnapshot())
  21555. {
  21556. runtime->tracks[4].playing.store (0);
  21557. runtime->tracks[4].progress.store (0.3f);
  21558. runtime->tracks[4].recording.store (1);
  21559. runtime->tracks[4].recordFrom.store (0.0);
  21560. runtime->clockNow.store (8.0 * lynx::ppq + 2.0 * lynx::ppq / 4.0);
  21561. }
  21562. write ("rec-second");
  21563. if (auto* runtime = offline.launcherStateForSnapshot())
  21564. {
  21565. runtime->tracks[4].playing.store (-1);
  21566. runtime->tracks[4].recording.store (-1);
  21567. }
  21568. offline.editSong ([] (lynx::Song& s) {
  21569. if (lynx::session::cut (s, 4, 0) && ! s.patterns.empty())
  21570. s.patterns.pop_back();
  21571. }, false);
  21572. offline.dispatchPendingMessages();
  21573. }
  21574. offline.setGridTrackArmed (4, false);
  21575. offline.setGridTrackArmed (5, false);
  21576. offline.dispatchPendingMessages();
  21577. }
  21578. ui.setClipGridView (lynx::PlaylistArea::GridView::song);
  21579. write ("song");
  21580. ui.setClipLaunchWorkflow (false);
  21581. write ("pattern-after");
  21582. juce::File (prefix + "-counts.txt").replaceWithText ("runtimes before " + juce::String (madeBefore) + ", after " + juce::String (lynx::launcher::Runtime::instances.load()) + "\n");
  21583. }
  21584. // Round 190bu: the Simple workflow's track dock (ui/SimpleDock.h), off-screen
  21585. void runSimpleFxShot (const juce::String& prefix)
  21586. {
  21587. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  21588. lynx::AudioEngine offline (false);
  21589. lynx::MainComponent ui (offline, false);
  21590. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  21591. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  21592. const auto writeImage = [&prefix] (const juce::Image& image, const juce::String& name) {
  21593. const auto file = juce::File (prefix + "-" + name + ".png");
  21594. file.deleteFile();
  21595. juce::FileOutputStream out (file);
  21596. juce::PNGImageFormat().writeImageToStream (image, out);
  21597. };
  21598. juce::String report;
  21599. const auto line = [&report] (const juce::String& text) { report << text << "\n"; };
  21600. const auto check = [&report] (const juce::String& what, bool ok) { report << (ok ? "OK " : "ERROR ") << what << "\n"; };
  21601. const auto madeBefore = lynx::SimpleWorkflow::instances.load();
  21602. ui.selectTabForSnapshot (2);
  21603. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  21604. offline.dispatchPendingMessages();
  21605. auto* simple = ui.getSimpleWorkflowForSnapshot();
  21606. if (simple == nullptr)
  21607. {
  21608. juce::File (prefix + "-report.txt").replaceWithText ("ERROR no Simple workflow\n");
  21609. return;
  21610. }
  21611. simple->hideChooser();
  21612. // three tracks: a voice, keys with a few chords, a drum kit
  21613. int keysInsert = -1;
  21614. offline.editSong ([&keysInsert] (lynx::Song& s) {
  21615. namespace st = lynx::simpletracks;
  21616. st::Request q;
  21617. q.kind = st::Kind::voice;
  21618. q.name = "Lead vocal";
  21619. st::addTrack (s, q);
  21620. q = {};
  21621. q.kind = st::Kind::instrument;
  21622. q.name = "Keys";
  21623. lynx::ChannelDef keys;
  21624. keys.instrument = lynx::InstrumentKind::synth;
  21625. q.channel = keys;
  21626. lynx::Pattern chords;
  21627. for (int i = 0; i < 4; ++i)
  21628. for (int k : { 60, 64, 67 })
  21629. chords.notes.push_back (lynx::Note { (std::int64_t) i * 4 * lynx::ppq, 4 * lynx::ppq - lynx::ppq / 4, 0, k });
  21630. q.pattern = chords;
  21631. keysInsert = st::addTrack (s, q).insert;
  21632. q = {};
  21633. q.kind = st::Kind::drums;
  21634. for (auto kind : { lynx::InstrumentKind::kick, lynx::InstrumentKind::snare, lynx::InstrumentKind::hat })
  21635. {
  21636. lynx::ChannelDef c;
  21637. c.instrument = kind;
  21638. c.name = kind == lynx::InstrumentKind::kick ? "Kick" : kind == lynx::InstrumentKind::snare ? "Snare" : "Hat";
  21639. q.kit.push_back (c);
  21640. }
  21641. lynx::Pattern beat;
  21642. for (int step = 0; step < 16; step += 2)
  21643. beat.notes.push_back (lynx::Note { (std::int64_t) step * lynx::ticksPerStep, lynx::ticksPerStep, 2, 60 });
  21644. q.pattern = beat;
  21645. st::addTrack (s, q);
  21646. });
  21647. offline.dispatchPendingMessages();
  21648. simple->hideChooser();
  21649. auto& playlist = ui.getPlaylistForSnapshot();
  21650. // the tracks' places in the Playlist
  21651. int voiceTrack = -1, keysTrack = -1, drumsTrack = -1;
  21652. {
  21653. const auto& song = offline.getSong();
  21654. for (int t = 0; t < (int) song.playlistTracks.size(); ++t)
  21655. if (const auto kind = lynx::simpletracks::kindOf (song, t))
  21656. {
  21657. if (*kind == lynx::simpletracks::Kind::audio && voiceTrack < 0)
  21658. voiceTrack = t;
  21659. else if (*kind == lynx::simpletracks::Kind::instrument && keysTrack < 0)
  21660. keysTrack = t;
  21661. else if (*kind == lynx::simpletracks::Kind::drums && drumsTrack < 0)
  21662. drumsTrack = t;
  21663. }
  21664. }
  21665. check ("three Simple tracks (voice, keys, drums)", voiceTrack >= 0 && keysTrack >= 0 && drumsTrack >= 0);
  21666. playlist.selectTrack (keysTrack);
  21667. offline.dispatchPendingMessages();
  21668. auto* dock = simple->dockForSnapshot();
  21669. if (dock == nullptr)
  21670. {
  21671. juce::File (prefix + "-report.txt").replaceWithText (report + "ERROR no dock\n");
  21672. return;
  21673. }
  21674. // the whole window and the dock alone, at 1x and 2x
  21675. const auto shots = [&] (const juce::String& name) {
  21676. offline.dispatchPendingMessages();
  21677. for (float scale : { 1.0f, 2.0f })
  21678. {
  21679. const auto suffix = scale > 1.0f ? juce::String ("@2x") : juce::String();
  21680. writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, scale), name + suffix);
  21681. writeImage (dock->createComponentSnapshot (dock->getLocalBounds(), true, scale), "dock-" + name + suffix);
  21682. }
  21683. };
  21684. const auto menuShot = [&] (const juce::PopupMenu& menu, const juce::String& title, const juce::String& subTitle, const juce::String& name) {
  21685. juce::StringArray names { title };
  21686. std::vector<juce::PopupMenu> menus { menu };
  21687. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  21688. if (it.getItem().subMenu != nullptr && it.getItem().text == subTitle)
  21689. {
  21690. names.add (subTitle);
  21691. menus.push_back (*it.getItem().subMenu);
  21692. }
  21693. saveMenus (names, menus, prefix + "-" + name + ".png");
  21694. };
  21695. // --- the Instrument tab ---------------------------------------------------------------------------------------
  21696. check ("the dock shows the selected track", dock->shownTrack() == keysTrack && dock->isVisible() && dock->getParentComponent() != nullptr);
  21697. check ("an instrument track opens on its sound", dock->hasInstrumentTabForCheck() && dock->getTab() == lynx::SimpleDock::Tab::instrument);
  21698. const auto channel = dock->channelForCheck();
  21699. line ("sound at first: " + dock->soundNameForCheck() + ", rows in its category: " + juce::String (dock->soundRowsForCheck()));
  21700. shots ("instrument");
  21701. // a click on a row of another category: the track plays that sound, its own settings stay
  21702. const auto before = offline.getSong().channels[(std::size_t) channel];
  21703. dock->showCategoryForSnapshot ((int) lynx::soundlib::Category::pad);
  21704. offline.dispatchPendingMessages();
  21705. const auto padRows = dock->soundRowsForCheck();
  21706. dock->clickSoundForCheck (juce::jmin (2, padRows - 1));
  21707. offline.dispatchPendingMessages();
  21708. {
  21709. const auto& now = offline.getSong().channels[(std::size_t) channel];
  21710. const auto found = lynx::soundlib::find (lynx::soundlib::builtIn(), now);
  21711. check ("a click on a sound puts it on the track's channel (" + dock->soundNameForCheck() + ")",
  21712. padRows > 0 && found >= 0 && lynx::soundlib::builtIn()[(std::size_t) found].category == lynx::soundlib::Category::pad
  21713. && ! lynx::soundlib::sameSound (before, now));
  21714. check ("the channel keeps its name, level and insert", now.name == before.name && now.volume == before.volume && now.mixerTrack == before.mixerTrack);
  21715. double seconds = 0.0;
  21716. const auto heard = offline.auditionSound (now, { 60, 64, 67 }, &seconds);
  21717. check ("the sound's audition renders (" + juce::String (seconds, 2) + " s)", heard && seconds > 1.0);
  21718. }
  21719. shots ("instrument-pad");
  21720. const auto picked = dock->soundNameForCheck();
  21721. dock->stepSoundForCheck (1);
  21722. offline.dispatchPendingMessages();
  21723. const auto stepped = dock->soundNameForCheck();
  21724. dock->stepSoundForCheck (-1);
  21725. offline.dispatchPendingMessages();
  21726. check ("the arrows step through the category (" + picked + " -> " + stepped + " -> back)", stepped != picked && dock->soundNameForCheck() == picked);
  21727. check ("one undo step per sound", offline.canUndo());
  21728. // the user's SoundFont files (an index made here: no file is read)
  21729. {
  21730. std::vector<lynx::sf::IndexedFont> fonts (2);
  21731. fonts[0].path = "/home/me/SoundFonts/Concert Band.sf2";
  21732. fonts[0].name = "Concert Band";
  21733. int program = 0;
  21734. for (const char* name : { "Grand Piano", "Bright Piano", "Electric Piano", "Harpsichord", "Clavinet", "Celesta", "Music Box", "Vibraphone" })
  21735. fonts[0].presets.push_back ({ name, 0, program++ });
  21736. 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 } })
  21737. fonts[0].presets.push_back ({ name, 0, p });
  21738. fonts[0].presets.push_back ({ "Standard Kit", 128, 0 });
  21739. fonts[1].path = "/home/me/SoundFonts/Old Upright.sf2";
  21740. fonts[1].name = "Old Upright";
  21741. fonts[1].presets.push_back ({ "Old Upright", 0, 0 });
  21742. fonts[1].presets.push_back ({ "Old Upright Soft", 0, 1 });
  21743. dock->setFontsForSnapshot (fonts);
  21744. dock->showCategoryForSnapshot ((int) lynx::soundlib::Category::keys);
  21745. offline.dispatchPendingMessages();
  21746. check ("My SoundFonts lists the presets of the user's files by category (Keys: " + juce::String (dock->soundRowsForCheck()) + " of 17)", dock->soundRowsForCheck() == 7);
  21747. dock->clickSoundForCheck (0);
  21748. offline.dispatchPendingMessages();
  21749. const auto& now = offline.getSong().channels[(std::size_t) channel];
  21750. check ("a SoundFont preset becomes the track's sound (" + dock->soundNameForCheck() + ")",
  21751. now.instrument == lynx::InstrumentKind::soundfont && juce::String (now.samplePath).endsWith (".sf2"));
  21752. shots ("instrument-soundfonts");
  21753. }
  21754. // --- the Effects tab ------------------------------------------------------------------------------------------
  21755. playlist.selectTrack (voiceTrack);
  21756. offline.dispatchPendingMessages();
  21757. const auto insert = dock->insertForCheck();
  21758. check ("an audio track has no Instrument tab and opens on its effects",
  21759. dock->shownTrack() == voiceTrack && ! dock->hasInstrumentTabForCheck() && dock->getTab() == lynx::SimpleDock::Tab::effects && insert > 0);
  21760. check ("no effects yet: no cards", dock->cardCountForCheck() == 0);
  21761. shots ("effects-empty");
  21762. menuShot (dock->addMenuForSnapshot(), lynx::tr ("Add an effect"), {}, "menu-add");
  21763. // + adds one-knob effects at the end of the chain
  21764. dock->addOneKnobForCheck (lynx::goals::brighter);
  21765. dock->addOneKnobForCheck (lynx::goals::room);
  21766. dock->addOneKnobForCheck (lynx::goals::level);
  21767. offline.dispatchPendingMessages();
  21768. const auto slotsText = [&offline] (int t) {
  21769. juce::String text;
  21770. const auto rows = lynx::mixerops::effectRows (offline.getSong().mixer[(std::size_t) t].effects); // (the Mixer's slot of each)
  21771. std::size_t at = 0;
  21772. for (const auto& fx : offline.getSong().mixer[(std::size_t) t].effects)
  21773. text << "[slot " << rows[at++] + 1 << " " << lynx::effectInfo (fx.kind).name
  21774. << (lynx::goals::active (fx) ? " = " + juce::String (lynx::goals::name (fx.goal)) + " " + juce::String (juce::roundToInt (fx.goalAmount * 100.0f)) + "%" : juce::String())
  21775. << (fx.enabled ? "" : " off") << "] ";
  21776. return text.trimEnd();
  21777. };
  21778. line ("after + x3: " + slotsText (insert));
  21779. check ("three cards, three one-knob effects", dock->cardCountForCheck() == 3 && dock->oneKnobCardsForCheck() == 3);
  21780. // the knob writes the effect's own parameters
  21781. const auto roomBefore = offline.getSong().mixer[(std::size_t) insert].effects[1];
  21782. dock->turnKnobForCheck (1, 0.8f);
  21783. offline.dispatchPendingMessages();
  21784. {
  21785. const auto& room = offline.getSong().mixer[(std::size_t) insert].effects[1];
  21786. 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));
  21787. }
  21788. // ‹ › reorder, × removes
  21789. dock->moveCardForCheck (2, -1);
  21790. offline.dispatchPendingMessages();
  21791. line ("Level moved left: " + slotsText (insert));
  21792. {
  21793. const auto& fx = offline.getSong().mixer[(std::size_t) insert].effects;
  21794. check ("the card moved one place earlier", fx.size() == 3 && fx[1].goal == lynx::goals::level && fx[2].goal == lynx::goals::room);
  21795. }
  21796. dock->removeCardForCheck (0);
  21797. offline.dispatchPendingMessages();
  21798. line ("Brighter removed: " + slotsText (insert));
  21799. check ("the card is gone", dock->cardCountForCheck() == 2 && offline.getSong().mixer[(std::size_t) insert].effects.size() == 2);
  21800. // a hand edit in the full editor: the slot is an ordinary effect again (its card shows Mix)
  21801. offline.editSong ([insert] (lynx::Song& s) {
  21802. auto& slot = s.mixer[(std::size_t) insert].effects[0];
  21803. const auto moved = (std::size_t) lynx::goals::mapping (slot.goal, slot.goalAmount).back().param;
  21804. slot.params[moved] = slot.params[moved] > 0.5f ? 0.2f : 0.9f;
  21805. });
  21806. offline.dispatchPendingMessages();
  21807. check ("a parameter moved by hand makes the card an ordinary effect", dock->cardCountForCheck() == 2 && dock->oneKnobCardsForCheck() == 1);
  21808. dock->turnKnobForCheck (0, 0.5f); // (its knob is the slot's Mix now)
  21809. offline.dispatchPendingMessages();
  21810. 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);
  21811. // a preset replaces the chain; Blend is the chain's dry/wet
  21812. if (const auto* preset = lynx::chains::find ("Clear Voice"))
  21813. offline.editSongStructural ([insert, preset] (lynx::Song& s) { lynx::chains::apply (s, insert, *preset); });
  21814. offline.dispatchPendingMessages();
  21815. line ("preset Clear Voice: " + slotsText (insert));
  21816. 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)
  21817. && dock->cardCountForCheck() == (int) offline.getSong().mixer[(std::size_t) insert].effects.size());
  21818. shots ("effects-preset");
  21819. menuShot (dock->presetMenuForSnapshot(), lynx::tr ("Preset"), lynx::tr ("Voice"), "menu-preset");
  21820. dock->setBlendForCheck (0.7f);
  21821. dock->addOneKnobForCheck (lynx::goals::echo);
  21822. offline.dispatchPendingMessages();
  21823. check ("Blend 70 % is the insert's chain blend; the preset shows as edited",
  21824. std::abs (offline.getSong().mixer[(std::size_t) insert].chainBlend - 0.7f) < 1.0e-6f && ! lynx::chains::unchanged (offline.getSong(), insert));
  21825. shots ("effects-edited");
  21826. // a user preset: saved to a file, loaded on another track (its slots and Blend; that track's level stays)
  21827. const auto mine = offline.getSong().mixer[(std::size_t) insert];
  21828. const auto saved = lynx::SimpleDock::saveUserPreset (offline, insert, "My voice");
  21829. const auto file = lynx::SimpleDock::userPresetFolder().getChildFile ("My voice.lynxtrack");
  21830. check ("the preset is saved as " + file.getFileName(), saved && file.existsAsFile() && offline.getSong().mixer[(std::size_t) insert].chainPreset == "My voice");
  21831. offline.editSong ([keysInsert] (lynx::Song& s) { s.mixer[(std::size_t) keysInsert].volume = 0.42f; });
  21832. const auto loaded = keysInsert > 0 && lynx::SimpleDock::loadUserPreset (offline, keysInsert, file);
  21833. offline.dispatchPendingMessages();
  21834. {
  21835. const auto& other = offline.getSong().mixer[(std::size_t) keysInsert];
  21836. auto same = loaded && other.effects.size() == mine.effects.size() && std::abs (other.chainBlend - mine.chainBlend) < 1.0e-6f && other.chainPreset == "My voice";
  21837. for (std::size_t i = 0; same && i < mine.effects.size(); ++i)
  21838. same = other.effects[i].kind == mine.effects[i].kind && other.effects[i].goal == mine.effects[i].goal
  21839. && 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]);
  21840. check ("loaded on the Keys track: the same slots and Blend", same);
  21841. check ("the Keys track keeps its level", std::abs (other.volume - 0.42f) < 1.0e-6f);
  21842. line ("Keys after load: " + slotsText (keysInsert));
  21843. }
  21844. menuShot (dock->presetMenuForSnapshot(), lynx::tr ("Preset"), lynx::tr ("My presets"), "menu-preset-mine");
  21845. file.deleteFile();
  21846. // the drums: effects only (a kit has no single sound to pick)
  21847. playlist.selectTrack (drumsTrack);
  21848. offline.dispatchPendingMessages();
  21849. check ("the Drums track shows its insert's effects, no Instrument tab", dock->shownTrack() == drumsTrack && ! dock->hasInstrumentTabForCheck() && dock->insertForCheck() > 0);
  21850. if (const auto* preset = lynx::chains::find ("Smash Room"))
  21851. offline.editSongStructural ([t = dock->insertForCheck(), preset] (lynx::Song& s) { lynx::chains::apply (s, t, *preset); });
  21852. shots ("effects-drums");
  21853. // the project file keeps all of it
  21854. {
  21855. juce::String error;
  21856. const auto json = lynx::ProjectFile::toJson (offline.getSong());
  21857. const auto back = lynx::ProjectFile::fromJson (json, error);
  21858. auto same = back && back->mixer.size() == offline.getSong().mixer.size();
  21859. for (std::size_t t = 0; same && t < back->mixer.size(); ++t)
  21860. {
  21861. const auto& a = offline.getSong().mixer[t];
  21862. const auto& b = back->mixer[t];
  21863. same = a.effects.size() == b.effects.size() && std::abs (a.chainBlend - b.chainBlend) < 1.0e-6f && a.chainPreset == b.chainPreset;
  21864. for (std::size_t i = 0; same && i < a.effects.size(); ++i)
  21865. 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
  21866. && std::abs (a.effects[i].goalAmount - b.effects[i].goalAmount) < 1.0e-6f;
  21867. }
  21868. check ("saved and loaded as a project: the same chains, knobs, Blend and preset names", same);
  21869. }
  21870. // --- the same plugins in the same slots in FL's layout --------------------------------------------------------
  21871. const auto simpleSong = offline.getSong();
  21872. const auto inSimple = slotsText (insert);
  21873. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
  21874. offline.dispatchPendingMessages();
  21875. check ("Pattern workflow: the dock is gone", dock->getParentComponent() == nullptr);
  21876. ui.selectTabForSnapshot (3);
  21877. ui.getMixerForSnapshot().selectTrack (insert);
  21878. offline.dispatchPendingMessages();
  21879. for (float scale : { 1.0f, 2.0f })
  21880. writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, scale), juce::String ("pattern-mixer") + (scale > 1.0f ? "@2x" : ""));
  21881. line ("Simple layout: " + inSimple);
  21882. line ("Pattern layout: " + slotsText (insert));
  21883. check ("the same effects in the same Mixer slots in the Pattern workflow", offline.getSong().mixer == simpleSong.mixer && offline.getSong().channels == simpleSong.channels);
  21884. // an effect added in the Mixer's way shows as a card when the Simple workflow comes back
  21885. offline.editSongStructural ([insert] (lynx::Song& s) { lynx::mixerops::insertEffectAtRow (s, insert, lynx::makeEffectSlot (lynx::EffectKind::chorus), 7); });
  21886. ui.selectTabForSnapshot (2);
  21887. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  21888. offline.dispatchPendingMessages();
  21889. simple->hideChooser();
  21890. playlist.selectTrack (voiceTrack);
  21891. offline.dispatchPendingMessages();
  21892. check ("back in Simple: the dock shows the insert as it is now, the Mixer's new effect too",
  21893. dock->getParentComponent() != nullptr && dock->cardCountForCheck() == (int) offline.getSong().mixer[(std::size_t) insert].effects.size()
  21894. && lynx::mixerops::effectRows (offline.getSong().mixer[(std::size_t) insert].effects).back() == 7);
  21895. line ("Simple again: " + slotsText (insert));
  21896. shots ("effects-back");
  21897. // hidden with its key, shown again by "+FX"
  21898. simple->toggleDock();
  21899. offline.dispatchPendingMessages();
  21900. check ("Ctrl+Alt+L hides the dock", ! simple->isDockShowing() && ! lynx::SimpleDock::shownSetting);
  21901. writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, 1.0f), "dock-hidden");
  21902. simple->showEffectsOfInsert (keysInsert);
  21903. offline.dispatchPendingMessages();
  21904. check ("+FX on a track header shows the dock on that track's effects",
  21905. simple->isDockShowing() && dock->shownTrack() == keysTrack && dock->getTab() == lynx::SimpleDock::Tab::effects && dock->insertForCheck() == keysInsert);
  21906. simple->cycleDockTab();
  21907. check ("Shift+Tab goes to the Instrument tab", dock->getTab() == lynx::SimpleDock::Tab::instrument);
  21908. line ("Simple workflow objects: " + juce::String (madeBefore) + " before, " + juce::String (lynx::SimpleWorkflow::instances.load()) + " after");
  21909. line (report.contains ("ERROR ") ? "RESULT ERROR" : "RESULT OK");
  21910. juce::File (prefix + "-report.txt").replaceWithText (report);
  21911. }
  21912. // --simpleclosetest (round 190fc, 0.1.27 RC blocker B1): every close in the Simple layout crashed (the Simple workflow
  21913. // was destroyed after the Workspace and its destructor called into it). Off-screen, no window: the main window in the
  21914. // Simple layout with everything of it open — Welcome, the first-song tour's card, Start from, a demo song, each dock
  21915. // tab (the Editor tab docks the Piano roll), Finish, Lyrics, the chooser — then destroyed as the app's shutdown does.
  21916. // A second main window goes Simple -> Pattern -> Simple and closes too. Checks: no Simple workflow outlives its main
  21917. // window's destructor body, none is left at all. (Under ASan on Linux the old order is a heap-use-after-free.)
  21918. bool runDonateShot (const juce::String& prefix)
  21919. {
  21920. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  21921. juce::String report;
  21922. bool ok = true;
  21923. const auto line = [&report, &prefix] (const juce::String& text) {
  21924. report << text << "\n";
  21925. juce::File (prefix + "-report.txt").replaceWithText (report); // (written as it goes)
  21926. };
  21927. const auto check = [&line, &ok] (const juce::String& what, bool good) {
  21928. line ((good ? "ok " : "FAIL ") + what);
  21929. ok = ok && good;
  21930. };
  21931. const auto writeImage = [&prefix] (const juce::Image& image, const juce::String& name) {
  21932. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  21933. file.deleteFile();
  21934. juce::FileOutputStream out (file);
  21935. juce::PNGImageFormat().writeImageToStream (image, out);
  21936. };
  21937. // a window as the --snapshot route saves one (off the desktop, on the theme's panel colour), at 1x and 2x
  21938. const auto saveAlert = [&] (juce::AlertWindow& w, const juce::String& name) {
  21939. if (w.isOnDesktop())
  21940. w.removeFromDesktop();
  21941. w.setOpaque (true);
  21942. juce::Component frame;
  21943. frame.setSize (w.getWidth(), w.getHeight());
  21944. frame.setOpaque (true);
  21945. frame.addAndMakeVisible (w);
  21946. w.setTopLeftPosition (0, 0);
  21947. writeImage (lynx::shot::paint (frame, lynx::theme::panel), name);
  21948. writeImage (frame.createComponentSnapshot (frame.getLocalBounds(), true, 2.0f), name + "@2x");
  21949. frame.removeChildComponent (&w);
  21950. };
  21951. const auto buttonTexts = [] (juce::AlertWindow& w) {
  21952. juce::StringArray texts;
  21953. for (int b = 0; b < w.getNumButtons(); ++b)
  21954. if (auto* button = w.getButton (b))
  21955. texts.add (button->getButtonText());
  21956. return texts;
  21957. };
  21958. check ("the donation page is one constant, on Ko-fi", juce::String (lynx::links::donate).startsWith ("https://ko-fi"));
  21959. line ("donate URL: " + juce::String (lynx::links::donate));
  21960. const auto stateFile = lynx::PluginHost::settingsFolder().getChildFile ("support-note.txt");
  21961. const auto hadState = stateFile.existsAsFile();
  21962. const auto oldState = stateFile.loadFileAsString();
  21963. line ("state file: " + stateFile.getFullPathName() + (hadState ? " (exists; put back at the end)" : ""));
  21964. {
  21965. lynx::AudioEngine offline (false);
  21966. lynx::MainComponent ui (offline, false);
  21967. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  21968. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  21969. ui.setVisible (true);
  21970. const auto settle = [&] {
  21971. for (int k = 0; k < 3; ++k)
  21972. offline.dispatchPendingMessages();
  21973. };
  21974. // --- Help › Support LYNX SHARE..., right above About, in the three layouts ----------------------------------
  21975. for (auto [style, name] : { std::pair { lynx::layoutstyle::Style::pattern, "pattern" }, { lynx::layoutstyle::Style::clipLaunch, "cliplaunch" },
  21976. { lynx::layoutstyle::Style::simple, "simple" } })
  21977. {
  21978. ui.setLayoutStyle (style);
  21979. settle();
  21980. const auto help = ui.getMenuForSnapshot (ui.getMenuNamesForSnapshot().indexOf (lynx::tr ("Help")));
  21981. juce::StringArray items;
  21982. for (juce::PopupMenu::MenuItemIterator it (help); it.next();)
  21983. if (! it.getItem().isSeparator)
  21984. items.add (it.getItem().text);
  21985. const auto support = items.indexOf (lynx::tr ("Support LYNX SHARE..."));
  21986. const auto about = items.indexOf (lynx::tr ("About LYNX SHARE"));
  21987. check (juce::String ("Help has Support LYNX SHARE... right above About LYNX SHARE (") + name + " layout)",
  21988. support >= 0 && about == support + 1);
  21989. saveMenus ({ lynx::tr ("Help") }, { help }, prefix + "-menu-help-" + name + ".png");
  21990. }
  21991. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
  21992. settle();
  21993. // --- the Support window -------------------------------------------------------------------------------------
  21994. {
  21995. auto w = lynx::support::makeSupportWindow();
  21996. const auto texts = buttonTexts (*w);
  21997. check ("Support window: Donate on Ko-fi, Close", texts == juce::StringArray { lynx::tr ("Donate on Ko-fi"), lynx::tr ("Close") });
  21998. check ("Support window: Donate on Ko-fi points at the constant",
  21999. w->getButton (0) != nullptr && w->getButton (0)->getTooltip() == juce::String (lynx::links::donate));
  22000. check ("Support window title", w->getName() == lynx::tr ("Support LYNX SHARE"));
  22001. saveAlert (*w, "support");
  22002. }
  22003. // --- the About window ---------------------------------------------------------------------------------------
  22004. {
  22005. auto w = lynx::MainComponent::makeAboutWindow();
  22006. const auto texts = buttonTexts (*w);
  22007. check ("About window: Support LYNX SHARE (result 2) and OK", texts == juce::StringArray { lynx::tr ("Support LYNX SHARE"), lynx::tr ("OK") });
  22008. saveAlert (*w, "about");
  22009. }
  22010. // --- Settings › General › Show the support note -------------------------------------------------------------
  22011. {
  22012. auto page = lynx::makeGeneralPage (offline, {}, false);
  22013. bool found = false;
  22014. std::function<void (juce::Component&)> walk = [&] (juce::Component& c) {
  22015. if (auto* t = dynamic_cast<juce::ToggleButton*> (&c); t != nullptr && t->getButtonText() == lynx::tr ("Show the support note"))
  22016. found = t->getToggleState();
  22017. for (auto* child : c.getChildren())
  22018. walk (*child);
  22019. };
  22020. walk (*page);
  22021. check ("Settings > General: \"Show the support note\", ticked by default", found);
  22022. }
  22023. // --- the start-up note's rules, end to end on the saved state ----------------------------------------------
  22024. lynx::supportnote::Moment moment; // (the main window here is off-screen: the moment is set by hand)
  22025. lynx::support::StartupNote note (ui, [&moment] { return moment; }, [] { return 0; });
  22026. const auto state = [] { return lynx::support::loadState(); };
  22027. const auto setState = [] (int launches, int next, bool show) { lynx::support::saveState ({ launches, next, show }); };
  22028. stateFile.deleteFile();
  22029. for (int k = 0; k < 15; ++k)
  22030. note.begin (true);
  22031. note.pollForSnapshot();
  22032. check ("test mode / CI runs: 15 starts, nothing counted, no file, no card", ! stateFile.existsAsFile() && ! note.isCardShowing());
  22033. check ("a first start's defaults: next at start 10, shown", state() == lynx::supportnote::State { 0, 10, true });
  22034. for (int k = 1; k <= 9; ++k)
  22035. {
  22036. note.begin (false);
  22037. note.pollForSnapshot();
  22038. }
  22039. check ("starts 1 to 9: counted, no card", state().launches == 9 && ! note.isCardShowing());
  22040. moment.playing = true;
  22041. note.begin (false); // the 10th start
  22042. note.pollForSnapshot();
  22043. check ("10th start while playing: the card waits", state().launches == 10 && ! note.isCardShowing());
  22044. moment = {};
  22045. moment.dialogOpen = true;
  22046. note.pollForSnapshot();
  22047. check ("... and while a dialog is open", ! note.isCardShowing());
  22048. moment = {};
  22049. note.pollForSnapshot();
  22050. check ("10th start, a quiet moment: the card shows", note.isCardShowing());
  22051. check ("shown: left without an answer it comes back 30 starts later", state().nextAt == 40);
  22052. if (auto* card = note.cardForSnapshot())
  22053. {
  22054. const auto b = card->getBounds();
  22055. check ("the card sits in the bottom-right corner", b.getRight() <= ui.getWidth() - 8 && b.getRight() >= ui.getWidth() - 40
  22056. && b.getBottom() <= ui.getHeight() - 4 && b.getBottom() >= ui.getHeight() - 40);
  22057. writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, 1.0f), "note-in-window");
  22058. writeImage (card->createComponentSnapshot (card->getLocalBounds(), true, 2.0f), "note@2x");
  22059. // the corner of the window around the card, at 2x
  22060. writeImage (ui.createComponentSnapshot (b.expanded (220, 120).getIntersection (ui.getLocalBounds()), true, 2.0f), "note-corner@2x");
  22061. }
  22062. moment.playing = true;
  22063. note.pollForSnapshot();
  22064. check ("playback starts: the card steps aside", ! note.isCardShowing());
  22065. moment = {};
  22066. // Not now: again after 30 more starts
  22067. setState (10, 10, true);
  22068. note.begin (false); // start 11
  22069. note.pollForSnapshot();
  22070. if (auto* card = note.cardForSnapshot(); card != nullptr && card->buttonForSnapshot (lynx::supportnote::Choice::notNow) != nullptr)
  22071. card->buttonForSnapshot (lynx::supportnote::Choice::notNow)->onClick();
  22072. note.closeCard(); // (the click closes it on the next message turn)
  22073. check ("Not now: next at start 41", state() == lynx::supportnote::State { 11, 41, true });
  22074. for (int k = 12; k <= 40; ++k)
  22075. {
  22076. note.begin (false);
  22077. note.pollForSnapshot();
  22078. if (note.isCardShowing())
  22079. break;
  22080. }
  22081. check ("Not now: starts 12 to 40 without the card", ! note.isCardShowing() && state().launches == 40);
  22082. note.begin (false);
  22083. note.pollForSnapshot();
  22084. check ("Not now: the card again at start 41", note.isCardShowing());
  22085. // Don't show again: never, and Settings shows the box unticked
  22086. if (auto* card = note.cardForSnapshot())
  22087. card->buttonForSnapshot (lynx::supportnote::Choice::never)->onClick();
  22088. note.closeCard();
  22089. check ("Don't show again: off", ! state().show && ! lynx::support::noteEnabled());
  22090. for (int k = 0; k < 200; ++k)
  22091. {
  22092. note.begin (false);
  22093. note.pollForSnapshot();
  22094. }
  22095. check ("Don't show again: 200 more starts, never", ! note.isCardShowing());
  22096. // Support: opens the Support window (on the next message turn) and the note doesn't come back
  22097. setState (20, 10, true);
  22098. note.begin (false);
  22099. note.pollForSnapshot();
  22100. if (auto* card = note.cardForSnapshot())
  22101. card->buttonForSnapshot (lynx::supportnote::Choice::support)->onClick();
  22102. note.closeCard();
  22103. check ("Support: the note has done its job", ! state().show);
  22104. // Settings off: never; on again: counts from now
  22105. setState (5, 10, true);
  22106. lynx::support::setNoteEnabled (false);
  22107. for (int k = 0; k < 100; ++k)
  22108. {
  22109. note.begin (false);
  22110. note.pollForSnapshot();
  22111. }
  22112. check ("Settings off: 100 starts, never", ! note.isCardShowing() && state().launches == 105);
  22113. lynx::support::setNoteEnabled (true);
  22114. check ("Settings on again: next 30 starts later", state() == lynx::supportnote::State { 105, 135, true });
  22115. note.closeCard();
  22116. }
  22117. stateFile.deleteFile();
  22118. if (hadState)
  22119. stateFile.replaceWithText (oldState);
  22120. line (ok ? "result=OK" : "result=FAILED");
  22121. return ok;
  22122. }
  22123. bool runSimpleCloseTest (const juce::String& reportPath)
  22124. {
  22125. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  22126. juce::String report;
  22127. bool ok = true;
  22128. const auto line = [&report, &reportPath] (const juce::String& text) {
  22129. report << text << "\n";
  22130. juce::File (reportPath).replaceWithText (report); // (written as it goes: a crash still leaves the last step)
  22131. };
  22132. const auto check = [&line, &ok] (const juce::String& what, bool good) {
  22133. line ((good ? "ok " : "FAIL ") + what);
  22134. ok = ok && good;
  22135. };
  22136. const auto aliveBefore = lynx::SimpleWorkflow::alive.load();
  22137. {
  22138. lynx::AudioEngine offline (false);
  22139. {
  22140. lynx::MainComponent ui (offline, false);
  22141. ui.setSize (1600, 900);
  22142. ui.setVisible (true); // (no window: the docked editor and the tour only need their parents visible)
  22143. const auto settle = [&] {
  22144. for (int k = 0; k < 3; ++k)
  22145. offline.dispatchPendingMessages();
  22146. };
  22147. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  22148. settle();
  22149. auto* simple = ui.getSimpleWorkflowForSnapshot();
  22150. check ("the Simple workflow is up", simple != nullptr);
  22151. if (simple != nullptr)
  22152. {
  22153. const auto empty = lynx::builtInTemplateIndex ("Empty");
  22154. offline.setSong (empty >= 0 ? lynx::makeNewProject (empty) : lynx::makeNewProject());
  22155. settle();
  22156. simple->showWelcome();
  22157. settle();
  22158. auto* tour = simple->tourForSnapshot();
  22159. check ("Welcome screen shown", tour != nullptr && tour->isWelcomeShowing());
  22160. simple->startOrContinueTour();
  22161. settle();
  22162. simple->doTourStep (lynx::tour::beat);
  22163. settle();
  22164. check ("the tour runs with its card up", simple->tourRunning() && tour != nullptr && tour->cardForSnapshot() != nullptr);
  22165. // a demo song from Start from (the panel stays up over the Playlist)
  22166. if (auto* start = simple->startFromForSnapshot(); start != nullptr && lynx::demos::count > 1)
  22167. {
  22168. offline.setSong (lynx::demos::make (1));
  22169. settle();
  22170. check ("a demo song opened, Start from up", simple->isStartFromShowing() && ! offline.getSong().playlist.empty());
  22171. }
  22172. // the dock on a track, every tab (the Editor tab docks the Piano roll)
  22173. if (auto* dock = simple->dockForSnapshot())
  22174. {
  22175. simple->trackSelected ([] (const lynx::Song& song) { // the first Instrument track (the dock's Keyboard and Editor tabs are for it)
  22176. for (int t = 0; t < (int) song.playlistTracks.size(); ++t)
  22177. if (lynx::simpletracks::kindOf (song, t) == lynx::simpletracks::Kind::instrument)
  22178. return t;
  22179. return 0;
  22180. } (offline.getSong()));
  22181. for (auto tab : { lynx::SimpleDock::Tab::instrument, lynx::SimpleDock::Tab::keyboard, lynx::SimpleDock::Tab::editor,
  22182. lynx::SimpleDock::Tab::effects, lynx::SimpleDock::Tab::editor })
  22183. {
  22184. dock->setTab (tab);
  22185. settle();
  22186. }
  22187. check ("the dock shows", simple->isDockShowing());
  22188. line ("dock tab at the close: " + juce::String ((int) dock->getTab()) + " (2 = Editor, the docked Piano roll)");
  22189. }
  22190. ui.toggleLyrics(); // (Lyrics, then Finish: they share the dock on the right)
  22191. settle();
  22192. simple->showFinish();
  22193. settle();
  22194. check ("Finish open", simple->isFinishShowing());
  22195. simple->showChooser();
  22196. settle();
  22197. line ("Simple workflow objects alive before the close: " + juce::String (lynx::SimpleWorkflow::alive.load() - aliveBefore));
  22198. }
  22199. } // (the main window goes as at shutdown)
  22200. check ("no Simple workflow outlived its main window's destructor body (it reaches the Workspace)",
  22201. lynx::MainComponent::simpleWorkflowAliveAfterTeardown == aliveBefore);
  22202. check ("none left after the close", lynx::SimpleWorkflow::alive.load() == aliveBefore);
  22203. // Simple, then Pattern, then Simple again, and closed
  22204. {
  22205. lynx::MainComponent ui (offline, false);
  22206. ui.setSize (1600, 900);
  22207. ui.setVisible (true);
  22208. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  22209. offline.dispatchPendingMessages();
  22210. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
  22211. offline.dispatchPendingMessages();
  22212. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  22213. offline.dispatchPendingMessages();
  22214. if (auto* simple = ui.getSimpleWorkflowForSnapshot())
  22215. simple->showWelcome();
  22216. offline.dispatchPendingMessages();
  22217. }
  22218. check ("Simple -> Pattern -> Simple, closed: none outlived the destructor body", lynx::MainComponent::simpleWorkflowAliveAfterTeardown == aliveBefore
  22219. && lynx::SimpleWorkflow::alive.load() == aliveBefore);
  22220. }
  22221. line (ok ? "result=OK" : "result=FAILED");
  22222. return ok;
  22223. }
  22224. void runTour190dvShot (const juce::String& prefix)
  22225. {
  22226. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  22227. lynx::AudioEngine offline (false);
  22228. lynx::MainComponent ui (offline, false);
  22229. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  22230. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  22231. ui.setVisible (true); // (no window: the docked editor and the ring's targets only need their parents visible)
  22232. const auto writeImage = [&prefix] (const juce::Image& image, const juce::String& name) {
  22233. const auto file = juce::File (prefix + "-" + name + ".png");
  22234. file.deleteFile();
  22235. juce::FileOutputStream out (file);
  22236. juce::PNGImageFormat().writeImageToStream (image, out);
  22237. };
  22238. juce::String report;
  22239. // (written as it goes: a run that stops halfway still leaves its checks)
  22240. const auto line = [&report, &prefix] (const juce::String& text) {
  22241. report << text << "\n";
  22242. juce::File (prefix + "-report.txt").replaceWithText (report);
  22243. };
  22244. const auto check = [&line] (const juce::String& what, bool ok) { line ((ok ? "OK " : "ERROR ") + what); };
  22245. ui.selectTabForSnapshot (2);
  22246. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  22247. offline.dispatchPendingMessages();
  22248. auto* simple = ui.getSimpleWorkflowForSnapshot();
  22249. auto* tour = simple != nullptr ? simple->tourForSnapshot() : nullptr;
  22250. if (tour == nullptr)
  22251. {
  22252. juce::File (prefix + "-report.txt").replaceWithText ("ERROR no Simple workflow / tour\n");
  22253. return;
  22254. }
  22255. check ("no Welcome screen by itself in a --snapshot route (not a real first start)", ! tour->isWelcomeShowing());
  22256. const auto settle = [&] {
  22257. for (int k = 0; k < 3; ++k)
  22258. offline.dispatchPendingMessages();
  22259. };
  22260. const auto window = [&] (const juce::String& name, bool twoX = false) {
  22261. settle();
  22262. tour->ringForSnapshot(); // (the ring follows the layout: resolved now, as its timer would)
  22263. writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, 1.0f), name);
  22264. if (twoX)
  22265. if (auto* card = tour->cardForSnapshot(); card != nullptr && card->getParentComponent() != nullptr)
  22266. writeImage (card->createComponentSnapshot (card->getLocalBounds(), true, 2.0f), name + "-card@2x");
  22267. };
  22268. const auto stepIs = [&] (int step, const juce::String& target) {
  22269. settle();
  22270. const auto ring = tour->ringForSnapshot();
  22271. const auto id = tour->targetIdForSnapshot();
  22272. line ("step " + juce::String (tour->step() + 1) + " (" + lynx::tour::stepId (tour->step()) + "): ring on " + (id.isEmpty() ? juce::String ("-") : id) + " "
  22273. + ring.toString());
  22274. check (juce::String ("the card shows step ") + lynx::tour::stepId (step), tour->isRunning() && tour->step() == step);
  22275. if (target.isNotEmpty())
  22276. check ("the ring is on " + target, id == target && ! ring.isEmpty());
  22277. };
  22278. // --- the Welcome screen (on a new, empty project: the built-in "Empty" template, as File › New can give) -------------
  22279. const auto emptyProject = [] {
  22280. const auto index = lynx::builtInTemplateIndex ("Empty");
  22281. return index >= 0 ? lynx::makeNewProject (index) : lynx::makeNewProject();
  22282. };
  22283. offline.setSong (emptyProject());
  22284. settle();
  22285. check ("the new project is empty for the Simple workflow (it opens on the chooser)", lynx::simpletracks::isEmptySong (offline.getSong()));
  22286. simple->showWelcome();
  22287. settle();
  22288. check ("Help › Welcome screen shows it", tour->isWelcomeShowing());
  22289. window ("welcome");
  22290. if (auto* w = tour->welcomeForSnapshot())
  22291. writeImage (w->createComponentSnapshot (w->getLocalBounds(), true, 2.0f), "welcome@2x");
  22292. tour->clickForSnapshot ("welcome.tour");
  22293. settle();
  22294. check ("Make my first song: the Welcome screen closes, the tour starts, the chooser comes up for the beat",
  22295. ! tour->isWelcomeShowing() && tour->isRunning() && simple->isChooserShowing());
  22296. // --- step 1: the beat ---------------------------------------------------------------------------------------------
  22297. stepIs (lynx::tour::beat, "simple.tile.drums");
  22298. window ("step1-beat", true);
  22299. simple->showStarterPageForSnapshot();
  22300. stepIs (lynx::tour::beat, "simple.starters");
  22301. window ("step1-beat-starters");
  22302. tour->clickForSnapshot ("do");
  22303. settle();
  22304. check ("Do it for me added a starter beat", lynx::tour::hasBeat (offline.getSong()));
  22305. // --- step 2: the key ----------------------------------------------------------------------------------------------
  22306. stepIs (lynx::tour::key, "toolbar.key");
  22307. window ("step2-key", true);
  22308. tour->clickForSnapshot ("do");
  22309. settle();
  22310. check ("Do it for me set A minor", lynx::projectkey::get (offline.getSong()).has_value());
  22311. // --- step 3: an instrument (Add track opens the chooser: the ring moves to its tile) ------------------------------
  22312. stepIs (lynx::tour::instrument, "simple.addTrack");
  22313. window ("step3-instrument", true);
  22314. simple->showChooser();
  22315. stepIs (lynx::tour::instrument, "simple.tile.instrument");
  22316. window ("step3-instrument-chooser");
  22317. tour->clickForSnapshot ("do");
  22318. settle();
  22319. check ("Do it for me added an Instrument track (the chooser closed)", lynx::tour::firstInstrumentTrack (offline.getSong()) >= 0 && ! simple->isChooserShowing());
  22320. // --- step 4: chords -----------------------------------------------------------------------------------------------
  22321. stepIs (lynx::tour::chords, "keyboard.chordPad");
  22322. window ("step4-chords", true);
  22323. tour->clickForSnapshot ("do");
  22324. settle();
  22325. check ("Do it for me wrote four chords (12 notes) on the instrument's pattern", [&] {
  22326. const auto& song = offline.getSong();
  22327. const auto p = lynx::simpletracks::patternOf (song, lynx::tour::firstInstrumentTrack (song));
  22328. return p >= 0 && song.patterns[(std::size_t) p].notes.size() == 12;
  22329. }());
  22330. // --- step 5: a voice or a loop (no "Do it for me": a loop is dropped as a user would) ------------------------------
  22331. stepIs (lynx::tour::loop, "simple.addTrack");
  22332. window ("step5-loop", true);
  22333. {
  22334. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-190dv-loops");
  22335. dir.deleteRecursively();
  22336. dir.createDirectory();
  22337. const auto wav = dir.getChildFile ("Warm Keys 120 Am.wav");
  22338. const int frames = 192000;
  22339. juce::AudioBuffer<float> audio (1, frames);
  22340. for (int i = 0; i < frames; ++i)
  22341. {
  22342. const auto t = (double) i / 48000.0;
  22343. double v = 0.0;
  22344. for (const auto key : { 57, 60, 64 })
  22345. v += std::sin (2.0 * juce::MathConstants<double>::pi * 440.0 * std::pow (2.0, (key - 69) / 12.0) * t);
  22346. audio.setSample (0, i, (float) (0.1 * v * (1.0 - std::exp (-std::fmod (t, 0.5) * 60.0))));
  22347. }
  22348. {
  22349. juce::WavAudioFormat format;
  22350. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  22351. if (auto* w = format.createWriterFor (out.get(), 48000.0, 1, 16, {}, 0))
  22352. {
  22353. out.release();
  22354. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  22355. writer->writeFromAudioSampleBuffer (audio, 0, frames);
  22356. }
  22357. }
  22358. simple->dropFiles ({ wav.getFullPathName() }, 0);
  22359. settle();
  22360. check ("a dropped loop (A minor in its name) follows the key", [&] {
  22361. for (const auto& c : offline.getSong().playlist)
  22362. if (c.kind == lynx::ClipKind::audio)
  22363. return c.followKey;
  22364. return false;
  22365. }());
  22366. }
  22367. // --- step 6: a one-knob effect --------------------------------------------------------------------------------------
  22368. stepIs (lynx::tour::effect, "simple.dock.addEffect");
  22369. window ("step6-effect", true);
  22370. tour->clickForSnapshot ("do");
  22371. settle();
  22372. check ("Do it for me put Room on the instrument track", lynx::tour::hasOneKnob (offline.getSong()));
  22373. // --- step 7: Finish -----------------------------------------------------------------------------------------------
  22374. stepIs (lynx::tour::finish, "simple.finish");
  22375. window ("step7-finish", true);
  22376. tour->clickForSnapshot ("do");
  22377. settle();
  22378. check ("Do it for me opened Finish and chose Balanced", simple->isFinishShowing() && lynx::looks::present (offline.getSong()));
  22379. // --- the end card, Back / Next, close -------------------------------------------------------------------------------
  22380. settle();
  22381. check ("the end card", tour->isRunning() && tour->step() == lynx::tour::stepCount);
  22382. window ("end", true);
  22383. tour->clickForSnapshot ("back");
  22384. settle();
  22385. check ("Back: the Finish step again, shown done (the tour waits for Next)", tour->step() == lynx::tour::finish
  22386. && tour->machineForCheck().shownDone (offline.getSong()));
  22387. window ("back-done", true);
  22388. tour->clickForSnapshot ("next");
  22389. settle();
  22390. check ("Next: the end card again", tour->step() == lynx::tour::stepCount);
  22391. check ("all seven steps done by the song", tour->machineForCheck().state().completed == 0x7fu);
  22392. tour->clickForSnapshot ("close");
  22393. settle();
  22394. check ("closing the end card ends the tour (not continued from Help)", ! tour->isRunning() && ! tour->canContinue()
  22395. && tour->machineForCheck().state().done);
  22396. line ("-- paused tour");
  22397. // --- a paused tour, the Help menu and the chooser's button ---------------------------------------------------------
  22398. offline.setSong (emptyProject());
  22399. settle();
  22400. tour->machineForCheck() = lynx::tour::Machine {};
  22401. simple->startOrContinueTour();
  22402. settle();
  22403. line ("-- do beat");
  22404. simple->doTourStep (lynx::tour::beat);
  22405. settle();
  22406. check ("a new tour on an empty project: the beat done moves it to the key", tour->step() == lynx::tour::key);
  22407. tour->clickForSnapshot ("close");
  22408. settle();
  22409. check ("closing the card pauses the tour (Help continues it)", ! tour->isRunning() && tour->canContinue());
  22410. line ("-- help menu");
  22411. {
  22412. const auto help = ui.getMenuForSnapshot (ui.getMenuNamesForSnapshot().indexOf (lynx::tr ("Help")));
  22413. bool continueItem = false, welcomeItem = false;
  22414. for (juce::PopupMenu::MenuItemIterator it (help); it.next();)
  22415. {
  22416. continueItem = continueItem || it.getItem().text.startsWith (lynx::tr ("Continue the first-song tour (step {0} of {1})", { "2", "7" }));
  22417. welcomeItem = welcomeItem || it.getItem().text == lynx::tr ("Welcome screen...");
  22418. }
  22419. check ("Help: Continue the first-song tour (step 2 of 7) and Welcome screen...", continueItem && welcomeItem);
  22420. saveMenus ({ lynx::tr ("Help") }, { help }, prefix + "-menu-help.png");
  22421. }
  22422. simple->startOrContinueTour();
  22423. settle();
  22424. check ("Help › Continue: back on the key step", tour->isRunning() && tour->step() == lynx::tour::key);
  22425. tour->clickForSnapshot ("skip");
  22426. settle();
  22427. check ("Skip tour ends it", ! tour->isRunning() && ! tour->canContinue());
  22428. offline.setSong (emptyProject());
  22429. settle();
  22430. simple->showChooser();
  22431. window ("chooser");
  22432. line ("-- start from");
  22433. // --- Start from: the three demo songs; a demo opened in Simple -------------------------------------------------------
  22434. if (auto* start = simple->startFromForSnapshot())
  22435. {
  22436. settle();
  22437. writeImage (start->createComponentSnapshot (start->getLocalBounds(), true, 1.0f), "startfrom");
  22438. const auto list = lynx::startfrom::entries();
  22439. int demos = 0;
  22440. for (const auto& e : list)
  22441. demos += e.kind == lynx::startfrom::Entry::Kind::demo && e.playable ? 1 : 0;
  22442. check ("Start from lists three playable demo songs first", demos == 3 && list.size() >= 3 && list[1].demo == 1 && list[2].demo == 2);
  22443. for (int d = 1; d < 3 && d < (int) list.size(); ++d)
  22444. 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");
  22445. simple->hideStartFrom();
  22446. }
  22447. line ("-- demos");
  22448. for (int d = 1; d < lynx::demos::count; ++d)
  22449. {
  22450. offline.setSong (lynx::demos::make (d));
  22451. settle();
  22452. simple->hideChooser();
  22453. window (juce::String ("demo-") + (d == 1 ? "hiphop" : "pop"));
  22454. // the committed file is the generated song
  22455. const auto file = juce::File::getCurrentWorkingDirectory().getChildFile ("resources/demos").getChildFile (lynx::demos::fileName (d));
  22456. juce::String error;
  22457. const auto loaded = lynx::ProjectFile::load (file, error);
  22458. check ("resources/demos/" + juce::String (lynx::demos::fileName (d)) + " loads and is the generated song",
  22459. loaded.has_value() && lynx::ProjectFile::toJson (*loaded, false) == lynx::ProjectFile::toJson (lynx::demos::make (d), false));
  22460. }
  22461. line (report.contains ("ERROR ") ? "RESULT ERROR" : "RESULT OK");
  22462. juce::File (prefix + "-report.txt").replaceWithText (report);
  22463. }
  22464. // --patterns190ea (round 190ea): FL keeps at least one pattern; the engine now does too (AudioEngine::publishSong,
  22465. // Song::keepOnePattern). Before, a Song without a pattern crashed the docked Piano roll's listener.
  22466. bool runPatterns190ea (const juce::String& reportPath)
  22467. {
  22468. namespace st = lynx::simpletracks;
  22469. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  22470. lynx::AudioEngine offline (false);
  22471. lynx::MainComponent ui (offline, false);
  22472. ui.setSize (1600, 900);
  22473. ui.setVisible (true); // (no window: the docked editor only needs its parents visible)
  22474. juce::String report;
  22475. bool ok = true;
  22476. const auto check = [&report, &ok] (const juce::String& what, bool good) {
  22477. report << (good ? "OK " : "ERROR ") << what << "\n";
  22478. ok = ok && good;
  22479. };
  22480. const auto save = [&report, &reportPath] { juce::File (reportPath).replaceWithText (report); };
  22481. const auto settle = [&] { offline.dispatchPendingMessages(); ui.getPianoRollForSnapshot().repaint(); };
  22482. const auto onePattern = [&offline] {
  22483. const auto& s = offline.getSong();
  22484. return s.patterns.size() >= 1 && s.currentPattern >= 0 && s.currentPattern < (int) s.patterns.size();
  22485. };
  22486. // the hand-built songs the engine can be given: none of them has a pattern
  22487. const auto bare = [] {
  22488. lynx::Song s;
  22489. s.mixer = lynx::Song::defaultMixer();
  22490. return s;
  22491. };
  22492. // every way to reach "no pattern" in the current layout
  22493. const auto paths = [&] (const juce::String& where) {
  22494. offline.setSong (bare());
  22495. settle();
  22496. check (where + ": a song without a pattern opens with one empty \"Pattern 1\"",
  22497. onePattern() && offline.getSong().patterns.size() == 1 && offline.getSong().patterns[0].name == "Pattern 1"
  22498. && offline.getSong().patterns[0].notes.empty());
  22499. offline.editSong ([] (lynx::Song& s) { s.patterns.clear(); });
  22500. settle();
  22501. check (where + ": an edit that clears every pattern leaves one", onePattern());
  22502. offline.editSong ([] (lynx::Song& s) {
  22503. s.patterns.resize (2);
  22504. s.patterns[1].notes.push_back ({});
  22505. s.currentPattern = 1;
  22506. });
  22507. settle();
  22508. offline.editSong ([] (lynx::Song& s) { s.removePattern (s.currentPattern); });
  22509. offline.editSong ([] (lynx::Song& s) { s.removePattern (s.currentPattern); });
  22510. settle();
  22511. check (where + ": deleting the last pattern leaves an empty \"Pattern 1\" (FL's invariant)",
  22512. onePattern() && offline.getSong().patterns.size() == 1 && offline.getSong().patterns[0].notes.empty());
  22513. for (int k = 0; k < 6; ++k)
  22514. {
  22515. offline.undo();
  22516. settle();
  22517. }
  22518. check (where + ": undo back over those steps keeps a pattern", onePattern());
  22519. for (int k = 0; k < 6; ++k)
  22520. {
  22521. offline.redo();
  22522. settle();
  22523. }
  22524. check (where + ": redo keeps a pattern", onePattern());
  22525. offline.applyRemote (bare());
  22526. settle();
  22527. check (where + ": a live session's remote song without a pattern gets one", onePattern());
  22528. offline.editSong ([] (lynx::Song& s) { s.currentPattern = 99; });
  22529. settle();
  22530. check (where + ": a current pattern out of range is put back in range", onePattern() && offline.getSong().currentPattern == 0);
  22531. };
  22532. // the Simple layout with the Piano roll docked in the Editor tab (round 190dv's crash)
  22533. ui.selectTabForSnapshot (2);
  22534. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  22535. settle();
  22536. auto* simple = ui.getSimpleWorkflowForSnapshot();
  22537. check ("the Simple workflow is up", simple != nullptr);
  22538. if (simple == nullptr)
  22539. {
  22540. save();
  22541. return false;
  22542. }
  22543. simple->hideChooser();
  22544. st::Request q;
  22545. q.kind = st::Kind::instrument;
  22546. q.name = "Keys";
  22547. lynx::ChannelDef synth;
  22548. synth.instrument = lynx::InstrumentKind::synth;
  22549. q.channel = synth;
  22550. q.emptyBars = 4;
  22551. st::Result r;
  22552. offline.editSong ([&] (lynx::Song& s) { r = st::addTrack (s, q); });
  22553. settle();
  22554. ui.getPlaylistForSnapshot().selectTrack (r.track);
  22555. simple->trackSelected (r.track);
  22556. settle();
  22557. auto* dock = simple->dockForSnapshot();
  22558. check ("the instrument track's dock has the Editor tab", dock != nullptr && dock->hasPlayTabsForCheck());
  22559. if (dock != nullptr)
  22560. dock->setTab (lynx::SimpleDock::Tab::editor);
  22561. settle();
  22562. check ("the Piano roll is docked in the Editor tab", dock != nullptr && dock->isEditorDocked() && dock->isParentOf (&ui.getPianoRollForSnapshot()));
  22563. paths ("Simple, Editor tab");
  22564. // the Pattern layout with the Piano roll panel, then the Clip-launch layout
  22565. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
  22566. settle();
  22567. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::pianoRoll });
  22568. settle();
  22569. paths ("Pattern layout, Piano roll");
  22570. ui.setLayoutStyle (lynx::layoutstyle::Style::clipLaunch);
  22571. settle();
  22572. paths ("Clip-launch layout");
  22573. report << (ok ? "RESULT OK\n" : "RESULT FAILED\n");
  22574. save();
  22575. return ok;
  22576. }
  22577. // round 190fo: the Simple layout's Sampler track (16 pads) and a folder of stems and MIDI files, off-screen at 1x and
  22578. // 2x, with a text report of the checks (.lynx round trip, kits, typing keys, the folder import)
  22579. void runReabl190foShot (const juce::String& prefix)
  22580. {
  22581. namespace st = lynx::simpletracks;
  22582. namespace sp = lynx::simplepads;
  22583. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  22584. lynx::AudioEngine offline (false);
  22585. lynx::MainComponent ui (offline, false);
  22586. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  22587. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  22588. ui.setVisible (true);
  22589. const auto writeImage = [&prefix] (const juce::Image& image, const juce::String& name) {
  22590. const auto file = juce::File (prefix + "-" + name + ".png");
  22591. file.deleteFile();
  22592. juce::FileOutputStream out (file);
  22593. juce::PNGImageFormat().writeImageToStream (image, out);
  22594. };
  22595. juce::String report;
  22596. const auto line = [&report] (const juce::String& text) { report << text << "\n"; };
  22597. const auto check = [&report] (const juce::String& what, bool ok) { report << (ok ? "OK " : "ERROR ") << what << "\n"; };
  22598. ui.selectTabForSnapshot (2);
  22599. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  22600. offline.dispatchPendingMessages();
  22601. auto* simple = ui.getSimpleWorkflowForSnapshot();
  22602. if (simple == nullptr)
  22603. {
  22604. juce::File (prefix + "-report.txt").replaceWithText ("ERROR no Simple workflow\n");
  22605. return;
  22606. }
  22607. const auto whole = [&] (const juce::String& name) {
  22608. offline.dispatchPendingMessages();
  22609. for (float scale : { 1.0f, 2.0f })
  22610. writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, scale), name + (scale > 1.0f ? "@2x" : ""));
  22611. };
  22612. // the chooser: the Sampler tile (16 pads, "On keys..." for one sample over the keys) and Import's "Folder..."
  22613. simple->showChooser();
  22614. whole ("chooser");
  22615. simple->hideChooser();
  22616. // --- test sounds -------------------------------------------------------------------------------------------------
  22617. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-190fo");
  22618. dir.deleteRecursively();
  22619. dir.createDirectory();
  22620. const auto writeWav = [] (const juce::File& wav, int frames, const std::function<float (int)>& f) {
  22621. juce::AudioBuffer<float> audio (1, frames);
  22622. for (int i = 0; i < frames; ++i)
  22623. audio.setSample (0, i, f (i));
  22624. wav.getParentDirectory().createDirectory();
  22625. juce::WavAudioFormat format;
  22626. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  22627. if (auto* w = format.createWriterFor (out.get(), 48000.0, 1, 16, {}, 0))
  22628. {
  22629. out.release();
  22630. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  22631. writer->writeFromAudioSampleBuffer (audio, 0, frames);
  22632. }
  22633. return wav;
  22634. };
  22635. juce::Random rnd (190);
  22636. const auto pi = juce::MathConstants<double>::pi;
  22637. const auto kick = writeWav (dir.getChildFile ("pads/Kick.wav"), 24000, [pi] (int i) {
  22638. const auto t = i / 48000.0;
  22639. 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));
  22640. });
  22641. 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)); });
  22642. 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)); });
  22643. const auto chord = writeWav (dir.getChildFile ("pads/Chord stab.wav"), 48000, [pi] (int i) {
  22644. const auto t = i / 48000.0;
  22645. double v = 0.0;
  22646. for (int k : { 57, 60, 64 })
  22647. v += std::sin (2.0 * pi * 440.0 * std::pow (2.0, (k - 69) / 12.0) * t);
  22648. return (float) (0.2 * v * std::exp (-t * 2.5));
  22649. });
  22650. const auto vox = writeWav (dir.getChildFile ("pads/Vox hey.wav"), 30000, [pi] (int i) {
  22651. const auto t = i / 48000.0;
  22652. 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));
  22653. });
  22654. // --- the Sampler track ---------------------------------------------------------------------------------------------
  22655. check ("the Sampler tile's track was added", simple->addPads());
  22656. offline.dispatchPendingMessages();
  22657. const auto& song0 = offline.getSong();
  22658. int track = -1;
  22659. for (int t = 0; t < (int) song0.playlistTracks.size() && track < 0; ++t)
  22660. if (st::kindOf (song0, t) == st::Kind::pads)
  22661. track = t;
  22662. check ("a Sampler track with 16 pads", track >= 0 && [&] {
  22663. const auto c = sp::padChannels (song0, track);
  22664. return std::all_of (c.begin(), c.end(), [] (int i) { return i >= 0; });
  22665. }());
  22666. auto* dock = simple->dockForSnapshot();
  22667. if (dock == nullptr || track < 0)
  22668. {
  22669. juce::File (prefix + "-report.txt").replaceWithText (report + "ERROR no dock / track\n");
  22670. return;
  22671. }
  22672. simple->trackSelected (track);
  22673. offline.dispatchPendingMessages();
  22674. check ("the dock opens on the Pads tab", dock->hasPadsTabForCheck() && dock->getTab() == lynx::SimpleDock::Tab::pads);
  22675. const auto shots = [&] (const juce::String& name) {
  22676. offline.dispatchPendingMessages();
  22677. for (float scale : { 1.0f, 2.0f })
  22678. {
  22679. const auto suffix = scale > 1.0f ? juce::String ("@2x") : juce::String();
  22680. writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, scale), name + suffix);
  22681. writeImage (dock->createComponentSnapshot (dock->getLocalBounds(), true, scale), "dock-" + name + suffix);
  22682. }
  22683. };
  22684. shots ("pads-empty");
  22685. const juce::File files[] { kick, snare, hat, hat, chord, vox };
  22686. for (int p = 0; p < 6; ++p)
  22687. dock->padsLoadForCheck (p, files[p]);
  22688. offline.dispatchPendingMessages();
  22689. check ("six pads hold a sound", [&] {
  22690. int n = 0;
  22691. for (int p = 0; p < sp::padCount; ++p)
  22692. n += sp::hasSample (offline.getSong(), track, p) ? 1 : 0;
  22693. return n == 6;
  22694. }());
  22695. // pad 3 = the open hat: one-shot, group 1 with pad 2 (closed hat), a colour; pad 4 = the chord, looped and darker
  22696. dock->padsSelectForCheck (2);
  22697. dock->padsModeForCheck (1);
  22698. dock->padsSelectForCheck (3);
  22699. dock->padsModeForCheck (1);
  22700. offline.editSong ([track] (lynx::Song& s) {
  22701. for (int p : { 2, 3 })
  22702. if (const auto c = sp::padChannel (s, track, p); c >= 0)
  22703. {
  22704. s.channels[(std::size_t) c].simplePad.group = 1;
  22705. s.channels[(std::size_t) c].simplePad.colour = 2;
  22706. sp::apply (s.channels[(std::size_t) c], 4800);
  22707. }
  22708. });
  22709. dock->padsSelectForCheck (4);
  22710. dock->padsModeForCheck (2);
  22711. dock->padsKnobForCheck (2, 0.3f); // tone: a low-pass
  22712. dock->padsKnobForCheck (1, 0.35f); // release
  22713. dock->padsRegionForCheck (0.05f, 0.7f);
  22714. dock->padsNormalizeForCheck();
  22715. dock->padsUpdateForCheck();
  22716. {
  22717. const auto& s = offline.getSong();
  22718. const auto& c = s.channels[(std::size_t) sp::padChannel (s, track, 4)];
  22719. line ("pad 5: mode " + juce::String ((int) c.simplePad.mode) + " tone " + juce::String (c.simplePad.tone, 2) + " cutoff " + juce::String (c.sampler.cutoff, 0)
  22720. + " release " + juce::String (c.sampler.release, 3) + " region " + juce::String (c.sampler.regionStart, 2) + "-" + juce::String (c.sampler.regionEnd, 2)
  22721. + " gain " + juce::String (c.sampler.gainDb, 2) + " dB zones " + juce::String ((int) c.zones.size()));
  22722. 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
  22723. && c.sampler.filterType == 0 && c.sampler.cutoff < 5000.0f && c.sampler.gainDb > 0.5f);
  22724. const auto& h = s.channels[(std::size_t) sp::padChannel (s, track, 3)];
  22725. 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);
  22726. }
  22727. shots ("pads");
  22728. dock->padsHitForCheck (0);
  22729. dock->lightPad (2);
  22730. shots ("pads-hit");
  22731. // the typing keys: V plays pad 1, M pad 4, 7 pad 16; Z is not a pad key
  22732. check ("typing keys reach the pads", simple->padChannelForKey ('V') == sp::padChannel (offline.getSong(), track, 0)
  22733. && simple->padChannelForKey ('m') == sp::padChannel (offline.getSong(), track, 3)
  22734. && simple->padChannelForKey ('7') == sp::padChannel (offline.getSong(), track, 15)
  22735. && simple->padChannelForKey ('Z') == -1);
  22736. // drag pad 6 (vox) onto the empty pad 9: it moves; Alt-drag pad 1 onto pad 10: a copy
  22737. dock->padsDragForCheck (5, 8, false);
  22738. dock->padsDragForCheck (0, 9, true);
  22739. check ("a pad moved and a pad copied", ! sp::hasSample (offline.getSong(), track, 5) && sp::hasSample (offline.getSong(), track, 8)
  22740. && sp::hasSample (offline.getSong(), track, 9) && sp::hasSample (offline.getSong(), track, 0));
  22741. dock->padsSelectForCheck (4);
  22742. shots ("pads-moved");
  22743. saveMenus ({ "Pad menu", "Colour", "Copy a value to every pad" }, [&] {
  22744. const auto top = dock->padMenuForSnapshot (4);
  22745. std::vector<juce::PopupMenu> menus { top };
  22746. for (juce::PopupMenu::MenuItemIterator it (top); it.next();)
  22747. if (it.getItem().subMenu != nullptr)
  22748. menus.push_back (*it.getItem().subMenu);
  22749. return menus;
  22750. }(), prefix + "-menu-pad.png");
  22751. // kits: saved, the pads cleared, opened again
  22752. const auto kitFile = lynx::platform::documentsFolder().getChildFile ("LYNX/Sampler kits/Test kit 190fo.lynxkit");
  22753. kitFile.deleteFile();
  22754. check ("the pads saved as a kit", dock->saveKitForCheck ("Test kit 190fo") && kitFile.existsAsFile());
  22755. saveMenus ({ "Kit", "My kits" }, [&] {
  22756. const auto top = dock->kitMenuForSnapshot();
  22757. std::vector<juce::PopupMenu> menus { top };
  22758. for (juce::PopupMenu::MenuItemIterator it (top); it.next();)
  22759. if (it.getItem().subMenu != nullptr && it.getItem().text == lynx::tr ("My kits"))
  22760. menus.push_back (*it.getItem().subMenu);
  22761. return menus;
  22762. }(), prefix + "-menu-kit.png");
  22763. const auto before = offline.getSong().channels;
  22764. offline.editSong ([track] (lynx::Song& s) {
  22765. for (int p = 0; p < sp::padCount; ++p)
  22766. sp::clearPad (s, track, p);
  22767. });
  22768. check ("the kit opens the same pads again", dock->openKitForCheck (kitFile) && [&] {
  22769. const auto& now = offline.getSong().channels;
  22770. for (int p = 0; p < sp::padCount; ++p)
  22771. {
  22772. const auto c = sp::padChannel (offline.getSong(), track, p);
  22773. 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
  22774. || 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)
  22775. return false;
  22776. }
  22777. return true;
  22778. }());
  22779. {
  22780. const auto renamed = kitFile.getSiblingFile ("Renamed kit 190fo.lynxkit");
  22781. renamed.deleteFile();
  22782. check ("a kit renamed (and a one-letter name refused)", ! lynx::SimpleDock::renameKitForCheck (kitFile, "x")
  22783. && lynx::SimpleDock::renameKitForCheck (kitFile, "Renamed kit 190fo") && renamed.existsAsFile()
  22784. && ! kitFile.exists());
  22785. renamed.deleteFile();
  22786. }
  22787. kitFile.deleteFile();
  22788. // a beat on the pads (the track's pattern) and the .lynx round trip
  22789. offline.editSong ([track] (lynx::Song& s) {
  22790. const auto pattern = [&] {
  22791. for (const auto& c : s.playlist)
  22792. if (c.track == track && c.kind == lynx::ClipKind::pattern)
  22793. return c.pattern;
  22794. return -1;
  22795. }();
  22796. if (pattern < 0)
  22797. return;
  22798. for (int step = 0; step < 16; ++step)
  22799. {
  22800. const int pad = step % 4 == 0 ? 0 : step % 8 == 4 ? 1 : 2;
  22801. lynx::Note n;
  22802. n.channel = sp::padChannel (s, track, pad);
  22803. n.key = sp::padKey;
  22804. n.start = (std::int64_t) step * lynx::ticksPerStep;
  22805. n.length = lynx::ticksPerStep;
  22806. s.patterns[(std::size_t) pattern].notes.push_back (n);
  22807. }
  22808. });
  22809. {
  22810. const auto json = lynx::ProjectFile::toJson (offline.getSong());
  22811. juce::String error;
  22812. const auto back = lynx::ProjectFile::fromJson (json, error);
  22813. bool same = back.has_value() && back->channels.size() == offline.getSong().channels.size() && st::kindOf (*back, track) == st::Kind::pads;
  22814. for (std::size_t c = 0; same && c < back->channels.size(); ++c)
  22815. {
  22816. const auto& a = back->channels[c];
  22817. const auto& b = offline.getSong().channels[c];
  22818. same = a.simplePad == b.simplePad && a.zones == b.zones && a.cutGroup == b.cutGroup && a.cutBy == b.cutBy && a.samplePath == b.samplePath
  22819. && a.sampler.regionStart == b.sampler.regionStart && a.sampler.release == b.sampler.release && a.sampler.cutoff == b.sampler.cutoff;
  22820. }
  22821. check ("pads, their modes, groups and loops survive .lynx", same);
  22822. lynx::Song plain = lynx::Song::makeDefault();
  22823. check ("a project without pads writes no pad field", ! lynx::ProjectFile::toJson (plain).contains ("simplePad"));
  22824. }
  22825. ui.getPlaylistForSnapshot().selectTrack (track);
  22826. // --- a folder of stems and MIDI files (the other app's "download stems" naming) --------------------------------------
  22827. const auto stems = dir.getChildFile ("My song stems");
  22828. writeWav (stems.getChildFile ("01_Drums.wav"), 96000, [&rnd] (int i) { return (i % 24000) < 2000 ? (rnd.nextFloat() - 0.5f) * 0.8f : 0.0f; });
  22829. writeWav (stems.getChildFile ("02_Bass.wav"), 96000, [pi] (int i) { return (float) (0.3 * std::sin (2.0 * pi * 55.0 * i / 48000.0)); });
  22830. 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)); });
  22831. {
  22832. juce::MidiMessageSequence seq;
  22833. for (int k = 0; k < 8; ++k)
  22834. {
  22835. seq.addEvent (juce::MidiMessage::noteOn (1, 36 + (k % 4) * 3, (juce::uint8) 100), k * 480.0);
  22836. seq.addEvent (juce::MidiMessage::noteOff (1, 36 + (k % 4) * 3), k * 480.0 + 400.0);
  22837. }
  22838. seq.updateMatchedPairs();
  22839. juce::MidiFile midi;
  22840. midi.setTicksPerQuarterNote (960);
  22841. midi.addTrack (seq);
  22842. for (const auto& name : { "02_Bass.mid", "03_Keys.mid" })
  22843. {
  22844. juce::FileOutputStream out (stems.getChildFile (name));
  22845. midi.writeTo (out);
  22846. }
  22847. }
  22848. const auto tracksBefore = [&] {
  22849. int n = 0;
  22850. for (int t = 0; t < (int) offline.getSong().playlistTracks.size(); ++t)
  22851. n += st::kindOf (offline.getSong(), t).has_value() ? 1 : 0;
  22852. return n;
  22853. }();
  22854. simple->addFilesForCheck ({ stems });
  22855. offline.dispatchPendingMessages();
  22856. {
  22857. const auto& s = offline.getSong();
  22858. juce::StringArray names;
  22859. int muted = 0, count = 0;
  22860. for (int t = 0; t < (int) s.playlistTracks.size(); ++t)
  22861. if (st::kindOf (s, t).has_value())
  22862. {
  22863. ++count;
  22864. if (count > tracksBefore)
  22865. {
  22866. names.add (juce::String::fromUTF8 (s.playlistTracks[(std::size_t) t].name.c_str()) + (s.playlistTracks[(std::size_t) t].muted ? " (muted)" : ""));
  22867. muted += s.playlistTracks[(std::size_t) t].muted ? 1 : 0;
  22868. }
  22869. }
  22870. line ("folder tracks: " + names.joinIntoString (", "));
  22871. check ("the folder gave 5 tracks in number order, named without numbers, the Bass notes muted (its stem plays)",
  22872. names == juce::StringArray { "Drums", "Bass", "Lead Vox", "Bass 2 (muted)", "Keys" } && muted == 1);
  22873. bool atZero = true;
  22874. for (const auto& c : s.playlist)
  22875. if (c.track >= 0 && st::kindOf (s, c.track) == st::Kind::audio)
  22876. atZero = atZero && c.start == 0;
  22877. check ("every stem starts at the song's start", atZero);
  22878. }
  22879. simple->hideChooser();
  22880. whole ("folder-import");
  22881. dir.deleteRecursively();
  22882. line (report.contains ("ERROR ") ? "RESULT ERROR" : "RESULT OK");
  22883. juce::File (prefix + "-report.txt").replaceWithText (report);
  22884. }
  22885. void runSimple190dsShot (const juce::String& prefix)
  22886. {
  22887. namespace st = lynx::simpletracks;
  22888. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  22889. lynx::AudioEngine offline (false);
  22890. lynx::MainComponent ui (offline, false);
  22891. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  22892. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  22893. ui.setVisible (true); // (no window: the docked editor only needs its parents visible)
  22894. const auto writeImage = [&prefix] (const juce::Image& image, const juce::String& name) {
  22895. const auto file = juce::File (prefix + "-" + name + ".png");
  22896. file.deleteFile();
  22897. juce::FileOutputStream out (file);
  22898. juce::PNGImageFormat().writeImageToStream (image, out);
  22899. };
  22900. juce::String report;
  22901. const auto line = [&report] (const juce::String& text) { report << text << "\n"; };
  22902. const auto check = [&report] (const juce::String& what, bool ok) { report << (ok ? "OK " : "ERROR ") << what << "\n"; };
  22903. ui.selectTabForSnapshot (2);
  22904. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  22905. offline.dispatchPendingMessages();
  22906. auto* simple = ui.getSimpleWorkflowForSnapshot();
  22907. if (simple == nullptr)
  22908. {
  22909. juce::File (prefix + "-report.txt").replaceWithText ("ERROR no Simple workflow\n");
  22910. return;
  22911. }
  22912. simple->hideChooser();
  22913. auto& playlist = ui.getPlaylistForSnapshot();
  22914. // --- three loops: two with their key in the name, one only in its sound ---------------------------------------
  22915. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-190ds-loops");
  22916. dir.deleteRecursively();
  22917. dir.createDirectory();
  22918. // a chord loop (two bars at 120 BPM, 48 kHz): each chord's notes with six harmonics, a soft attack per beat
  22919. const auto writeLoop = [&dir] (const juce::String& name, std::vector<std::vector<int>> chords) {
  22920. const int frames = 192000;
  22921. juce::AudioBuffer<float> audio (1, frames);
  22922. audio.clear();
  22923. for (int i = 0; i < frames; ++i)
  22924. {
  22925. const auto& chord = chords[(std::size_t) (i / (frames / (int) chords.size()))];
  22926. const auto t = (double) i / 48000.0;
  22927. const auto beat = std::fmod (t, 0.5);
  22928. double v = 0.0;
  22929. for (const auto key : chord)
  22930. {
  22931. const auto f = 440.0 * std::pow (2.0, (key - 69) / 12.0);
  22932. for (int h = 1; h <= 6; ++h)
  22933. v += std::sin (2.0 * juce::MathConstants<double>::pi * f * h * t) / (h * h);
  22934. }
  22935. audio.setSample (0, i, (float) (0.08 * v * (1.0 - std::exp (-beat * 60.0)) * (0.6 + 0.4 * std::exp (-beat * 3.0))));
  22936. }
  22937. const auto wav = dir.getChildFile (name);
  22938. juce::WavAudioFormat format;
  22939. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  22940. if (auto* w = format.createWriterFor (out.get(), 48000.0, 1, 16, {}, 0))
  22941. {
  22942. out.release();
  22943. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  22944. writer->writeFromAudioSampleBuffer (audio, 0, frames);
  22945. }
  22946. return wav.getFullPathName();
  22947. };
  22948. const auto gMinor = writeLoop ("Night Pad 120 Gm.wav", { { 55, 58, 62 }, { 51, 55, 58 }, { 53, 57, 60 }, { 55, 58, 62 } });
  22949. const auto dMinor = writeLoop ("Pluck_120_D_minor.wav", { { 50, 53, 57 }, { 46, 50, 53 }, { 48, 52, 55 }, { 50, 53, 57 } });
  22950. 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 } });
  22951. lynx::SimpleWorkflow::answerForSnapshot = 1; // "Set the project key to G minor?" — yes
  22952. simple->dropFiles ({ gMinor, dMinor, eMinor }, 0);
  22953. lynx::SimpleWorkflow::answerForSnapshot = -1;
  22954. offline.dispatchPendingMessages();
  22955. simple->hideChooser();
  22956. line ("question: " + simple->lastKeyQuestionForCheck());
  22957. check ("the first keyed loop offered its key (G minor)", simple->lastKeyQuestionForCheck().contains ("G minor"));
  22958. {
  22959. const auto& song = offline.getSong();
  22960. const auto key = lynx::projectkey::get (song);
  22961. check ("the project key is G minor", key && key->root == 7 && lynx::projectkey::isMinor (*key));
  22962. std::vector<int> clips;
  22963. for (int i = 0; i < (int) song.playlist.size(); ++i)
  22964. if (song.playlist[(std::size_t) i].kind == lynx::ClipKind::audio)
  22965. clips.push_back (i);
  22966. check ("three loop clips", clips.size() == 3);
  22967. const int expect[] { 0, 5, 3 }; // G minor, D minor (F -> Bb: +5), E minor detected (G -> Bb: +3)
  22968. const int roots[] { 7, 2, 4 };
  22969. const int sources[] { 1, 1, 2 };
  22970. for (std::size_t k = 0; k < clips.size() && k < 3; ++k)
  22971. {
  22972. const auto& c = song.playlist[(std::size_t) clips[k]];
  22973. const auto& sampler = song.channels[(std::size_t) c.channel].sampler;
  22974. line ("loop " + juce::String ((int) k + 1) + ": key " + juce::String (sampler.loopKeyRoot) + (sampler.loopKeyMinor ? "m" : "") + " source "
  22975. + juce::String ((int) sampler.loopKeySource) + " follow " + juce::String (c.followKey ? 1 : 0) + " shift " + juce::String ((int) c.keyShift)
  22976. + " pitch " + juce::String (c.pitch));
  22977. check ("loop " + juce::String ((int) k + 1) + " key, source and move", sampler.loopKeyRoot == roots[k] && sampler.loopKeyMinor
  22978. && sampler.loopKeySource == sources[k] && c.followKey
  22979. && c.keyShift == expect[k] && std::abs (c.pitch - (float) expect[k]) < 1.0e-4f);
  22980. }
  22981. }
  22982. // the key changes: every following loop moves with it (one undo step)
  22983. offline.editSong ([] (lynx::Song& s) { lynx::projectkey::set (s, lynx::projectkey::Key { 9, lynx::projectkey::commonFirst()[1] }); });
  22984. offline.dispatchPendingMessages();
  22985. {
  22986. const auto& song = offline.getSong();
  22987. std::vector<int> shifts;
  22988. for (const auto& c : song.playlist)
  22989. if (c.kind == lynx::ClipKind::audio)
  22990. shifts.push_back (c.keyShift);
  22991. line ("after A minor: " + juce::String (shifts.size() > 2 ? shifts[0] : 99) + " " + juce::String (shifts.size() > 2 ? shifts[1] : 99) + " "
  22992. + juce::String (shifts.size() > 2 ? shifts[2] : 99));
  22993. check ("A minor: the loops move by +2, -5, +5", shifts == std::vector<int> { 2, -5, 5 });
  22994. }
  22995. // the loop tracks in the dock: the switch and what it does
  22996. int loopTrack = -1;
  22997. for (const auto& c : offline.getSong().playlist)
  22998. if (c.kind == lynx::ClipKind::audio && loopTrack < 0)
  22999. loopTrack = c.track;
  23000. playlist.selectTrack (loopTrack);
  23001. offline.dispatchPendingMessages();
  23002. auto* dock = simple->dockForSnapshot();
  23003. if (dock == nullptr)
  23004. {
  23005. juce::File (prefix + "-report.txt").replaceWithText (report + "ERROR no dock\n");
  23006. return;
  23007. }
  23008. simple->trackSelected (loopTrack);
  23009. offline.dispatchPendingMessages();
  23010. const auto shots = [&] (const juce::String& name) {
  23011. offline.dispatchPendingMessages();
  23012. for (float scale : { 1.0f, 2.0f })
  23013. {
  23014. const auto suffix = scale > 1.0f ? juce::String ("@2x") : juce::String();
  23015. writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, scale), name + suffix);
  23016. writeImage (dock->createComponentSnapshot (dock->getLocalBounds(), true, scale), "dock-" + name + suffix);
  23017. }
  23018. };
  23019. const auto menuShot = [&] (const juce::PopupMenu& menu, const juce::String& title, const juce::String& subTitle, const juce::String& name) {
  23020. juce::StringArray names { title };
  23021. std::vector<juce::PopupMenu> menus { menu };
  23022. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  23023. if (it.getItem().subMenu != nullptr && it.getItem().text.startsWith (subTitle))
  23024. {
  23025. names.add (subTitle);
  23026. menus.push_back (*it.getItem().subMenu);
  23027. }
  23028. saveMenus (names, menus, prefix + "-" + name + ".png");
  23029. };
  23030. check ("the dock shows the follow switch for the loop track", dock->followShownForCheck());
  23031. shots ("follow-on");
  23032. {
  23033. int clip = -1;
  23034. for (int i = 0; i < (int) offline.getSong().playlist.size() && clip < 0; ++i)
  23035. if (offline.getSong().playlist[(std::size_t) i].kind == lynx::ClipKind::audio)
  23036. clip = i;
  23037. const auto menu = playlist.getClipMenuForSnapshot (clip);
  23038. bool follow = false, keyItem = false;
  23039. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  23040. {
  23041. follow = follow || (it.getItem().text.startsWith (lynx::tr ("Follow the project key")) && it.getItem().isTicked);
  23042. keyItem = keyItem || it.getItem().text.startsWith (lynx::tr ("Loop key"));
  23043. }
  23044. check ("the clip menu has Follow the project key (ticked) and Loop key", follow && keyItem);
  23045. menuShot (menu, lynx::tr ("Audio clip"), lynx::tr ("Loop key"), "menu-clip-key");
  23046. }
  23047. dock->clickFollowForCheck(); // off: back to its own key
  23048. offline.dispatchPendingMessages();
  23049. {
  23050. float pitch = 99.0f;
  23051. bool following = true;
  23052. for (const auto& c : offline.getSong().playlist)
  23053. if (c.kind == lynx::ClipKind::audio && c.track == loopTrack)
  23054. pitch = c.pitch, following = c.followKey;
  23055. check ("switched off: the loop plays in its own key (pitch 0)", ! following && std::abs (pitch) < 1.0e-6f);
  23056. }
  23057. shots ("follow-off");
  23058. dock->clickFollowForCheck();
  23059. offline.dispatchPendingMessages();
  23060. // --- an instrument track from the tile: a pattern to write into, the Editor tab ------------------------------
  23061. {
  23062. st::Request q;
  23063. q.kind = st::Kind::instrument;
  23064. q.name = "Keys";
  23065. lynx::ChannelDef synth;
  23066. synth.instrument = lynx::InstrumentKind::synth;
  23067. q.channel = synth;
  23068. q.emptyBars = 4;
  23069. st::Result r;
  23070. offline.editSong ([&] (lynx::Song& s) { r = st::addTrack (s, q); });
  23071. offline.dispatchPendingMessages();
  23072. check ("the new Instrument track has an empty 4-bar pattern on it", r.ok() && r.pattern >= 0
  23073. && st::patternOf (offline.getSong(), r.track) == r.pattern
  23074. && offline.getSong().patterns[(std::size_t) r.pattern].notes.empty());
  23075. // a few notes, as the first clicks would write them (A minor: A C E, then G B D)
  23076. offline.editSong ([r] (lynx::Song& s) {
  23077. auto& p = s.patterns[(std::size_t) r.pattern];
  23078. const int keys[] { 57, 60, 64, 67, 71, 74, 69, 72 };
  23079. for (int i = 0; i < 8; ++i)
  23080. {
  23081. lynx::Note n;
  23082. n.channel = r.channels.front();
  23083. n.key = keys[i];
  23084. n.start = (std::int64_t) (i / 3) * lynx::ppq * 2 + (i % 3 == 0 ? 0 : 0);
  23085. n.length = lynx::ppq * 2;
  23086. n.velocity = 0.8f;
  23087. p.notes.push_back (n);
  23088. }
  23089. p.sortNotes();
  23090. });
  23091. offline.dispatchPendingMessages();
  23092. playlist.selectTrack (r.track);
  23093. simple->trackSelected (r.track);
  23094. offline.dispatchPendingMessages();
  23095. check ("the instrument track has the Keyboard and Editor tabs", dock->hasPlayTabsForCheck());
  23096. dock->setTab (lynx::SimpleDock::Tab::editor);
  23097. offline.dispatchPendingMessages();
  23098. check ("the Piano roll is docked in the Editor tab", dock->isEditorDocked());
  23099. check ("on the track's pattern", offline.getSong().currentPattern == r.pattern);
  23100. ui.getPianoRollForSnapshot().scrollToNotes(); // (done asynchronously when it docks)
  23101. shots ("editor");
  23102. dock->clickFoldForCheck (true); // "Only notes in key"
  23103. check ("Only notes in key folds the rows to A minor", ui.getPianoRollForSnapshot().isFoldedToScale());
  23104. ui.getPianoRollForSnapshot().scrollToNotes();
  23105. shots ("editor-in-key");
  23106. dock->clickFoldForCheck (false);
  23107. // --- the keyboard's modes ------------------------------------------------------------------------------
  23108. auto& keyboard = lynx::scalekeys::current();
  23109. const auto saved = keyboard;
  23110. keyboard = {};
  23111. keyboard.lockToKey = true;
  23112. dock->setTab (lynx::SimpleDock::Tab::keyboard);
  23113. if (auto* panel = dock->keyboardPanelForSnapshot())
  23114. {
  23115. lynx::refreshKeyboardPanel (*panel);
  23116. shots ("keys-locked");
  23117. keyboard.lockToKey = false;
  23118. keyboard.mode = lynx::scalekeys::Mode::scaleKeys;
  23119. lynx::refreshKeyboardPanel (*panel);
  23120. shots ("scale-keys");
  23121. keyboard.mode = lynx::scalekeys::Mode::chordPad;
  23122. keyboard.complexity = lynx::scalekeys::Complexity::seventh;
  23123. keyboard.strumMs = 40;
  23124. lynx::refreshKeyboardPanel (*panel);
  23125. shots ("chord-pad");
  23126. }
  23127. check ("the Keyboard tab shows the keyboard panel", dock->keyboardPanelForSnapshot() != nullptr);
  23128. // the same panel as the Touch keyboard window, each mode with a key / pad held
  23129. for (const auto& [mode, name, pressed] : { std::tuple { lynx::scalekeys::Mode::scaleKeys, juce::String ("window-scale-keys"), 4 },
  23130. std::tuple { lynx::scalekeys::Mode::chordPad, juce::String ("window-chord-pad"), 3 } })
  23131. {
  23132. auto panel = lynx::makeKeyboardPanelForSnapshot (offline, mode, pressed, [ch = r.channels.front()] { return ch; });
  23133. panel->setSize (1100, 260);
  23134. for (float scale : { 1.0f, 2.0f })
  23135. writeImage (panel->createComponentSnapshot (panel->getLocalBounds(), true, scale), name + (scale > 1.0f ? "@2x" : ""));
  23136. if (mode == lynx::scalekeys::Mode::chordPad)
  23137. menuShot (lynx::chordPadMenuForSnapshot (*panel, 3), lynx::tr ("Edit chord"), lynx::tr ("Chord type"), "menu-chord-edit");
  23138. }
  23139. // the Chord pad on an FL Studio Mobile chord set (the default set's shape: C Dm Em F G Am B° C)
  23140. {
  23141. 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})");
  23142. check ("an FLM chord set reads as 8 chords (B diminished)", set.size() == 8 && set[6].quality == 3);
  23143. offline.editSong ([set] (lynx::Song& s) { s.keyboardChords = set; });
  23144. keyboard.projectChords = true;
  23145. keyboard.complexity = lynx::scalekeys::Complexity::triad;
  23146. auto panel = lynx::makeKeyboardPanelForSnapshot (offline, lynx::scalekeys::Mode::chordPad, 5, [ch = r.channels.front()] { return ch; });
  23147. panel->setSize (1100, 260);
  23148. for (float scale : { 1.0f, 2.0f })
  23149. writeImage (panel->createComponentSnapshot (panel->getLocalBounds(), true, scale), juce::String ("window-chord-set") + (scale > 1.0f ? "@2x" : ""));
  23150. }
  23151. // the typing keys in each mode (A minor; Z = the root)
  23152. {
  23153. const auto& song = offline.getSong();
  23154. lynx::scalekeys::Settings s;
  23155. s.mode = lynx::scalekeys::Mode::scaleKeys;
  23156. juce::String z;
  23157. for (const int typed : { 60, 62, 64, 65, 67, 69, 71, 72, 61 })
  23158. {
  23159. const auto n = lynx::scalekeys::typedNotes (song, s, typed, 60);
  23160. z << (n.empty() ? juce::String ("-") : juce::String (n.front())) << " ";
  23161. }
  23162. line ("Scale keys, typing C D E F G A B C C#: " + z);
  23163. check ("Scale keys: the white typing keys play A minor from A", z.trim() == "69 71 72 74 76 77 79 81 -");
  23164. s.mode = lynx::scalekeys::Mode::chordPad;
  23165. s.projectChords = false;
  23166. const auto pad = lynx::scalekeys::typedNotes (song, s, 60, 60);
  23167. check ("Chord pad: Z plays A minor (A C E)", pad == std::vector<int> { 69, 72, 76 });
  23168. }
  23169. keyboard = saved;
  23170. }
  23171. // --- the project round trip --------------------------------------------------------------------------------
  23172. {
  23173. const auto json = lynx::ProjectFile::toJson (offline.getSong());
  23174. juce::String error;
  23175. const auto back = lynx::ProjectFile::fromJson (json, error);
  23176. bool same = back.has_value() && back->keyboardChords == offline.getSong().keyboardChords && back->playlist.size() == offline.getSong().playlist.size();
  23177. for (std::size_t i = 0; same && i < back->playlist.size(); ++i)
  23178. same = back->playlist[i].followKey == offline.getSong().playlist[i].followKey && back->playlist[i].keyShift == offline.getSong().playlist[i].keyShift
  23179. && back->playlist[i].pitch == offline.getSong().playlist[i].pitch;
  23180. for (std::size_t c = 0; same && c < back->channels.size(); ++c)
  23181. same = back->channels[c].sampler.loopKeyRoot == offline.getSong().channels[c].sampler.loopKeyRoot
  23182. && back->channels[c].sampler.loopKeySource == offline.getSong().channels[c].sampler.loopKeySource;
  23183. check ("follow, key moves, loop keys and the chord set survive .lynx", same);
  23184. }
  23185. dir.deleteRecursively();
  23186. line (report.contains ("ERROR ") ? "RESULT ERROR" : "RESULT OK");
  23187. juce::File (prefix + "-report.txt").replaceWithText (report);
  23188. }
  23189. void runSimple190dgShot (const juce::String& prefix)
  23190. {
  23191. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  23192. lynx::AudioEngine offline (false);
  23193. lynx::MainComponent ui (offline, false);
  23194. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  23195. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  23196. const auto writeImage = [&prefix] (const juce::Image& image, const juce::String& name) {
  23197. const auto file = juce::File (prefix + "-" + name + ".png");
  23198. file.deleteFile();
  23199. juce::FileOutputStream out (file);
  23200. juce::PNGImageFormat().writeImageToStream (image, out);
  23201. };
  23202. juce::String report;
  23203. const auto line = [&report] (const juce::String& text) { report << text << "\n"; };
  23204. const auto check = [&report] (const juce::String& what, bool ok) { report << (ok ? "OK " : "ERROR ") << what << "\n"; };
  23205. ui.selectTabForSnapshot (2);
  23206. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  23207. offline.dispatchPendingMessages();
  23208. auto* simple = ui.getSimpleWorkflowForSnapshot();
  23209. if (simple == nullptr)
  23210. {
  23211. juce::File (prefix + "-report.txt").replaceWithText ("ERROR no Simple workflow\n");
  23212. return;
  23213. }
  23214. simple->hideChooser();
  23215. offline.editSong ([] (lynx::Song& s) {
  23216. namespace st = lynx::simpletracks;
  23217. st::Request q;
  23218. q.kind = st::Kind::voice;
  23219. q.name = "Lead vocal";
  23220. st::addTrack (s, q);
  23221. q = {};
  23222. q.kind = st::Kind::instrument;
  23223. q.name = "Keys";
  23224. lynx::ChannelDef keys;
  23225. keys.instrument = lynx::InstrumentKind::synth;
  23226. q.channel = keys;
  23227. st::addTrack (s, q);
  23228. });
  23229. offline.dispatchPendingMessages();
  23230. simple->hideChooser();
  23231. auto& playlist = ui.getPlaylistForSnapshot();
  23232. int voiceTrack = -1, keysTrack = -1;
  23233. {
  23234. const auto& song = offline.getSong();
  23235. for (int t = 0; t < (int) song.playlistTracks.size(); ++t)
  23236. if (const auto kind = lynx::simpletracks::kindOf (song, t))
  23237. {
  23238. if (*kind == lynx::simpletracks::Kind::audio && voiceTrack < 0)
  23239. voiceTrack = t;
  23240. else if (*kind == lynx::simpletracks::Kind::instrument && keysTrack < 0)
  23241. keysTrack = t;
  23242. }
  23243. }
  23244. check ("two Simple tracks (voice, keys)", voiceTrack >= 0 && keysTrack >= 0);
  23245. playlist.selectTrack (voiceTrack);
  23246. offline.dispatchPendingMessages();
  23247. auto* dock = simple->dockForSnapshot();
  23248. if (dock == nullptr)
  23249. {
  23250. juce::File (prefix + "-report.txt").replaceWithText (report + "ERROR no dock\n");
  23251. return;
  23252. }
  23253. const auto shots = [&] (const juce::String& name) {
  23254. offline.dispatchPendingMessages();
  23255. for (float scale : { 1.0f, 2.0f })
  23256. {
  23257. const auto suffix = scale > 1.0f ? juce::String ("@2x") : juce::String();
  23258. writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, scale), name + suffix);
  23259. writeImage (dock->createComponentSnapshot (dock->getLocalBounds(), true, scale), "dock-" + name + suffix);
  23260. }
  23261. };
  23262. const auto menuShot = [&] (const juce::PopupMenu& menu, const juce::String& title, const juce::String& subTitle, const juce::String& name) {
  23263. juce::StringArray names { title };
  23264. std::vector<juce::PopupMenu> menus { menu };
  23265. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  23266. if (it.getItem().subMenu != nullptr && it.getItem().text == subTitle)
  23267. {
  23268. names.add (subTitle);
  23269. menus.push_back (*it.getItem().subMenu);
  23270. }
  23271. saveMenus (names, menus, prefix + "-" + name + ".png");
  23272. };
  23273. const auto insert = dock->insertForCheck();
  23274. // --- every one-knob effect as a card, each at a knob position of its own -------------------------------------
  23275. const float at[] { 0.0f, 0.55f, 0.40f, 0.70f, 0.30f, 0.60f, 0.45f, 0.35f, 0.80f };
  23276. for (int id = 1; id <= lynx::goals::count; ++id)
  23277. dock->addOneKnobForCheck (id);
  23278. offline.dispatchPendingMessages();
  23279. for (int id = 1; id <= lynx::goals::count; ++id)
  23280. dock->turnKnobForCheck (id - 1, at[id]);
  23281. offline.dispatchPendingMessages();
  23282. check ("eight one-knob cards on the insert", dock->cardCountForCheck() == 8 && dock->oneKnobCardsForCheck() == 8);
  23283. {
  23284. const auto& fx = offline.getSong().mixer[(std::size_t) insert].effects;
  23285. bool turned = fx.size() == 8;
  23286. for (std::size_t i = 0; turned && i < fx.size(); ++i)
  23287. turned = lynx::goals::active (fx[i]) && std::abs (fx[i].goalAmount - at[i + 1]) < 1.0e-6f;
  23288. check ("each knob wrote its effect's parameters", turned);
  23289. }
  23290. shots ("effects-all");
  23291. offline.dispatchPendingMessages();
  23292. for (int card = 0; card < dock->cardCountForCheck(); ++card)
  23293. {
  23294. const auto area = dock->cardBoundsForSnapshot (card);
  23295. const auto name = juce::String (lynx::goals::name (card + 1)).toLowerCase();
  23296. check ("card " + juce::String (card + 1) + " (" + name + ") is on screen", ! area.isEmpty() && dock->getLocalBounds().contains (area));
  23297. for (float scale : { 1.0f, 2.0f })
  23298. writeImage (dock->createComponentSnapshot (area.expanded (4), true, scale), "card-" + name + (scale > 1.0f ? "@2x" : ""));
  23299. }
  23300. // --- a chain preset with Blend --------------------------------------------------------------------------------
  23301. if (const auto* preset = lynx::chains::find ("Canyon"))
  23302. offline.editSongStructural ([insert, preset] (lynx::Song& s) { lynx::chains::apply (s, insert, *preset); });
  23303. offline.dispatchPendingMessages();
  23304. dock->setBlendForCheck (0.6f);
  23305. offline.dispatchPendingMessages();
  23306. check ("preset Canyon with Blend 60 % (shown as edited)", offline.getSong().mixer[(std::size_t) insert].chainPreset == "Canyon"
  23307. && std::abs (offline.getSong().mixer[(std::size_t) insert].chainBlend - 0.6f) < 1.0e-6f
  23308. && ! lynx::chains::unchanged (offline.getSong(), insert));
  23309. shots ("effects-preset-blend");
  23310. // favourites: the track's preset starred; the menu lists it first
  23311. const auto favFile = lynx::SimpleDock::favouritesFile();
  23312. const auto hadFavourites = favFile.existsAsFile();
  23313. const auto oldFavourites = favFile.loadFileAsString();
  23314. lynx::SimpleDock::setFavouritePreset ("Canyon", true);
  23315. lynx::SimpleDock::setFavouritePreset ("Clear Voice", true);
  23316. lynx::SimpleDock::setFavouritePreset ("Canyon", true); // (twice: once in the list)
  23317. check ("two favourites kept, in order", lynx::SimpleDock::favouritePresets() == juce::StringArray { "Canyon", "Clear Voice" });
  23318. {
  23319. bool first = false, toggle = false;
  23320. const auto menu = dock->presetMenuForSnapshot();
  23321. juce::PopupMenu::MenuItemIterator it (menu);
  23322. if (it.next())
  23323. first = it.getItem().subMenu != nullptr && it.getItem().text.contains (lynx::tr ("Favourites"));
  23324. for (juce::PopupMenu::MenuItemIterator all (menu); all.next();)
  23325. toggle = toggle || all.getItem().text == lynx::tr ("Remove \"{0}\" from favourites", { "Canyon" });
  23326. check ("the Preset menu starts with the favourites and offers to unstar the track's preset", first && toggle);
  23327. menuShot (menu, lynx::tr ("Preset"), juce::String::fromUTF8 ("\xe2\x98\x85 ") + lynx::tr ("Favourites"), "menu-preset-favourites");
  23328. }
  23329. lynx::SimpleDock::setFavouritePreset ("Canyon", false);
  23330. check ("unstarred", lynx::SimpleDock::favouritePresets() == juce::StringArray { "Clear Voice" });
  23331. if (hadFavourites)
  23332. favFile.replaceWithText (oldFavourites);
  23333. else
  23334. favFile.deleteFile();
  23335. // --- the sound picker: a search, and the installed plugins -----------------------------------------------------
  23336. playlist.selectTrack (keysTrack);
  23337. offline.dispatchPendingMessages();
  23338. check ("the Keys track opens on its sound", dock->getTab() == lynx::SimpleDock::Tab::instrument);
  23339. dock->showCategoryForSnapshot ((int) lynx::soundlib::Category::bass);
  23340. dock->setSearchForSnapshot ("sub");
  23341. offline.dispatchPendingMessages();
  23342. line ("search \"sub\" in Bass: " + juce::String (dock->soundRowsForCheck()) + " rows");
  23343. check ("a search narrows the category", dock->soundRowsForCheck() > 0 && dock->soundRowsForCheck() < (int) lynx::soundlib::filter (lynx::soundlib::builtIn(), lynx::soundlib::Category::bass).size());
  23344. shots ("picker-search");
  23345. dock->setSearchForSnapshot ({});
  23346. // a made-up list of installed plugins (nothing is scanned or loaded)
  23347. dock->setPluginsForSnapshot ({ { "VST3-demo-1", "Analog Mono", "Example Audio", "VST3", "Instrument|Synth" },
  23348. { "VST3-demo-2", "Grand Upright", "Example Audio", "VST3", "Instrument|Piano" },
  23349. { "VST3-demo-3", "Beat Kit 808", "Sample Lab", "VST3", "Instrument|Drum" },
  23350. { "CLAP-demo-4", "Orchestra Strings", "Sample Lab", "CLAP", "Instrument|Sampler" },
  23351. { "VST3-demo-5", "Wave Table One", "Example Audio", "VST3", "Instrument|Synth" },
  23352. { "VST-demo-6", "Sub Bass Machine", "Low End", "VST", "Synth" },
  23353. { "VST3-demo-7", "Sample Player", "Sample Lab", "VST3", "Instrument|Sampler" } });
  23354. dock->showCategoryForSnapshot ((int) lynx::soundlib::Category::synths);
  23355. offline.dispatchPendingMessages();
  23356. check ("My plugins: the generic synths and samplers in their own category (" + juce::String (dock->soundRowsForCheck()) + " of 7)", dock->soundRowsForCheck() == 3);
  23357. shots ("picker-plugins");
  23358. line (report.contains ("ERROR ") ? "RESULT ERROR" : "RESULT OK");
  23359. juce::File (prefix + "-report.txt").replaceWithText (report);
  23360. }
  23361. void runSimpleShot (const juce::String& prefix)
  23362. {
  23363. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  23364. lynx::AudioEngine offline (false);
  23365. lynx::MainComponent ui (offline, false);
  23366. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  23367. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  23368. const auto writeImage = [&prefix] (const juce::Image& image, const char* name) {
  23369. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  23370. file.deleteFile();
  23371. juce::FileOutputStream out (file);
  23372. juce::PNGImageFormat().writeImageToStream (image, out);
  23373. };
  23374. const auto write = [&ui, &writeImage] (const char* name) { writeImage (lynx::shot::snapshot (ui), name); };
  23375. // View › Layout style, with its submenu, as it is with `style` chosen
  23376. const auto viewMenu = [&ui] {
  23377. const auto names = ui.getMenuNamesForSnapshot();
  23378. const auto view = names.indexOf (lynx::tr ("View"));
  23379. return ui.getMenuForSnapshot (juce::jmax (0, view));
  23380. };
  23381. const auto saveStyleMenus = [&] (const juce::String& suffix) {
  23382. const auto view = viewMenu();
  23383. juce::StringArray names { lynx::tr ("View") };
  23384. std::vector<juce::PopupMenu> menus { view };
  23385. for (juce::PopupMenu::MenuItemIterator it (view); it.next();)
  23386. if (it.getItem().subMenu != nullptr && it.getItem().text == lynx::tr ("Layout style"))
  23387. {
  23388. names.add (lynx::tr ("Layout style"));
  23389. menus.push_back (*it.getItem().subMenu);
  23390. }
  23391. saveMenus (names, menus, prefix + "-menu-" + suffix + ".png");
  23392. };
  23393. // Settings › General with `style` selected, and its style list
  23394. const auto saveSettings = [&] (lynx::layoutstyle::Style style, const char* name) {
  23395. lynx::SettingsHooks hooks;
  23396. hooks.getGeneral = [style] {
  23397. lynx::GeneralOptions o;
  23398. o.language = lynx::i18n::current();
  23399. o.layoutStyle = (int) style;
  23400. return o;
  23401. };
  23402. auto page = lynx::makeSettingsPanel (offline, lynx::SettingsPage::general, false, hooks);
  23403. const auto image = lynx::shot::paint (*page, lynx::theme::panel, -1, juce::jmin (page->getHeight(), 420));
  23404. writeImage (image, name);
  23405. std::function<juce::ComboBox* (juce::Component&)> find = [&find] (juce::Component& c) -> juce::ComboBox* {
  23406. if (c.getComponentID() == "layoutStyle")
  23407. return dynamic_cast<juce::ComboBox*> (&c);
  23408. for (auto* child : c.getChildren())
  23409. if (auto* box = find (*child))
  23410. return box;
  23411. return nullptr;
  23412. };
  23413. if (auto* box = find (*page); box != nullptr && box->getRootMenu() != nullptr)
  23414. saveMenus (juce::StringArray { lynx::tr ("Layout style") }, std::vector<juce::PopupMenu> { *box->getRootMenu() },
  23415. prefix + "-" + name + "-list.png");
  23416. };
  23417. const auto madeBefore = lynx::SimpleWorkflow::instances.load();
  23418. ui.selectTabForSnapshot (2); // the Playlist panel, maximized (as --gridshot)
  23419. write ("pattern");
  23420. saveStyleMenus ("pattern");
  23421. saveSettings (lynx::layoutstyle::Style::pattern, "settings-pattern");
  23422. const auto madePattern = lynx::SimpleWorkflow::instances.load();
  23423. ui.setLayoutStyle (lynx::layoutstyle::Style::clipLaunch);
  23424. saveStyleMenus ("cliplaunch");
  23425. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  23426. offline.dispatchPendingMessages();
  23427. if (auto* simple = ui.getSimpleWorkflowForSnapshot())
  23428. simple->showChooser(); // (an empty project opens on it by itself; the offline project may hold the default song)
  23429. write ("simple"); // the New track chooser (slice S3)
  23430. if (auto* simple = ui.getSimpleWorkflowForSnapshot())
  23431. {
  23432. simple->showStarterPageForSnapshot();
  23433. write ("simple-starter");
  23434. simple->hideChooser();
  23435. write ("simple-closed");
  23436. // round 190p: a loop keeps time. Two files with the same 4.8 s of audio dropped on the empty Simple timeline:
  23437. // "Guitar loop 100.wav" (2 bars at 100 BPM) lasts 2 bars at the project's tempo, "Guitar take.wav" plays at
  23438. // its own speed. Both are undone again, so the shots after this one are as they were.
  23439. {
  23440. const auto folder = juce::File (prefix + "-loops");
  23441. folder.createDirectory();
  23442. juce::StringArray files;
  23443. for (const auto* name : { "Guitar loop 100.wav", "Guitar take.wav" })
  23444. {
  23445. const auto file = folder.getChildFile (name);
  23446. file.deleteFile();
  23447. const auto rate = 44100.0;
  23448. const auto frames = (int) (4.8 * rate);
  23449. juce::AudioBuffer<float> audio (1, frames);
  23450. for (int i = 0; i < frames; ++i)
  23451. {
  23452. const auto t = (double) i / rate, inBeat = std::fmod (t, 0.6); // a plucked note on every beat at 100 BPM
  23453. audio.setSample (0, i, (float) (0.7 * std::exp (-inBeat * 7.0) * std::sin (juce::MathConstants<double>::twoPi * 196.0 * t)));
  23454. }
  23455. if (auto out = file.createOutputStream())
  23456. if (auto writer = std::unique_ptr<juce::AudioFormatWriter> (juce::WavAudioFormat().createWriterFor (out.get(), rate, 1, 16, {}, 0)))
  23457. {
  23458. out.release();
  23459. writer->writeFromAudioSampleBuffer (audio, 0, frames);
  23460. }
  23461. files.add (file.getFullPathName());
  23462. }
  23463. simple->dropFiles (files, 0);
  23464. offline.dispatchPendingMessages();
  23465. // the clips' waveforms are analysed in the background and drawn once ready (a live window repaints by
  23466. // itself; one off-screen paint came too early and showed empty clips)
  23467. for (const auto& path : files)
  23468. lynx::ui::WaveformCache::getInstance()->find (path, [&offline, path] { return offline.getSampleLibrary().load (path); });
  23469. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (30000);
  23470. offline.dispatchPendingMessages();
  23471. write ("simple-loop");
  23472. const auto& song = offline.getSong();
  23473. juce::String report;
  23474. for (const auto& clip : song.playlist)
  23475. if (clip.kind == lynx::ClipKind::audio)
  23476. report << song.channels[(std::size_t) clip.channel].name << ": " << juce::String ((double) clip.length / lynx::ppq, 3) << " beats, stretch "
  23477. << juce::String (song.channels[(std::size_t) clip.channel].sampler.stretchBeats, 2) << "\n";
  23478. juce::File (prefix + "-loop.txt").replaceWithText ("tempo " + juce::String (song.bpm, 1) + "\n" + report);
  23479. for (int i = 0; i < files.size() && offline.canUndo(); ++i) // (one undo step per dropped file)
  23480. offline.undo();
  23481. offline.dispatchPendingMessages();
  23482. simple->hideChooser();
  23483. }
  23484. // round 190t, slice A: one click on a starter beat adds it, placed for four bars (undone again)
  23485. {
  23486. const auto clipsBefore = offline.getSong().playlist.size();
  23487. const auto tempoBefore = offline.getSong().bpm;
  23488. simple->clickStarterForSnapshot (1);
  23489. offline.dispatchPendingMessages();
  23490. write ("simple-starter-added");
  23491. const auto& song = offline.getSong();
  23492. juce::String report ("tempo " + juce::String (tempoBefore, 1) + " -> " + juce::String (song.bpm, 1) + "\n");
  23493. for (auto i = clipsBefore; i < song.playlist.size(); ++i)
  23494. report << "clip at beat " << juce::String ((double) song.playlist[i].start / lynx::ppq, 2) << ", " << juce::String ((double) song.playlist[i].length / lynx::ppq, 2)
  23495. << " beats, pattern " << song.playlist[i].pattern << ", track " << song.playlist[i].track << "\n";
  23496. juce::File (prefix + "-starter.txt").replaceWithText (report);
  23497. if (song.playlist.size() > clipsBefore && offline.canUndo())
  23498. offline.undo();
  23499. offline.dispatchPendingMessages();
  23500. simple->hideChooser();
  23501. }
  23502. // slice S4: the Simple headers with a few tracks (voice, instrument, drums, an audio file), some levels moved
  23503. offline.editSong ([] (lynx::Song& s) {
  23504. namespace st = lynx::simpletracks;
  23505. st::Request q;
  23506. q.kind = st::Kind::voice;
  23507. q.name = "Lead vocal";
  23508. st::addTrack (s, q);
  23509. q = {};
  23510. q.kind = st::Kind::instrument;
  23511. q.name = "Keys";
  23512. lynx::ChannelDef keys;
  23513. keys.instrument = lynx::InstrumentKind::synth;
  23514. q.channel = keys;
  23515. lynx::Pattern chords;
  23516. for (int i = 0; i < 4; ++i)
  23517. for (int k : { 60, 64, 67 })
  23518. chords.notes.push_back (lynx::Note { (std::int64_t) i * 4 * lynx::ppq, 4 * lynx::ppq - lynx::ppq / 4, 0, k });
  23519. q.pattern = chords;
  23520. const auto r = st::addTrack (s, q);
  23521. q = {};
  23522. q.kind = st::Kind::drums;
  23523. for (auto kind : { lynx::InstrumentKind::kick, lynx::InstrumentKind::snare, lynx::InstrumentKind::hat })
  23524. {
  23525. lynx::ChannelDef c;
  23526. c.instrument = kind;
  23527. c.name = kind == lynx::InstrumentKind::kick ? "Kick" : kind == lynx::InstrumentKind::snare ? "Snare" : "Hat";
  23528. q.kit.push_back (c);
  23529. }
  23530. lynx::Pattern beat;
  23531. const auto hit = [&beat] (int step, int row) { beat.notes.push_back (lynx::Note { (std::int64_t) step * lynx::ticksPerStep, lynx::ticksPerStep, row, 60 }); };
  23532. for (int step = 0; step < 16; step += 2)
  23533. hit (step, 2); // hats on the 8ths, kick on 1 and 3, snare on 2 and 4
  23534. for (int step : { 0, 8 })
  23535. hit (step, 0);
  23536. for (int step : { 4, 12 })
  23537. hit (step, 1);
  23538. q.pattern = beat;
  23539. q.bpm = 96.0;
  23540. st::addTrack (s, q);
  23541. if (r.insert > 0)
  23542. {
  23543. s.mixer[(std::size_t) r.insert].volume = 0.55f;
  23544. s.mixer[(std::size_t) r.insert].pan = -0.4f;
  23545. s.mixer[(std::size_t) r.insert].solo = true;
  23546. }
  23547. });
  23548. offline.dispatchPendingMessages();
  23549. ui.getPlaylistForSnapshot().selectTrack (1);
  23550. write ("simple-tracks");
  23551. // round 190t, slice E: the backup status beside the title tools, in each of its states
  23552. {
  23553. const auto now = juce::Time::currentTimeMillis();
  23554. juce::String states;
  23555. int n = 0;
  23556. for (const auto& text : { lynx::MainComponent::simpleSaveStatusText (true, false, 0, now), lynx::MainComponent::simpleSaveStatusText (true, false, now - 5000, now),
  23557. lynx::MainComponent::simpleSaveStatusText (true, true, now - 125000, now), lynx::MainComponent::simpleSaveStatusText (false, true, 0, now),
  23558. lynx::MainComponent::simpleSaveStatusText (false, false, 0, now) })
  23559. {
  23560. simple->setStatusForSnapshot (text);
  23561. offline.dispatchPendingMessages();
  23562. states << n << ": " << text << "\n";
  23563. writeImage (lynx::shot::snapshot (ui, ui.getLocalBounds().withTop (juce::jmin (ui.getHeight() - 1, 70)).withHeight (juce::jmin (ui.getHeight(), 44))),
  23564. ("status-" + juce::String (n++)).toRawUTF8());
  23565. }
  23566. juce::File (prefix + "-status.txt").replaceWithText (states);
  23567. simple->setStatusForSnapshot (lynx::MainComponent::simpleSaveStatusText (true, true, now - 125000, now));
  23568. offline.dispatchPendingMessages();
  23569. write ("simple-status");
  23570. }
  23571. // slice S8: the Finish dock, empty, then with a look on the Master (Balanced, Normal, a little Tone)
  23572. simple->showFinish();
  23573. offline.dispatchPendingMessages();
  23574. write ("simple-finish-empty");
  23575. offline.editSongStructural ([] (lynx::Song& s) { lynx::looks::apply (s, lynx::MasterLookSettings { lynx::looks::balanced, 0.5f, { 1.5f, 0.0f, 1.0f }, -3.0f }); });
  23576. offline.dispatchPendingMessages();
  23577. simple->showFinish();
  23578. write ("simple-finish");
  23579. simple->hideFinish();
  23580. }
  23581. saveStyleMenus ("simple");
  23582. saveSettings (lynx::layoutstyle::Style::simple, "settings-simple");
  23583. // round 184a S11: the Key panel (no key, then an A minor riff and its guesses) and its menu
  23584. const auto toolbarShot = [&] (const char* name) {
  23585. writeImage (lynx::shot::snapshot (ui, ui.getLocalBounds().withHeight (juce::jmin (ui.getHeight(), 80))), name);
  23586. };
  23587. toolbarShot ("key-none");
  23588. saveMenus (juce::StringArray { lynx::tr ("Key") }, std::vector<juce::PopupMenu> { ui.getKeyMenuForSnapshot() }, prefix + "-key-menu-empty.png");
  23589. offline.editSong ([] (lynx::Song& s) {
  23590. if (s.channels.empty())
  23591. s.channels.resize (1);
  23592. if (s.patterns.empty())
  23593. s.patterns.emplace_back();
  23594. int t = 0;
  23595. for (int k : { 57, 60, 64, 67, 69, 67, 64, 60, 57, 59, 60, 62, 64, 62, 60, 59, 57, 57, 64, 45 })
  23596. {
  23597. lynx::Note n;
  23598. n.channel = 0;
  23599. n.key = k;
  23600. n.start = t * lynx::ppq / 2;
  23601. n.length = k == 57 || k == 45 ? lynx::ppq : lynx::ppq / 2;
  23602. s.patterns[0].notes.push_back (n);
  23603. ++t;
  23604. }
  23605. });
  23606. offline.dispatchPendingMessages();
  23607. saveMenus (juce::StringArray { lynx::tr ("Key") }, std::vector<juce::PopupMenu> { ui.getKeyMenuForSnapshot() }, prefix + "-key-menu-guess.png");
  23608. const auto guesses = lynx::keyguess::guess (offline.getSong(), 3);
  23609. if (! guesses.empty())
  23610. offline.editSong ([k = guesses[0].key] (lynx::Song& s) { lynx::projectkey::set (s, k); });
  23611. offline.dispatchPendingMessages();
  23612. toolbarShot ("key-set");
  23613. write ("simple-key");
  23614. juce::String keyCounts;
  23615. for (const auto& g : guesses)
  23616. keyCounts << "guess " << lynx::projectkey::name (g.key) << " " << g.notesInScale << "/" << g.notes << " score " << g.score << "\n";
  23617. offline.editSong ([] (lynx::Song& s) { lynx::projectkey::set (s, std::nullopt); });
  23618. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
  23619. offline.dispatchPendingMessages();
  23620. toolbarShot ("key-pattern-toolbar");
  23621. write ("pattern-after");
  23622. // round 184a S17: the setup wizard with its Workflow choice — a first start (Pattern selected), then reopened in Simple
  23623. for (int style : { 0, 2 })
  23624. {
  23625. auto wizard = lynx::makeSetupWizardContent (offline, {}, {}, style, {});
  23626. auto image = lynx::shot::paint (*wizard);
  23627. writeImage (image, style == 0 ? "wizard-pattern" : "wizard-simple");
  23628. }
  23629. juce::File (prefix + "-counts.txt").replaceWithText ("simple workflows before " + juce::String (madeBefore) + ", in pattern workflow "
  23630. + juce::String (madePattern) + ", after " + juce::String (lynx::SimpleWorkflow::instances.load())
  23631. + "\nstyle after " + lynx::layoutstyle::id (ui.getLayoutStyle()) + "\n" + keyCounts);
  23632. }
  23633. void runLiveRackShot190hr (const juce::String& prefix)
  23634. {
  23635. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  23636. lynx::AudioEngine offline (false);
  23637. lynx::MainComponent ui (offline, false);
  23638. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  23639. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  23640. const auto write = [&prefix, &ui, &offline] (const char* name) {
  23641. offline.dispatchPendingMessages();
  23642. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  23643. file.deleteFile();
  23644. juce::FileOutputStream out (file);
  23645. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (ui), out);
  23646. };
  23647. const auto writeView = [&prefix] (juce::Component& c, const char* name) {
  23648. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  23649. file.deleteFile();
  23650. juce::FileOutputStream out (file);
  23651. juce::PNGImageFormat().writeImageToStream (lynx::shot::paint (c, lynx::theme::panel), out);
  23652. };
  23653. juce::String checks;
  23654. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  23655. const auto itemEnabled = [] (const juce::PopupMenu& menu, const juce::String& start) {
  23656. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  23657. if (it.getItem().text.startsWith (start))
  23658. return it.getItem().isEnabled ? 1 : 0;
  23659. return -1;
  23660. };
  23661. ui.setVisible (true);
  23662. lynx::DetailView::shownSetting = lynx::DetailView::devicesPage = true;
  23663. ui.setClipLaunchWorkflow (true);
  23664. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::browser, lynx::workspace::Panel::playlist });
  23665. offline.editSong ([] (lynx::Song& s) {
  23666. if (s.channels.size() < 1)
  23667. s.channels.resize (1);
  23668. s.channels[0].name = "Lead";
  23669. s.channels[0].instrument = lynx::InstrumentKind::synth;
  23670. s.channels[0].mixerTrack = 2;
  23671. if (s.mixer.size() < 4)
  23672. s.mixer.resize (4);
  23673. s.mixer[2].name = "Lead";
  23674. s.mixer[2].effects.clear();
  23675. for (auto kind : { lynx::EffectKind::eq, lynx::EffectKind::delay })
  23676. s.mixer[2].effects.push_back (lynx::makeEffectSlot (kind));
  23677. while (s.patterns.size() < 1)
  23678. s.patterns.emplace_back();
  23679. lynx::Note note;
  23680. note.channel = 0;
  23681. note.key = 60;
  23682. s.patterns[0].notes = { note };
  23683. s.patterns[0].lengthTicks = 4 * lynx::ppq;
  23684. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 3));
  23685. s.playlistTracks[1].name = "Lead";
  23686. lynx::Clip clip;
  23687. clip.pattern = 0;
  23688. clip.length = 4 * lynx::ppq;
  23689. lynx::launcher::setClip (s, 1, 0, clip);
  23690. }, false);
  23691. offline.dispatchPendingMessages();
  23692. auto* detail = ui.getDetailViewForSnapshot();
  23693. if (detail == nullptr)
  23694. {
  23695. juce::File (prefix + "-checks.txt").replaceWithText ("FAIL no detail view\n");
  23696. return;
  23697. }
  23698. detail->showSelection (1, 0);
  23699. detail->setPage (lynx::DetailView::Page::devices);
  23700. detail->selectCardForCheck (0); // the instrument
  23701. write ("01-devices");
  23702. auto menu = detail->cardMenuForSnapshot (0);
  23703. saveMenus (juce::StringArray { "Instrument" }, std::vector<juce::PopupMenu> { menu }, prefix + "-02-instrument-menu.png");
  23704. check ("instrument menu: Group on, Ungroup off", itemEnabled (menu, lynx::tr ("Group")) == 1 && itemEnabled (menu, lynx::tr ("Ungroup")) == 0);
  23705. // Ctrl+G: the synth into an Instrument Rack (the card becomes the rack's)
  23706. check ("Ctrl+G groups the instrument into an Instrument Rack", detail->groupCardForCheck (0, false));
  23707. const auto& grouped = offline.getSong().channels[0];
  23708. check ("the channel keeps its insert and the rack holds the synth",
  23709. grouped.mixerTrack == 2 && lynx::rack::isRack (grouped) && lynx::rack::rackOf (grouped.patcher)->kind == lynx::RackDoc::Kind::instrument
  23710. && lynx::rack::devices (*lynx::rack::rackOf (grouped.patcher), 0).size() == 1);
  23711. detail->selectCardForCheck (0);
  23712. write ("03-grouped");
  23713. menu = detail->cardMenuForSnapshot (0);
  23714. saveMenus (juce::StringArray { "Instrument Rack" }, std::vector<juce::PopupMenu> { menu }, prefix + "-04-rack-menu.png");
  23715. check ("rack menu: Ungroup on, Save as Live rack preset", itemEnabled (menu, lynx::tr ("Ungroup")) == 1
  23716. && itemEnabled (menu, lynx::tr ("Save as Live rack preset (.adg)...")) == 1);
  23717. check ("Ctrl+Shift+G ungroups it", detail->groupCardForCheck (0, true) && offline.getSong().channels[0].instrument == lynx::InstrumentKind::synth);
  23718. write ("05-ungrouped");
  23719. // a rack's view: Live's Save Preset button at the foot of the strip, the drop area
  23720. offline.editSong ([] (lynx::Song& s) {
  23721. auto rack = lynx::rack::makeRackSlot (lynx::RackDoc::Kind::audioEffect);
  23722. lynx::rack::rackOf (rack.patcher)->showDevices = true;
  23723. s.mixer[3].effects = { rack };
  23724. }, false);
  23725. offline.dispatchPendingMessages();
  23726. {
  23727. auto view = lynx::RackWindows::makeSlotView (offline, 3, 0, true);
  23728. view->setSize (std::max (520, view->preferredWidth (228)), 228);
  23729. writeView (*view, "06-rack-empty");
  23730. lynx::PatchNode fx;
  23731. fx.effect = lynx::makeEffectSlot (lynx::EffectKind::delay);
  23732. const juce::Point<int> inDevices { view->getWidth() - 30, view->getHeight() / 2 };
  23733. check ("an effect dropped on the chain goes in", view->dropNodeForCheck (fx, inDevices));
  23734. lynx::PatchNode synth;
  23735. synth.generator = true;
  23736. synth.channel.instrument = lynx::InstrumentKind::synth;
  23737. check ("an instrument dropped on an Audio Effect Rack is refused", ! view->dropNodeForCheck (synth, inDevices));
  23738. const auto* r = lynx::rack::rackOf (offline.getSong().mixer[3].effects[0].patcher);
  23739. check ("the chain holds one device", r != nullptr && lynx::rack::devices (*r, 0).size() == 1);
  23740. view->setSize (std::max (520, view->preferredWidth (228)), 228);
  23741. writeView (*view, "07-rack-after-drop");
  23742. // the rack as a Live preset and back
  23743. const auto out = lynx::exportLiveRackPreset (offline.getSong().mixer[3].effects[0].patcher, "Shot Rack");
  23744. check ("Save as .adg writes Live's preset form", out.xml.find ("<GroupDevicePreset>") != std::string::npos
  23745. && out.xml.find ("<AudioEffectBranchPreset ") != std::string::npos);
  23746. const auto back = lynx::importLiveDevicePreset (out.bytes);
  23747. check ("the .adg reads back as the rack", back.has_value() && lynx::rack::isRack (back->slot)
  23748. && lynx::rack::rackOf (back->slot.patcher)->chains.size() == 1);
  23749. }
  23750. // Live's own .adg (Core Library, read-only): before round 190hr it opened without chains
  23751. const juce::File live ("C:/ProgramData/Ableton/Live 12 Trial/Resources/Core Library/Racks/Audio Effect Racks/Distortion/Smokey Water.adg");
  23752. const juce::File liveWsl ("/mnt/c/ProgramData/Ableton/Live 12 Trial/Resources/Core Library/Racks/Audio Effect Racks/Distortion/Smokey Water.adg");
  23753. const auto adg = live.existsAsFile() ? live : liveWsl;
  23754. if (adg.existsAsFile())
  23755. {
  23756. juce::MemoryBlock data;
  23757. adg.loadFileAsData (data);
  23758. const auto* bytes = static_cast<const std::uint8_t*> (data.getData());
  23759. auto p = lynx::importLiveDevicePreset (std::vector<std::uint8_t> (bytes, bytes + data.getSize()));
  23760. check ("Live's Smokey Water.adg opens with its chain and devices", p.has_value() && lynx::rack::isRack (p->slot)
  23761. && ! lynx::rack::rackOf (p->slot.patcher)->chains.empty()
  23762. && lynx::rack::devices (*lynx::rack::rackOf (p->slot.patcher), 0).size() >= 3);
  23763. if (p)
  23764. {
  23765. lynx::rack::rackOf (p->slot.patcher)->showDevices = true;
  23766. lynx::rack::rackOf (p->slot.patcher)->showChains = true;
  23767. offline.editSong ([slot = p->slot] (lynx::Song& s) { s.mixer[3].effects = { slot }; }, false);
  23768. offline.dispatchPendingMessages();
  23769. auto view = lynx::RackWindows::makeSlotView (offline, 3, 0, true);
  23770. view->setSize (std::max (520, view->preferredWidth (228)), 228);
  23771. writeView (*view, "08-live-adg-smokey-water");
  23772. }
  23773. }
  23774. else
  23775. checks << "skip Live's Core Library is not on this machine\n";
  23776. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  23777. }
  23778. void runLiveShot190ce (const juce::String& prefix)
  23779. {
  23780. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  23781. lynx::AudioEngine offline (false);
  23782. lynx::MainComponent ui (offline, false);
  23783. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  23784. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  23785. const auto write = [&prefix, &ui, &offline] (const char* name) {
  23786. offline.dispatchPendingMessages();
  23787. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  23788. file.deleteFile();
  23789. juce::FileOutputStream out (file);
  23790. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (ui), out);
  23791. };
  23792. juce::String checks;
  23793. const auto check = [&checks] (const char* what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  23794. // a small library of its own (empty files: only names are shown)
  23795. const auto lib = juce::File (prefix + "-library");
  23796. lib.deleteRecursively();
  23797. for (const auto* path : { "Drums/Kicks/Kick Hard.wav", "Drums/Kicks/Kick Soft.wav", "Drums/Snare Tight.wav", "Drums/Hat Closed.wav",
  23798. "Loops/Break 120.wav", "Loops/Shaker 98.wav", "Textures/Vinyl Noise.wav", "Textures/Rain.wav" })
  23799. lib.getChildFile (path).create();
  23800. auto& browser = ui.getBrowserForSnapshot();
  23801. auto& store = lynx::BrowserComponent::collectionStore();
  23802. store = {};
  23803. const auto item = [&lib] (const char* path) { return lib.getChildFile (path).getFullPathName().toStdString(); };
  23804. ui.setVisible (true);
  23805. lynx::DetailView::shownSetting = lynx::DetailView::devicesPage = true;
  23806. ui.setClipLaunchWorkflow (true);
  23807. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::browser, lynx::workspace::Panel::playlist });
  23808. offline.editSong ([] (lynx::Song& s) {
  23809. if (s.channels.size() < 2)
  23810. s.channels.resize (2);
  23811. s.channels[0].name = "Bass synth";
  23812. s.channels[0].mixerTrack = 2;
  23813. s.channels[1].mixerTrack = 3;
  23814. if (s.mixer.size() < 4)
  23815. s.mixer.resize (4);
  23816. s.mixer[2].name = "Bass";
  23817. s.mixer[2].effects.clear();
  23818. for (auto kind : { lynx::EffectKind::eq, lynx::EffectKind::compressor, lynx::EffectKind::delay })
  23819. {
  23820. lynx::EffectSlot fx;
  23821. fx.kind = kind;
  23822. const auto& info = lynx::effectInfo (kind);
  23823. for (std::size_t k = 0; k < info.params.size() && k < fx.params.size(); ++k)
  23824. fx.params[k] = info.params[k].defaultValue;
  23825. s.mixer[2].effects.push_back (fx);
  23826. }
  23827. s.mixer[2].effects[1].enabled = false; // the compressor: off, at half mix
  23828. s.mixer[2].effects[1].mix = 0.5f;
  23829. while (s.patterns.size() < 2)
  23830. s.patterns.emplace_back();
  23831. s.patterns[0].name = "Bass line";
  23832. lynx::Note note;
  23833. note.channel = 0;
  23834. note.key = 36;
  23835. s.patterns[0].notes = { note };
  23836. s.patterns[0].lengthTicks = 4 * lynx::ppq;
  23837. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 3));
  23838. s.playlistTracks[1].name = "Bass";
  23839. lynx::Clip clip;
  23840. clip.pattern = 0;
  23841. clip.length = 4 * lynx::ppq;
  23842. lynx::launcher::setClip (s, 1, 0, clip);
  23843. }, false);
  23844. offline.dispatchPendingMessages();
  23845. auto* detail = ui.getDetailViewForSnapshot();
  23846. if (detail == nullptr)
  23847. {
  23848. juce::File (prefix + "-checks.txt").replaceWithText ("FAIL no detail view\n");
  23849. return;
  23850. }
  23851. detail->showSelection (1, 0);
  23852. detail->setPage (lynx::DetailView::Page::devices);
  23853. detail->selectCardForCheck (2); // the compressor (card 0 is the instrument)
  23854. write ("01-devices"); // the cards' title buttons: hot-swap, save, fold
  23855. saveMenus (juce::StringArray { "Device (effect card)" }, std::vector<juce::PopupMenu> { detail->cardMenuForSnapshot (2) }, prefix + "-02-device-menu.png");
  23856. // hot-swap on for the compressor: the Browser's bar, the Plugin database's effects, the card's button lit
  23857. const auto compressor = lynx::hotswap::targetOfEffect (offline.getSong(), 2, 1);
  23858. browser.beginHotSwap (compressor);
  23859. write ("03-hotswap-effect");
  23860. check ("hot-swap links the compressor", browser.isHotSwapping() && browser.hotSwapTarget() == compressor);
  23861. // a swap through the Browser itself (the row of LYNX's Reverb, then Enter): the slot keeps its place, its off
  23862. // state and its Mix; the link moves to the new device
  23863. {
  23864. browser.showPluginDatabase ("LYNX SHARE", 0); // (the folder of LYNX's own effects, opened as a click would)
  23865. browser.selectRowForSnapshot (lynx::tr (lynx::effectInfo (lynx::EffectKind::reverb).name));
  23866. write ("03a-hotswap-row"); // the candidate's row selected
  23867. check ("swap: Enter on the Reverb row is taken by hot-swap", browser.hotSwapLoadSelected());
  23868. offline.dispatchPendingMessages();
  23869. const auto& slot = offline.getSong().mixer[2].effects[1];
  23870. // (round 190cy: the device comes in with its own on / off state, on, as in Live 12.4.16; the Mix stays)
  23871. 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);
  23872. check ("swap: three effects as before", offline.getSong().mixer[2].effects.size() == 3);
  23873. check ("swap: the Browser is linked to the new device", browser.isHotSwapping() && browser.hotSwapTarget() == lynx::hotswap::targetOfEffect (offline.getSong(), 2, 1)
  23874. && ! (browser.hotSwapTarget() == compressor));
  23875. write ("03b-hotswap-swapped");
  23876. offline.undo();
  23877. offline.dispatchPendingMessages();
  23878. const auto& back = offline.getSong().mixer[2].effects[1];
  23879. check ("undo: the compressor is back with its instance", back.kind == lynx::EffectKind::compressor && back.instance.id == compressor.instance);
  23880. check ("undo: the Browser is still linked to it", browser.isHotSwapping() && browser.hotSwapTarget() == compressor);
  23881. }
  23882. // round 190cy (Live 12.4.16 live check 190cw shot 02a): hot-swap starts on the device's current preset. The
  23883. // compressor got its settings from a saved preset of LYNX's ("Glue bus", in this run's own settings folder)
  23884. {
  23885. browser.endHotSwap();
  23886. const auto folder = lynx::pluginheader::userFolder (lynx::EffectKind::compressor);
  23887. folder.createDirectory();
  23888. const auto& fx = offline.getSong().mixer[2].effects[1];
  23889. for (const auto* name : { "Glue bus", "Gentle", "Parallel smash" })
  23890. folder.getChildFile (juce::String (name) + ".lynxpreset").replaceWithText (lynx::presets::toText (lynx::EffectKind::compressor, name, fx.params));
  23891. offline.editSong ([] (lynx::Song& s) { s.mixer[2].effects[1].presetName = "Glue bus"; }, false);
  23892. offline.dispatchPendingMessages();
  23893. browser.beginHotSwap (compressor);
  23894. write ("03c-hotswap-current-preset");
  23895. check ("hot-swap starts on the current preset", browser.getSelectedFile() == folder.getChildFile ("Glue bus.lynxpreset"));
  23896. // a preset of the same effect swapped in comes in on (the compressor was off)
  23897. browser.selectRowForSnapshot ("Gentle.lynxpreset");
  23898. check ("swap: the preset row is taken by hot-swap", browser.hotSwapLoadSelected());
  23899. offline.dispatchPendingMessages();
  23900. const auto& now = offline.getSong().mixer[2].effects[1];
  23901. check ("swap: the preset's settings, the device on", now.kind == lynx::EffectKind::compressor && now.presetName == "Gentle" && now.enabled);
  23902. write ("03d-hotswap-preset-swapped");
  23903. offline.undo();
  23904. offline.dispatchPendingMessages();
  23905. check ("undo: the compressor off again", ! offline.getSong().mixer[2].effects[1].enabled);
  23906. browser.endHotSwap();
  23907. check ("hot-swap ended: the preset list goes", ! browser.isHotSwapping());
  23908. browser.beginHotSwap (compressor);
  23909. }
  23910. // linked to the instrument instead
  23911. const auto bass = lynx::hotswap::targetOfChannel (offline.getSong(), 0);
  23912. browser.beginHotSwap (bass);
  23913. detail->selectCardForCheck (0);
  23914. write ("04-hotswap-instrument");
  23915. check ("re-link to the instrument", browser.hotSwapTarget() == bass);
  23916. browser.endHotSwap();
  23917. check ("hot-swap ended", ! browser.isHotSwapping());
  23918. write ("05-hotswap-ended"); // the Browser as it was before
  23919. // the device is deleted while linked: the mode ends by itself
  23920. browser.beginHotSwap (lynx::hotswap::targetOfEffect (offline.getSong(), 2, 2));
  23921. offline.editSong ([] (lynx::Song& s) { s.mixer[2].effects.pop_back(); });
  23922. offline.dispatchPendingMessages();
  23923. check ("deleting the linked device ends hot-swap", ! browser.isHotSwapping());
  23924. offline.undo();
  23925. offline.dispatchPendingMessages();
  23926. // Duplicate (Ctrl+D) of the EQ
  23927. check ("duplicate", detail->duplicateCardForCheck (1));
  23928. offline.dispatchPendingMessages();
  23929. check ("duplicate: four effects, EQ twice", offline.getSong().mixer[2].effects.size() == 4 && offline.getSong().mixer[2].effects[1].kind == lynx::EffectKind::eq
  23930. && offline.getSong().mixer[2].effects[0].instance.id != offline.getSong().mixer[2].effects[1].instance.id);
  23931. write ("06-duplicated");
  23932. // --- collections ---
  23933. browser.showFilterForSnapshot (lib, lynx::browserview::ContentFilter::all);
  23934. ui.waitForBrowserForSnapshot();
  23935. browser.setInCollection (item ("Drums/Kicks/Kick Hard.wav"), 0, true);
  23936. browser.setInCollection (item ("Drums/Snare Tight.wav"), 0, true);
  23937. browser.setInCollection (item ("Loops"), 0, true);
  23938. browser.setTab (lynx::BrowserComponent::starredTab);
  23939. write ("07-starred-only"); // only Starred shown: the tab as it always was
  23940. browser.setInCollection (item ("Drums/Kicks/Kick Hard.wav"), 4, true); // also Blue
  23941. browser.setInCollection (item ("Loops/Break 120.wav"), 4, true);
  23942. browser.setInCollection (item ("Textures/Vinyl Noise.wav"), 3, true);
  23943. browser.setInCollection (item ("Textures/Rain.wav"), 3, true);
  23944. browser.setInCollection (item ("Drums/Hat Closed.wav"), 1, true);
  23945. store.rename (3, "Textures");
  23946. browser.setCollectionShown (1, true);
  23947. browser.setCollectionShown (3, true);
  23948. browser.setCollectionShown (4, true);
  23949. write ("08-collections"); // a heading per collection shown
  23950. check ("collections: four shown", store.shown().size() == 4);
  23951. check ("collections: an item in two", store.mask (item ("Drums/Kicks/Kick Hard.wav")) == 0b10001);
  23952. // round 190cy: the Clip-launch workflow's row menu lists the collections flat, as Live's item menu (shot 05);
  23953. // the Pattern workflow keeps the "Collections" sub-menu
  23954. browser.setLiveItemMenus (false);
  23955. saveMenus (juce::StringArray { "Collections (Pattern workflow: a row's sub-menu)" }, std::vector<juce::PopupMenu> { browser.collectionsMenuForSnapshot (item ("Drums/Kicks/Kick Hard.wav")) },
  23956. prefix + "-09-collections-menu.png");
  23957. browser.setLiveItemMenus (true);
  23958. saveMenus (juce::StringArray { "Collections (Clip-launch workflow: a row's menu)" }, std::vector<juce::PopupMenu> { browser.collectionsMenuForSnapshot (item ("Drums/Kicks/Kick Hard.wav")) },
  23959. prefix + "-09b-collections-flat.png");
  23960. // the key of a hidden collection (6, Purple) labels the row and the collection appears
  23961. check ("hidden collection: not shown before", ! store.isShown (5));
  23962. browser.setInCollection (item ("Textures/Rain.wav"), 5, true);
  23963. check ("hidden collection: its key shows it", store.isShown (5) && store.has (item ("Textures/Rain.wav"), 5));
  23964. write ("08b-hidden-collection-shown");
  23965. saveMenus (juce::StringArray { "Browser options" }, std::vector<juce::PopupMenu> { browser.buildViewMenu() }, prefix + "-10-browser-options.png");
  23966. browser.setTab (lynx::BrowserComponent::allTab);
  23967. write ("11-all-tab-chips"); // the colour chips on the rows of the ALL tab
  23968. browser.setSearchForSnapshot ("textures");
  23969. ui.waitForBrowserForSnapshot();
  23970. write ("12-search-collection-name"); // found by the collection's name
  23971. browser.setSearchForSnapshot ({});
  23972. // the file round trip
  23973. {
  23974. const auto text = store.toText();
  23975. check ("collections: text round trip", lynx::collections::Store::fromText (text) == store);
  23976. }
  23977. store = {};
  23978. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  23979. lib.deleteRecursively();
  23980. }
  23981. void runLinkShot190gl (const juce::String& prefix)
  23982. {
  23983. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  23984. lynx::AudioEngine offline (false);
  23985. lynx::MainComponent ui (offline, false);
  23986. ui.setSize (1600, 900);
  23987. ui.setVisible (true);
  23988. juce::String checks;
  23989. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  23990. const auto writeImage = [&prefix] (const juce::Image& image, const char* name) {
  23991. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  23992. file.deleteFile();
  23993. juce::FileOutputStream out (file);
  23994. juce::PNGImageFormat().writeImageToStream (image, out);
  23995. };
  23996. const auto toolbarShot = [&] (const char* name) {
  23997. ui.tickLinkForSnapshot();
  23998. writeImage (lynx::shot::snapshot (ui, ui.getToolbarBoundsForSnapshot()), name);
  23999. };
  24000. auto& link = offline.getLink();
  24001. auto& transport = offline.getTransport();
  24002. link.deviceStarted (44100.0);
  24003. // the audio callbacks the offline engine has none of: Link's per-block step, in real time
  24004. const auto pump = [&] (double seconds, std::function<bool()> until = {}) {
  24005. const auto end = juce::Time::getMillisecondCounterHiRes() + seconds * 1000.0;
  24006. while (juce::Time::getMillisecondCounterHiRes() < end)
  24007. {
  24008. const auto start = link.beginBlock (transport, 256, 0.0);
  24009. if (start >= 0)
  24010. transport.playing.store (true);
  24011. if (transport.playing.load())
  24012. transport.positionTicks.store (transport.positionTicks.load() + 256 * transport.ticksPerSample());
  24013. juce::Thread::sleep (6);
  24014. if (until && until())
  24015. return true;
  24016. }
  24017. return ! until || until();
  24018. };
  24019. auto peer = lynx::AbletonLink::makeTestPeer (97.0); // the other app in the session (it was there first)
  24020. juce::Thread::sleep (1500); // (a session that started at the same moment as LYNX's could take either tempo)
  24021. using lynx::toolbarlayout::Group;
  24022. // FL's Pattern layout: no Link toggle on a new install
  24023. check ("Pattern layout: the Link toggle is hidden by default", ! ui.getToolbarLayoutForSnapshot().isShown (Group::link));
  24024. toolbarShot ("toolbar-fl-default");
  24025. // shown by hand (Settings › Ableton Link › Show Link Toggle): "Link", off
  24026. auto layout = ui.getToolbarLayoutForSnapshot();
  24027. layout.setShown (Group::link, true);
  24028. ui.setToolbarLayoutForSnapshot (layout);
  24029. toolbarShot ("toolbar-fl-link-off");
  24030. check ("off: the toggle says Link", ui.getLinkToggleForSnapshot().text() == lynx::trc ("@Ableton Link: Link"));
  24031. // on: the session the other peer runs (its tempo, 97 BPM, wins over the project's)
  24032. link.setEnabled (true, offline.getSong().bpm);
  24033. // (a new peer is counted at once; its session's tempo is taken after Link measured it, a moment later)
  24034. const auto joined = pump (8.0, [&] { return link.peers() > 0 && link.startProgress() >= 0.0 && std::abs (link.sessionTempo() - 97.0) < 1e-3; });
  24035. check ("Link on: one peer found", joined && link.peers() == 1);
  24036. 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);
  24037. toolbarShot ("toolbar-fl-link-on");
  24038. check ("on with one peer: the toggle says 1 Link", ui.getLinkToggleForSnapshot().text() == lynx::trc ("@Ableton Link: {0} Link").replace ("{0}", "1"));
  24039. check ("stopped with a peer: the position display shows the session's progress", link.startProgress() >= 0.0);
  24040. // the Clip-launch layout: the toggle is shown by default (the reference DAW's "Show Link Toggle": Show)
  24041. ui.setToolbarLayoutForSnapshot (lynx::toolbarlayout::Layout::makeDefault());
  24042. ui.setClipLaunchWorkflow (true);
  24043. check ("Clip-launch layout: the Link toggle is shown by default", ui.getToolbarLayoutForSnapshot().isShown (Group::link));
  24044. pump (0.4);
  24045. toolbarShot ("toolbar-cliplaunch-1link");
  24046. writeImage (lynx::shot::snapshot (ui), "window-cliplaunch");
  24047. // Play: it waits for the session's phase (the play button lit, the progress bar running), then starts
  24048. transport.playing.store (true);
  24049. pump (0.05);
  24050. const auto waited = offline.isLinkWaiting();
  24051. check ("Play with a peer waits for the session's phase", waited);
  24052. toolbarShot ("toolbar-cliplaunch-waiting");
  24053. const auto started = pump (4.0, [&] { return transport.playing.load() && ! offline.isLinkWaiting(); });
  24054. check ("then playback starts on the session's phase", started);
  24055. pump (0.5);
  24056. toolbarShot ("toolbar-cliplaunch-playing");
  24057. check ("playing: no progress bar", link.startProgress() < 0.0);
  24058. // the toggle's drop-down and the Options menu
  24059. saveMenus (juce::StringArray { lynx::trc ("@Ableton Link: Link") }, std::vector<juce::PopupMenu> { ui.getLinkToggleForSnapshot().makeMenu() },
  24060. prefix + "-menu-link.png");
  24061. {
  24062. const auto names = ui.getMenuNamesForSnapshot();
  24063. for (int m = 0; m < names.size(); ++m)
  24064. if (names[m] == lynx::tr ("Options"))
  24065. saveMenus (juce::StringArray { names[m] }, std::vector<juce::PopupMenu> { ui.getMenuForSnapshot (m) }, prefix + "-menu-options.png");
  24066. }
  24067. // Settings › Ableton Link
  24068. {
  24069. lynx::SettingsHooks hooks;
  24070. hooks.linkToggleShown = [] { return true; };
  24071. auto panel = lynx::makeSettingsPanel (offline, lynx::SettingsPage::link, false, hooks);
  24072. panel->setSize (680, 620);
  24073. writeImage (lynx::shot::snapshot (*panel), "settings-link");
  24074. }
  24075. // off: the project's own tempo comes back on the display
  24076. transport.playing.store (false);
  24077. pump (0.1);
  24078. link.setEnabled (false, offline.getSong().bpm);
  24079. pump (0.1);
  24080. toolbarShot ("toolbar-cliplaunch-link-off");
  24081. check ("off: the tempo display shows the project's tempo again", std::abs (offline.shownTempo() - offline.getSong().bpm) < 1e-9);
  24082. const auto stats = link.stats();
  24083. checks << "audio-thread cost of the Link step: mean " << juce::String (stats.meanUs, 2) << " us, max " << juce::String (stats.maxUs, 1)
  24084. << " us over " << (juce::int64) stats.blocks << " blocks\n";
  24085. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  24086. }
  24087. // LYNX --communityshot190hp <prefix> (round 190hp): the three community slices off-screen, with checks in
  24088. // prefix-checks.txt — B9 the MIDI Map Mode's "In every project (LYNX)" (the row menu, the Mapping Browser with the
  24089. // global rows, a new project still playing on the mapped CC, Settings' list), B16 the Mixer menu's Mix snapshots
  24090. // (take, recall, Compare A/B, the .lynx round trip), B18 the audio clip menu's "Split at silence..." (the dialog and
  24091. // the Playlist before / after).
  24092. void runCommunityShot190hp (const juce::String& prefix)
  24093. {
  24094. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  24095. lynx::AudioEngine offline (false);
  24096. lynx::MainComponent ui (offline, false);
  24097. ui.setSize (1600, 900);
  24098. const auto write = [&prefix] (juce::Component& c, const char* name) {
  24099. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  24100. file.deleteFile();
  24101. juce::FileOutputStream out (file);
  24102. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (c), out);
  24103. };
  24104. juce::String checks;
  24105. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  24106. const auto plain = [] (juce::String t) { return t.upToFirstOccurrenceOf ("\t", false, false).removeCharacters ("&"); };
  24107. const auto find = [&plain] (const juce::PopupMenu& menu, const juce::String& text) -> const juce::PopupMenu::Item* {
  24108. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  24109. if (plain (it.getItem().text) == plain (text))
  24110. return &it.getItem();
  24111. return nullptr;
  24112. };
  24113. const auto click = [&find] (const juce::PopupMenu& menu, const juce::String& text) {
  24114. const auto* item = find (menu, text);
  24115. if (item == nullptr || ! item->isEnabled || item->action == nullptr)
  24116. return false;
  24117. item->action();
  24118. return true;
  24119. };
  24120. using namespace lynx::remotemap;
  24121. ui.setVisible (true);
  24122. // ---- B9: the MIDI Map Mode's mappings for every project ---------------------------------------------------------
  24123. ui.setClipLaunchWorkflow (true);
  24124. offline.editSong ([] (lynx::Song& s) {
  24125. auto& grid = lynx::launcher::ensureGrid (s);
  24126. grid.scenes.resize (4);
  24127. assignMidi (s, Target::of (lynx::RemoteAction::play), { 0, 118, -1 });
  24128. assignMidi (s, Target::of (lynx::RemoteAction::stop), { 0, 117, -1 });
  24129. assignMidi (s, Target::sceneLaunch (0), { 0, lynx::linkNoteBase + 44, -1 });
  24130. assignMidi (s, Target::slot (0, 0), { 0, lynx::linkNoteBase + 36, -1 });
  24131. assignMidi (s, Target::parameter ({ lynx::AutomationTargetKind::mixerVolume, 0, 0, 0 }), { 0, 7, -1 });
  24132. }, false);
  24133. offline.dispatchPendingMessages();
  24134. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::playlist, lynx::workspace::Panel::browser });
  24135. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  24136. ui.setMapMode (Mode::midi);
  24137. auto* list = ui.mappingBrowserForSnapshot();
  24138. if (list == nullptr)
  24139. {
  24140. juce::File (prefix + "-checks.txt").replaceWithText (checks + "FAIL no Mapping Browser\n");
  24141. return;
  24142. }
  24143. list->setMode (Mode::midi);
  24144. ui.resized();
  24145. const auto rowOf = [&] (const Target& t) {
  24146. const auto rows = list->rowsShown();
  24147. for (int r = 0; r < (int) rows.size(); ++r)
  24148. if (rows[(std::size_t) r].target == t)
  24149. return r;
  24150. return -1;
  24151. };
  24152. const auto everyProject = lynx::tr ("In every project (LYNX)");
  24153. {
  24154. const auto slotMenu = list->rowMenu (rowOf (Target::slot (0, 0)));
  24155. const auto* item = find (slotMenu, everyProject);
  24156. check ("row menu: a clip slot cannot be for every project (greyed)", item != nullptr && ! item->isEnabled);
  24157. const auto playRow = rowOf (Target::of (lynx::RemoteAction::play));
  24158. list->selectRow (playRow);
  24159. const auto playMenu = list->rowMenu (playRow);
  24160. const auto* p = find (playMenu, everyProject);
  24161. check ("row menu: Play can, unticked", p != nullptr && p->isEnabled && ! p->isTicked);
  24162. saveMenus (juce::StringArray { "Row" }, std::vector<juce::PopupMenu> { playMenu }, prefix + "-b9-01-row-menu.png");
  24163. check ("Play goes to every project", click (playMenu, everyProject) && offline.getMidiPrefs().globalMappings.size() == 1);
  24164. }
  24165. check ("Stop goes too", click (list->rowMenu (rowOf (Target::of (lynx::RemoteAction::stop))), everyProject));
  24166. check ("the Master volume link goes too (FL's global links)",
  24167. click (list->rowMenu (rowOf (Target::parameter ({ lynx::AutomationTargetKind::mixerVolume, 0, 0, 0 }))), everyProject)
  24168. && offline.getMidiPrefs().globalLinks.size() == 1 && offline.getSong().midiLinks.empty());
  24169. list->setMode (Mode::midi);
  24170. const auto shown = list->rowsShown();
  24171. check ("Mapping Browser: 2 project rows, then 3 global ones (" + juce::String ((int) shown.size()) + ")",
  24172. shown.size() == 5 && ! shown[0].global && ! shown[1].global && shown[2].global && shown[4].global);
  24173. {
  24174. const auto* ticked = find (list->rowMenu (2), everyProject);
  24175. check ("a global row's item is ticked", ticked != nullptr && ticked->isTicked);
  24176. }
  24177. write (*list, "b9-02-mapping-browser-global");
  24178. // a new project: the global mappings are there and act (CC 118 plays, CC 117 stops)
  24179. offline.setSong (lynx::Song::makeDefault());
  24180. offline.dispatchPendingMessages();
  24181. list->setMode (Mode::midi);
  24182. const auto fresh = list->rowsShown();
  24183. check ("new project: the 3 global rows (" + juce::String ((int) fresh.size()) + ")", fresh.size() == 3 && fresh[0].global);
  24184. write (*list, "b9-03-new-project-browser");
  24185. ui.setMapMode (Mode::off);
  24186. offline.injectControllerForTest (118, 0, 127);
  24187. offline.dispatchPendingMessages();
  24188. check ("new project: CC 118 plays", offline.getTransport().playing.load());
  24189. offline.injectControllerForTest (118, 0, 0);
  24190. offline.injectControllerForTest (117, 0, 127);
  24191. offline.dispatchPendingMessages();
  24192. check ("new project: CC 117 stops", ! offline.getTransport().playing.load());
  24193. offline.injectControllerForTest (7, 0, 0);
  24194. offline.dispatchPendingMessages();
  24195. check ("new project: CC 7 moves the Master", offline.currentTargetValue ({ lynx::AutomationTargetKind::mixerVolume, 0, 0, 0 }) < 0.01f);
  24196. // the Pattern layout: they act there too, and Settings › MIDI lists them
  24197. ui.setClipLaunchWorkflow (false);
  24198. offline.injectControllerForTest (117, 0, 0);
  24199. offline.injectControllerForTest (118, 0, 127);
  24200. offline.dispatchPendingMessages();
  24201. check ("Pattern layout: CC 118 plays", offline.getTransport().playing.load());
  24202. offline.stop();
  24203. // back into one project, then cleared (the settings of this test engine are never written)
  24204. ui.setClipLaunchWorkflow (true);
  24205. ui.setMapMode (Mode::midi);
  24206. list->setMode (Mode::midi);
  24207. check ("back into this project", click (list->rowMenu (rowOf (Target::of (lynx::RemoteAction::play))), everyProject)
  24208. && offline.getMidiPrefs().globalMappings.size() == 1 && offline.getSong().remoteMappings.size() == 1);
  24209. ui.setMapMode (Mode::off);
  24210. ui.setClipLaunchWorkflow (false);
  24211. // ---- B16: Mix snapshots ----------------------------------------------------------------------------------------
  24212. offline.setSong (lynx::Song::makeDefault());
  24213. offline.dispatchPendingMessages();
  24214. offline.editSong ([] (lynx::Song& s) {
  24215. const char* names[] { "Master", "Drums", "Bass", "Keys", "Vox", "Reverb" };
  24216. for (int i = 1; i < 6 && i < (int) s.mixer.size(); ++i)
  24217. s.mixer[(std::size_t) i].name = names[i];
  24218. s.mixer[1].volume = 0.7f;
  24219. s.mixer[4].pan = -0.3f;
  24220. s.setRoute (4, 5, true, 0.5f);
  24221. });
  24222. juce::PopupMenu mixerMenu;
  24223. lynx::mixeroptions::addItems (mixerMenu, offline, false);
  24224. const auto* snaps = find (mixerMenu, lynx::tr ("Mix snapshots (LYNX)"));
  24225. check ("Mixer menu: Mix snapshots (LYNX)", snaps != nullptr && snaps->subMenu != nullptr);
  24226. check ("Take snapshot", click (lynx::mixeroptions::snapshotsMenu (offline), lynx::tr ("Take snapshot")) && offline.getSong().mixSnapshots.size() == 1);
  24227. offline.editSong ([] (lynx::Song& s) {
  24228. s.mixer[1].volume = 0.4f;
  24229. s.mixer[4].pan = 0.6f;
  24230. s.mixer[3].muted = true;
  24231. s.setRoute (4, 5, false);
  24232. });
  24233. check ("Take snapshot again", click (lynx::mixeroptions::snapshotsMenu (offline), lynx::tr ("Take snapshot")) && offline.getSong().mixSnapshots.size() == 2);
  24234. {
  24235. const auto menu = lynx::mixeroptions::snapshotsMenu (offline);
  24236. const auto* first = find (menu, juce::String ("Snapshot 1 (B)"));
  24237. check ("snapshot 1 listed as B", first != nullptr && first->subMenu != nullptr && ! first->isTicked);
  24238. const auto* second = find (menu, juce::String ("Snapshot 2 (A)"));
  24239. check ("snapshot 2 ticked: the mix is it", second != nullptr && second->isTicked);
  24240. saveMenus (juce::StringArray { "Mixer", "Mix snapshots (LYNX)", "Snapshot 1" },
  24241. std::vector<juce::PopupMenu> { mixerMenu, menu, first != nullptr ? *first->subMenu : juce::PopupMenu() }, prefix + "-b16-01-menus.png");
  24242. check ("Recall snapshot 1", first != nullptr && click (*first->subMenu, lynx::tr ("Recall")));
  24243. }
  24244. const auto& m = offline.getSong().mixer;
  24245. check ("recalled: fader, pan, mute, send", m[1].volume == 0.7f && m[4].pan == -0.3f && ! m[3].muted && offline.getSong().routes (4, 5));
  24246. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::mixer });
  24247. ui.resized();
  24248. offline.dispatchPendingMessages();
  24249. write (ui, "b16-02-mixer-recalled");
  24250. check ("Compare A/B", click (lynx::mixeroptions::snapshotsMenu (offline), lynx::tr ("Compare A/B: back to \"{0}\"", { "Snapshot 2" }))
  24251. && m[1].volume == 0.4f && m[3].muted);
  24252. offline.undo();
  24253. check ("one undo step: back to snapshot 1", m[1].volume == 0.7f);
  24254. {
  24255. const auto file = juce::File (prefix + "-b16-snapshots.lynx");
  24256. juce::String error;
  24257. const auto saved = lynx::ProjectFile::save (offline.getSong(), file, error);
  24258. const auto back = lynx::ProjectFile::load (file, error);
  24259. check ("saved and loaded: the snapshots and A/B", saved && back && back->mixSnapshots == offline.getSong().mixSnapshots
  24260. && back->mixSnapshotCurrent == offline.getSong().mixSnapshotCurrent
  24261. && back->mixSnapshotPrevious == offline.getSong().mixSnapshotPrevious);
  24262. file.deleteFile();
  24263. }
  24264. // ---- B18: Split at silence -------------------------------------------------------------------------------------
  24265. {
  24266. // a "vocal take": 0.5 s silence, three phrases with pauses of 0.6 s and 0.15 s, quiet hiss in the gaps
  24267. const double rate = 44100.0;
  24268. juce::AudioBuffer<float> buffer (1, (int) (rate * 4.0));
  24269. buffer.clear();
  24270. juce::Random noise (190);
  24271. for (int i = 0; i < buffer.getNumSamples(); ++i)
  24272. {
  24273. const auto t = i / rate;
  24274. const auto phrase = (t >= 0.5 && t < 1.4) || (t >= 2.0 && t < 2.6) || (t >= 2.75 && t < 3.3);
  24275. buffer.setSample (0, i, phrase ? (float) (0.4 * std::sin (juce::MathConstants<double>::twoPi * 180.0 * t) * (0.6 + 0.4 * std::sin (6.0 * t)))
  24276. : (noise.nextFloat() - 0.5f) * 0.0004f);
  24277. }
  24278. const auto wav = juce::File (prefix + "-b18-take.wav");
  24279. wav.deleteFile();
  24280. juce::WavAudioFormat format;
  24281. if (auto out = std::unique_ptr<juce::AudioFormatWriter> (format.createWriterFor (wav.createOutputStream().release(), rate, 1, 16, {}, 0)))
  24282. out->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
  24283. auto song = lynx::Song::makeDefault();
  24284. song.channels.push_back ({});
  24285. song.channels.back().name = "Vocal take";
  24286. song.channels.back().instrument = lynx::InstrumentKind::audioClip;
  24287. song.channels.back().samplePath = wav.getFullPathName().toStdString();
  24288. lynx::Clip c;
  24289. c.kind = lynx::ClipKind::audio;
  24290. c.channel = (int) song.channels.size() - 1;
  24291. c.track = 1;
  24292. c.start = 4 * lynx::ppq;
  24293. c.length = (std::int64_t) std::llround (4.0 * song.bpm / 60.0 * lynx::ppq); // (the whole file at the song tempo)
  24294. song.playlist.push_back (c);
  24295. offline.setSong (std::move (song));
  24296. offline.dispatchPendingMessages();
  24297. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::playlist });
  24298. ui.resized();
  24299. auto& playlist = ui.getPlaylistForSnapshot();
  24300. const auto index = (int) offline.getSong().playlist.size() - 1;
  24301. const auto menu = playlist.getClipMenuForSnapshot (index);
  24302. const auto* item = find (menu, lynx::tr ("Split at silence..."));
  24303. const auto* splitHere = find (menu, lynx::tr ("Split here"));
  24304. check ("clip menu: Split at silence... in LYNX extras, enabled", item != nullptr && item->isEnabled && splitHere != nullptr);
  24305. savePng (columnMenuImage (menu), prefix + "-b18-01-clip-menu.png");
  24306. {
  24307. auto dialog = playlist.makeSplitSilenceDialogForSnapshot (index);
  24308. write (*dialog, "b18-02-dialog");
  24309. }
  24310. offline.dispatchPendingMessages();
  24311. write (ui, "b18-03-playlist-before");
  24312. juce::String why;
  24313. const auto made = playlist.splitClipsAtSilence ({ index }, lynx::PlaylistComponent::splitSilenceOptions(), &why);
  24314. offline.dispatchPendingMessages();
  24315. const auto& clips = offline.getSong().playlist;
  24316. std::vector<const lynx::Clip*> audio;
  24317. for (const auto& x : clips)
  24318. if (x.kind == lynx::ClipKind::audio)
  24319. audio.push_back (&x);
  24320. std::sort (audio.begin(), audio.end(), [] (const lynx::Clip* a, const lynx::Clip* b) { return a->start < b->start; });
  24321. const auto secondsAt = [&] (std::int64_t ticks) { return (double) (ticks - 4 * lynx::ppq) / lynx::ppq * 60.0 / offline.getSong().bpm; };
  24322. check ("split into 2 clips (the 0.15 s pause stays inside): " + juce::String (made) + ", " + why, made == 2 && audio.size() == 2);
  24323. if (audio.size() == 2)
  24324. check ("the clips start at the phrases less the pre-roll, end after them: " + juce::String (secondsAt (audio[0]->start), 3) + "-"
  24325. + juce::String (secondsAt (audio[0]->end()), 3) + ", " + juce::String (secondsAt (audio[1]->start), 3) + "-" + juce::String (secondsAt (audio[1]->end()), 3),
  24326. std::abs (secondsAt (audio[0]->start) - 0.49) < 0.02 && std::abs (secondsAt (audio[0]->end()) - 1.45) < 0.02
  24327. && std::abs (secondsAt (audio[1]->start) - 1.99) < 0.02 && std::abs (secondsAt (audio[1]->end()) - 3.35) < 0.02
  24328. && audio[1]->offset - audio[0]->offset == audio[1]->start - audio[0]->start);
  24329. write (ui, "b18-04-playlist-after");
  24330. offline.undo();
  24331. check ("one undo step", offline.getSong().playlist.size() == clips.size() && std::count_if (offline.getSong().playlist.begin(), offline.getSong().playlist.end(),
  24332. [] (const lynx::Clip& x) { return x.kind == lynx::ClipKind::audio; }) == 1);
  24333. lynx::stripsilence::Options loud;
  24334. loud.thresholdDb = -1.0f;
  24335. check ("all below the threshold: nothing split", playlist.splitClipsAtSilence ({ index }, loud, &why) == 0);
  24336. wav.deleteFile();
  24337. }
  24338. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  24339. }
  24340. void runMapShot190ef (const juce::String& prefix)
  24341. {
  24342. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  24343. lynx::AudioEngine offline (false);
  24344. lynx::MainComponent ui (offline, false);
  24345. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  24346. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  24347. const auto write = [&prefix] (juce::Component& c, const char* name) {
  24348. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  24349. file.deleteFile();
  24350. juce::FileOutputStream out (file);
  24351. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (c), out);
  24352. };
  24353. juce::String checks;
  24354. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  24355. using namespace lynx::remotemap;
  24356. ui.setVisible (true);
  24357. // the Pattern layout first: Ctrl+M stays FL's metronome there and no map mode starts
  24358. {
  24359. const auto before = offline.getTransport().metronome.load();
  24360. ui.keyPressed (juce::KeyPress ('M', juce::ModifierKeys::ctrlModifier, 0));
  24361. check ("Pattern layout: Ctrl+M is the metronome, no map mode", ui.getMapMode() == Mode::off && offline.getTransport().metronome.load() != before);
  24362. ui.keyPressed (juce::KeyPress ('M', juce::ModifierKeys::ctrlModifier, 0));
  24363. ui.setMapMode (Mode::midi);
  24364. check ("Pattern layout: setMapMode stays off", ui.getMapMode() == Mode::off);
  24365. }
  24366. ui.setClipLaunchWorkflow (true);
  24367. offline.editSong ([] (lynx::Song& s) {
  24368. if (s.mixer.size() < 6)
  24369. s.mixer.resize (6);
  24370. const char* inserts[] { "Master", "Drums", "Bass", "Keys", "Vox", "Reverb" };
  24371. for (int i = 1; i < 6; ++i)
  24372. s.mixer[(std::size_t) i].name = inserts[i];
  24373. const int channels = (int) s.channels.size();
  24374. s.channels.resize ((std::size_t) channels + 3);
  24375. const char* names[] { "Drum kit", "Bass synth", "Keys" };
  24376. for (int k = 0; k < 3; ++k)
  24377. {
  24378. auto& ch = s.channels[(std::size_t) (channels + k)];
  24379. ch.name = names[k];
  24380. ch.instrument = k == 0 ? lynx::InstrumentKind::sampler : lynx::InstrumentKind::synth;
  24381. ch.mixerTrack = k + 1;
  24382. }
  24383. s.mixer[2].effects.clear();
  24384. for (auto kind : { lynx::EffectKind::eq, lynx::EffectKind::compressor })
  24385. {
  24386. lynx::EffectSlot fx;
  24387. fx.kind = kind;
  24388. const auto& info = lynx::effectInfo (kind);
  24389. for (std::size_t k = 0; k < info.params.size() && k < fx.params.size(); ++k)
  24390. fx.params[k] = info.params[k].defaultValue;
  24391. s.mixer[2].effects.push_back (fx);
  24392. }
  24393. while (s.patterns.size() < 3)
  24394. s.patterns.emplace_back();
  24395. const char* patterns[] { "Beat", "Bassline", "Chords" };
  24396. for (int p = 0; p < 3; ++p)
  24397. {
  24398. auto& pattern = s.patterns[(std::size_t) p];
  24399. pattern.name = patterns[p];
  24400. lynx::Note n;
  24401. n.channel = channels + p;
  24402. n.key = 48 + p * 5;
  24403. pattern.notes = { n };
  24404. pattern.lengthTicks = 4 * lynx::ppq;
  24405. }
  24406. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 8));
  24407. const char* tracks[] { "Drums", "Bass", "Keys", "Vox" };
  24408. for (int t = 0; t < 4; ++t)
  24409. s.playlistTracks[(std::size_t) t].name = tracks[t];
  24410. for (int t = 0; t < 3; ++t)
  24411. for (int r = 0; r < 3; ++r)
  24412. {
  24413. lynx::Clip clip;
  24414. clip.pattern = t;
  24415. clip.length = 4 * lynx::ppq;
  24416. lynx::launcher::setClip (s, t, r, clip);
  24417. }
  24418. auto& grid = lynx::launcher::ensureGrid (s);
  24419. const char* scenes[] { "Intro", "Verse", "Drop" };
  24420. grid.scenes.resize (4);
  24421. for (int r = 0; r < 3; ++r)
  24422. grid.scenes[(std::size_t) r].name = scenes[r];
  24423. // some mappings, as the lesson's pictures show them (pads on slots and scenes, knobs on volume and pan)
  24424. assignMidi (s, Target::slot (0, 0), { 0, lynx::linkNoteBase + 36, -1 });
  24425. assignMidi (s, Target::slot (1, 0), { 0, lynx::linkNoteBase + 37, -1 });
  24426. assignMidi (s, Target::sceneLaunch (1), { 0, lynx::linkNoteBase + 44, -1 });
  24427. assignMidi (s, Target::parameter ({ lynx::AutomationTargetKind::mixerVolume, 1, 0, 0 }), { 0, 17, -1 });
  24428. assignMidi (s, Target::parameter ({ lynx::AutomationTargetKind::mixerPan, 1, 0, 0 }), { 0, 16, -1 });
  24429. assignMidi (s, Target::of (lynx::RemoteAction::play), { 0, 118, -1 });
  24430. setRange (s, rows (s, Mode::midi)[0], 0.0f, 0.85f);
  24431. assignKey (s, Target::slot (0, 1), 'A');
  24432. assignKey (s, Target::slot (1, 1), 'S');
  24433. assignKey (s, Target::sceneLaunch (2), '3');
  24434. assignKey (s, Target::parameter ({ lynx::AutomationTargetKind::mixerVolume, 2, 0, 0 }), 'V');
  24435. }, false);
  24436. offline.dispatchPendingMessages();
  24437. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::playlist, lynx::workspace::Panel::browser }); // (no floating Channel Rack over the grid)
  24438. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  24439. offline.dispatchPendingMessages();
  24440. ui.resized();
  24441. if (auto* detail = ui.getDetailViewForSnapshot())
  24442. {
  24443. detail->showSelection (1, 0);
  24444. detail->setPage (lynx::DetailView::Page::devices);
  24445. }
  24446. ui.resized();
  24447. offline.dispatchPendingMessages();
  24448. write (ui, "00-clip-launch-before");
  24449. // Ctrl+M in the Clip-launch layout: MIDI Map Mode (the metronome stays as it was)
  24450. const auto metronome = offline.getTransport().metronome.load();
  24451. ui.keyPressed (juce::KeyPress ('M', juce::ModifierKeys::ctrlModifier, 0));
  24452. check ("Clip-launch layout: Ctrl+M starts MIDI Map Mode", ui.getMapMode() == Mode::midi && offline.getTransport().metronome.load() == metronome);
  24453. auto* overlay = ui.mapOverlayForSnapshot();
  24454. auto* list = ui.mappingBrowserForSnapshot();
  24455. if (overlay == nullptr || list == nullptr)
  24456. {
  24457. juce::File (prefix + "-checks.txt").replaceWithText (checks + "FAIL no overlay\n");
  24458. return;
  24459. }
  24460. overlay->refresh();
  24461. const auto& spots = overlay->spots();
  24462. 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; }); };
  24463. const auto params = [&] (lynx::AutomationTargetKind k) {
  24464. 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; });
  24465. };
  24466. check ("overlay: clip slots (" + juce::String (count (lynx::RemoteAction::clipSlot)) + ")", count (lynx::RemoteAction::clipSlot) >= 12);
  24467. check ("overlay: scene launch buttons (" + juce::String (count (lynx::RemoteAction::sceneLaunch)) + ")", count (lynx::RemoteAction::sceneLaunch) >= 4);
  24468. check ("overlay: track stop buttons", count (lynx::RemoteAction::trackStop) >= 4);
  24469. check ("overlay: Stop all clips, Session Record", count (lynx::RemoteAction::stopAllClips) == 1 && count (lynx::RemoteAction::sessionRecord) == 1);
  24470. check ("overlay: transport play / stop / record / metronome", count (lynx::RemoteAction::play) == 1 && count (lynx::RemoteAction::stop) == 1
  24471. && count (lynx::RemoteAction::record) == 1 && count (lynx::RemoteAction::metronome) == 1);
  24472. check ("overlay: tempo", params (lynx::AutomationTargetKind::tempo) == 1);
  24473. check ("overlay: mixer volume / pan (" + juce::String (params (lynx::AutomationTargetKind::mixerVolume)) + " / " + juce::String (params (lynx::AutomationTargetKind::mixerPan)) + ")",
  24474. params (lynx::AutomationTargetKind::mixerVolume) >= 3 && params (lynx::AutomationTargetKind::mixerPan) >= 3);
  24475. check ("overlay: device knobs (" + juce::String (params (lynx::AutomationTargetKind::effectParam)) + ")", params (lynx::AutomationTargetKind::effectParam) >= 2);
  24476. // a click on Keys' first slot selects it; a MIDI control assigns it (as the engine's catch would)
  24477. for (const auto& spot : spots)
  24478. if (spot.target == Target::slot (2, 0))
  24479. {
  24480. auto source = juce::Desktop::getInstance().getMainMouseSource();
  24481. const auto now = juce::Time::getCurrentTime();
  24482. const auto at = spot.area.getCentre().toFloat();
  24483. overlay->mouseDown (juce::MouseEvent (source, at, juce::ModifierKeys (juce::ModifierKeys::leftButtonModifier), 1.0f, 0.0f, 0.0f, 0.0f, 0.0f,
  24484. overlay, overlay, now, at, now, 1, false));
  24485. break;
  24486. }
  24487. if (spots.empty())
  24488. {
  24489. juce::File (prefix + "-checks.txt").replaceWithText (checks + "FAIL no spots\n");
  24490. return;
  24491. }
  24492. check ("a click selects the slot", overlay->selection() == std::optional<Target> (Target::slot (2, 0)));
  24493. check ("the overlay takes clicks only on elements", overlay->hitTest (spots.front().area.getCentreX(), spots.front().area.getCentreY()) && ! overlay->hitTest (2, ui.getHeight() - 2));
  24494. check ("a pad assigns it", overlay->assignMidi ({ 0, lynx::linkNoteBase + 38, -1 }) && midiOf (offline.getSong(), Target::slot (2, 0)).number == lynx::linkNoteBase + 38);
  24495. check ("the same pad again on track 0 is refused", ! (overlay->select (Target::slot (0, 2)), overlay->assignMidi ({ 0, lynx::linkNoteBase + 36, -1 })));
  24496. overlay->select (Target::slot (2, 0));
  24497. list->setMode (Mode::midi);
  24498. list->selectRow (0);
  24499. ui.resized();
  24500. overlay->refresh();
  24501. write (ui, "01-midi-map-mode");
  24502. check ("Mapping Browser rows (MIDI): " + juce::String ((int) list->rowsShown().size()), list->rowsShown().size() == 7);
  24503. write (*list, "02-mapping-browser-midi");
  24504. saveMenus (juce::StringArray { "Row" }, std::vector<juce::PopupMenu> { list->rowMenu (0) }, prefix + "-03-row-menu.png");
  24505. // Ctrl+K: Key Map Mode; a key assigns the selected element
  24506. ui.keyPressed (juce::KeyPress ('K', juce::ModifierKeys::ctrlModifier, 0));
  24507. check ("Ctrl+K switches to Key Map Mode", ui.getMapMode() == Mode::key && offline.getMapMode() == Mode::key);
  24508. overlay->select (Target::sceneLaunch (0));
  24509. ui.keyPressed (juce::KeyPress ('1', {}, '1'));
  24510. check ("a key assigns the selected scene", keyOf (offline.getSong(), Target::sceneLaunch (0)).key == '1');
  24511. overlay->select (Target::sceneLaunch (1));
  24512. ui.keyPressed (juce::KeyPress ('A', {}, 'a'));
  24513. check ("a key already on a slot is refused for a scene", ! keyOf (offline.getSong(), Target::sceneLaunch (1)).found);
  24514. overlay->refresh();
  24515. write (ui, "04-key-map-mode");
  24516. write (*list, "05-mapping-browser-key");
  24517. {
  24518. // round 190em: Min / Max in the parameter's unit, Path "<track> | Mixer", Name "Track Volume" / "Slot n"
  24519. const lynx::remotemap::Target volume = Target::parameter ({ lynx::AutomationTargetKind::mixerVolume, 2, 0, 0 });
  24520. const auto [path, name] = lynx::mapmode::describe (offline, volume);
  24521. check ("browser: volume row Path / Name = " + path + " / " + name, path == "Bass | Mixer" && name == "Track Volume");
  24522. check ("browser: volume Min / Max = " + lynx::mapmode::rangeText (offline, volume, 0.0f) + " / " + lynx::mapmode::rangeText (offline, volume, 1.0f),
  24523. lynx::mapmode::rangeText (offline, volume, 0.0f) == juce::String::fromUTF8 ("\xe2\x88\x92\xe2\x88\x9e dB")
  24524. && lynx::mapmode::rangeText (offline, volume, 1.0f).endsWith (" dB"));
  24525. const lynx::remotemap::Target pan = Target::parameter ({ lynx::AutomationTargetKind::mixerPan, 1, 0, 0 });
  24526. check ("browser: pan Min / Max = " + lynx::mapmode::rangeText (offline, pan, 0.25f) + " / " + lynx::mapmode::rangeText (offline, pan, 0.5f),
  24527. lynx::mapmode::rangeText (offline, pan, 0.25f) == "50L" && lynx::mapmode::rangeText (offline, pan, 0.5f) == "C"
  24528. && lynx::mapmode::rangeText (offline, pan, 1.0f) == "100R");
  24529. const auto typed = lynx::mapmode::rangeValueOf (offline, volume, "0 dB");
  24530. check ("browser: typing 0 dB", typed.has_value() && std::abs (lynx::mapmode::rangeText (offline, volume, *typed).getDoubleValue()) < 0.15);
  24531. check ("browser: typing 50L", lynx::mapmode::rangeValueOf (offline, pan, "50L") == std::optional<float> (0.25f));
  24532. check ("browser: Key column = " + lynx::mapmode::listKeyText ('V') + ", " + lynx::mapmode::listKeyText ('3'),
  24533. lynx::mapmode::listKeyText ('V') == "Key v" && lynx::mapmode::listKeyText ('3') == "Key 3");
  24534. check ("browser: slot row Name = " + lynx::mapmode::describe (offline, Target::slot (0, 2)).second,
  24535. lynx::mapmode::describe (offline, Target::slot (0, 2)) == std::pair<juce::String, juce::String> ("Drums", "Slot 3"));
  24536. }
  24537. // off again: the key mapping on a parameter toggles it between Min and Max
  24538. ui.keyPressed (juce::KeyPress ('K', juce::ModifierKeys::ctrlModifier, 0));
  24539. check ("Ctrl+K again ends it", ui.getMapMode() == Mode::off && ! overlay->isVisible() && ! list->isVisible());
  24540. const lynx::AutomationTarget keysVolume { lynx::AutomationTargetKind::mixerVolume, 2, 0, 0 };
  24541. // (round 190em, Live 12.4.16: the first press goes to Min, then Max, then Min)
  24542. ui.keyPressed (juce::KeyPress ('V', {}, 'v'));
  24543. check ("the mapped key V moves Bass's volume to Min first", std::abs (offline.currentTargetValue (keysVolume)) < 0.01f);
  24544. ui.keyStateChanged (false); // (V is not down any more: its release)
  24545. ui.keyPressed (juce::KeyPress ('V', {}, 'v'));
  24546. check ("again: to Max", std::abs (offline.currentTargetValue (keysVolume) - 1.0f) < 0.01f);
  24547. ui.keyStateChanged (false);
  24548. ui.keyPressed (juce::KeyPress ('V', {}, 'v'));
  24549. check ("again: to Min", std::abs (offline.currentTargetValue (keysVolume)) < 0.01f);
  24550. ui.keyStateChanged (false);
  24551. // the title bar switches
  24552. ui.setMapMode (Mode::midi);
  24553. write (ui, "06-switches-midi-on");
  24554. ui.setMapMode (Mode::off);
  24555. ui.setClipLaunchWorkflow (false);
  24556. check ("leaving the Clip-launch layout ends the map mode", ui.getMapMode() == Mode::off);
  24557. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  24558. }
  24559. void runSceneShot190ef (const juce::String& prefix)
  24560. {
  24561. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  24562. lynx::AudioEngine offline (false);
  24563. lynx::MainComponent ui (offline, false);
  24564. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  24565. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  24566. const auto write = [&prefix] (juce::Component& c, const char* name) {
  24567. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  24568. file.deleteFile();
  24569. juce::FileOutputStream out (file);
  24570. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (c), out);
  24571. };
  24572. juce::String checks;
  24573. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  24574. ui.setVisible (true);
  24575. lynx::DetailView::shownSetting = false;
  24576. ui.setClipLaunchWorkflow (true);
  24577. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::playlist });
  24578. offline.editSong ([] (lynx::Song& s) {
  24579. const int channels = (int) s.channels.size();
  24580. s.channels.resize ((std::size_t) channels + 3);
  24581. const char* names[] { "Drum kit", "Bass synth", "Keys" };
  24582. for (int k = 0; k < 3; ++k)
  24583. {
  24584. auto& ch = s.channels[(std::size_t) (channels + k)];
  24585. ch.name = names[k];
  24586. ch.instrument = k == 0 ? lynx::InstrumentKind::sampler : lynx::InstrumentKind::synth;
  24587. }
  24588. while (s.patterns.size() < 3)
  24589. s.patterns.emplace_back();
  24590. const char* patterns[] { "Beat", "Bassline", "Chords" };
  24591. for (int p = 0; p < 3; ++p)
  24592. {
  24593. auto& pattern = s.patterns[(std::size_t) p];
  24594. pattern.name = patterns[p];
  24595. lynx::Note n;
  24596. n.channel = channels + p;
  24597. n.key = 48 + p * 5;
  24598. pattern.notes = { n };
  24599. pattern.lengthTicks = 4 * lynx::ppq;
  24600. }
  24601. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 6));
  24602. const char* tracks[] { "Drums", "Bass", "Keys" };
  24603. const std::uint32_t colours[] { 0xFFE0533Bu, 0xFF3B8BE0u, 0xFF46C27Au };
  24604. for (int t = 0; t < 3; ++t)
  24605. {
  24606. s.playlistTracks[(std::size_t) t].name = tracks[t];
  24607. s.playlistTracks[(std::size_t) t].colour = colours[t];
  24608. }
  24609. for (int t = 0; t < 3; ++t)
  24610. for (int r = 0; r < 3; ++r)
  24611. if (! (t == 2 && r == 0))
  24612. {
  24613. lynx::Clip clip;
  24614. clip.pattern = t;
  24615. clip.length = 4 * lynx::ppq;
  24616. lynx::launcher::setClip (s, t, r, clip);
  24617. }
  24618. auto& grid = lynx::launcher::ensureGrid (s);
  24619. grid.scenes.resize (4);
  24620. const char* scenes[] { "Intro", "Verse", "Drop" };
  24621. for (int r = 0; r < 3; ++r)
  24622. grid.scenes[(std::size_t) r].name = scenes[r];
  24623. lynx::session::setSceneTempo (s, 1, 128.0);
  24624. lynx::session::setSceneSignature (s, 1, 3, 4); // (as the live check's "Verse": 3 / 4)
  24625. lynx::session::setSceneSignature (s, 2, 6, 8); // (round 190em: a denominator of its own)
  24626. grid.scenes[2].colour = 0xFF8E5BD6u;
  24627. }, false);
  24628. offline.dispatchPendingMessages();
  24629. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  24630. offline.dispatchPendingMessages();
  24631. ui.resized();
  24632. auto* gridView = ui.getClipGridForSnapshot();
  24633. if (gridView == nullptr)
  24634. {
  24635. juce::File (prefix + "-checks.txt").replaceWithText ("FAIL no grid\n");
  24636. return;
  24637. }
  24638. lynx::clipGridSceneTempoShown() = true;
  24639. lynx::refreshClipGrid (*gridView);
  24640. lynx::selectClipGridScene (*gridView, 1);
  24641. write (*gridView, "01-scene-fields");
  24642. {
  24643. // round 190em: a plain scene's launch triangle in Live's dark grey (#1E1E1E), scene 4 (row 3)
  24644. const auto image = lynx::shot::snapshot (*gridView);
  24645. int dark = 0;
  24646. for (int y = 0; y < image.getHeight(); ++y)
  24647. for (int x = image.getWidth() - 240; x < image.getWidth() - 180; ++x)
  24648. if (const auto p = image.getPixelAt (x, y); y > 3 * 24 + 26 && y < 4 * 24 + 26 && std::abs (p.getRed() - 0x1e) <= 2
  24649. && std::abs (p.getGreen() - 0x1e) <= 2 && std::abs (p.getBlue() - 0x1e) <= 2)
  24650. ++dark;
  24651. check ("plain scene triangle in Live's #1E1E1E (" + juce::String (dark) + " px)", dark >= 20);
  24652. }
  24653. saveMenus (juce::StringArray { "Scene menu (Verse)" }, std::vector<juce::PopupMenu> { lynx::clipGridSceneMenu (*gridView, 1) }, prefix + "-02-scene-menu.png");
  24654. saveMenus (juce::StringArray { "Scene tempo field", "Scene time signature field" },
  24655. std::vector<juce::PopupMenu> { lynx::clipGridSceneFieldMenu (*gridView, 1, 1), lynx::clipGridSceneFieldMenu (*gridView, 2, 2) },
  24656. prefix + "-03-field-menus.png");
  24657. saveMenus (juce::StringArray { "Column title (Bass)" }, std::vector<juce::PopupMenu> { lynx::clipGridHeaderMenu (*gridView, 1) }, prefix + "-04-title-menu.png");
  24658. const auto clipsIn = [&offline] (int row) {
  24659. int n = 0;
  24660. if (const auto& g = offline.getSong().clipGrid)
  24661. for (int t = 0; t < 8; ++t)
  24662. n += lynx::launcher::clipAt (*g, t, row) != nullptr ? 1 : 0;
  24663. return n;
  24664. };
  24665. const auto before = clipsIn (1);
  24666. const auto dup = lynx::duplicateClipGridScene (*gridView, 1);
  24667. offline.dispatchPendingMessages();
  24668. const auto& scenesNow = offline.getSong().clipGrid->scenes;
  24669. check ("duplicate: Verse's copy is row 2, with its clips and tempo", dup == 2 && clipsIn (2) == before && scenesNow.size() > 2
  24670. && scenesNow[2].name == "Verse" && scenesNow[2].tempo == 128.0);
  24671. write (*gridView, "05-scene-duplicated");
  24672. const auto cap = lynx::captureClipGridScene (*gridView, 3, { 0, 2, 1 }); // Drums row 0, Bass row 2, Keys row 1
  24673. offline.dispatchPendingMessages();
  24674. check ("capture: a new row 4 with the three playing clips", cap == 4 && clipsIn (4) == 3);
  24675. {
  24676. const auto& sc = offline.getSong().clipGrid->scenes;
  24677. check ("capture while playing: the new scene is plain (no name, fields off)", sc.size() > 4 && sc[4] == lynx::ClipGridScene {});
  24678. }
  24679. write (*gridView, "06-scene-captured");
  24680. // round 190em: nothing plays: an empty scene like the selected one (name, tempo, signature), selected
  24681. const auto empty = lynx::captureClipGridScene (*gridView, 1, { -1, -1 });
  24682. offline.dispatchPendingMessages();
  24683. {
  24684. const auto& sc = offline.getSong().clipGrid->scenes;
  24685. check ("capture with nothing playing: an empty row 2 named Verse, 128 BPM, 3 / 4", empty == 2 && clipsIn (2) == 0 && sc[2].name == "Verse"
  24686. && sc[2].tempo == 128.0 && sc[2].beatsPerBar == 3 && sc[2].beatUnit == 4);
  24687. }
  24688. write (*gridView, "06b-scene-captured-stopped");
  24689. // round 190em: Capture and Insert while clips play: playback moves to the new row (the runtime view shows what
  24690. // the player reports once the published song holds the moved slots)
  24691. {
  24692. const auto rowsBefore = offline.getSong().clipGrid->scenes.size();
  24693. lynx::selectClipGridScene (*gridView, 0);
  24694. const auto at = lynx::captureClipGridScene (*gridView, 0, { 0, 0, -1 });
  24695. offline.dispatchPendingMessages();
  24696. const auto& g = *offline.getSong().clipGrid;
  24697. check ("capture while playing: row 1 holds the moved playing slots", at == 1 && g.scenes.size() == rowsBefore + 1
  24698. && clipsIn (1) == 2 && clipsIn (0) == 2 && g.scenes[1] == lynx::ClipGridScene {});
  24699. if (auto* runtime = offline.launcherStateForSnapshot())
  24700. for (int t = 0; t < 2; ++t)
  24701. runtime->tracks[(std::size_t) t].playing.store (1);
  24702. lynx::refreshClipGrid (*gridView);
  24703. write (*gridView, "09-capture-playing-moves");
  24704. if (auto* runtime = offline.launcherStateForSnapshot())
  24705. for (int t = 0; t < 2; ++t)
  24706. runtime->tracks[(std::size_t) t].playing.store (-1);
  24707. }
  24708. // round 190em: the fields as "n / d", a selected field, Del = Return to Default
  24709. lynx::clipGridSceneTempoShown() = true;
  24710. lynx::refreshClipGrid (*gridView);
  24711. {
  24712. const auto& sc = offline.getSong().clipGrid->scenes;
  24713. int verse = -1;
  24714. for (int r = 0; r < (int) sc.size() && verse < 0; ++r)
  24715. if (sc[(std::size_t) r].name == "Verse" && sc[(std::size_t) r].tempo > 0.0)
  24716. verse = r;
  24717. lynx::selectClipGridSceneField (*gridView, verse, 1);
  24718. write (*gridView, "10-field-selected");
  24719. gridView->keyPressed (juce::KeyPress (juce::KeyPress::deleteKey));
  24720. offline.dispatchPendingMessages();
  24721. const auto& after = offline.getSong().clipGrid->scenes;
  24722. check ("Del on a selected tempo field returns it to default (scene kept)", verse >= 0 && after.size() == sc.size()
  24723. && after[(std::size_t) verse].tempo == 0.0 && after[(std::size_t) verse].beatsPerBar == 3);
  24724. write (*gridView, "11-field-returned-to-default");
  24725. }
  24726. // round 190em: Capture MIDI to the armed track (Bass), the selected scene's slot, the tempo from the phrase
  24727. {
  24728. offline.stop();
  24729. offline.setGridTrackArmed (1, true, true);
  24730. lynx::selectClipGridScene (*gridView, 0);
  24731. int empty = 0;
  24732. while (lynx::launcher::clipAt (*offline.getSong().clipGrid, 1, empty) != nullptr)
  24733. ++empty;
  24734. const auto now = juce::Time::getMillisecondCounterHiRes();
  24735. const auto beat = 60000.0 / 148.0;
  24736. for (int i = 0; i < 8; ++i)
  24737. {
  24738. const auto at = now - 9.0 * beat + i * beat;
  24739. offline.logPlayedNoteForTest (at, 0, 60 + (i % 4) * 2, 0.8f, true);
  24740. offline.logPlayedNoteForTest (at + beat * 0.5, 0, 60 + (i % 4) * 2, 0.8f, false);
  24741. }
  24742. int placed = -1;
  24743. bool into = true;
  24744. const auto r = offline.captureMidiToSlot (1, empty, placed, into);
  24745. offline.dispatchPendingMessages();
  24746. check ("Capture MIDI: 8 notes into Bass row " + juce::String (placed) + ", tempo " + juce::String (offline.getSong().bpm, 2),
  24747. r.notes == 8 && placed == empty && ! into && std::abs (offline.getSong().bpm - 148.0) < 0.5 && offline.getTransport().playing.load());
  24748. const auto& capturedGrid = *offline.getSong().clipGrid;
  24749. const auto* capturedClip = lynx::launcher::clipAt (capturedGrid, 1, placed);
  24750. const auto* slot = capturedClip != nullptr ? &capturedGrid.slots[(std::size_t) capturedClip->gridSlot] : nullptr;
  24751. check ("Capture MIDI: the clip has no name of its own (blank label, as Live)", slot != nullptr && slot->name.empty() && slot->blankName);
  24752. if (auto* runtime = offline.launcherStateForSnapshot())
  24753. runtime->tracks[1].playing.store (placed);
  24754. lynx::refreshClipGrid (*gridView);
  24755. write (*gridView, "12-capture-midi");
  24756. if (auto* runtime = offline.launcherStateForSnapshot())
  24757. runtime->tracks[1].playing.store (-1);
  24758. offline.stop();
  24759. }
  24760. write (ui, "07-window");
  24761. lynx::clipGridSceneTempoShown() = false;
  24762. lynx::refreshClipGrid (*gridView);
  24763. write (*gridView, "08-fields-off");
  24764. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  24765. }
  24766. void runDrawShot190ef (const juce::String& prefix)
  24767. {
  24768. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  24769. lynx::AudioEngine offline (false);
  24770. lynx::MainComponent ui (offline, false);
  24771. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  24772. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  24773. const auto write = [&prefix] (juce::Component& c, const char* name) {
  24774. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  24775. file.deleteFile();
  24776. juce::FileOutputStream out (file);
  24777. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (c), out);
  24778. };
  24779. juce::String checks;
  24780. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  24781. ui.setVisible (true);
  24782. ui.setClipLaunchWorkflow (true);
  24783. ui.setClipGridView (lynx::PlaylistArea::GridView::song);
  24784. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::playlist });
  24785. lynx::autolanes::setShown (true);
  24786. offline.editSong ([] (lynx::Song& s) {
  24787. if (s.mixer.size() < 4)
  24788. s.mixer.resize (4);
  24789. s.mixer[1].name = "Bass";
  24790. s.mixer[2].name = "Pad";
  24791. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 6));
  24792. s.playlistTracks[0].name = "Bass";
  24793. s.playlistTracks[0].mode = lynx::PlaylistTrackMode::audio;
  24794. s.playlistTracks[0].mixerTrack = 1;
  24795. s.playlistTracks[1].name = "Pad";
  24796. s.playlistTracks[1].mode = lynx::PlaylistTrackMode::audio;
  24797. s.playlistTracks[1].mixerTrack = 2;
  24798. }, false);
  24799. lynx::createAutomationLane (offline, { lynx::AutomationTargetKind::mixerVolume, 1, 0, 0 }, 0);
  24800. lynx::createAutomationLane (offline, { lynx::AutomationTargetKind::mixerPan, 2, 0, 0 }, 1);
  24801. offline.editSong ([] (lynx::Song& s) {
  24802. for (int t = 0; t < 2; ++t)
  24803. if (! s.playlistTracks[(std::size_t) t].lanes.empty())
  24804. s.playlistTracks[(std::size_t) t].lanes[0].height = 110;
  24805. }, false);
  24806. offline.dispatchPendingMessages();
  24807. auto& playlist = ui.getPlaylistForSnapshot();
  24808. playlist.setViewForSnapshot (180.0, 0, 0);
  24809. ui.resized();
  24810. offline.dispatchPendingMessages();
  24811. const auto& song = offline.getSong();
  24812. const auto laneA = song.playlistTracks[0].lanes.empty() ? -1 : song.playlistTracks[0].lanes[0].automation;
  24813. const auto laneB = song.playlistTracks[1].lanes.empty() ? -1 : song.playlistTracks[1].lanes[0].automation;
  24814. check ("two lanes made", laneA >= 0 && laneB >= 0);
  24815. if (laneA < 0 || laneB < 0)
  24816. {
  24817. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  24818. return;
  24819. }
  24820. write (ui, "00-lanes-before");
  24821. const auto before = song.automations[(std::size_t) laneA].points;
  24822. // a drag through the Playlist's own handlers (the events a real mouse sends)
  24823. auto source = juce::Desktop::getInstance().getMainMouseSource();
  24824. const auto now = juce::Time::getCurrentTime();
  24825. const auto stroke = [&] (int track, const std::vector<juce::Point<float>>& path, juce::ModifierKeys extra) {
  24826. const juce::ModifierKeys mods (juce::ModifierKeys::leftButtonModifier | extra.getRawFlags());
  24827. const auto event = [&] (juce::Point<float> p, juce::ModifierKeys m, bool dragged) {
  24828. return juce::MouseEvent (source, p, m, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, &playlist, &playlist, now, path.front(), now, 1, dragged);
  24829. };
  24830. juce::ignoreUnused (track);
  24831. // (the engine joins the edits of one press into one undo step while a button is down)
  24832. const auto held = juce::ModifierKeys::currentModifiers;
  24833. juce::ModifierKeys::currentModifiers = mods;
  24834. playlist.mouseDown (event (path.front(), mods, false));
  24835. for (std::size_t i = 1; i < path.size(); ++i)
  24836. playlist.mouseDrag (event (path[i], mods, true));
  24837. juce::ModifierKeys::currentModifiers = held;
  24838. playlist.mouseUp (event (path.back(), extra, true));
  24839. };
  24840. const auto bodyA = playlist.laneBodyForSnapshot (0, 0), bodyB = playlist.laneBodyForSnapshot (1, 0);
  24841. const auto bar = (double) (4 * lynx::ppq);
  24842. const auto x = [&] (double bars) { return (float) playlist.xOfTickForSnapshot (bars * bar); };
  24843. const auto y = [] (juce::Rectangle<float> body, float v) { return body.getBottom() - v * body.getHeight(); };
  24844. lynx::drawmode::set (true);
  24845. // steps: a rise over bar 1 and a fall over bar 2, at the Playlist's grid (Line, at this zoom)
  24846. std::vector<juce::Point<float>> steps;
  24847. for (int k = 0; k <= 16; ++k)
  24848. steps.push_back ({ x (1.0 + k / 16.0) + 2.0f, y (bodyA, 0.15f + 0.05f * (float) k) });
  24849. for (int k = 0; k <= 16; ++k)
  24850. steps.push_back ({ x (2.0 + k / 16.0) + 2.0f, y (bodyA, 0.95f - 0.05f * (float) k) });
  24851. stroke (0, steps, {});
  24852. const auto& afterSteps = offline.getSong().automations[(std::size_t) laneA].points;
  24853. check ("Draw Mode drag made steps (" + juce::String ((int) afterSteps.size()) + " points)", afterSteps.size() > before.size() + 4);
  24854. bool unchangedOutside = true;
  24855. for (double t = 0.0; t < 6.0 * bar; t += 37.0)
  24856. if ((t < bar - 1.0 || t > 3.1 * bar) && std::abs (lynx::automationCurveAt (before, t) - lynx::automationCurveAt (afterSteps, t)) > 1.0e-4f)
  24857. unchangedOutside = false;
  24858. check ("the curve outside the drawn bars is unchanged", unchangedOutside);
  24859. {
  24860. // flat inside each drawn cell: the values in a cell's first and last tick are the same
  24861. int flatCells = 0, cells = 0;
  24862. for (double t = bar; t < 3.0 * bar; t += lynx::ppq / 4.0)
  24863. {
  24864. ++cells;
  24865. if (std::abs (lynx::automationCurveAt (afterSteps, t + 1.0) - lynx::automationCurveAt (afterSteps, t + lynx::ppq / 4.0 - 1.0)) < 1.0e-5f)
  24866. ++flatCells;
  24867. }
  24868. check ("each sixteenth inside bars 2-3 is flat (" + juce::String (flatCells) + " / " + juce::String (cells) + ")", flatCells == cells);
  24869. }
  24870. // freehand: Alt (no grid) on the pad's pan lane, a wave over bars 1-4
  24871. const auto panBefore = offline.getSong().automations[(std::size_t) laneB].points;
  24872. // (off-screen every press has the same mouse-down time, which the undo history uses to join one press's edits:
  24873. // an edit with no button down in between separates the two strokes, as a real second press does)
  24874. offline.editSong ([] (lynx::Song&) {});
  24875. std::vector<juce::Point<float>> wave;
  24876. for (int k = 0; k <= 60; ++k)
  24877. wave.push_back ({ x (1.0 + 3.0 * k / 60.0), y (bodyB, 0.5f + 0.4f * std::sin ((float) k * 0.3f)) });
  24878. stroke (1, wave, juce::ModifierKeys (juce::ModifierKeys::altModifier));
  24879. const auto& pan = offline.getSong().automations[(std::size_t) laneB].points;
  24880. check ("Alt drag drew freehand (" + juce::String ((int) pan.size()) + " points)", pan.size() > 30);
  24881. playlist.repaint();
  24882. write (ui, "01-draw-mode-steps-and-freehand");
  24883. if (auto* parent = playlist.getParentComponent())
  24884. write (*parent, "01b-playlist");
  24885. // one stroke is one undo step
  24886. offline.undo();
  24887. check ("one undo takes the whole freehand stroke back", offline.getSong().automations[(std::size_t) laneB].points == panBefore);
  24888. // Draw Mode off: the same press adds one point, as before
  24889. lynx::drawmode::set (false);
  24890. const auto countOff = offline.getSong().automations[(std::size_t) laneA].points.size();
  24891. stroke (0, { { x (4.5), y (bodyA, 0.8f) } }, {});
  24892. check ("Draw Mode off: a press adds one point", offline.getSong().automations[(std::size_t) laneA].points.size() == countOff + 1);
  24893. // the Options menu (Clip-launch layout) with the switch
  24894. lynx::drawmode::set (true);
  24895. {
  24896. const auto names = ui.getMenuNamesForSnapshot();
  24897. const auto index = names.indexOf (TRANS ("Options"));
  24898. if (index >= 0)
  24899. saveMenus (juce::StringArray { "Options" }, std::vector<juce::PopupMenu> { ui.getMenuForSnapshot (index) }, prefix + "-02-options-menu.png");
  24900. check ("Options menu found", index >= 0);
  24901. }
  24902. lynx::drawmode::set (false);
  24903. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  24904. }
  24905. void runClipEnvShot190gi (const juce::String& prefix)
  24906. {
  24907. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  24908. lynx::AudioEngine offline (false);
  24909. lynx::MainComponent ui (offline, false);
  24910. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  24911. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  24912. const auto write = [&prefix] (juce::Component& c, const char* name) {
  24913. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  24914. file.deleteFile();
  24915. juce::FileOutputStream out (file);
  24916. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (c), out);
  24917. };
  24918. juce::String checks;
  24919. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  24920. // two files: a sustained pad (4 s, a slow swell, for the envelope over its waveform) and a one-bar loop of clicks
  24921. const auto writeWav = [] (const juce::File& file, int seconds, const std::function<float (int, double)>& fn) {
  24922. const double rate = 48000.0;
  24923. juce::AudioBuffer<float> buffer (2, (int) (rate * seconds));
  24924. for (int ch = 0; ch < 2; ++ch)
  24925. for (int i = 0; i < buffer.getNumSamples(); ++i)
  24926. buffer.setSample (ch, i, fn (i, rate));
  24927. file.deleteFile();
  24928. if (auto out = std::unique_ptr<juce::FileOutputStream> (file.createOutputStream()))
  24929. if (auto* writer = juce::WavAudioFormat().createWriterFor (out.get(), rate, 2, 16, {}, 0))
  24930. {
  24931. out.release();
  24932. std::unique_ptr<juce::AudioFormatWriter> owned (writer);
  24933. owned->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
  24934. }
  24935. return file;
  24936. };
  24937. const auto pad = writeWav (juce::File (prefix + "-pad.wav"), 4, [] (int i, double rate) {
  24938. const auto t = i / rate;
  24939. return (float) (0.45 * (std::sin (juce::MathConstants<double>::twoPi * 220.0 * t) + 0.5 * std::sin (juce::MathConstants<double>::twoPi * 331.0 * t))
  24940. * (0.7 + 0.3 * std::sin (juce::MathConstants<double>::twoPi * 1.5 * t)));
  24941. });
  24942. const auto loop = writeWav (juce::File (prefix + "-loop.wav"), 2, [] (int i, double) {
  24943. const auto k = i % 12000;
  24944. const auto hit = i / 12000;
  24945. return k < 3000 ? (float) (std::sin (k * (hit % 4 == 0 ? 0.05 : 0.3)) * std::exp (-k / 500.0) * 0.8) : 0.0f;
  24946. });
  24947. ui.setVisible (true);
  24948. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::playlist });
  24949. offline.editSong ([&] (lynx::Song& s) {
  24950. const auto add = [&s] (const char* name, const juce::File& file) {
  24951. lynx::ChannelDef ch;
  24952. ch.name = name;
  24953. ch.instrument = lynx::InstrumentKind::audioClip;
  24954. ch.samplePath = file.getFullPathName().toStdString();
  24955. s.channels.push_back (ch);
  24956. return (int) s.channels.size() - 1;
  24957. };
  24958. const auto padChannel = add ("Pad", pad), loopChannel = add ("Loop", loop);
  24959. s.playlist.clear();
  24960. lynx::Clip a;
  24961. a.kind = lynx::ClipKind::audio;
  24962. a.channel = padChannel;
  24963. a.length = 8 * lynx::ppq;
  24964. a.track = 0;
  24965. s.playlist.push_back (a);
  24966. a.track = 1;
  24967. s.playlist.push_back (a);
  24968. lynx::Clip b = a;
  24969. b.channel = loopChannel;
  24970. b.track = 2;
  24971. b.length = 4 * lynx::ppq;
  24972. s.playlist.push_back (b);
  24973. // the first clip: a volume envelope (a swell, a dip, FL's curve modes on two segments)
  24974. auto& e = lynx::clipenv::own (s, s.playlist[0]);
  24975. e.shown = lynx::clipenv::volumeLane;
  24976. e.volume = { { 0, 0.15f, 0.0f, 0 }, { lynx::ppq * 2, 1.0f, -0.6f, 0 }, { lynx::ppq * 4, 1.0f, 0.0f, 0 },
  24977. { lynx::ppq * 5, 0.45f, 0.0f, 2 }, { lynx::ppq * 6, 0.9f, 0.0f, 0 }, { lynx::ppq * 8, 0.9f, 0.0f, 0 } };
  24978. // the second: its pan lane shown (only pan made)
  24979. lynx::clipenv::show (s, s.playlist[1], lynx::clipenv::panLane);
  24980. auto& p = lynx::clipenv::own (s, s.playlist[1]);
  24981. 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 } };
  24982. if (s.playlistTracks.size() < 3)
  24983. s.playlistTracks.resize (3);
  24984. for (int t = 0; t < 3; ++t)
  24985. s.playlistTracks[(std::size_t) t].height = 96;
  24986. }, false);
  24987. offline.dispatchPendingMessages();
  24988. auto& playlist = ui.getPlaylistForSnapshot();
  24989. playlist.setViewForSnapshot (360.0, 0, 0);
  24990. ui.resized();
  24991. offline.dispatchPendingMessages();
  24992. (void) lynx::shot::snapshot (ui); // (a paint starts the waveform analyses; the shot waits for them)
  24993. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (8000);
  24994. offline.dispatchPendingMessages();
  24995. write (ui, "01-playlist-envelopes");
  24996. // the clip menu: LYNX's extras with Clip envelope ›, Auto-warp, Quantize audio (Auto-warp run from it on the loop)
  24997. {
  24998. const auto menu = playlist.getClipMenuForSnapshot (2);
  24999. const juce::PopupMenu* envelopeMenu = nullptr;
  25000. bool autoWarp = false, quantize = false;
  25001. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  25002. {
  25003. if (it.getItem().text == lynx::tr ("Clip envelope") && it.getItem().subMenu != nullptr)
  25004. envelopeMenu = it.getItem().subMenu.get();
  25005. autoWarp = autoWarp || (it.getItem().text == lynx::tr ("Auto-warp") && it.getItem().isEnabled);
  25006. quantize = quantize || (it.getItem().text == lynx::tr ("Quantize audio") && it.getItem().isEnabled);
  25007. }
  25008. check ("clip menu: Clip envelope submenu, Auto-warp, Quantize audio", envelopeMenu != nullptr && autoWarp && quantize);
  25009. saveMenus (juce::StringArray { lynx::tr ("Audio clip"), lynx::tr ("Clip envelope") },
  25010. std::vector<juce::PopupMenu> { menu, envelopeMenu != nullptr ? *envelopeMenu : juce::PopupMenu() }, prefix + "-02-clip-menu.png");
  25011. check ("Auto-warp from the clip menu places markers", clickMenuItem (menu, lynx::tr ("Auto-warp")));
  25012. offline.dispatchPendingMessages();
  25013. const auto& s = offline.getSong();
  25014. const auto& loopClip = s.playlist[2];
  25015. check ("the loop's channel is warped", s.channels[(std::size_t) loopClip.channel].sampler.warp.size() >= 2
  25016. && s.channels[(std::size_t) loopClip.channel].sampler.keepPitch);
  25017. // the first clip's menu: Show volume envelope ticked
  25018. const auto first = playlist.getClipMenuForSnapshot (0);
  25019. bool ticked = false;
  25020. for (juce::PopupMenu::MenuItemIterator it (first); it.next();)
  25021. if (it.getItem().text == lynx::tr ("Clip envelope") && it.getItem().subMenu != nullptr)
  25022. for (juce::PopupMenu::MenuItemIterator sub (*it.getItem().subMenu); sub.next();)
  25023. ticked = ticked || (sub.getItem().text == lynx::tr ("Show volume envelope") && sub.getItem().isTicked);
  25024. check ("Show volume envelope is ticked on the first clip", ticked);
  25025. }
  25026. // gestures through the Playlist's own handlers
  25027. auto source = juce::Desktop::getInstance().getMainMouseSource();
  25028. const auto now = juce::Time::getCurrentTime();
  25029. const auto press = [&] (juce::Point<float> from, juce::Point<float> to, juce::ModifierKeys button, juce::ModifierKeys extra) {
  25030. const juce::ModifierKeys mods (button.getRawFlags() | extra.getRawFlags());
  25031. const auto event = [&] (juce::Point<float> p, juce::ModifierKeys m, bool dragged) {
  25032. return juce::MouseEvent (source, p, m, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, &playlist, &playlist, now, from, now, 1, dragged);
  25033. };
  25034. const auto held = juce::ModifierKeys::currentModifiers;
  25035. juce::ModifierKeys::currentModifiers = mods;
  25036. playlist.mouseDown (event (from, mods, false));
  25037. if (to != from)
  25038. playlist.mouseDrag (event (to, mods, true));
  25039. juce::ModifierKeys::currentModifiers = held;
  25040. playlist.mouseUp (event (to, extra, to != from));
  25041. };
  25042. const auto x = [&] (double beats) { return (float) playlist.xOfTickForSnapshot (beats * lynx::ppq); };
  25043. {
  25044. const auto body = playlist.curveBodyForSnapshot (0);
  25045. const auto points = offline.getSong().clipEnvelopes[(std::size_t) offline.getSong().playlist[0].envelope].volume.size();
  25046. // [RMB] in the curve's area adds a point there (FL's in-Playlist automation editing, round 165)
  25047. press ({ x (7.0), body.getBottom() - 0.3f * body.getHeight() }, { x (7.0), body.getBottom() - 0.3f * body.getHeight() },
  25048. juce::ModifierKeys::rightButtonModifier, {});
  25049. offline.dispatchPendingMessages();
  25050. const auto& s = offline.getSong();
  25051. const auto* e = lynx::clipenv::of (s, s.playlist[0]);
  25052. check ("[RMB] on the clip's volume lane adds a point", e != nullptr && e->volume.size() == points + 1
  25053. && std::abs (lynx::automationCurveAt (e->volume, 7.0 * lynx::ppq) - 0.3f) < 0.05f);
  25054. // drag that point up with the Pencil
  25055. press ({ x (7.0), body.getBottom() - 0.3f * body.getHeight() }, { x (7.0), body.getBottom() - 0.7f * body.getHeight() },
  25056. juce::ModifierKeys::leftButtonModifier, {});
  25057. offline.dispatchPendingMessages();
  25058. const auto* moved = lynx::clipenv::of (offline.getSong(), offline.getSong().playlist[0]);
  25059. check ("dragging the point moves it", moved != nullptr && std::abs (lynx::automationCurveAt (moved->volume, 7.0 * lynx::ppq) - 0.7f) < 0.05f);
  25060. check ("the edits are undoable", offline.canUndo());
  25061. }
  25062. write (ui, "03-playlist-edited");
  25063. {
  25064. // warp: a double-click on the loop clip's flag strip adds a marker; Alt + drag on its line (mid clip) moves it
  25065. const auto bounds = playlist.clipBoundsForSnapshot (2);
  25066. const auto channelOf = [&] { return offline.getSong().playlist[2].channel; };
  25067. const auto markers = [&] { return offline.getSong().channels[(std::size_t) channelOf()].sampler.warp; };
  25068. const auto before = markers().size();
  25069. const juce::Point<float> strip { x (1.5), (float) bounds.getY() + 13.0f + 3.0f };
  25070. playlist.mouseDoubleClick (juce::MouseEvent (source, strip, juce::ModifierKeys::leftButtonModifier, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, &playlist, &playlist,
  25071. now, strip, now, 2, false));
  25072. offline.dispatchPendingMessages();
  25073. check ("a double-click on the flag strip adds a warp marker", markers().size() == before + 1);
  25074. if (markers().size() != before + 1)
  25075. checks << " (strip seconds " << playlist.warpStripSecondsForSnapshot (2, strip.toInt()) << ", played markers "
  25076. << (int) playlist.warpMarkerCountForSnapshot (2) << ", file seconds " << playlist.clipFileSecondsForSnapshot (2)
  25077. << ", channel markers " << (int) before << ", clip at " << bounds.toString() << ", strip " << strip.toString() << ")\n";
  25078. int added = -1;
  25079. for (int k = 0; k < (int) markers().size(); ++k)
  25080. if (std::abs (markers()[(std::size_t) k].beats - 1.5) < 0.05)
  25081. added = k;
  25082. check ("the marker sits on the beat it was added on", added > 0);
  25083. if (added > 0)
  25084. {
  25085. const juce::Point<float> line { x (1.5), (float) bounds.getCentreY() + 10.0f };
  25086. press (line, line.translated (x (1.75) - x (1.5), 0.0f), juce::ModifierKeys::leftButtonModifier, juce::ModifierKeys::altModifier);
  25087. offline.dispatchPendingMessages();
  25088. 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);
  25089. }
  25090. }
  25091. write (ui, "04-playlist-warp");
  25092. // the Clip-launch layout: the Clip View's Envelopes tab of a grid audio clip
  25093. offline.editSong ([&] (lynx::Song& s) {
  25094. auto clip = s.playlist[0];
  25095. clip.start = 0;
  25096. lynx::launcher::setClip (s, 0, 0, clip);
  25097. lynx::launcher::ensureGrid (s).scenes.resize (std::max<std::size_t> (1, lynx::launcher::ensureGrid (s).scenes.size()));
  25098. }, false);
  25099. offline.dispatchPendingMessages();
  25100. const auto shootPanel = [&] (const char* name, bool envelopes, std::uint8_t lane) {
  25101. auto panel = lynx::makeClipAudioPanel (offline, 0, 0);
  25102. if (panel == nullptr)
  25103. return false;
  25104. panel->setSize (1100, 300);
  25105. for (auto* child : panel->getChildren())
  25106. if (auto* b = dynamic_cast<juce::TextButton*> (child); b != nullptr && b->getButtonText() == (envelopes ? lynx::tr ("Envelopes") : lynx::tr ("Sample")))
  25107. if (b->onClick)
  25108. b->onClick();
  25109. if (lane != 0)
  25110. offline.editSong ([lane] (lynx::Song& s) {
  25111. if (s.clipGrid)
  25112. if (auto* c = const_cast<lynx::Clip*> (lynx::launcher::clipAt (*s.clipGrid, 0, 0)); c != nullptr)
  25113. lynx::clipenv::show (s, *c, lane);
  25114. }, false);
  25115. offline.dispatchPendingMessages();
  25116. write (*panel, name);
  25117. return true;
  25118. };
  25119. check ("Clip View: Sample tab", shootPanel ("05-clipview-sample", false, 0));
  25120. check ("Clip View: Envelopes tab, Clip > Gain", shootPanel ("06-clipview-envelopes-gain", true, lynx::clipenv::volumeLane));
  25121. check ("Clip View: Envelopes tab, Mixer > Track Panning", shootPanel ("07-clipview-envelopes-pan", true, lynx::clipenv::panLane));
  25122. {
  25123. const auto* c = offline.getSong().clipGrid ? lynx::launcher::clipAt (*offline.getSong().clipGrid, 0, 0) : nullptr;
  25124. check ("the grid clip keeps the volume envelope", c != nullptr && lynx::clipenv::activeOf (offline.getSong(), *c) != nullptr);
  25125. }
  25126. shootPanel ("08-clipview-sample-again", false, 0); // (the tab choice back to Sample for the next run)
  25127. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  25128. }
  25129. void runLiveFactsShot190gx (const juce::String& prefix)
  25130. {
  25131. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  25132. lynx::AudioEngine offline (false);
  25133. juce::String checks;
  25134. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  25135. // a 1 kHz sine, 20 s at 48 kHz (Live's 190gu clip-envelope stimulus), −9 dBFS
  25136. const auto wav = juce::File (prefix + "-sine1k.wav");
  25137. wav.deleteFile();
  25138. {
  25139. const double rate = 48000.0;
  25140. juce::AudioBuffer<float> buffer (2, (int) (rate * 20.0));
  25141. for (int k = 0; k < buffer.getNumSamples(); ++k)
  25142. for (int ch = 0; ch < 2; ++ch)
  25143. buffer.setSample (ch, k, (float) (0.3535 * std::sin (2.0 * juce::MathConstants<double>::pi * 1000.0 * k / rate)));
  25144. if (auto out = std::unique_ptr<juce::FileOutputStream> (wav.createOutputStream()))
  25145. if (auto* writer = juce::WavAudioFormat().createWriterFor (out.get(), rate, 2, 16, {}, 0))
  25146. {
  25147. out.release();
  25148. std::unique_ptr<juce::AudioFormatWriter> owned (writer);
  25149. owned->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
  25150. }
  25151. }
  25152. offline.editSong ([&wav] (lynx::Song& s) {
  25153. s.bpm = 120.0;
  25154. lynx::ChannelDef ch;
  25155. ch.name = "sine1k";
  25156. ch.instrument = lynx::InstrumentKind::audioClip;
  25157. ch.samplePath = wav.getFullPathName().toStdString();
  25158. s.channels.push_back (ch);
  25159. const auto c = (int) s.channels.size() - 1;
  25160. lynx::clipsample::setWarp (s, c, true, 20.0);
  25161. lynx::warpmodes::setMode (s, c, (int) lynx::StretchMethod::beats);
  25162. lynx::Clip audio;
  25163. audio.kind = lynx::ClipKind::audio;
  25164. audio.channel = c;
  25165. audio.length = 40 * lynx::ppq;
  25166. // Live's Clip Gain staircase of the 190gu render (−1 … 1 in 0.1 steps, 2 beats each), as LYNX lane values
  25167. lynx::ClipEnvelope e;
  25168. for (int k = 0; k <= 20; ++k)
  25169. {
  25170. const auto v = lynx::clipenv::fromLive (lynx::clipenv::volumeLane, -1.0 + 0.1 * k);
  25171. for (const auto at : { 2 * k, 2 * k + 2 })
  25172. {
  25173. lynx::AutomationPoint p;
  25174. p.tick = (std::int64_t) at * lynx::ppq;
  25175. p.value = v;
  25176. e.volume.push_back (p);
  25177. }
  25178. }
  25179. e.shown = lynx::clipenv::volumeLane;
  25180. s.clipEnvelopes.push_back (e);
  25181. audio.envelope = (int) s.clipEnvelopes.size() - 1;
  25182. lynx::launcher::setClip (s, 0, 0, audio);
  25183. lynx::launcher::ensureGrid (s).scenes.resize (1);
  25184. }, false);
  25185. offline.dispatchPendingMessages();
  25186. const auto channelOf = [&] {
  25187. const auto* c = lynx::warpmodes::gridAudioClip (const_cast<lynx::Song&> (offline.getSong()), 0, 0);
  25188. return c != nullptr ? c->channel : -1;
  25189. };
  25190. const auto shoot = [&] (const char* name, int w, int h, int tab) {
  25191. auto panel = lynx::makeClipAudioPanel (offline, 0, 0);
  25192. if (panel == nullptr)
  25193. return std::unique_ptr<juce::Component>();
  25194. panel->setSize (w, h);
  25195. if (tab != 0)
  25196. for (auto* child : panel->getChildren())
  25197. if (auto* b = dynamic_cast<juce::TextButton*> (child); b != nullptr && b->getButtonText() == (tab == 2 ? lynx::tr ("Envelopes") : lynx::tr ("Sample")))
  25198. if (b->onClick)
  25199. b->onClick();
  25200. offline.dispatchPendingMessages();
  25201. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  25202. file.deleteFile();
  25203. juce::FileOutputStream out (file);
  25204. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (*panel), out);
  25205. return panel;
  25206. };
  25207. const auto visibleText = [] (juce::Component& panel, const juce::String& text) {
  25208. for (auto* child : panel.getChildren())
  25209. if (auto* b = dynamic_cast<juce::TextButton*> (child); b != nullptr && b->getButtonText() == text)
  25210. return b->isVisible();
  25211. return false;
  25212. };
  25213. const auto setMode = [&] (int method) {
  25214. offline.editSong ([&] (lynx::Song& s) { lynx::warpmodes::setMode (s, channelOf(), method); }, false);
  25215. offline.dispatchPendingMessages();
  25216. };
  25217. check ("01 Beats (Preserve label + chooser, loop icon + Transient Envelope)", shoot ("01-audio-beats", 900, 250, 1) != nullptr);
  25218. setMode ((int) lynx::StretchMethod::tones);
  25219. check ("02 Tones (Grain Size 30.00)", shoot ("02-audio-tones", 900, 250, 1) != nullptr);
  25220. setMode ((int) lynx::StretchMethod::texture);
  25221. check ("03 Texture (Grain Size 65.00, Flux only when it plays)", shoot ("03-audio-texture", 900, 250, 1) != nullptr);
  25222. if constexpr (lynx::warpmodes::complexProPlays)
  25223. {
  25224. offline.editSong ([&] (lynx::Song& s) { lynx::warpmodes::setComplexPro (s, channelOf()); }, false);
  25225. offline.dispatchPendingMessages();
  25226. check ("04 Complex Pro (Formants 100.00, Envelope 128)", shoot ("04-audio-complex-pro", 900, 250, 1) != nullptr);
  25227. }
  25228. else
  25229. {
  25230. setMode ((int) lynx::StretchMethod::complex);
  25231. check ("04 Complex (nothing under the chooser)", shoot ("04-audio-complex", 900, 250, 1) != nullptr);
  25232. }
  25233. setMode ((int) lynx::StretchMethod::beats);
  25234. {
  25235. auto panel = shoot ("05-envelopes-clip-gain-staircase", 1390, 420, 2);
  25236. check ("05 Envelopes tab shown on a warped clip", panel != nullptr && visibleText (*panel, lynx::tr ("Envelopes")));
  25237. }
  25238. offline.editSong ([&] (lynx::Song& s) { lynx::clipsample::setWarp (s, channelOf(), false, 20.0); }, false);
  25239. offline.dispatchPendingMessages();
  25240. {
  25241. auto panel = shoot ("06-unwarped-sample-only", 1390, 420, 2);
  25242. check ("06 an unwarped clip has no Envelopes tab (Live)", panel != nullptr && ! visibleText (*panel, lynx::tr ("Envelopes"))
  25243. && visibleText (*panel, lynx::tr ("Sample")));
  25244. }
  25245. // the law: Live's staircase values round trip through the lane values
  25246. bool law = true;
  25247. for (int k = 0; k <= 20; ++k)
  25248. {
  25249. const auto L = -1.0 + 0.1 * k;
  25250. law = law && std::abs (lynx::clipenv::toLive (lynx::clipenv::volumeLane, lynx::clipenv::fromLive (lynx::clipenv::volumeLane, L)) - L) < 2.0e-3;
  25251. }
  25252. check ("Clip Gain values round trip (Live → lane → Live)", law);
  25253. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  25254. }
  25255. void runDvShot190hr (const juce::String& prefix)
  25256. {
  25257. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  25258. lynx::AudioEngine offline (false);
  25259. lynx::MainComponent ui (offline, false);
  25260. ui.setSize (1600, 900);
  25261. juce::String checks;
  25262. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  25263. const auto write = [&prefix] (juce::Component& c, const char* name) {
  25264. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  25265. file.deleteFile();
  25266. juce::FileOutputStream out (file);
  25267. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (c), out);
  25268. };
  25269. ui.setVisible (true);
  25270. lynx::DetailView::shownSetting = true;
  25271. ui.selectTabForSnapshot (2);
  25272. ui.setLayoutStyle (lynx::layoutstyle::Style::clipLaunch);
  25273. offline.editSong ([] (lynx::Song& s) {
  25274. const int ch = (int) s.channels.size();
  25275. s.channels.resize ((std::size_t) ch + 1);
  25276. s.channels[(std::size_t) ch].name = "Keys";
  25277. s.channels[(std::size_t) ch].instrument = lynx::InstrumentKind::synth;
  25278. while (s.patterns.empty())
  25279. s.patterns.emplace_back();
  25280. auto& p = s.patterns[0];
  25281. p.name = "Riff";
  25282. p.notes.clear();
  25283. const int keys[] { 62, 65, 69, 72, 64, 67 };
  25284. for (int i = 0; i < 6; ++i)
  25285. {
  25286. lynx::Note n;
  25287. n.channel = ch;
  25288. n.key = keys[i];
  25289. n.start = i * lynx::ppq / 2 + (i % 2 ? 37 : -0) + 11; // a little off the 1/16 grid
  25290. n.length = lynx::ppq / 3;
  25291. p.notes.push_back (n);
  25292. }
  25293. p.lengthTicks = 4 * lynx::ppq;
  25294. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 3));
  25295. s.playlistTracks[0].name = "Keys";
  25296. lynx::Clip clip;
  25297. clip.pattern = 0;
  25298. clip.length = 4 * lynx::ppq;
  25299. const auto id = lynx::launcher::setClip (s, 0, 0, clip);
  25300. lynx::launcher::setClip (s, 0, 1, clip);
  25301. auto& grid = lynx::launcher::ensureGrid (s);
  25302. grid.scenes.resize (3);
  25303. if (id >= 0)
  25304. {
  25305. auto& slot = grid.slots[(std::size_t) id];
  25306. slot.name = "Riff";
  25307. slot.startMarker = 2 * lynx::ppq; // Start 1. 3. 1 inside the loop 1. 1. 1 + 1 bar
  25308. slot.ownScale = true;
  25309. slot.scaleRoot = 2; // D, the scale list's first (Major)
  25310. slot.scaleIndex = (std::int16_t) lynx::projectkey::commonFirst().front();
  25311. slot.follow.enabled = true;
  25312. slot.follow.a = lynx::FollowKind::next;
  25313. slot.follow.b = lynx::FollowKind::jump;
  25314. slot.follow.jumpB = 1;
  25315. slot.follow.chanceA = 70;
  25316. slot.follow.chanceB = 30;
  25317. slot.follow.linked = true;
  25318. slot.follow.iterations = 2;
  25319. }
  25320. }, false);
  25321. offline.dispatchPendingMessages();
  25322. ui.resized();
  25323. auto* detail = ui.getDetailViewForSnapshot();
  25324. if (detail == nullptr)
  25325. {
  25326. juce::File (prefix + "-checks.txt").replaceWithText ("FAIL no detail view\n");
  25327. return;
  25328. }
  25329. detail->showSelection (0, 0);
  25330. detail->setPage (lynx::DetailView::Page::clip);
  25331. offline.dispatchPendingMessages();
  25332. ui.resized();
  25333. write (ui, "01-clip-view-midi");
  25334. write (*detail, "01b-detail-alone");
  25335. auto& roll = ui.getPianoRollForSnapshot();
  25336. check ("the docked editor uses the reference's grid (" + roll.liveGridTextForCheck() + ")", roll.liveGridOn() && roll.liveGridTextForCheck().isNotEmpty());
  25337. check ("Start marker inside the loop kept by the launcher (lead 2 beats)", lynx::launcher::startLead (offline.getSong().clipGrid->slots[0], 4 * lynx::ppq) == 2.0 * lynx::ppq);
  25338. {
  25339. std::vector<juce::PopupMenu> menus { roll.liveGridMenu() };
  25340. saveMenus (juce::StringArray { "Grid" }, menus, prefix + "-02-grid-menu.png");
  25341. }
  25342. roll.liveGrid.fixed = true;
  25343. roll.liveGrid.fixedIndex = lynx::livegrid::defaultFixed;
  25344. roll.resized();
  25345. const auto sixteenth = roll.gridStepForCheck();
  25346. roll.runAction ("pianoRoll.liveGridNarrower");
  25347. const auto narrower = roll.gridStepForCheck();
  25348. roll.runAction ("pianoRoll.liveGridTriplet");
  25349. const auto triplet = roll.gridStepForCheck();
  25350. check ("fixed 1/16 = 240 ticks, Ctrl+1 -> 1/32 = 120, Ctrl+3 -> 1/32T = 80 (" + juce::String (sixteenth) + ", " + juce::String (narrower) + ", " + juce::String (triplet) + ")",
  25351. sixteenth == lynx::ppq / 4 && narrower == lynx::ppq / 8 && triplet == lynx::ppq / 12);
  25352. write (roll, "03-editor-grid-1-32T");
  25353. roll.runAction ("pianoRoll.liveGridTriplet");
  25354. roll.runAction ("pianoRoll.liveGridWider");
  25355. const auto before = offline.getSong().patterns[0].notes;
  25356. roll.runAction ("pianoRoll.liveQuantize"); // (Live 12: Edit › Quantize, the Quantize tool's settings: Grid = 1/16 here)
  25357. offline.dispatchPendingMessages();
  25358. {
  25359. const auto& after = offline.getSong().patterns[0].notes;
  25360. bool onGrid = ! after.empty();
  25361. for (const auto& n : after)
  25362. onGrid = onGrid && n.start % (lynx::ppq / 4) == 0;
  25363. check ("Ctrl+U quantized every note start onto the editor's 1/16 grid", onGrid && after.size() == before.size() && after != before);
  25364. }
  25365. roll.runAction ("pianoRoll.liveQuantizeSettings"); // (Live 12: Quantize Settings… opens the MIDI Tools' Quantize tool)
  25366. offline.dispatchPendingMessages();
  25367. check ("Ctrl+Shift+U shows the MIDI Tools' Quantize tool", detail->midiToolsForSnapshot().getTool() == lynx::MidiToolsPanel::quantize
  25368. && detail->midiToolsForSnapshot().isVisible());
  25369. ui.resized();
  25370. write (*detail, "04-after-quantize-tool");
  25371. // an audio clip transposed +30 st 25 ct (Live's ±48 st)
  25372. const auto wav = juce::File (prefix + "-tone.wav");
  25373. wav.deleteFile();
  25374. {
  25375. const double rate = 48000.0;
  25376. juce::AudioBuffer<float> buffer (1, (int) (rate * 2.0));
  25377. for (int k = 0; k < buffer.getNumSamples(); ++k)
  25378. buffer.setSample (0, k, (float) (0.5 * std::sin (k * 0.05)));
  25379. if (auto out = std::unique_ptr<juce::FileOutputStream> (wav.createOutputStream()))
  25380. if (auto* writer = juce::WavAudioFormat().createWriterFor (out.get(), rate, 1, 16, {}, 0))
  25381. {
  25382. out.release();
  25383. std::unique_ptr<juce::AudioFormatWriter> owned (writer);
  25384. owned->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
  25385. }
  25386. }
  25387. offline.editSong ([&wav] (lynx::Song& s) {
  25388. lynx::ChannelDef ch;
  25389. ch.name = "Tone";
  25390. ch.instrument = lynx::InstrumentKind::audioClip;
  25391. ch.samplePath = wav.getFullPathName().toStdString();
  25392. s.channels.push_back (ch);
  25393. lynx::Clip audio;
  25394. audio.kind = lynx::ClipKind::audio;
  25395. audio.channel = (int) s.channels.size() - 1;
  25396. audio.length = 4 * lynx::ppq;
  25397. audio.pitch = 30.25f;
  25398. lynx::launcher::setClip (s, 1, 0, audio);
  25399. }, false);
  25400. offline.dispatchPendingMessages();
  25401. if (auto panel = lynx::makeClipAudioPanel (offline, 1, 0))
  25402. {
  25403. panel->setSize (900, 250);
  25404. write (*panel, "06-audio-transpose-30");
  25405. check ("audio clip transpose +30.25 st kept", std::abs (lynx::launcher::clipAt (*offline.getSong().clipGrid, 1, 0)->pitch - 30.25f) < 1e-4f);
  25406. }
  25407. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  25408. }
  25409. void runWarpShot190fm (const juce::String& prefix)
  25410. {
  25411. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  25412. lynx::AudioEngine offline (false);
  25413. juce::String checks;
  25414. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  25415. // a one-bar loop of clicks (2 s at 48 kHz) for the audio clips
  25416. const auto wav = juce::File (prefix + "-loop.wav");
  25417. wav.deleteFile();
  25418. {
  25419. const double rate = 48000.0;
  25420. juce::AudioBuffer<float> buffer (2, (int) (rate * 2.0));
  25421. buffer.clear();
  25422. for (int hit = 0; hit < 8; ++hit)
  25423. for (int k = 0; k < 3000; ++k)
  25424. for (int ch = 0; ch < 2; ++ch)
  25425. buffer.setSample (ch, hit * 12000 + k, (float) (std::sin (k * (hit % 4 == 0 ? 0.05 : 0.3)) * std::exp (-k / 500.0) * 0.8));
  25426. if (auto out = std::unique_ptr<juce::FileOutputStream> (wav.createOutputStream()))
  25427. if (auto* writer = juce::WavAudioFormat().createWriterFor (out.get(), rate, 2, 16, {}, 0))
  25428. {
  25429. out.release();
  25430. std::unique_ptr<juce::AudioFormatWriter> owned (writer);
  25431. owned->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
  25432. }
  25433. }
  25434. offline.editSong ([&wav] (lynx::Song& s) {
  25435. lynx::ChannelDef ch;
  25436. ch.name = "Loop";
  25437. ch.instrument = lynx::InstrumentKind::audioClip;
  25438. ch.samplePath = wav.getFullPathName().toStdString();
  25439. s.channels.push_back (ch);
  25440. const auto c = (int) s.channels.size() - 1;
  25441. lynx::clipsample::setWarp (s, c, true, 2.0);
  25442. lynx::warpmodes::setMode (s, c, (int) lynx::StretchMethod::beats); // (keeps the pitch: Beats, not Re-Pitch)
  25443. lynx::Clip audio;
  25444. audio.kind = lynx::ClipKind::audio;
  25445. audio.channel = c;
  25446. audio.length = 4 * lynx::ppq;
  25447. lynx::launcher::setClip (s, 0, 0, audio);
  25448. lynx::launcher::setClip (s, 0, 1, audio); // (a second clip on the same channel: O16)
  25449. lynx::launcher::ensureGrid (s).scenes.resize (2);
  25450. }, false);
  25451. offline.dispatchPendingMessages();
  25452. const auto shoot = [&] (const char* name) {
  25453. auto panel = lynx::makeClipAudioPanel (offline, 0, 0);
  25454. if (panel == nullptr)
  25455. return false;
  25456. panel->setSize (900, 250);
  25457. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  25458. file.deleteFile();
  25459. juce::FileOutputStream out (file);
  25460. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (*panel), out);
  25461. return true;
  25462. };
  25463. const auto channelOf = [&] (int scene) {
  25464. const auto* c = lynx::warpmodes::gridAudioClip (const_cast<lynx::Song&> (offline.getSong()), 0, scene);
  25465. return c != nullptr ? c->channel : -1;
  25466. };
  25467. const auto beatsOn = [&] { const auto& sm = offline.getSong().channels[(std::size_t) channelOf (0)].sampler; return sm.keepPitch && sm.stretchMethod == lynx::StretchMethod::beats; };
  25468. check ("01 Beats panel (defaults: Transients, Back-and-Forth, 100)", beatsOn() && shoot ("01-beats-defaults"));
  25469. offline.editSong ([&] (lynx::Song& s) {
  25470. const auto c = lynx::warpmodes::ownChannelForGridClip (s, 0, 0);
  25471. lynx::warpmodes::setPreserve (s, c, 3);
  25472. lynx::warpmodes::setLoopMode (s, c, 0);
  25473. lynx::warpmodes::setEnvelope (s, c, 40.0);
  25474. }, false);
  25475. offline.dispatchPendingMessages();
  25476. 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);
  25477. check ("02 Beats panel (1/8, Loop Off, 40)", beatsOn() && shoot ("02-beats-set"));
  25478. offline.editSong ([&] (lynx::Song& s) { lynx::warpmodes::setMode (s, channelOf (0), (int) lynx::StretchMethod::tones); }, false);
  25479. offline.dispatchPendingMessages();
  25480. check ("03 Tones panel (Grain Size 30)", shoot ("03-tones"));
  25481. offline.editSong ([&] (lynx::Song& s) {
  25482. lynx::warpmodes::setMode (s, channelOf (0), (int) lynx::StretchMethod::texture);
  25483. lynx::warpmodes::setGrain (s, channelOf (0), 120.0);
  25484. }, false);
  25485. offline.dispatchPendingMessages();
  25486. check ("04 Texture panel (Grain Size 120)", shoot ("04-texture"));
  25487. check ("Texture grain kept 120, Tones grain still 30", offline.getSong().channels[(std::size_t) channelOf (0)].sampler.warpModes.textureGrain == 120.0f
  25488. && offline.getSong().channels[(std::size_t) channelOf (0)].sampler.warpModes.tonesGrain == 30.0f);
  25489. offline.editSong ([&] (lynx::Song& s) { lynx::warpmodes::setMode (s, channelOf (0), (int) lynx::StretchMethod::complex); }, false);
  25490. offline.dispatchPendingMessages();
  25491. check ("05 Complex panel (no settings row)", shoot ("05-complex"));
  25492. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  25493. }
  25494. void runDesign190igShot (const juce::String& prefix, const juce::String& project)
  25495. {
  25496. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  25497. lynx::AudioEngine offline (false);
  25498. lynx::MainComponent ui (offline, false);
  25499. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1920x1080"), "x", "");
  25500. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  25501. const auto write = [&prefix] (juce::Component& c, const char* name) {
  25502. savePng (lynx::shot::snapshot (c), prefix + "-" + name + ".png");
  25503. };
  25504. if (project.isNotEmpty())
  25505. ui.openFile (juce::File (project));
  25506. offline.dispatchPendingMessages();
  25507. ui.selectTabForSnapshot (2); // the Playlist, maximized
  25508. auto& playlist = ui.getPlaylistForSnapshot();
  25509. offline.dispatchPendingMessages();
  25510. const auto settle = [&] { // (the waveforms are analysed in the background on the first paint)
  25511. write (playlist, "warmup");
  25512. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (60000);
  25513. offline.dispatchPendingMessages();
  25514. juce::File (prefix + "-warmup.png").deleteFile();
  25515. };
  25516. const auto heights = [&] (int h) {
  25517. offline.editSong ([h] (lynx::Song& s) {
  25518. for (auto& t : s.playlistTracks)
  25519. t.height = h;
  25520. }, false);
  25521. offline.dispatchPendingMessages();
  25522. };
  25523. // FL's default view (shots/ref/fl-playlist.png): 26 px tracks, bar 21 at the left, 15.6 px a bar, CUTS at the top
  25524. heights (26);
  25525. playlist.setViewForSnapshot (15.6, 20, 0);
  25526. playlist.setScrollYForSnapshot (19 * 26);
  25527. settle();
  25528. write (ui, "01-default");
  25529. write (playlist, "01-default-playlist");
  25530. // FL's "Zoom level 17" (shots/ref/fl-playlist-zoom-audioclips.png): 50 px tracks, 39.75 px a bar, Saw Bass at the top
  25531. heights (50);
  25532. playlist.setViewForSnapshot (39.75, 20, 0);
  25533. playlist.setScrollYForSnapshot (24 * 50 + 4);
  25534. settle();
  25535. write (ui, "02-zoom17");
  25536. write (playlist, "02-zoom17-playlist");
  25537. // playing (shots/ref/fl-playing.png): the playhead at bar 33, the activity column lit for the tracks that sound
  25538. offline.getTransport().positionTicks.store ((double) (32 * offline.getSong().barTicks()));
  25539. offline.getTransport().playing.store (true);
  25540. playlist.frameStepForSnapshot();
  25541. playlist.frameStepForSnapshot();
  25542. write (ui, "03-playing");
  25543. offline.getTransport().playing.store (false);
  25544. playlist.frameStepForSnapshot();
  25545. heights (26);
  25546. playlist.setViewForSnapshot (15.6, 0, 0);
  25547. playlist.setScrollYForSnapshot (0);
  25548. write (ui, "04-default-start");
  25549. }
  25550. void runDesign190igS4Shot (const juce::String& prefix, const juce::String& projectPath)
  25551. {
  25552. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  25553. lynx::AudioEngine offline (false);
  25554. lynx::MainComponent ui (offline, false);
  25555. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  25556. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  25557. juce::String checks;
  25558. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  25559. const auto write = [&prefix] (juce::Component& c, const juce::String& name) {
  25560. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  25561. file.deleteFile();
  25562. juce::FileOutputStream out (file);
  25563. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (c), out);
  25564. };
  25565. ui.setVisible (true);
  25566. ui.selectTabForSnapshot (2);
  25567. ui.setClipLaunchWorkflow (true); // (first: an .als opened in the Clip-launch layout takes Live's own colours)
  25568. offline.dispatchPendingMessages();
  25569. if (projectPath.isNotEmpty())
  25570. {
  25571. ui.openFile (juce::File (projectPath));
  25572. offline.dispatchPendingMessages();
  25573. }
  25574. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  25575. offline.dispatchPendingMessages();
  25576. ui.resized();
  25577. auto* gridView = ui.getClipGridForSnapshot();
  25578. auto* runtime = offline.launcherStateForSnapshot();
  25579. const auto& song = offline.getSong();
  25580. if (gridView == nullptr || ! song.clipGrid)
  25581. {
  25582. juce::File (prefix + "-checks.txt").replaceWithText ("FAIL no grid\n");
  25583. return;
  25584. }
  25585. if (! song.mixer.empty())
  25586. checks << "first mixer colours:";
  25587. for (std::size_t m = 1; m < std::min<std::size_t> (song.mixer.size(), 6); ++m)
  25588. checks << " " << juce::String::toHexString ((int) (song.mixer[m].colour & 0xffffff)).paddedLeft ('0', 6);
  25589. checks << "\n";
  25590. gridView->resized();
  25591. write (ui, "01-window-idle");
  25592. write (*gridView, "02-grid-idle");
  25593. if (runtime == nullptr)
  25594. {
  25595. check ("a launcher runtime exists", false);
  25596. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  25597. return;
  25598. }
  25599. // the frame strip: the first five tracks; the scene each plays or waits for, by the clips the set has
  25600. const auto& grid = *song.clipGrid;
  25601. const auto rowWithClip = [&grid] (int track, int from) {
  25602. for (int r = from; r < 64; ++r)
  25603. if (lynx::launcher::clipAt (grid, track, r) != nullptr)
  25604. return r;
  25605. return -1;
  25606. };
  25607. const auto reset = [&] {
  25608. for (auto& v : runtime->tracks)
  25609. {
  25610. v.playing.store (-1);
  25611. v.pending.store (-1);
  25612. v.stopping.store (false);
  25613. v.recording.store (-1);
  25614. v.recordPending.store (-1);
  25615. v.progress.store (0.0f);
  25616. }
  25617. runtime->running.store (true);
  25618. };
  25619. const auto bar = (double) song.barTicks();
  25620. const auto state = [&] (const juce::String& name) {
  25621. gridView->repaint();
  25622. write (*gridView, name);
  25623. };
  25624. // playing (Live frame 1): tracks 0..3 play their first clip, a third of the way into its second loop
  25625. reset();
  25626. for (int t = 0; t < 4; ++t)
  25627. if (const auto r = rowWithClip (t, 0); r >= 0)
  25628. {
  25629. runtime->tracks[(std::size_t) t].playing.store (r);
  25630. runtime->tracks[(std::size_t) t].progress.store (0.33f);
  25631. const auto length = (double) lynx::launcher::clipAt (grid, t, r)->length;
  25632. runtime->tracks[(std::size_t) t].anchor.store (0.0);
  25633. runtime->clockNow.store (length * 1.33);
  25634. }
  25635. state ("10-playing");
  25636. // queued (Live frames 2 and 3): the same, and each track's next clip waits for its start; both blink phases
  25637. for (int t = 0; t < 4; ++t)
  25638. if (const auto r = runtime->tracks[(std::size_t) t].playing.load(); r >= 0)
  25639. if (const auto next = rowWithClip (t, r + 1); next >= 0)
  25640. runtime->tracks[(std::size_t) t].pending.store (next);
  25641. lynx::setClipGridBlinkPhaseForSnapshot (0);
  25642. state ("11-queued-dark");
  25643. lynx::setClipGridBlinkPhaseForSnapshot (1);
  25644. state ("12-queued-lit");
  25645. // Animations off: the lit green, steady
  25646. lynx::ui::motion::enabled() = false;
  25647. lynx::setClipGridBlinkPhaseForSnapshot (-1);
  25648. state ("13-queued-animations-off");
  25649. lynx::ui::motion::enabled() = true;
  25650. // a stop waiting (both phases)
  25651. reset();
  25652. for (int t = 0; t < 4; ++t)
  25653. if (const auto r = rowWithClip (t, 0); r >= 0)
  25654. {
  25655. runtime->tracks[(std::size_t) t].playing.store (r);
  25656. runtime->tracks[(std::size_t) t].progress.store (0.5f);
  25657. runtime->tracks[(std::size_t) t].stopping.store (t % 2 == 0);
  25658. }
  25659. lynx::setClipGridBlinkPhaseForSnapshot (0);
  25660. state ("14-stopping-dark");
  25661. lynx::setClipGridBlinkPhaseForSnapshot (1);
  25662. state ("15-stopping-lit");
  25663. // recording into an empty slot of track 1 (the counter one beat in) and a launch waiting on an empty slot (a stop)
  25664. reset();
  25665. {
  25666. int empty = -1;
  25667. for (int r = 0; r < 16 && empty < 0; ++r)
  25668. if (lynx::launcher::clipAt (grid, 1, r) == nullptr)
  25669. empty = r;
  25670. if (empty >= 0)
  25671. {
  25672. runtime->tracks[1].recording.store (empty);
  25673. runtime->tracks[1].recordFrom.store (0.0);
  25674. runtime->clockNow.store ((double) lynx::ppq);
  25675. }
  25676. check ("recording: an empty slot on track 2", empty >= 0);
  25677. }
  25678. state ("16-recording");
  25679. // the status pie at 25 / 50 / 75 % in the second loop
  25680. for (const auto [name, p] : { std::pair ("17-pie-25", 0.25f), std::pair ("18-pie-50", 0.5f), std::pair ("19-pie-75", 0.75f) })
  25681. {
  25682. reset();
  25683. for (int t = 0; t < 4; ++t)
  25684. if (const auto r = rowWithClip (t, 0); r >= 0)
  25685. {
  25686. const auto length = (double) lynx::launcher::clipAt (grid, t, r)->length;
  25687. runtime->tracks[(std::size_t) t].playing.store (r);
  25688. runtime->tracks[(std::size_t) t].progress.store (p);
  25689. runtime->tracks[(std::size_t) t].anchor.store (0.0);
  25690. runtime->clockNow.store (length * (1.0 + (double) p));
  25691. }
  25692. state (name);
  25693. }
  25694. juce::ignoreUnused (bar);
  25695. // round 181a's look, the option (View › Classic LYNX look for the clip grid)
  25696. reset();
  25697. for (int t = 0; t < 4; ++t)
  25698. if (const auto r = rowWithClip (t, 0); r >= 0)
  25699. runtime->tracks[(std::size_t) t].playing.store (r);
  25700. lynx::clipGridClassicLook() = true;
  25701. lynx::refreshClipGrid (*gridView);
  25702. state ("20-classic-look-option");
  25703. lynx::clipGridClassicLook() = false;
  25704. lynx::refreshClipGrid (*gridView);
  25705. lynx::setClipGridBlinkPhaseForSnapshot (-1);
  25706. reset();
  25707. runtime->running.store (false);
  25708. write (ui, "21-window-after");
  25709. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  25710. ui.setClipLaunchWorkflow (false);
  25711. }
  25712. void runLiveShot190dr (const juce::String& prefix)
  25713. {
  25714. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  25715. lynx::AudioEngine offline (false);
  25716. lynx::MainComponent ui (offline, false);
  25717. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  25718. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  25719. const auto write = [&prefix] (juce::Component& c, const char* name) {
  25720. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  25721. file.deleteFile();
  25722. juce::FileOutputStream out (file);
  25723. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (c), out);
  25724. };
  25725. juce::String checks;
  25726. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  25727. // a two-bar loop of clicks for the audio clip
  25728. const auto wav = juce::File (prefix + "-loop.wav");
  25729. wav.deleteFile();
  25730. {
  25731. const double rate = 48000.0;
  25732. juce::AudioBuffer<float> buffer (2, (int) (rate * 4.0));
  25733. buffer.clear();
  25734. for (int hit = 0; hit < 16; ++hit)
  25735. for (int k = 0; k < 3000 && hit * 12000 + k < buffer.getNumSamples(); ++k)
  25736. for (int ch = 0; ch < 2; ++ch)
  25737. buffer.setSample (ch, hit * 12000 + k, (float) (std::sin (k * (hit % 4 == 0 ? 0.05 : 0.3)) * std::exp (-k / 500.0) * 0.8));
  25738. if (auto out = std::unique_ptr<juce::FileOutputStream> (wav.createOutputStream()))
  25739. if (auto* writer = juce::WavAudioFormat().createWriterFor (out.get(), rate, 2, 16, {}, 0))
  25740. {
  25741. out.release();
  25742. std::unique_ptr<juce::AudioFormatWriter> owned (writer);
  25743. owned->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
  25744. }
  25745. }
  25746. ui.setVisible (true);
  25747. lynx::DetailView::shownSetting = true;
  25748. lynx::DetailView::devicesPage = false;
  25749. ui.setClipLaunchWorkflow (true);
  25750. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::browser, lynx::workspace::Panel::playlist });
  25751. ui.getPlaylistForSnapshot().addAudioClipAtPlayhead (wav);
  25752. offline.dispatchPendingMessages();
  25753. int audioChannel = -1;
  25754. offline.editSong ([&audioChannel] (lynx::Song& s) {
  25755. lynx::Clip audio;
  25756. if (! s.playlist.empty())
  25757. {
  25758. audio = s.playlist.front();
  25759. audioChannel = audio.channel;
  25760. s.playlist.clear();
  25761. }
  25762. const int channels = (int) s.channels.size();
  25763. s.channels.resize ((std::size_t) channels + 3);
  25764. const char* names[] { "Drum kit", "Bass synth", "Keys" };
  25765. for (int k = 0; k < 3; ++k)
  25766. {
  25767. auto& ch = s.channels[(std::size_t) (channels + k)];
  25768. ch.name = names[k];
  25769. ch.instrument = k == 0 ? lynx::InstrumentKind::sampler : lynx::InstrumentKind::synth;
  25770. ch.mixerTrack = k + 1;
  25771. }
  25772. if (audioChannel >= 0)
  25773. s.channels[(std::size_t) audioChannel].mixerTrack = 5;
  25774. if (s.mixer.size() < 8)
  25775. s.mixer.resize (8);
  25776. const char* inserts[] { "Master", "Drums", "Bass", "Keys", "Vox", "Loop", "Reverb", "Delay" };
  25777. for (int i = 1; i < 8; ++i)
  25778. s.mixer[(std::size_t) i].name = inserts[i];
  25779. s.mixer[1].volume = lynx::sessionmixer::positionForDb (-3.0);
  25780. s.mixer[2].pan = 0.3f;
  25781. s.mixer[2].effects.clear();
  25782. for (auto kind : { lynx::EffectKind::eq, lynx::EffectKind::compressor, lynx::EffectKind::delay })
  25783. {
  25784. lynx::EffectSlot fx;
  25785. fx.kind = kind;
  25786. const auto& info = lynx::effectInfo (kind);
  25787. for (std::size_t k = 0; k < info.params.size() && k < fx.params.size(); ++k)
  25788. fx.params[k] = info.params[k].defaultValue;
  25789. s.mixer[2].effects.push_back (fx);
  25790. }
  25791. s.mixer[3].muted = true; // the Keys' activator off
  25792. s.mixer[4].inputChannel = 0;
  25793. s.mixer[4].inputStereo = true;
  25794. s.mixer[4].monitor = lynx::InputMonitor::automatic;
  25795. s.mixer[4].effects.clear();
  25796. {
  25797. lynx::EffectSlot fx;
  25798. fx.kind = lynx::EffectKind::reverb;
  25799. s.mixer[4].effects.push_back (fx);
  25800. }
  25801. s.mixer[5].solo = true;
  25802. 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 } })
  25803. {
  25804. lynx::MixerSend send;
  25805. send.target = to;
  25806. send.level = lynx::faderGain (level);
  25807. s.mixer[(std::size_t) from].sends.push_back (send);
  25808. }
  25809. while (s.patterns.size() < 3)
  25810. s.patterns.emplace_back();
  25811. const char* patterns[] { "Beat", "Bassline", "Chords" };
  25812. for (int p = 0; p < 3; ++p)
  25813. {
  25814. auto& pattern = s.patterns[(std::size_t) p];
  25815. pattern.name = patterns[p];
  25816. lynx::Note n;
  25817. n.channel = channels + p;
  25818. n.key = 48 + p * 5;
  25819. pattern.notes = { n };
  25820. pattern.lengthTicks = 4 * lynx::ppq;
  25821. }
  25822. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 8));
  25823. const char* tracks[] { "Drums", "Bass", "Keys", "Vox", "Loop", "FX" };
  25824. for (int t = 0; t < 6; ++t)
  25825. s.playlistTracks[(std::size_t) t].name = tracks[t];
  25826. s.playlistTracks[3].mode = lynx::PlaylistTrackMode::audio;
  25827. s.playlistTracks[3].mixerTrack = 4;
  25828. for (int t = 0; t < 3; ++t)
  25829. for (int r = 0; r < 3; ++r)
  25830. if (! (t == 2 && r == 0))
  25831. {
  25832. lynx::Clip clip;
  25833. clip.pattern = t;
  25834. clip.length = 4 * lynx::ppq;
  25835. lynx::launcher::setClip (s, t, r, clip);
  25836. }
  25837. if (audioChannel >= 0)
  25838. {
  25839. lynx::clipsample::setWarp (s, audioChannel, true, 4.0); // (Warp on, as a dropped loop in Live)
  25840. audio.track = 4;
  25841. audio.start = 0;
  25842. lynx::launcher::setClip (s, 4, 0, audio);
  25843. lynx::launcher::setClip (s, 4, 1, audio);
  25844. }
  25845. auto& grid = lynx::launcher::ensureGrid (s);
  25846. const char* scenes[] { "Intro", "Verse", "Drop" };
  25847. grid.scenes.resize (5);
  25848. for (int r = 0; r < 3; ++r)
  25849. grid.scenes[(std::size_t) r].name = scenes[r];
  25850. }, false);
  25851. offline.dispatchPendingMessages();
  25852. offline.setGridTrackArmed (3, true);
  25853. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  25854. offline.dispatchPendingMessages();
  25855. ui.resized();
  25856. auto* gridView = ui.getClipGridForSnapshot();
  25857. auto* mixer = gridView != nullptr ? lynx::clipGridMixer (*gridView) : nullptr;
  25858. auto* detail = ui.getDetailViewForSnapshot();
  25859. if (gridView == nullptr || mixer == nullptr || detail == nullptr)
  25860. {
  25861. juce::File (prefix + "-checks.txt").replaceWithText ("FAIL no grid, mixer or detail view\n");
  25862. return;
  25863. }
  25864. // the meters: a level per insert, as a playing song leaves them (offscreen nothing plays), two ticks
  25865. const auto levels = [&] {
  25866. for (int k = 0; k < 2; ++k)
  25867. {
  25868. const float peaks[] { 0.9f, 0.5f, 0.7f, 0.0f, 0.3f, 0.45f, 0.2f, 0.12f };
  25869. for (int i = 0; i < 8; ++i)
  25870. offline.getMeters().accumulate (i, peaks[i], peaks[i] * 0.85f);
  25871. mixer->tick();
  25872. }
  25873. };
  25874. if (auto* runtime = offline.launcherStateForSnapshot())
  25875. {
  25876. runtime->tracks[0].playing.store (1);
  25877. runtime->tracks[0].progress.store (0.3f);
  25878. runtime->tracks[1].playing.store (1);
  25879. runtime->tracks[1].progress.store (0.3f);
  25880. runtime->tracks[4].playing.store (0);
  25881. runtime->tracks[4].progress.store (0.5f);
  25882. runtime->running.store (true);
  25883. }
  25884. levels();
  25885. gridView->resized();
  25886. write (ui, "01-session-mixer");
  25887. write (*gridView, "01b-grid-alone");
  25888. using Part = lynx::SessionMixerComponent::Part;
  25889. check ("mixer: Sends rows are the two buses (Reverb 6, Delay 7)", mixer->sendTargets() == std::vector<int> { 6, 7 });
  25890. check ("mixer: the arm buttons moved into the Volume section", mixer->armsShown());
  25891. check ("mixer: Drums strip has activator, solo, arm, pan, volume", ! mixer->partBounds (0, Part::activator).isEmpty() && ! mixer->partBounds (0, Part::solo).isEmpty()
  25892. && ! mixer->partBounds (0, Part::arm).isEmpty() && ! mixer->partBounds (0, Part::pan).isEmpty()
  25893. && ! mixer->partBounds (0, Part::volume).isEmpty());
  25894. check ("mixer: Vox strip (audio track) has Audio From, its channel, Monitor and Audio To", ! mixer->partBounds (3, Part::inType).isEmpty()
  25895. && ! mixer->partBounds (3, Part::inChannel).isEmpty()
  25896. && ! mixer->partBounds (3, Part::monAuto).isEmpty()
  25897. && ! mixer->partBounds (3, Part::output).isEmpty());
  25898. check ("mixer: Bass strip (instrument) shows MIDI From, no Monitor", mixer->partBounds (1, Part::monIn).isEmpty() && ! mixer->partBounds (1, Part::output).isEmpty());
  25899. check ("mixer: FX strip (no clips) has no activator but an arm", mixer->partBounds (5, Part::activator).isEmpty() && ! mixer->partBounds (5, Part::arm).isEmpty());
  25900. check ("mixer: Main strip has volume and pan, no activator", ! mixer->partBounds (-2, Part::volume).isEmpty() && mixer->partBounds (-2, Part::activator).isEmpty());
  25901. {
  25902. const auto hit = mixer->hitAt (mixer->partBounds (2, Part::solo).getCentre());
  25903. check ("mixer: a click on the Keys' S is its solo", hit.column == 2 && hit.part == Part::solo);
  25904. const auto send = mixer->hitAt (mixer->partBounds (1, Part::send, 1).getCentre());
  25905. check ("mixer: the Bass' second knob is its send to Delay", send.column == 1 && send.part == Part::send && send.row == 1);
  25906. }
  25907. {
  25908. juce::PopupMenu menu;
  25909. mixer->addViewItems (menu);
  25910. saveMenus (juce::StringArray { "Mixer (footer button)" }, std::vector<juce::PopupMenu> { menu }, prefix + "-02-mixer-view-menu.png");
  25911. }
  25912. offline.editSong ([] (lynx::Song& s) { lynx::launcher::ensureGrid (s).mixerView.trackOptions = true; }, false);
  25913. offline.dispatchPendingMessages();
  25914. gridView->resized();
  25915. levels();
  25916. write (*gridView, "03-mixer-track-options");
  25917. offline.editSong ([] (lynx::Song& s) {
  25918. auto& v = lynx::launcher::ensureGrid (s).mixerView;
  25919. v.trackOptions = v.io = v.sends = false;
  25920. }, false);
  25921. offline.dispatchPendingMessages();
  25922. gridView->resized();
  25923. levels();
  25924. write (*gridView, "04-mixer-volume-only");
  25925. offline.editSong ([] (lynx::Song& s) { lynx::launcher::ensureGrid (s).mixerView.shown = false; }, false);
  25926. offline.dispatchPendingMessages();
  25927. gridView->resized();
  25928. write (*gridView, "05-mixer-hidden");
  25929. check ("mixer hidden: the arm buttons are back in the status row", ! mixer->armsShown() && mixer->getHeight() == 0);
  25930. offline.editSong ([] (lynx::Song& s) { lynx::launcher::ensureGrid (s).mixerView = {}; }, false);
  25931. offline.dispatchPendingMessages();
  25932. gridView->resized();
  25933. // the Clip page of the Loop clip (track 4, scene 0) while it plays: Warp on, the Set buttons lit, the title
  25934. detail->showSelection (4, 0);
  25935. detail->setPage (lynx::DetailView::Page::clip);
  25936. offline.editSong ([] (lynx::Song&) {}, false); // (a change message: the Clip panel reads the playing state)
  25937. offline.dispatchPendingMessages();
  25938. write (ui, "06-clip-audio-warp-on");
  25939. // round 190ig (round 190ia CL-20a, the BPM row bug): the Audio box at Live's 190 px, 260 px and 350 px detail
  25940. // heights, in Re-Pitch (no settings rows) and in Beats (three rows: the most a mode shows)
  25941. if (audioChannel >= 0)
  25942. {
  25943. const auto heightBefore = lynx::DetailView::preferredHeight;
  25944. for (const auto beats : { false, true })
  25945. {
  25946. offline.editSong ([audioChannel, beats] (lynx::Song& s) {
  25947. auto& sampler = s.channels[(std::size_t) audioChannel].sampler;
  25948. sampler.keepPitch = beats;
  25949. sampler.stretchMethod = beats ? lynx::StretchMethod::beats : sampler.stretchMethod;
  25950. }, false);
  25951. offline.dispatchPendingMessages();
  25952. for (const auto h : { 190, 260, 350 })
  25953. {
  25954. lynx::DetailView::preferredHeight = h;
  25955. ui.resized();
  25956. if (auto* area = detail->getParentComponent()) // (the Playlist area lays its docked detail view out)
  25957. area->resized();
  25958. offline.dispatchPendingMessages();
  25959. write (ui, (juce::String ("06h-audio-box-") + (beats ? "beats-" : "repitch-") + juce::String (h)).toRawUTF8());
  25960. check ("audio box at " + juce::String (h) + " px: the detail view is that high", detail->getHeight() == h);
  25961. }
  25962. }
  25963. offline.editSong ([audioChannel] (lynx::Song& s) { s.channels[(std::size_t) audioChannel].sampler.keepPitch = false; }, false);
  25964. offline.dispatchPendingMessages();
  25965. lynx::DetailView::preferredHeight = heightBefore;
  25966. ui.resized();
  25967. if (auto* area = detail->getParentComponent())
  25968. area->resized();
  25969. offline.dispatchPendingMessages();
  25970. }
  25971. if (audioChannel >= 0)
  25972. {
  25973. const auto beforeLength = lynx::launcher::clipAt (*offline.getSong().clipGrid, 4, 0)->length;
  25974. offline.editSong ([audioChannel] (lynx::Song& s) { lynx::clipsample::setWarp (s, audioChannel, false, 4.0); });
  25975. offline.dispatchPendingMessages();
  25976. write (ui, "07-clip-audio-warp-off");
  25977. check ("warp off: the channel plays at its own speed", ! lynx::clipsample::isWarped (offline.getSong().channels[(std::size_t) audioChannel].sampler));
  25978. offline.undo();
  25979. offline.dispatchPendingMessages();
  25980. check ("warp: undo gives the clip back as it was", lynx::launcher::clipAt (*offline.getSong().clipGrid, 4, 0)->length == beforeLength
  25981. && lynx::clipsample::isWarped (offline.getSong().channels[(std::size_t) audioChannel].sampler));
  25982. // Set (start) at the play position, half way: one undo step
  25983. const auto clipBefore = *lynx::launcher::clipAt (*offline.getSong().clipGrid, 4, 0);
  25984. offline.editSong ([] (lynx::Song& s) {
  25985. for (auto& c : s.clipGrid->clips)
  25986. if (c.track == 4 && c.gridSlot >= 0 && s.clipGrid->slots[(std::size_t) c.gridSlot].scene == 0)
  25987. lynx::clipsample::setStartAt (c, lynx::clipsample::playPosition (c, 0.5f));
  25988. });
  25989. const auto& after = *lynx::launcher::clipAt (*offline.getSong().clipGrid, 4, 0);
  25990. check ("set start: the clip starts half way and ends where it did", after.offset == clipBefore.offset + clipBefore.length / 2
  25991. && after.offset + after.length == clipBefore.offset + clipBefore.length);
  25992. offline.undo();
  25993. offline.dispatchPendingMessages();
  25994. }
  25995. // a MIDI clip's Clip page too (the Set buttons are there for every clip), playing through a groove of the pool
  25996. offline.editSong ([] (lynx::Song& s) {
  25997. const auto& bank = lynx::groove::factoryBank();
  25998. if (bank.size() > 9)
  25999. lynx::groove::setClipGroove (s, 0, 1, lynx::groove::add (s.grooves, bank[9].groove));
  26000. }, false);
  26001. detail->showSelection (0, 1);
  26002. offline.editSong ([] (lynx::Song&) {}, false);
  26003. offline.dispatchPendingMessages();
  26004. write (ui, "08-clip-midi-set-buttons");
  26005. // the Device View of Bass (insert 2): its compressor dragged onto Keys (insert 3), then Ctrl-dragged onto Vox
  26006. detail->showSelection (1, 0);
  26007. detail->setPage (lynx::DetailView::Page::devices);
  26008. offline.dispatchPendingMessages();
  26009. write (ui, "09-devices-bass-before");
  26010. lynx::setClipGridDeviceDropForSnapshot (*gridView, 2);
  26011. write (ui, "10-device-dragged-over-keys");
  26012. lynx::setClipGridDeviceDropForSnapshot (*gridView, -1);
  26013. int fromId = 0;
  26014. {
  26015. const auto& s = offline.getSong();
  26016. fromId = (int) (s.mixer[2].effects[1].instance.id & 0x7fffffff);
  26017. }
  26018. offline.editSongStructural ([] (lynx::Song& s) { lynx::detailchain::moveEffectToInsert (s, 2, 1, 3, false); });
  26019. offline.dispatchPendingMessages();
  26020. check ("drag to Keys: the compressor moved (same device)", offline.getSong().mixer[2].effects.size() == 2 && offline.getSong().mixer[3].effects.size() == 1
  26021. && (int) (offline.getSong().mixer[3].effects[0].instance.id & 0x7fffffff) == fromId);
  26022. detail->showSelection (2, 1);
  26023. offline.dispatchPendingMessages();
  26024. write (ui, "11-devices-keys-after-move");
  26025. offline.editSongStructural ([] (lynx::Song& s) { lynx::detailchain::moveEffectToInsert (s, 2, 0, 4, true); });
  26026. offline.dispatchPendingMessages();
  26027. check ("Ctrl-drag to Vox: a copy of the EQ after its reverb, Bass keeps its own", offline.getSong().mixer[4].effects.size() == 2
  26028. && offline.getSong().mixer[4].effects[1].kind == lynx::EffectKind::eq
  26029. && offline.getSong().mixer[2].effects[0].kind == lynx::EffectKind::eq);
  26030. offline.undo();
  26031. offline.undo();
  26032. offline.dispatchPendingMessages();
  26033. check ("undo twice: Bass has its three devices again, Keys none", offline.getSong().mixer[2].effects.size() == 3 && offline.getSong().mixer[3].effects.empty()
  26034. && offline.getSong().mixer[4].effects.size() == 1);
  26035. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  26036. wav.deleteFile();
  26037. }
  26038. void runWarpShot (const juce::String& prefix)
  26039. {
  26040. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  26041. lynx::AudioEngine offline (false);
  26042. lynx::MainComponent ui (offline, false);
  26043. ui.setSize (1600, 900);
  26044. const auto write = [&prefix] (juce::Component& c, const char* name) {
  26045. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  26046. file.deleteFile();
  26047. juce::FileOutputStream out (file);
  26048. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (c), out);
  26049. };
  26050. // a two-bar loop of clicks, a little off the grid (what Quantize is for)
  26051. const auto wav = juce::File (prefix + "-loop.wav");
  26052. wav.deleteFile();
  26053. {
  26054. const double rate = 44100.0;
  26055. juce::AudioBuffer<float> buffer (1, (int) (rate * 4.0));
  26056. buffer.clear();
  26057. for (int hit = 0; hit < 8; ++hit)
  26058. {
  26059. const auto at = (int) ((hit * 0.5 + (hit % 3) * 0.035) * rate);
  26060. for (int k = 0; k < 4000 && at + k < buffer.getNumSamples(); ++k)
  26061. buffer.setSample (0, at + k, (float) (std::sin (k * (hit % 2 ? 0.25 : 0.06)) * std::exp (-k / 700.0) * 0.8));
  26062. }
  26063. if (auto out = std::unique_ptr<juce::FileOutputStream> (wav.createOutputStream()))
  26064. if (auto* writer = juce::WavAudioFormat().createWriterFor (out.get(), rate, 1, 16, {}, 0))
  26065. {
  26066. out.release();
  26067. std::unique_ptr<juce::AudioFormatWriter> owned (writer);
  26068. owned->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
  26069. }
  26070. }
  26071. ui.setVisible (true);
  26072. lynx::DetailView::shownSetting = true;
  26073. ui.selectTabForSnapshot (2);
  26074. ui.setLayoutStyle (lynx::layoutstyle::Style::clipLaunch);
  26075. lynx::autolanes::setShown (true);
  26076. ui.getPlaylistForSnapshot().addAudioClipAtPlayhead (wav);
  26077. offline.dispatchPendingMessages();
  26078. int channel = -1;
  26079. offline.editSong ([&channel] (lynx::Song& s) {
  26080. if (s.playlist.empty())
  26081. return;
  26082. auto audio = s.playlist.front();
  26083. channel = audio.channel;
  26084. audio.track = 1;
  26085. s.playlist.front() = audio;
  26086. for (int k = 1; k < 3; ++k)
  26087. {
  26088. auto more = audio;
  26089. more.start = audio.start + k * 8 * lynx::ppq;
  26090. s.playlist.push_back (more);
  26091. }
  26092. while (s.patterns.size() < 1)
  26093. s.patterns.emplace_back();
  26094. for (int t = 2; t < 5; ++t)
  26095. for (int k = 0; k < 4; ++k)
  26096. {
  26097. lynx::Clip c;
  26098. c.pattern = 0;
  26099. c.track = t;
  26100. c.start = k * 4 * lynx::ppq;
  26101. c.length = 4 * lynx::ppq;
  26102. s.playlist.push_back (c);
  26103. }
  26104. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 6));
  26105. s.playlistTracks[1].name = "Loop";
  26106. s.playlistTracks[2].name = "Drums";
  26107. s.playlistTracks[3].name = "Kick";
  26108. s.playlistTracks[4].name = "Hats";
  26109. s.playlistTracks[4].folded = true;
  26110. lynx::noteedit::groupWithAbove (s, 3);
  26111. lynx::noteedit::groupWithAbove (s, 4);
  26112. lynx::arrange::makeGroupBus (s, 3);
  26113. lynx::autolanes::addLane (s, 1, { lynx::AutomationTargetKind::tempo, 0, 0, 0 }, "Tempo", lynx::valueFromTempo (s.bpm));
  26114. if (! s.automations.empty())
  26115. s.automations.back().points = { { 0, lynx::valueFromTempo (120.0), 0.0f }, { 8 * lynx::ppq, lynx::valueFromTempo (120.0), 0.0f },
  26116. { 12 * lynx::ppq, lynx::valueFromTempo (180.0), 0.0f }, { 16 * lynx::ppq, lynx::valueFromTempo (140.0), 0.0f } };
  26117. s.addMarker ({ 4 * lynx::ppq, "Verse", 0, 0 });
  26118. s.addMarker ({ 8 * lynx::ppq, {}, 3, 4 });
  26119. s.addMarker ({ 14 * lynx::ppq, {}, 4, 4 });
  26120. s.loopStart = 4 * lynx::ppq;
  26121. s.loopEnd = 12 * lynx::ppq;
  26122. s.loopOff = true;
  26123. s.tempoViewLow = 60.0; // the tempo lane's range
  26124. s.tempoViewHigh = 200.0;
  26125. std::stable_sort (s.playlist.begin(), s.playlist.end(), [] (const lynx::Clip& a, const lynx::Clip& b) { return a.start < b.start; });
  26126. // the same audio in the clip grid, for the Clip page
  26127. lynx::Clip slot = audio;
  26128. slot.start = 0;
  26129. slot.pitch = -2.25f;
  26130. slot.gain = 0.7f;
  26131. lynx::launcher::setClip (s, 1, 0, slot);
  26132. // a few warp markers, as Quantize leaves them
  26133. if (channel >= 0 && channel < (int) s.channels.size())
  26134. {
  26135. auto& sampler = s.channels[(std::size_t) channel].sampler;
  26136. lynx::warpedit::ensureMarkers (sampler, 4.0, s.bpm);
  26137. std::vector<double> attacks;
  26138. for (int hit = 1; hit < 8; ++hit)
  26139. attacks.push_back (hit * 0.5 + (hit % 3) * 0.035);
  26140. lynx::warptools::quantize (sampler, attacks, 0.0, 4.0, 0.5, 1.0);
  26141. lynx::warpedit::syncLength (sampler, 4.0);
  26142. }
  26143. }, false);
  26144. offline.dispatchPendingMessages();
  26145. ui.resized();
  26146. write (ui, "arrangement-loop-off");
  26147. offline.editSong ([] (lynx::Song& s) { s.loopOff = false; }, false);
  26148. offline.dispatchPendingMessages();
  26149. write (ui, "arrangement-loop-on");
  26150. juce::String facts;
  26151. {
  26152. const auto& s = offline.getSong();
  26153. facts << "channel " << channel << ", warp markers " << (channel >= 0 ? (int) s.channels[(std::size_t) channel].sampler.warp.size() : -1)
  26154. << ", group bus insert " << lynx::arrange::groupBus (s, 3) << ", folded track 4: " << (lynx::arrange::isFolded (s, 4) ? 1 : 0) << "\n";
  26155. }
  26156. if (auto* detail = ui.getDetailViewForSnapshot())
  26157. {
  26158. detail->showSelection (1, 0);
  26159. detail->setPage (lynx::DetailView::Page::clip);
  26160. offline.dispatchPendingMessages();
  26161. write (ui, "clip-audio");
  26162. }
  26163. if (channel >= 0)
  26164. if (auto editor = lynx::makeAudioEditorPanel (offline, channel, 0, true))
  26165. {
  26166. editor->setSize (1120, 600);
  26167. write (*editor, "audio-editor-warp");
  26168. // round 190cy (Live 12.4.16 live check 190cw shot 09): a plain drag of marker 3 holds it two sixteenths
  26169. // later (its audio goes there); Shift + drag slides the audio under it. Round 190db: the Clip-launch
  26170. // workflow draws the warped clip in beats, so the held drag shows the audio stretched around the marker
  26171. // (plain) or slid under it, its attack later (Shift, to the right as in Live's shot)
  26172. const auto& w = offline.getSong().channels[(std::size_t) channel].sampler.warp;
  26173. if (w.size() > 4)
  26174. {
  26175. lynx::holdAudioEditorWarpDragForSnapshot (*editor, 3, w[3].beats + 0.5, false);
  26176. write (*editor, "audio-editor-drag-stretch");
  26177. lynx::holdAudioEditorWarpDragForSnapshot (*editor, 3, w[3].seconds - 0.12, true);
  26178. write (*editor, "audio-editor-drag-slide");
  26179. }
  26180. // the same clip in file time (the Pattern workflow's view, or "Show the audio in beats" off)
  26181. if (auto inFileTime = lynx::makeAudioEditorPanel (offline, channel, 0, true))
  26182. {
  26183. inFileTime->setSize (1120, 600);
  26184. lynx::setAudioEditorBeatTimeForSnapshot (*inFileTime, 0);
  26185. write (*inFileTime, "audio-editor-file-time");
  26186. if (w.size() > 4)
  26187. {
  26188. lynx::holdAudioEditorWarpDragForSnapshot (*inFileTime, 3, w[3].beats + 0.5, false);
  26189. write (*inFileTime, "audio-editor-file-time-drag");
  26190. }
  26191. }
  26192. }
  26193. // round 190cy (Live 12.4.16 live check 190cw shot 02): ÷2 from the editor of the first Playlist clip halves that
  26194. // clip's length with the markers' beats; ÷2 on the grid clip's Clip page halves the grid clip
  26195. {
  26196. const auto lengthOf = [&offline] (int index) { return index < (int) offline.getSong().playlist.size() ? offline.getSong().playlist[(std::size_t) index].length : -1; };
  26197. const auto gridLength = [&offline] {
  26198. const auto& s = offline.getSong();
  26199. const auto* c = s.clipGrid ? lynx::launcher::clipAt (*s.clipGrid, 1, 0) : nullptr;
  26200. return c != nullptr ? c->length : (std::int64_t) -1;
  26201. };
  26202. const auto first = [&offline] {
  26203. const auto& s = offline.getSong();
  26204. for (int i = 0; i < (int) s.playlist.size(); ++i)
  26205. if (s.playlist[(std::size_t) i].kind == lynx::ClipKind::audio)
  26206. return i;
  26207. return -1;
  26208. }();
  26209. facts << "halve: playlist clip " << first << " length " << lengthOf (first);
  26210. if (first >= 0)
  26211. if (auto editor = lynx::makeAudioEditorPanel (offline, offline.getSong().playlist[(std::size_t) first].channel, first, true))
  26212. {
  26213. lynx::scaleAudioEditorTempoForSnapshot (*editor, 0.5);
  26214. offline.dispatchPendingMessages();
  26215. }
  26216. facts << " -> " << lengthOf (first) << "; grid clip length " << gridLength();
  26217. if (channel >= 0)
  26218. if (auto editor = lynx::makeAudioEditorPanel (offline, channel, -1, true))
  26219. {
  26220. lynx::setAudioEditorGridClip (*editor, 1, 0);
  26221. lynx::scaleAudioEditorTempoForSnapshot (*editor, 0.5);
  26222. offline.dispatchPendingMessages();
  26223. }
  26224. facts << " -> " << gridLength() << "\n";
  26225. ui.resized();
  26226. write (ui, "arrangement-halved");
  26227. // Duplicate Time over beats 4-8 holding the locator "Verse" (beat 4): a second "Verse" at beat 8
  26228. offline.editSong ([] (lynx::Song& s) { lynx::arrange::duplicateTime (s, 4 * lynx::ppq, 8 * lynx::ppq); });
  26229. offline.dispatchPendingMessages();
  26230. int verses = 0;
  26231. for (const auto& m : offline.getSong().markers())
  26232. verses += m.name == "Verse" ? 1 : 0;
  26233. facts << "duplicate time: locators named Verse " << verses << "\n";
  26234. write (ui, "arrangement-duplicated-time");
  26235. }
  26236. juce::File (prefix + "-facts.txt").replaceWithText (facts);
  26237. lynx::autolanes::setShown (false);
  26238. }
  26239. void runMtShot190fm (const juce::String& prefix)
  26240. {
  26241. lynx::AudioEngine offline (false);
  26242. offline.editSong ([] (lynx::Song& s) {
  26243. if (s.patterns.empty())
  26244. s.patterns.emplace_back();
  26245. s.patterns[0].notes.clear();
  26246. s.patterns[0].lengthTicks = 4 * lynx::ppq;
  26247. s.currentPattern = 0;
  26248. }, false);
  26249. lynx::MidiToolsPanel panel (offline, [] {
  26250. lynx::MidiToolsPanel::Target t;
  26251. t.pattern = 0;
  26252. t.grid = lynx::ppq / 4;
  26253. t.channel = 0;
  26254. t.length = 4 * lynx::ppq; // one bar, no time selection
  26255. return t;
  26256. });
  26257. panel.setSize (lynx::MidiToolsPanel::panelWidth, lynx::MidiToolsPanel::panelHeight);
  26258. panel.setSection (lynx::MidiToolsPanel::generateSection);
  26259. panel.setGenerateShotSettingsForSnapshot();
  26260. const auto write = [&prefix] (const juce::Image& image, const juce::String& name) {
  26261. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  26262. file.deleteFile();
  26263. juce::FileOutputStream out (file);
  26264. juce::PNGImageFormat().writeImageToStream (image, out);
  26265. };
  26266. std::vector<juce::Image> images;
  26267. juce::String checks;
  26268. for (int g = 0; g < lynx::midigen::Settings::toolCount; ++g)
  26269. {
  26270. panel.setGenerator (g);
  26271. const auto name = juce::String (lynx::midigen::toolName (g)).toLowerCase();
  26272. images.push_back (lynx::shot::paint (panel, lynx::theme::colour::bg2));
  26273. write (images.back(), "generate-" + name);
  26274. panel.generateNow();
  26275. offline.dispatchPendingMessages();
  26276. const auto made = (int) offline.getSong().patterns[0].notes.size();
  26277. offline.undo();
  26278. offline.dispatchPendingMessages();
  26279. const auto after = (int) offline.getSong().patterns[0].notes.size();
  26280. checks << name << ": generated " << made << " notes, after undo " << after << (made > 0 && after == 0 ? " OK" : " FAIL") << "\n";
  26281. }
  26282. // the five side by side (6 px apart, on the window's background)
  26283. const auto gap = juce::roundToInt (6.0f * lynx::shot::scale());
  26284. int width = gap, height = 0;
  26285. for (const auto& image : images)
  26286. {
  26287. width += image.getWidth() + gap;
  26288. height = std::max (height, image.getHeight());
  26289. }
  26290. juce::Image strip (juce::Image::RGB, width, height + 2 * gap, true);
  26291. {
  26292. juce::Graphics g (strip);
  26293. g.fillAll (lynx::theme::colour::bg0);
  26294. int x = gap;
  26295. for (const auto& image : images)
  26296. {
  26297. g.drawImageAt (image, x, gap);
  26298. x += image.getWidth() + gap;
  26299. }
  26300. }
  26301. write (strip, "generate-panels");
  26302. checks << "settings saved with the project: " << (offline.getSong().midiGenerate.stacksOptions.sequence.size() == 2 ? "OK" : "FAIL") << "\n";
  26303. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  26304. }
  26305. // Round 190hy: see --mpeshot190hy
  26306. void runMpeShot190hy (const juce::String& prefix)
  26307. {
  26308. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  26309. lynx::AudioEngine offline (false);
  26310. lynx::MainComponent ui (offline, false);
  26311. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  26312. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  26313. const auto write = [&prefix, &ui] (const char* name) {
  26314. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  26315. file.deleteFile();
  26316. juce::FileOutputStream out (file);
  26317. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (ui), out);
  26318. };
  26319. ui.setVisible (true); // (not on the desktop: only so the Clip page sees itself shown and docks the Piano roll)
  26320. offline.editSong ([] (lynx::Song& s) {
  26321. if (s.channels.empty())
  26322. s.channels.resize (1);
  26323. s.channels[0].name = "MPE lead";
  26324. s.channels[0].mixerTrack = 1;
  26325. if (s.mixer.size() < 2)
  26326. s.mixer.resize (2);
  26327. while (s.patterns.empty())
  26328. s.patterns.emplace_back();
  26329. auto& p = s.patterns[0];
  26330. p.name = "MPE take";
  26331. p.notes.clear();
  26332. // four notes as an MPE controller plays them: a slide up an octave, a vibrato, a fall, a held chord tone
  26333. const auto note = [&p] (std::int64_t start, std::int64_t length, int key, lynx::NoteCurves c, float modX = 0.5f) {
  26334. lynx::Note n;
  26335. n.channel = 0;
  26336. n.start = start;
  26337. n.length = length;
  26338. n.key = key;
  26339. n.modX = modX;
  26340. n.curves = std::move (c);
  26341. p.notes.push_back (n);
  26342. };
  26343. const auto beat = (float) lynx::ppq;
  26344. lynx::NoteCurves glide;
  26345. glide.lane (lynx::NoteCurveLane::pitch) = { { 0.0f, 0.0f }, { beat * 0.5f, 0.0f }, { beat * 1.5f, 1200.0f }, { beat * 2.0f, 1200.0f } };
  26346. glide.lane (lynx::NoteCurveLane::timbre) = { { 0.0f, 0.3f }, { beat * 2.0f, 0.85f } };
  26347. glide.lane (lynx::NoteCurveLane::pressure) = { { 0.0f, 0.2f }, { beat * 0.4f, 0.9f }, { beat * 1.6f, 0.7f }, { beat * 2.0f, 0.0f } };
  26348. note (0, 2 * lynx::ppq, 60, glide, 0.3f);
  26349. lynx::NoteCurves vibrato;
  26350. for (int k = 0; k <= 24; ++k)
  26351. vibrato.lane (lynx::NoteCurveLane::pitch).push_back ({ beat * 0.0833f * (float) k, k < 4 ? 0.0f : 40.0f * std::sin ((float) k * 1.5708f) });
  26352. vibrato.lane (lynx::NoteCurveLane::pressure) = { { 0.0f, 0.5f }, { beat * 1.0f, 0.95f }, { beat * 2.0f, 0.4f } };
  26353. note (2 * lynx::ppq, 2 * lynx::ppq, 67, vibrato);
  26354. lynx::NoteCurves fall;
  26355. fall.lane (lynx::NoteCurveLane::pitch) = { { 0.0f, 0.0f }, { beat * 0.75f, 0.0f }, { beat * 1.0f, -500.0f } };
  26356. fall.lane (lynx::NoteCurveLane::timbre) = { { 0.0f, 0.6f }, { beat * 1.0f, 0.2f } };
  26357. note (4 * lynx::ppq, lynx::ppq, 72, fall, 0.6f);
  26358. note (5 * lynx::ppq, 3 * lynx::ppq, 64, {}); // (a note without curves: its own values, dashed)
  26359. p.lengthTicks = 8 * lynx::ppq;
  26360. }, false);
  26361. offline.dispatchPendingMessages();
  26362. juce::String checks;
  26363. auto& roll = ui.getPianoRollForSnapshot();
  26364. ui.selectTabForSnapshot (1);
  26365. roll.selectMidiToolResult ({ 0 });
  26366. roll.scrollToNotes();
  26367. for (const auto& [lane, name] : { std::pair { lynx::PianoRollComponent::laneMpePitch, "pitch" },
  26368. { lynx::PianoRollComponent::laneMpeSlide, "slide" },
  26369. { lynx::PianoRollComponent::laneMpePressure, "pressure" } })
  26370. {
  26371. roll.setLaneForSnapshot (lane);
  26372. offline.dispatchPendingMessages();
  26373. write (name);
  26374. checks << "lane " << name << ": areas " << (int) roll.mpeLaneAreasForTests().size() << "\n";
  26375. }
  26376. roll.setLaneForSnapshot (lynx::PianoRollComponent::laneVelocity);
  26377. int curved = 0;
  26378. for (const auto& n : offline.getSong().patterns[0].notes)
  26379. curved += n.curves.has() ? 1 : 0;
  26380. checks << "notes with curves: " << curved << " of " << (int) offline.getSong().patterns[0].notes.size() << "\n";
  26381. // the Clip-launch layout: the clip's Notes tab, then its MPE tab (Live 11+'s note expression lanes)
  26382. ui.selectTabForSnapshot (2);
  26383. lynx::DetailView::shownSetting = true;
  26384. lynx::DetailView::devicesPage = false;
  26385. ui.setClipLaunchWorkflow (true);
  26386. offline.editSong ([] (lynx::Song& s) {
  26387. lynx::Clip clip;
  26388. clip.pattern = 0;
  26389. clip.length = 8 * lynx::ppq;
  26390. lynx::launcher::setClip (s, 0, 0, clip);
  26391. }, false);
  26392. offline.dispatchPendingMessages();
  26393. if (auto* detail = ui.getDetailViewForSnapshot())
  26394. {
  26395. detail->showSelection (0, 0);
  26396. detail->setPage (lynx::DetailView::Page::clip);
  26397. detail->setClipTab (false);
  26398. offline.dispatchPendingMessages();
  26399. roll.scrollToNotes();
  26400. write ("clip-notes");
  26401. checks << "clip notes tab: mpe view " << (roll.isMpeView() ? 1 : 0) << "\n";
  26402. detail->setMpeTab();
  26403. offline.dispatchPendingMessages();
  26404. roll.selectMidiToolResult ({ 0 });
  26405. roll.scrollToNotes();
  26406. write ("clip-mpe");
  26407. checks << "clip MPE tab: mpe view " << (roll.isMpeView() ? 1 : 0) << ", lanes " << (int) roll.mpeLaneAreasForTests().size() << "\n";
  26408. detail->setClipTab (false);
  26409. offline.dispatchPendingMessages();
  26410. checks << "back to Notes: mpe view " << (roll.isMpeView() ? 1 : 0) << "\n";
  26411. }
  26412. else
  26413. checks << "no detail view\n";
  26414. lynx::shot::file (juce::File (prefix + "-checks.txt")).replaceWithText (checks);
  26415. }
  26416. void runDetailShot (const juce::String& prefix)
  26417. {
  26418. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  26419. lynx::AudioEngine offline (false);
  26420. lynx::MainComponent ui (offline, false);
  26421. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  26422. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  26423. const auto write = [&prefix, &ui] (const char* name) {
  26424. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  26425. file.deleteFile();
  26426. juce::FileOutputStream out (file);
  26427. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (ui), out);
  26428. };
  26429. ui.setVisible (true); // (not on the desktop: only so the Clip page sees itself shown and docks the Piano roll)
  26430. lynx::DetailView::shownSetting = lynx::DetailView::devicesPage = true;
  26431. ui.selectTabForSnapshot (2); // the Playlist panel, maximized
  26432. offline.editSong ([] (lynx::Song& s) {
  26433. if (s.channels.size() < 2)
  26434. s.channels.resize (2);
  26435. s.channels[0].name = "Bass synth";
  26436. s.channels[0].mixerTrack = 2;
  26437. s.channels[1].mixerTrack = 3;
  26438. if (s.mixer.size() < 4)
  26439. s.mixer.resize (4);
  26440. s.mixer[2].name = "Bass";
  26441. s.mixer[2].effects.clear();
  26442. for (auto kind : { lynx::EffectKind::eq, lynx::EffectKind::compressor, lynx::EffectKind::reverb, lynx::EffectKind::delay })
  26443. {
  26444. lynx::EffectSlot fx;
  26445. fx.kind = kind;
  26446. const auto& info = lynx::effectInfo (kind);
  26447. for (std::size_t k = 0; k < info.params.size() && k < fx.params.size(); ++k)
  26448. fx.params[k] = info.params[k].defaultValue;
  26449. fx.enabled = kind != lynx::EffectKind::compressor; // one switched off
  26450. s.mixer[2].effects.push_back (fx);
  26451. }
  26452. while (s.patterns.size() < 2)
  26453. s.patterns.emplace_back();
  26454. s.patterns[0].name = "Bass line";
  26455. s.patterns[0].notes.clear();
  26456. for (int n = 0; n < 4; ++n)
  26457. {
  26458. lynx::Note note;
  26459. note.channel = 0;
  26460. note.start = n * lynx::ppq;
  26461. note.key = 36 + (n % 2) * 7;
  26462. s.patterns[0].notes.push_back (note);
  26463. }
  26464. s.patterns[0].lengthTicks = 4 * lynx::ppq;
  26465. lynx::PatternEvents lane; // a volume swell for the Envelopes tab (slice 3)
  26466. lane.target = lynx::AutomationTarget { lynx::AutomationTargetKind::channelVolume, 0 };
  26467. for (int e = 0; e < 16; ++e)
  26468. lane.events.push_back ({ e * lynx::ppq / 4, 0.3f + 0.6f * (float) e / 15.0f });
  26469. s.patterns[0].events = { lane };
  26470. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 3));
  26471. s.playlistTracks[1].name = "Bass";
  26472. }, false);
  26473. offline.dispatchPendingMessages();
  26474. write ("pattern"); // Pattern workflow: no detail view exists
  26475. ui.setClipLaunchWorkflow (true);
  26476. offline.editSong ([] (lynx::Song& s) {
  26477. lynx::Clip clip;
  26478. clip.pattern = 0;
  26479. clip.length = 4 * lynx::ppq;
  26480. lynx::launcher::setClip (s, 1, 0, clip);
  26481. }, false);
  26482. offline.dispatchPendingMessages();
  26483. juce::String counts;
  26484. if (auto* detail = ui.getDetailViewForSnapshot())
  26485. {
  26486. detail->showSelection (1, 0);
  26487. detail->setPage (lynx::DetailView::Page::devices);
  26488. write ("devices");
  26489. counts << "cards " << detail->cardCountForCheck() << ", insert " << detail->chainInsertForCheck() << ", channel " << detail->chainChannelForCheck() << "\n";
  26490. detail->toggleFoldForCheck (3); // the reverb (card 0 is the instrument)
  26491. write ("folded");
  26492. counts << "folded card 3: " << (detail->isFoldedForCheck (3) ? 1 : 0) << "\n";
  26493. detail->showSelection (2, 0); // an empty track
  26494. write ("empty-track");
  26495. detail->showSelection (1, 0);
  26496. detail->setPage (lynx::DetailView::Page::clip);
  26497. offline.dispatchPendingMessages();
  26498. ui.getPianoRollForSnapshot().scrollToNotes(); // (the app does it on the message loop, which this shot doesn't run)
  26499. write ("clip"); // slice 2: the Piano roll docked here
  26500. {
  26501. // round 190s: the Transform panel with each MIDI tool, then Arpeggiate applied (and undone again)
  26502. auto& tools = detail->midiToolsForSnapshot();
  26503. for (int t = 0; t < lynx::MidiToolsPanel::toolCount; ++t)
  26504. {
  26505. tools.setTool (t);
  26506. write (("clip-mt-" + juce::String (lynx::MidiToolsPanel::toolName (t)).toLowerCase()).toRawUTF8());
  26507. }
  26508. // round 190aa: the pages again with the settings of the Live shots they are compared with
  26509. tools.setAuto (false);
  26510. tools.setLiveShotSettingsForSnapshot();
  26511. for (int t : { (int) lynx::MidiToolsPanel::chop, (int) lynx::MidiToolsPanel::quantize, (int) lynx::MidiToolsPanel::timeWarp })
  26512. {
  26513. tools.setTool (t);
  26514. write (("clip-mt-" + juce::String (lynx::MidiToolsPanel::toolName (t)).toLowerCase() + "-set").toRawUTF8());
  26515. }
  26516. tools.setAuto (true);
  26517. tools.setTool (lynx::MidiToolsPanel::arpeggiate);
  26518. tools.transformNow();
  26519. offline.dispatchPendingMessages();
  26520. write ("clip-mt-applied");
  26521. counts << "midi tools: arpeggiate made " << (int) offline.getSong().patterns[0].notes.size() << " notes of 4\n";
  26522. offline.undo();
  26523. offline.dispatchPendingMessages();
  26524. counts << "midi tools: undo gives " << (int) offline.getSong().patterns[0].notes.size() << " notes\n";
  26525. }
  26526. counts << "piano roll docked: " << (ui.getPianoRollForSnapshot().getParentComponent() != nullptr
  26527. && ui.getPianoRollForSnapshot().getParentComponent()->getParentComponent() == detail ? 1 : 0) << "\n";
  26528. detail->setClipTab (true); // slice 3: the pattern's events in the Envelopes tab
  26529. offline.dispatchPendingMessages();
  26530. write ("envelopes");
  26531. detail->setClipTab (false);
  26532. detail->setPage (lynx::DetailView::Page::devices);
  26533. // round 183c-card: an Audio Effect Rack in the chain draws as its own card (the rack's view, Rand / Map in its
  26534. // title bar), as Live's Device View shows a rack
  26535. offline.editSong ([] (lynx::Song& s) { s.mixer[2].effects.insert (s.mixer[2].effects.begin() + 1, shotRack()); }, false);
  26536. offline.dispatchPendingMessages();
  26537. detail->showSelection (2, 0);
  26538. detail->showSelection (1, 0);
  26539. write ("devices-rack");
  26540. counts << "rack card: cards " << detail->cardCountForCheck() << "\n";
  26541. offline.editSong ([] (lynx::Song& s) { s.mixer[2].effects.erase (s.mixer[2].effects.begin() + 1); }, false);
  26542. offline.dispatchPendingMessages();
  26543. counts << "piano roll back in its panel: " << (ui.getPianoRollForSnapshot().getParentComponent() != nullptr
  26544. && ui.getPianoRollForSnapshot().getParentComponent()->getParentComponent() != detail ? 1 : 0) << "\n";
  26545. }
  26546. else
  26547. counts << "no detail view\n";
  26548. ui.setClipLaunchWorkflow (false);
  26549. offline.dispatchPendingMessages();
  26550. write ("pattern-after");
  26551. juce::File (prefix + "-counts.txt").replaceWithText (counts);
  26552. }
  26553. void runPerfShot (const juce::String& prefix, const juce::String& projectPath)
  26554. {
  26555. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  26556. lynx::AudioEngine offline (false);
  26557. {
  26558. lynx::MainComponent ui (offline, false);
  26559. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  26560. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  26561. if (projectPath.isNotEmpty())
  26562. ui.openFile (juce::File (projectPath));
  26563. offline.dispatchPendingMessages();
  26564. // LYNX_PERFSHOT_PREPARE=1: Tools › Macros › Prepare for performance mode first (16 one-bar columns)
  26565. if (juce::SystemStats::getEnvironmentVariable ("LYNX_PERFSHOT_PREPARE", {}) == "1")
  26566. offline.editSong ([] (lynx::Song& s) { lynx::perf::prepareForPerformance (s, 16, 4 * lynx::ppq); }, false);
  26567. offline.editSong ([] (lynx::Song& s) { s.performanceMode = true; s.mode = lynx::PlayMode::song; }, false);
  26568. offline.dispatchPendingMessages();
  26569. // what the Player would publish: on each of the first tracks with zone clips, one clip playing (part way)
  26570. // and on every other one the next clip waiting for its sync point
  26571. const auto& song = offline.getSong();
  26572. auto& live = offline.performanceStateForSnapshot();
  26573. const auto zone = lynx::perf::zoneClips (song);
  26574. int lastTrack = -1, launched = 0;
  26575. for (const auto index : zone)
  26576. {
  26577. const auto& c = song.playlist[(std::size_t) index];
  26578. if (c.track == lastTrack || c.track >= lynx::perf::maxTracks)
  26579. continue;
  26580. lastTrack = c.track;
  26581. std::int64_t clips[64];
  26582. const auto n = lynx::perf::trackZoneClips (song, zone, c.track, clips, 64);
  26583. auto& view = live.tracks[(std::size_t) c.track];
  26584. view.playing.store (clips[(std::size_t) ((launched % 3) % n)]);
  26585. view.progress.store (0.2f + 0.15f * (float) (launched % 5));
  26586. if (launched % 2 == 1 && n > 1)
  26587. view.pending.store (clips[(std::size_t) ((launched % 3 + 1) % n)]);
  26588. ++launched;
  26589. }
  26590. live.anyPlaying.store (launched > 0);
  26591. ui.selectTabForSnapshot (2);
  26592. offline.dispatchPendingMessages();
  26593. auto& playlist = ui.getPlaylistForSnapshot();
  26594. savePng (lynx::shot::snapshot (playlist), prefix + "-playlist-song.png");
  26595. playlist.runAction ("playlist.zoomPerformance"); // as FL opens these demos: the zone fills the view
  26596. offline.dispatchPendingMessages();
  26597. saveSnapshot (ui, prefix + "-playlist.png");
  26598. savePng (lynx::shot::snapshot (playlist), prefix + "-playlist-only.png");
  26599. // patcherize: the first insert with effects (all of them) and the first channel that can be
  26600. auto patched = offline.getSong();
  26601. for (int t = 0; t < (int) patched.mixer.size(); ++t)
  26602. if (lynx::patcherize::slotsForAll (patched, t).size() > 1)
  26603. {
  26604. lynx::patcherize::patcherizeSlots (patched, t, 0, true);
  26605. break;
  26606. }
  26607. for (int c = 0; c < (int) patched.channels.size(); ++c)
  26608. if (lynx::patcherize::patcherizeChannel (patched, c))
  26609. break;
  26610. juce::String error;
  26611. lynx::ProjectFile::save (patched, juce::File (prefix + "-patcherized.lynx"), error);
  26612. }
  26613. }
  26614. void runPatcherShot (const juce::String& prefix, const juce::String& projectPath)
  26615. {
  26616. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  26617. lynx::AudioEngine offline (false);
  26618. {
  26619. lynx::MainComponent ui (offline, false);
  26620. ui.setSize (1280, 720);
  26621. if (projectPath.isNotEmpty())
  26622. ui.openFile (juce::File (projectPath));
  26623. else
  26624. {
  26625. auto song = lynx::Song::makeDefault();
  26626. song.mixer.resize (4);
  26627. auto slot = lynx::makeEffectSlot (lynx::EffectKind::patcher);
  26628. slot.patcher.wires.clear();
  26629. for (auto [kind, x, y] : { std::tuple { lynx::EffectKind::frequencySplitter, 200.0f, 60.0f }, { lynx::EffectKind::reverb, 420.0f, 0.0f },
  26630. { lynx::EffectKind::fruityDelay3, 420.0f, 120.0f }, { lynx::EffectKind::peakController, 200.0f, 260.0f } })
  26631. {
  26632. lynx::PatchNode n;
  26633. n.effect = lynx::makeEffectSlot (kind);
  26634. n.x = x;
  26635. n.y = y;
  26636. slot.patcher.nodes.push_back (n);
  26637. }
  26638. { // round 165c: a Hardware Insert node (its editor opens from the node)
  26639. lynx::PatchNode n;
  26640. n.effect = lynx::makeEffectSlot (lynx::EffectKind::hardwareInsert);
  26641. n.x = 420.0f, n.y = 260.0f;
  26642. slot.patcher.nodes.push_back (n);
  26643. }
  26644. auto wire = [&] (int from, int fromPort, int to, int toPort, float gain = 1.0f, lynx::PatchWire::Kind kind = lynx::PatchWire::Kind::audio) {
  26645. lynx::PatchWire w;
  26646. w.kind = kind;
  26647. w.from = from, w.fromPort = fromPort, w.to = to, w.toPort = toPort, w.gain = gain;
  26648. slot.patcher.wires.push_back (w);
  26649. };
  26650. wire (lynx::patchFromHost, 0, 0, 0);
  26651. wire (0, 1, 1, 0);
  26652. wire (0, 3, 2, 0, 0.5f);
  26653. wire (1, 0, lynx::patchToHost, 0);
  26654. wire (2, 0, lynx::patchToHost, 0);
  26655. wire (lynx::patchFromHost, 1, 3, 0);
  26656. wire (3, 1, 2, 2, 1.0f, lynx::PatchWire::Kind::control);
  26657. wire (0, 2, lynx::patchToHost, 1, 0.7f);
  26658. // round 171b (issue #65): a Surface knob on the reverb's parameter input 1, the reverb's parameter 0 out to
  26659. // the delay's parameter input 2 (FL's Inputs / Outputs › Parameters)
  26660. {
  26661. lynx::SurfaceControl knob;
  26662. knob.name = "Knob 1";
  26663. knob.value = 0.6f;
  26664. slot.patcher.surface = { knob };
  26665. slot.patcher.surfaceX = 200.0f, slot.patcher.surfaceY = 380.0f;
  26666. lynx::patcher::setParamInput (slot.patcher, 1, 1, true, "Reverb - 2");
  26667. lynx::patcher::setParamOutput (slot.patcher, 1, 0, true);
  26668. lynx::patcher::setParamInput (slot.patcher, 2, 2, true, "Delay - 3");
  26669. wire (lynx::patchSurface, 0, 1, 1, 1.0f, lynx::PatchWire::Kind::control);
  26670. wire (1, lynx::patchParamOutput (0), 2, 2, 1.0f, lynx::PatchWire::Kind::control);
  26671. }
  26672. slot.patcher.outputTracks = { 3 };
  26673. slot.patcher.inputX = -20.0f;
  26674. slot.patcher.outputX = 660.0f;
  26675. song.mixer[1].effects = { slot };
  26676. lynx::ChannelDef ch;
  26677. ch.name = "Patcher";
  26678. ch.instrument = lynx::InstrumentKind::patcher;
  26679. lynx::PatchNode synth, chorus;
  26680. synth.generator = true;
  26681. synth.channel.instrument = lynx::InstrumentKind::synth;
  26682. synth.channel.name = "Synth";
  26683. synth.x = 220.0f;
  26684. chorus.effect = lynx::makeEffectSlot (lynx::EffectKind::chorus);
  26685. chorus.x = 420.0f;
  26686. // round 162: a MIDI Out node between the "MIDI port 5" pin and "To LYNX" MIDI port 3, an Envelope Controller
  26687. // on the notes moving the chorus
  26688. lynx::PatchNode midiOut, envelope;
  26689. midiOut.generator = envelope.generator = true;
  26690. midiOut.channel.instrument = lynx::InstrumentKind::midiOut;
  26691. midiOut.channel.name = "MIDI Out";
  26692. lynx::midictl::writeMidiOut (midiOut.channel.pluginState, { 3, 0, 0, -1, -1 });
  26693. midiOut.x = 220.0f, midiOut.y = 160.0f;
  26694. envelope.channel.instrument = lynx::InstrumentKind::controller;
  26695. envelope.channel.name = "Envelope Controller";
  26696. envelope.channel.controllerState = lynx::writeEnvelopeController (lynx::defaultEnvelopeController());
  26697. envelope.x = 220.0f, envelope.y = 260.0f;
  26698. lynx::PatchNode osc; // round 164f: an FL engine node (its editor opens from the node)
  26699. osc.generator = true;
  26700. osc.channel = lynx::natives::makeChannel (lynx::InstrumentKind::threeosc, lynx::flStudioAccess()).value_or (lynx::ChannelDef {});
  26701. osc.channel.instrument = lynx::InstrumentKind::threeosc;
  26702. osc.channel.name = "3x Osc";
  26703. osc.x = 420.0f, osc.y = 260.0f;
  26704. // round 165c: Keyboard Controller, SoundFont player, Granulizer and Dashboard nodes (their editors open from the node)
  26705. lynx::PatchNode keys, soundfont, granulizer, dashboard;
  26706. keys.generator = soundfont.generator = granulizer.generator = dashboard.generator = true;
  26707. keys.channel.instrument = lynx::InstrumentKind::controller;
  26708. keys.channel.name = "Keyboard Controller";
  26709. {
  26710. lynx::KeyboardControllerData ramp;
  26711. for (std::size_t k = 0; k < ramp.keys.size(); ++k)
  26712. ramp.keys[k] = (float) k / (float) (ramp.keys.size() - 1);
  26713. lynx::writeKeyboardController (ramp, keys.channel.controllerState);
  26714. }
  26715. soundfont.channel = lynx::sf::makeChannel();
  26716. granulizer.channel = lynx::natives::makeChannel (lynx::InstrumentKind::granulizer, lynx::flStudioAccess()).value_or (lynx::ChannelDef {});
  26717. granulizer.channel.instrument = lynx::InstrumentKind::granulizer;
  26718. granulizer.channel.name = "Fruity Granulizer";
  26719. dashboard.channel.instrument = lynx::InstrumentKind::dashboard;
  26720. dashboard.channel.name = "Dashboard";
  26721. dashboard.channel.patcher.surface = lynx::surface::starterControls();
  26722. keys.x = 20.0f, keys.y = 440.0f;
  26723. soundfont.x = 220.0f, soundfont.y = 440.0f;
  26724. granulizer.x = 420.0f, granulizer.y = 440.0f;
  26725. dashboard.x = 20.0f, dashboard.y = 540.0f;
  26726. // and a Layer node playing the SoundFont and Granulizer nodes on its Children pin (crossfaded)
  26727. lynx::PatchNode layerNode;
  26728. layerNode.generator = true;
  26729. layerNode.channel.instrument = lynx::InstrumentKind::layer;
  26730. layerNode.channel.name = "Layer";
  26731. layerNode.channel.layer.crossfade = true;
  26732. layerNode.channel.layer.fade = 0.35f;
  26733. layerNode.x = 220.0f, layerNode.y = 540.0f;
  26734. ch.patcher.nodes = { synth, chorus, midiOut, envelope, osc, keys, soundfont, granulizer, dashboard, layerNode };
  26735. lynx::PatchWire notes, a, b, portIn, portOut, envNotes, envControl;
  26736. notes.kind = lynx::PatchWire::Kind::midi, notes.to = 0;
  26737. a.from = 0, a.to = 1;
  26738. b.from = 1;
  26739. portIn.kind = lynx::PatchWire::Kind::midi, portIn.fromPort = lynx::patchMidiPortPin (5), portIn.to = 2;
  26740. portOut.kind = lynx::PatchWire::Kind::midi, portOut.from = 2, portOut.to = lynx::patchToHost, portOut.toPort = 3;
  26741. envNotes.kind = lynx::PatchWire::Kind::midi, envNotes.to = 3;
  26742. envControl.kind = lynx::PatchWire::Kind::control, envControl.from = 3, envControl.to = 1, envControl.toPort = 0;
  26743. lynx::PatchWire oscNotes, oscOut;
  26744. oscNotes.kind = lynx::PatchWire::Kind::midi, oscNotes.to = 4;
  26745. oscOut.from = 4;
  26746. lynx::PatchWire layerNotes, layerToFont, layerToGrains, fontOut, grainsOut;
  26747. layerNotes.kind = layerToFont.kind = layerToGrains.kind = lynx::PatchWire::Kind::midi;
  26748. layerNotes.to = 9;
  26749. layerToFont.from = 9, layerToFont.to = 6;
  26750. layerToGrains.from = 9, layerToGrains.to = 7;
  26751. fontOut.from = 6;
  26752. grainsOut.from = 7;
  26753. ch.patcher.wires = { notes, a, b, portIn, portOut, envNotes, envControl, oscNotes, oscOut, layerNotes, layerToFont, layerToGrains, fontOut, grainsOut };
  26754. ch.patcher.fromMidiPorts = { 1, 5 };
  26755. ch.patcher.toMidiPorts = { 3 };
  26756. ch.patcher.outputX = 640.0f;
  26757. song.channels.push_back (ch);
  26758. // LYNX_PATCHERSHOT_SAVE=file.lynx: the demo as a project (a GUI check of the same Patchers, round 164f)
  26759. if (const auto save = juce::SystemStats::getEnvironmentVariable ("LYNX_PATCHERSHOT_SAVE", {}); save.isNotEmpty())
  26760. {
  26761. if (! song.patterns.empty())
  26762. for (int k = 0; k < 4; ++k)
  26763. 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 });
  26764. juce::String error;
  26765. lynx::ProjectFile::save (song, juce::File (save), error);
  26766. // round 171b: the saved Patchers come back the same (parameter ports, event cables, published)
  26767. juce::String report;
  26768. if (const auto loaded = lynx::ProjectFile::load (juce::File (save), error))
  26769. {
  26770. const auto same = loaded->mixer.size() > 1 && ! loaded->mixer[1].effects.empty()
  26771. && loaded->mixer[1].effects[0].patcher == song.mixer[1].effects[0].patcher;
  26772. const auto& d = loaded->mixer.size() > 1 && ! loaded->mixer[1].effects.empty() ? loaded->mixer[1].effects[0].patcher : lynx::PatcherDoc {};
  26773. report << "patcher round trip: " << (same ? "OK" : "DIFFERENT") << "\n";
  26774. if (! same && loaded->mixer.size() > 1 && ! loaded->mixer[1].effects.empty())
  26775. {
  26776. const auto& a = song.mixer[1].effects[0].patcher;
  26777. report << "wires " << (a.wires == d.wires ? "same" : "differ") << ", published " << (a.published == d.published ? "same" : "differ")
  26778. << ", surface " << (a.surface == d.surface ? "same" : "differ") << "\n";
  26779. for (std::size_t n = 0; n < std::min (a.nodes.size(), d.nodes.size()); ++n)
  26780. if (! (a.nodes[n] == d.nodes[n]))
  26781. report << "node " << (int) n << " differs: ports " << (a.nodes[n].paramIns == d.nodes[n].paramIns && a.nodes[n].paramOuts == d.nodes[n].paramOuts ? "same" : "differ")
  26782. << ", effect " << (a.nodes[n].effect == d.nodes[n].effect ? "same" : "differ") << ", xy "
  26783. << (a.nodes[n].x == d.nodes[n].x && a.nodes[n].y == d.nodes[n].y ? "same" : "differ") << "\n";
  26784. }
  26785. for (int n = 0; n < (int) d.nodes.size(); ++n)
  26786. report << "node " << n << " paramIns " << (int) d.nodes[(std::size_t) n].paramIns.size() << " paramOuts "
  26787. << (int) d.nodes[(std::size_t) n].paramOuts.size() << "\n";
  26788. for (const auto& w : d.wires)
  26789. if (w.kind == lynx::PatchWire::Kind::control)
  26790. report << "control " << w.from << ":" << w.fromPort << " -> " << w.to << ":" << w.toPort << "\n";
  26791. for (const auto& p : d.published)
  26792. report << "published " << p.node << ":" << p.param << " " << juce::String::fromUTF8 (p.name.c_str()) << "\n";
  26793. }
  26794. else
  26795. report << "patcher round trip: load failed: " << error << "\n";
  26796. juce::File (prefix + "-roundtrip.txt").replaceWithText (report);
  26797. }
  26798. offline.setSong (std::move (song));
  26799. }
  26800. offline.dispatchPendingMessages();
  26801. const auto& song = offline.getSong();
  26802. auto shootOpen = [&] (const juce::String& name) {
  26803. for (int k = 0; k < juce::TopLevelWindow::getNumTopLevelWindows(); ++k)
  26804. if (auto* w = dynamic_cast<juce::DocumentWindow*> (juce::TopLevelWindow::getTopLevelWindow (k)))
  26805. if (w->getName().startsWith (lynx::tr ("Patcher")) && w->getContentComponent() != nullptr)
  26806. {
  26807. auto* c = w->getContentComponent();
  26808. savePng (lynx::shot::snapshot (*c), prefix + name);
  26809. delete w;
  26810. return;
  26811. }
  26812. };
  26813. int shots = 0;
  26814. for (int t = 0; t < (int) song.mixer.size() && shots < 12; ++t)
  26815. for (int s = 0; s < (int) song.mixer[(std::size_t) t].effects.size(); ++s)
  26816. if (song.mixer[(std::size_t) t].effects[(std::size_t) s].kind == lynx::EffectKind::patcher)
  26817. {
  26818. lynx::PatcherWindows::openSlot (offline, t, s);
  26819. shootOpen ("-insert" + juce::String (t) + "-slot" + juce::String (s) + ".png");
  26820. // each built-in node's editor, as a double-click opens it (round 165c)
  26821. lynx::PatcherWindows::shootNodeEditors (offline, false, t, s, [&] (const juce::Image& image, int n) {
  26822. savePng (image, prefix + "-insert" + juce::String (t) + "-slot" + juce::String (s) + "-node" + juce::String (n) + ".png");
  26823. });
  26824. ++shots;
  26825. if (shots == 1) // its menus (round 162)
  26826. lynx::PatcherWindows::shootMenus (offline, false, t, s, [&] (const juce::Image& image, const juce::String& name) {
  26827. savePng (image, prefix + "-menu-" + name + ".png");
  26828. });
  26829. }
  26830. for (int c = 0; c < (int) song.channels.size(); ++c)
  26831. if (song.channels[(std::size_t) c].instrument == lynx::InstrumentKind::patcher)
  26832. {
  26833. lynx::PatcherWindows::openChannel (offline, c);
  26834. shootOpen ("-channel" + juce::String (c) + ".png");
  26835. // each node's editor, as a double-click opens it (round 164f; every built-in node since round 165c)
  26836. lynx::PatcherWindows::shootNodeEditors (offline, true, c, 0, [&] (const juce::Image& image, int n) {
  26837. savePng (image, prefix + "-channel" + juce::String (c) + "-node" + juce::String (n) + ".png");
  26838. });
  26839. lynx::PatcherWindows::shootMenus (offline, true, c, 0, [&] (const juce::Image& image, const juce::String& name) {
  26840. savePng (image, prefix + "-channel" + juce::String (c) + "-menu-" + name + ".png");
  26841. });
  26842. }
  26843. }
  26844. }
  26845. // Issue #64: FL's letter keys in a plugin menu (quickpick::showMenu), checked on the real menu windows
  26846. struct TypeAheadTest final : private juce::Timer
  26847. {
  26848. juce::File out;
  26849. juce::StringArray log;
  26850. int step = 0, picked = 0;
  26851. bool ok = true, menuShown = false;
  26852. std::unique_ptr<juce::DocumentWindow> owner;
  26853. juce::PopupMenu pending;
  26854. static juce::String highlighted()
  26855. {
  26856. if (auto* window = juce::Component::getCurrentlyModalComponent())
  26857. for (auto* child : window->getChildren())
  26858. if (auto* h = child->getAccessibilityHandler(); h != nullptr && h->hasFocus (false))
  26859. return h->getTitle();
  26860. return "(none)";
  26861. }
  26862. static void press (const juce::KeyPress& key)
  26863. {
  26864. if (auto* window = juce::Component::getCurrentlyModalComponent())
  26865. if (auto* peer = window->getPeer())
  26866. peer->handleKeyPress (key);
  26867. }
  26868. void expect (const juce::String& what, const juce::String& got, const juce::String& wanted)
  26869. {
  26870. const auto good = got == wanted;
  26871. ok = ok && good;
  26872. log.add ((good ? "ok " : "FAIL ") + what + ": " + got + (good ? juce::String() : " (wanted " + wanted + ")"));
  26873. }
  26874. void start()
  26875. {
  26876. juce::PopupMenu menu, sub;
  26877. auto item = [this] (juce::PopupMenu& m, int id, const char* text, bool enabled = true) {
  26878. m.addItem (text, enabled, false, [this, id] { picked = id; });
  26879. };
  26880. menu.addSectionHeader ("LYNX SHARE");
  26881. item (menu, 1, "Echoform");
  26882. item (menu, 2, "EQ");
  26883. item (menu, 3, "Halo");
  26884. menu.addSectionHeader ("Misc");
  26885. item (menu, 4, "Effector");
  26886. item (menu, 5, "Exciter (unavailable)", false);
  26887. item (sub, 10, "Delay");
  26888. item (sub, 11, "Edison");
  26889. item (sub, 12, "Eventide");
  26890. menu.addSubMenu ("Tree", sub);
  26891. // the menu belongs to a window in the foreground, as when the user right-clicks a mixer slot (JUCE closes a
  26892. // menu of a background process at once)
  26893. owner = std::make_unique<juce::DocumentWindow> ("LYNX type-ahead test", juce::Colours::black, 0);
  26894. owner->setBounds (200, 200, 300, 200);
  26895. owner->setVisible (true);
  26896. lynx::forceForegroundForTest (*owner);
  26897. pending = menu; // shown once the window is up and active (X11 maps and activates it asynchronously)
  26898. startTimer (300);
  26899. }
  26900. void timerCallback() override
  26901. {
  26902. const auto e = juce::KeyPress ('e', {}, 'e');
  26903. if (step == 0 && owner != nullptr && ! menuShown)
  26904. {
  26905. menuShown = true;
  26906. lynx::forceForegroundForTest (*owner);
  26907. lynx::quickpick::showMenu (pending, juce::PopupMenu::Options().withTargetComponent (owner.get()), {});
  26908. return;
  26909. }
  26910. switch (step++)
  26911. {
  26912. case 0: expect ("menu open", juce::String ((int) (juce::Component::getCurrentlyModalComponent() != nullptr)), "1"); break;
  26913. case 1: press (e); expect ("e", highlighted(), "Echoform"); break;
  26914. case 2: press (e); expect ("e again", highlighted(), "EQ"); break;
  26915. case 3: press (juce::KeyPress ('E', juce::ModifierKeys::shiftModifier, 'E')); expect ("E (shift)", highlighted(), "Effector"); break;
  26916. case 4: press (e); expect ("e wraps (skips the disabled one)", highlighted(), "Echoform"); break;
  26917. case 5: press (juce::KeyPress ('m', {}, 'm')); expect ("m (only a heading starts with it: no move)", highlighted(), "Echoform"); break;
  26918. case 6: press (juce::KeyPress (juce::KeyPress::downKey)); expect ("down arrow", highlighted(), "EQ"); break;
  26919. case 7: press (e); expect ("e after the arrow", highlighted(), "Effector"); break;
  26920. case 8: press (juce::KeyPress ('t', {}, 't')); expect ("t", highlighted(), "Tree"); break;
  26921. case 9: press (juce::KeyPress (juce::KeyPress::rightKey)); break; // opens the submenu (it takes the keys)
  26922. case 10: press (e); expect ("e in the submenu", highlighted(), "Edison"); break;
  26923. case 11: press (e); expect ("e again in the submenu", highlighted(), "Eventide"); break;
  26924. case 12: expect ("nothing picked by the letters", juce::String (picked), "0"); press (juce::KeyPress (juce::KeyPress::returnKey)); break;
  26925. case 13: break;
  26926. default:
  26927. expect ("Enter closed the menu", juce::String ((int) (juce::Component::getCurrentlyModalComponent() == nullptr)), "1");
  26928. expect ("Enter picked", juce::String (picked), "12");
  26929. stopTimer();
  26930. owner.reset();
  26931. log.add (ok ? "result=OK" : "result=FAIL");
  26932. out.replaceWithText (log.joinIntoString ("\n") + "\n");
  26933. juce::JUCEApplication::getInstance()->setApplicationReturnValue (ok ? 0 : 1);
  26934. juce::JUCEApplication::quit();
  26935. return;
  26936. }
  26937. }
  26938. };
  26939. std::unique_ptr<TypeAheadTest> typeAheadTest;
  26940. struct ChooserTest final : private juce::Timer
  26941. {
  26942. juce::File out, file;
  26943. juce::StringArray log;
  26944. std::unique_ptr<juce::FileChooser> chooser;
  26945. double started = 0;
  26946. bool shot = false, done = false;
  26947. void start()
  26948. {
  26949. log.add ("LYNX_FILE_DIALOG=" + juce::SystemStats::getEnvironmentVariable ("LYNX_FILE_DIALOG", {}));
  26950. log.add ("native=" + juce::String ((int) lynx::ui::filechooser::nativeDialogs()));
  26951. chooser = lynx::ui::makeFileChooser ("Open audio file", file.getParentDirectory(), "*.wav;*.flac");
  26952. started = juce::Time::getMillisecondCounterHiRes();
  26953. lynx::ui::launchChooser (chooser, juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectFiles,
  26954. [this] (const juce::FileChooser& fc) { finish (fc.getResult()); });
  26955. startTimer (200);
  26956. }
  26957. static juce::FileChooserDialogBox* builtInDialog()
  26958. {
  26959. for (int i = 0; i < juce::Desktop::getInstance().getNumComponents(); ++i)
  26960. if (auto* box = dynamic_cast<juce::FileChooserDialogBox*> (juce::Desktop::getInstance().getComponent (i)); box != nullptr && box->isShowing())
  26961. return box;
  26962. return nullptr;
  26963. }
  26964. static juce::FileBrowserComponent* findBrowser (juce::Component& c)
  26965. {
  26966. if (auto* b = dynamic_cast<juce::FileBrowserComponent*> (&c))
  26967. return b;
  26968. for (auto* child : c.getChildren())
  26969. if (auto* b = findBrowser (*child))
  26970. return b;
  26971. return nullptr;
  26972. }
  26973. void timerCallback() override
  26974. {
  26975. if (done)
  26976. return;
  26977. if (auto* box = builtInDialog(); box != nullptr && ! shot)
  26978. {
  26979. shot = true;
  26980. log.add ("built-in dialog shown after " + juce::String (juce::roundToInt (juce::Time::getMillisecondCounterHiRes() - started)) + " ms");
  26981. const auto image = lynx::shot::snapshot (*box);
  26982. juce::FileOutputStream png (out.getSiblingFile (out.getFileName() + ".png"));
  26983. if (png.openedOk())
  26984. {
  26985. png.setPosition (0), png.truncate();
  26986. juce::PNGImageFormat().writeImageToStream (image, png);
  26987. }
  26988. if (auto* browser = findBrowser (*box))
  26989. {
  26990. browser->setRoot (file.getParentDirectory());
  26991. browser->setFileName (file.getFileName());
  26992. log.add ("typed " + file.getFileName());
  26993. box->exitModalState (1);
  26994. }
  26995. else
  26996. log.add ("no file browser in the dialog");
  26997. }
  26998. if (juce::Time::getMillisecondCounterHiRes() - started > 30000.0)
  26999. finish ({}, "timeout");
  27000. }
  27001. void finish (const juce::File& result, const juce::String& why = {})
  27002. {
  27003. if (done)
  27004. return;
  27005. done = true;
  27006. stopTimer();
  27007. log.add ("callback after " + juce::String (juce::roundToInt (juce::Time::getMillisecondCounterHiRes() - started)) + " ms: "
  27008. + (why.isNotEmpty() ? why : result.getFullPathName().isEmpty() ? juce::String ("(no file)") : result.getFullPathName()));
  27009. log.add ("native now=" + juce::String ((int) lynx::ui::filechooser::nativeDialogs()));
  27010. const auto ok = result == file && result.existsAsFile();
  27011. log.add (ok ? "result=OK" : "result=FAIL");
  27012. out.replaceWithText (log.joinIntoString ("\n") + "\n");
  27013. juce::JUCEApplication::getInstance()->setApplicationReturnValue (ok ? 0 : 1);
  27014. juce::MessageManager::callAsync ([] { juce::JUCEApplication::quit(); });
  27015. }
  27016. };
  27017. std::unique_ptr<ChooserTest> chooserTest;
  27018. void runChooserTest (const juce::File& out, const juce::File& file)
  27019. {
  27020. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  27021. chooserTest = std::make_unique<ChooserTest>();
  27022. chooserTest->out = out;
  27023. chooserTest->file = file;
  27024. chooserTest->start();
  27025. }
  27026. void runTypeAheadTest (const juce::File& out)
  27027. {
  27028. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  27029. typeAheadTest = std::make_unique<TypeAheadTest>();
  27030. typeAheadTest->out = out;
  27031. typeAheadTest->start();
  27032. }
  27033. void runStabilityShot (const juce::String& folder)
  27034. {
  27035. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  27036. const juce::File dir (folder);
  27037. dir.createDirectory();
  27038. {
  27039. lynx::AudioEngine offline (false);
  27040. const auto save = [&dir] (std::unique_ptr<juce::Component> c, const juce::String& name) {
  27041. juce::Component frame;
  27042. frame.setSize (c->getWidth(), c->getHeight());
  27043. frame.setOpaque (true);
  27044. if (c->isOnDesktop()) // (an AlertWindow: never shown, so it takes no foreground)
  27045. c->removeFromDesktop();
  27046. frame.addAndMakeVisible (*c);
  27047. c->setTopLeftPosition (0, 0);
  27048. const auto image = lynx::shot::paint (frame, lynx::theme::panel);
  27049. const auto file = dir.getChildFile (name);
  27050. file.deleteFile();
  27051. juce::PNGImageFormat png;
  27052. if (auto out = file.createOutputStream())
  27053. png.writeImageToStream (image, *out);
  27054. };
  27055. save (lynx::PluginWindows::makeCrashPromptPanel ("Serum", false), "crash-prompt.png");
  27056. save (lynx::PluginWindows::makeCrashPromptPanel ("Serum", true), "crash-prompt-onload.png");
  27057. save (lynx::PluginWindows::makeCrashNoticePanel ("Serum", true), "crash-notice.png");
  27058. save (lynx::makePluginManagerPanel (offline, false), "plugin-manager.png");
  27059. save (lynx::makePluginMonitorPanel (offline), "plugin-monitor.png");
  27060. }
  27061. setApplicationReturnValue (0);
  27062. quit();
  27063. }
  27064. void runDetails190ihShot (const juce::String& prefix)
  27065. {
  27066. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  27067. juce::String report;
  27068. auto line = [&report] (const juce::String& t) { report << t << "\n"; };
  27069. {
  27070. // R2: Gross Beat on Insert 1 — the first time slot and a half-beat volume gate, as in FL's capture ("Empty",
  27071. // "1/2 Bt Gate")
  27072. lynx::AudioEngine offline (false);
  27073. lynx::Song song;
  27074. song.mixer = lynx::Song::defaultMixer (2);
  27075. song.bpm = 150.0;
  27076. auto gb = lynx::makeEffectSlot (lynx::EffectKind::grossBeat);
  27077. const auto names = lynx::grossbeat::slotNames (gb.state, true);
  27078. int gate = 0;
  27079. for (int k = 0; k < (int) names.size(); ++k)
  27080. if (names[(std::size_t) k] == "Gate 1/2 beat") // (LYNX's factory slot for FL's "1/2 Bt Gate")
  27081. gate = k;
  27082. gb.params[0] = lynx::grossbeat::paramFromRaw (0, 0);
  27083. gb.params[1] = lynx::grossbeat::paramFromRaw (1, gate);
  27084. song.mixer[1].effects.push_back (gb);
  27085. offline.setSong (std::move (song));
  27086. offline.dispatchPendingMessages();
  27087. // the real effect played to beat 2.9 of its bar: its published outputs go where the rack writes them
  27088. auto run = lynx::makeEffect (gb);
  27089. run->prepare (48000.0);
  27090. const auto tps = 150.0 / 60.0 * lynx::ppq / 48000.0;
  27091. std::vector<float> l (480, 0.3f), r (480, 0.3f);
  27092. std::size_t done = 0;
  27093. auto block = [&] (lynx::EffectParams& params) {
  27094. run->setSongPosition ((double) done * tps);
  27095. run->process (l.data(), r.data(), 480, params, 150.0);
  27096. done += 480;
  27097. };
  27098. auto publish = [&] (bool playing) {
  27099. const auto key = (std::size_t) (1 * lynx::maxEffectSlots + 0) * lynx::ProcessTimes::meterOutputs;
  27100. if (auto* times = offline.getProcessTimes())
  27101. for (int k = 0; k < lynx::ProcessTimes::meterOutputs; ++k)
  27102. times->effectMeters[key + (std::size_t) k].store (run->controlOutput (k), std::memory_order_relaxed);
  27103. else
  27104. line ("no process times: the editor shows nothing live");
  27105. offline.getTransport().playing.store (playing);
  27106. juce::String values;
  27107. for (int k = 0; k < 7; ++k)
  27108. values << " " << juce::String (run->controlOutput (k), 3);
  27109. line ("gross beat outputs:" + values);
  27110. };
  27111. while ((double) done * tps / lynx::ppq < 2.9)
  27112. block (gb.params);
  27113. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f);
  27114. editor->setSize (editor->getWidth(), editor->getHeight());
  27115. for (const int view : { 1, 0 })
  27116. {
  27117. lynx::showGrossBeatEnvelopeForSnapshot (*editor, view);
  27118. publish (true);
  27119. lynx::tickNativeEffectEditor (*editor);
  27120. savePng (lynx::shot::snapshot (*editor), prefix + "-r2-grossbeat-playing-" + (view == 1 ? "volume" : "time") + ".png");
  27121. }
  27122. lynx::ui::motion::enabled() = false;
  27123. lynx::tickNativeEffectEditor (*editor);
  27124. editor->repaint();
  27125. savePng (lynx::shot::snapshot (*editor), prefix + "-r2-grossbeat-playing-noanim.png");
  27126. lynx::ui::motion::enabled() = true;
  27127. // a click on another time slot: queued until the next 4 beats
  27128. auto queued = gb.params;
  27129. queued[0] = lynx::grossbeat::paramFromRaw (0, 5);
  27130. block (queued);
  27131. publish (true);
  27132. lynx::tickNativeEffectEditor (*editor);
  27133. savePng (lynx::shot::snapshot (*editor), prefix + "-r2-grossbeat-queued.png");
  27134. publish (false); // stopped: no locator, no fill
  27135. lynx::tickNativeEffectEditor (*editor);
  27136. savePng (lynx::shot::snapshot (*editor), prefix + "-r2-grossbeat-stopped.png");
  27137. offline.getTransport().playing.store (false);
  27138. }
  27139. {
  27140. // R7: the Envelope Controller's Keyboard / Velocity mapping pages after a note (key 64, velocity 0.8)
  27141. lynx::AudioEngine offline (false);
  27142. lynx::Song song;
  27143. lynx::ChannelDef env;
  27144. env.name = "Envelope Controller";
  27145. env.instrument = lynx::InstrumentKind::controller;
  27146. auto ec = lynx::defaultEnvelopeController();
  27147. ec[0].maps[lynx::mapKeyboard].count = 2;
  27148. ec[0].maps[lynx::mapKeyboard].time = { 0.2f, 0.8f };
  27149. ec[0].maps[lynx::mapKeyboard].level = { 0.0f, 1.0f };
  27150. ec[0].maps[lynx::mapVelocity] = ec[0].maps[lynx::mapKeyboard];
  27151. env.controllerState = lynx::writeEnvelopeController (ec);
  27152. song.channels.push_back (env);
  27153. song.patterns.emplace_back();
  27154. offline.setSong (std::move (song));
  27155. offline.dispatchPendingMessages();
  27156. auto editor = lynx::makeEnvelopeControllerEditor (
  27157. offline, [] (lynx::Song& s) -> lynx::ChannelDef* { return s.channels.empty() ? nullptr : &s.channels[0]; }, 0,
  27158. [] (int k) { return k == 8 ? 64.0f : k == 9 ? 0.8f : 0.5f; });
  27159. for (const int part : { 2, 3 })
  27160. {
  27161. for (auto* child : editor->getChildren())
  27162. if (auto* box = dynamic_cast<juce::ComboBox*> (child))
  27163. box->setSelectedItemIndex (part, juce::sendNotificationSync);
  27164. savePng (lynx::shot::snapshot (*editor), prefix + "-r7-ec-" + (part == 2 ? "keyboard" : "velocity") + "-line.png");
  27165. }
  27166. }
  27167. {
  27168. lynx::AudioEngine offline (false);
  27169. lynx::MainComponent ui (offline, false);
  27170. ui.setSize (1920, 1080);
  27171. lynx::Song song;
  27172. song.mixer = lynx::Song::defaultMixer (4);
  27173. for (const auto* name : { "Grv Kick 27", "Snare", "Hat", "Bass (locked)" })
  27174. {
  27175. lynx::ChannelDef c;
  27176. c.name = name;
  27177. c.instrument = lynx::InstrumentKind::sampler;
  27178. song.channels.push_back (c);
  27179. }
  27180. song.channels[3].receiveFrom = "MIDI keyboard";
  27181. song.patterns.emplace_back();
  27182. offline.setSong (std::move (song));
  27183. offline.dispatchPendingMessages();
  27184. ui.showDesktopForSnapshot (false);
  27185. offline.dispatchPendingMessages();
  27186. // R4: the rack's activity light — before, at note-on, held, after the release; a locked channel lit (orange)
  27187. auto& rack = ui.getRackForSnapshot();
  27188. const std::pair<const char*, float> states[] { { "before", 0.0f }, { "noteon", 1.0f }, { "held", lynx::activity::held }, { "after", 0.0f } };
  27189. for (const auto& [name, level] : states)
  27190. {
  27191. rack.setActivityForSnapshot (0, level);
  27192. rack.setActivityForSnapshot (3, level);
  27193. savePng (lynx::shot::snapshot (rack), prefix + "-r4-rack-" + name + ".png");
  27194. }
  27195. rack.setActivityForSnapshot (0, 0.0f);
  27196. rack.setActivityForSnapshot (3, 0.0f);
  27197. // R3: the transport stopped, playing, recording (both blink phases), armed and stopped; the hint bar
  27198. const auto toolbar = ui.getToolbarBoundsForSnapshot();
  27199. auto& transport = offline.getTransport();
  27200. ui.transportForSnapshot (false, true);
  27201. saveArea (ui, toolbar, prefix + "-r3-toolbar-stopped.png");
  27202. transport.playing.store (true);
  27203. ui.transportForSnapshot (true, true);
  27204. saveArea (ui, toolbar, prefix + "-r3-toolbar-playing.png");
  27205. transport.recording.store (true);
  27206. ui.transportForSnapshot (true, true);
  27207. saveArea (ui, toolbar, prefix + "-r3-toolbar-recording-lit.png");
  27208. ui.transportForSnapshot (true, false);
  27209. saveArea (ui, toolbar, prefix + "-r3-toolbar-recording-dark.png");
  27210. lynx::ui::motion::enabled() = false;
  27211. ui.transportForSnapshot (true, false);
  27212. saveArea (ui, toolbar, prefix + "-r3-toolbar-recording-noanim.png");
  27213. lynx::ui::motion::enabled() = true;
  27214. transport.playing.store (false);
  27215. ui.transportForSnapshot (false, false);
  27216. saveArea (ui, toolbar, prefix + "-r3-toolbar-armed-stopped.png");
  27217. transport.recording.store (false);
  27218. ui.transportForSnapshot (false, true);
  27219. for (const bool on : { true, false })
  27220. {
  27221. offline.markLiveNote (60, 100, on);
  27222. const auto hint = ui.liveNoteHintForSnapshot();
  27223. line ("hint: " + hint);
  27224. ui.setHintForSnapshot ({ hint, {}, false, false });
  27225. saveArea (ui, toolbar, prefix + "-r3-hint-note" + (on ? "on" : "off") + ".png");
  27226. }
  27227. offline.editSong ([] (lynx::Song& s) { s.bpm = 128.0; }); // (a change: the project is modified)
  27228. offline.dispatchPendingMessages();
  27229. const auto reminder = ui.saveReminderForSnapshot();
  27230. line ("reminder: " + reminder);
  27231. ui.setHintForSnapshot ({ reminder, {}, false, false });
  27232. saveArea (ui, toolbar, prefix + "-r3-save-reminder.png");
  27233. // R14: the Simple dock's input level
  27234. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  27235. offline.dispatchPendingMessages();
  27236. if (auto* simple = ui.getSimpleWorkflowForSnapshot())
  27237. if (auto* dock = simple->dockForSnapshot())
  27238. {
  27239. dock->inputLevelForSnapshot (0.72f);
  27240. offline.dispatchPendingMessages();
  27241. savePng (lynx::shot::snapshot (*dock), prefix + "-r14-dock-input-level.png");
  27242. line ("dock: " + juce::String (dock->getWidth()) + "x" + juce::String (dock->getHeight()));
  27243. }
  27244. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
  27245. offline.dispatchPendingMessages();
  27246. }
  27247. juce::File (prefix + "-report.txt").replaceWithText (report);
  27248. }
  27249. void runSnapshot (const juce::String& prefix, const juce::String& projectPath)
  27250. {
  27251. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  27252. // LYNX_SNAPSHOT_THEME=file.lynxtheme: the pictures in that theme (round 162d)
  27253. if (const auto themeFile = juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_THEME", {}); themeFile.isNotEmpty())
  27254. if (const auto spec = lynx::themeui::loadFile (juce::File (themeFile)))
  27255. lynx::themeui::apply (*spec, false);
  27256. {
  27257. lynx::AudioEngine offline (false);
  27258. lynx::MainComponent ui (offline, false); // default layout and keys, nothing saved
  27259. // LYNX_SNAPSHOT_SIZE=WxH (default 1280x720)
  27260. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1280x720"), "x", "");
  27261. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  27262. if (projectPath.isNotEmpty())
  27263. ui.openFile (juce::File (projectPath));
  27264. offline.dispatchPendingMessages(); // change notifications are asynchronous
  27265. ui.waitForBrowserForSnapshot();
  27266. // the workspace desktop: the default layout, then with the Piano Roll and Mixer floating too
  27267. // (and a sample hint in the status strip, as when hovering a knob)
  27268. ui.showDesktopForSnapshot (false);
  27269. ui.setMetersForSnapshot (0.23, (std::int64_t) 412 << 20, 6);
  27270. offline.dispatchPendingMessages();
  27271. saveSnapshot (ui, prefix + "-desktop.png");
  27272. // the first start: the setup wizard over the main window (round 140), also on a small screen (it scrolls)
  27273. {
  27274. const auto size = ui.getBounds();
  27275. ui.showSetupWizard();
  27276. offline.dispatchPendingMessages();
  27277. saveSnapshot (ui, prefix + "-desktop-setup.png");
  27278. ui.setSize (1024, 600);
  27279. offline.dispatchPendingMessages();
  27280. saveSnapshot (ui, prefix + "-desktop-setup-small.png");
  27281. ui.closeSetupWizardForSnapshot();
  27282. ui.setBounds (size);
  27283. offline.dispatchPendingMessages();
  27284. }
  27285. // the start-up desktop and the toolbar at the usual window sizes: the untouched default layout
  27286. // follows the window (default rects, not scaled ones); panels drop from the toolbar by priority
  27287. {
  27288. const auto size = ui.getBounds();
  27289. for (const auto& [w, h] : std::vector<std::pair<int, int>> { { 1280, 720 }, { 1366, 768 }, { 1600, 900 }, { 1920, 1080 }, { 2560, 1440 }, { 3840, 2160 } })
  27290. {
  27291. ui.setSize (w, h);
  27292. offline.dispatchPendingMessages();
  27293. saveSnapshot (ui, prefix + "-desktop-" + juce::String (w) + ".png");
  27294. saveArea (ui, ui.getToolbarBoundsForSnapshot(), prefix + "-toolbar-" + juce::String (w) + ".png");
  27295. if (w == 1920) // the rack scrolled to its last steps: the controls column stays in view (round 90)
  27296. {
  27297. ui.scrollRackForSnapshot (100000);
  27298. offline.dispatchPendingMessages();
  27299. saveSnapshot (ui, prefix + "-desktop-rack-scrolled.png");
  27300. ui.scrollRackForSnapshot (0);
  27301. }
  27302. }
  27303. // the toolbar with small and large icons, and a customized one (groups hidden and reordered)
  27304. ui.setSize (1600, 900);
  27305. for (auto [iconSize, name] : { std::pair { lynx::toolbarlayout::IconSize::small, "small" }, { lynx::toolbarlayout::IconSize::large, "large" } })
  27306. {
  27307. auto layout = lynx::toolbarlayout::Layout::makeDefault();
  27308. layout.iconSize = iconSize;
  27309. ui.setToolbarLayoutForSnapshot (layout);
  27310. saveArea (ui, ui.getToolbarBoundsForSnapshot(), prefix + "-toolbar-" + name + "-1600.png");
  27311. }
  27312. {
  27313. auto layout = lynx::toolbarlayout::Layout::makeDefault();
  27314. layout.move (lynx::toolbarlayout::Group::windows, -3);
  27315. layout.setShown (lynx::toolbarlayout::Group::record, false);
  27316. layout.setShown (lynx::toolbarlayout::Group::meters, false);
  27317. ui.setToolbarLayoutForSnapshot (layout);
  27318. saveArea (ui, ui.getToolbarBoundsForSnapshot(), prefix + "-toolbar-custom-1600.png");
  27319. }
  27320. {
  27321. // round 170e: the toolbar after a knob was moved: the last tweaked read-out (its caption) and the snap magnet
  27322. ui.setSize (1920, 1080); // the read-out needs room beside the hint bar
  27323. ui.setToolbarLayoutForSnapshot (lynx::toolbarlayout::Layout::makeDefault());
  27324. lynx::AutomationTarget t;
  27325. t.kind = lynx::AutomationTargetKind::mixerVolume;
  27326. t.index = 0;
  27327. offline.noteTweaked (t);
  27328. ui.refreshTweakReadoutForSnapshot();
  27329. offline.dispatchPendingMessages();
  27330. saveArea (ui, ui.getToolbarBoundsForSnapshot(), prefix + "-toolbar-tweak-1920.png");
  27331. ui.setSize (1600, 900);
  27332. }
  27333. {
  27334. // the toolbar's edit mode (round 115): outlined panels and the tray of panels under it
  27335. ui.setToolbarLayoutForSnapshot (lynx::toolbarlayout::Layout::makeDefault());
  27336. auto layout = lynx::toolbarlayout::Layout::makeDefault();
  27337. layout.setShown (lynx::toolbarlayout::Group::meters, false);
  27338. ui.setToolbarLayoutForSnapshot (layout);
  27339. ui.setToolbarEditingForSnapshot (true);
  27340. offline.dispatchPendingMessages();
  27341. saveArea (ui, ui.getToolbarBoundsForSnapshot().withHeight (ui.getToolbarAndTrayHeightForSnapshot()), prefix + "-toolbar-edit-1600.png");
  27342. ui.setToolbarEditingForSnapshot (false);
  27343. // Ctrl+F11: only the menu and the hint bar
  27344. layout = lynx::toolbarlayout::Layout::makeDefault();
  27345. layout.visible = false;
  27346. ui.setToolbarLayoutForSnapshot (layout);
  27347. saveArea (ui, ui.getLocalBounds().withHeight (120), prefix + "-toolbar-hidden-1600.png");
  27348. }
  27349. ui.setToolbarLayoutForSnapshot (lynx::toolbarlayout::Layout::makeDefault());
  27350. // quick tips: the toolbar and title bars with a few name bubbles, and every tip on one sheet
  27351. offline.dispatchPendingMessages();
  27352. saveQuickTips (ui, prefix);
  27353. ui.setBounds (size);
  27354. offline.dispatchPendingMessages();
  27355. }
  27356. // the hint bar: a value control while it is dragged (live value), a gesture line with mouse and key
  27357. // glyphs, and a text too long for one line (two lines)
  27358. {
  27359. const auto toolbar = ui.getToolbarBoundsForSnapshot().withWidth (juce::jmin (ui.getWidth(), 900));
  27360. const lynx::ui::Hint hints[] = {
  27361. { lynx::tr ("Volume") + " - " + lynx::tr ("drag (Ctrl: fine), wheel, Alt+click resets"), "-3.2 dB", true, true },
  27362. { lynx::tr ("Piano Roll: [LMB] add a note, drag to move [RMB] delete [Ctrl][LMB] drag to select [Ctrl][Wheel] zoom"), {}, false, false },
  27363. { lynx::tr ("Global snap: the grid of the Piano Roll and Playlist (when they follow it) and the quantise of recorded notes "
  27364. "[LMB] choose [Wheel] step [RMB] length of new notes [Backspace] snap on/off [Alt] while dragging: no snap"), {}, false, true },
  27365. };
  27366. for (int i = 0; i < 3; ++i)
  27367. {
  27368. ui.setHintForSnapshot (hints[i], i == 0);
  27369. saveArea (ui, toolbar, prefix + "-hint-" + juce::String (i + 1) + ".png");
  27370. }
  27371. }
  27372. ui.showDesktopForSnapshot (true);
  27373. ui.setHintForSnapshot ({ lynx::tr ("Volume") + " - " + lynx::tr ("drag (Ctrl: fine), wheel, Alt+click resets"), "78%", true, true });
  27374. saveSnapshot (ui, prefix + "-desktop-all.png");
  27375. ui.selectTabForSnapshot (0);
  27376. saveSnapshot (ui, prefix + "-rack.png");
  27377. // round 190io (design190ia FM-10…14): steps on the first channels, audio clip channels included (they show
  27378. // their steps as in FL), a few selected rows, a muted channel; then the project as it was
  27379. {
  27380. const auto& kept = offline.getSong();
  27381. const auto keptSelection = offline.getSelectedChannels();
  27382. const auto keptPrimary = offline.getSelectedChannel();
  27383. const auto channels = (int) kept.channels.size();
  27384. offline.editSong ([channels] (lynx::Song& s) {
  27385. auto& p = s.activePattern();
  27386. for (int c = 0; c < juce::jmin (12, channels); ++c)
  27387. for (const auto step : { 0, 4 + (c % 3) * 2, 8, 12 + (c % 2) * 2 })
  27388. if (! p.hasStep (c, step))
  27389. p.toggleStep (c, step);
  27390. if (channels > 5)
  27391. s.channels[5].muted = true;
  27392. });
  27393. if (channels > 3)
  27394. offline.setChannelSelection ({ 1, 2, 3 }, 2);
  27395. offline.dispatchPendingMessages();
  27396. saveSnapshot (ui, prefix + "-rack190io-steps.png");
  27397. offline.undo(); // (one undo step: the project and its history as they were)
  27398. offline.setChannelSelection (keptSelection, keptPrimary);
  27399. offline.dispatchPendingMessages();
  27400. }
  27401. {
  27402. // a pattern with piano-roll notes: those rows show a miniature instead of steps (round 90)
  27403. int found = -1;
  27404. const auto before = offline.getSong().currentPattern;
  27405. {
  27406. const auto& song = offline.getSong();
  27407. for (int p = 0; p < (int) song.patterns.size() && found < 0; ++p)
  27408. for (int c = 0; c < (int) song.channels.size() && found < 0; ++c)
  27409. if (lynx::showsNotePreview (song.patterns[(std::size_t) p], c))
  27410. found = p;
  27411. }
  27412. if (found >= 0)
  27413. {
  27414. offline.editSong ([found] (lynx::Song& s) { s.currentPattern = found; }, false);
  27415. offline.dispatchPendingMessages();
  27416. saveSnapshot (ui, prefix + "-rack-preview.png");
  27417. offline.editSong ([before] (lynx::Song& s) { s.currentPattern = before; }, false);
  27418. offline.dispatchPendingMessages();
  27419. }
  27420. }
  27421. ui.selectTabForSnapshot (1);
  27422. saveSnapshot (ui, prefix + "-pianoroll.png");
  27423. {
  27424. // View › Keyboard style › Piano keys (round 190j, discussion #136), also with tall keys
  27425. auto& roll = ui.getPianoRollForSnapshot();
  27426. lynx::PianoRollComponent::keyStyle = lynx::pianokeys::Style::piano;
  27427. roll.repaint();
  27428. saveSnapshot (ui, prefix + "-pianoroll-pianokeys.png");
  27429. lynx::PianoRollComponent::keyStyle = lynx::pianokeys::Style::flat;
  27430. roll.repaint();
  27431. // round 190j (discussion #10): the toolbar in a narrow window: the chord stamp as an icon button, and
  27432. // the menu button still there
  27433. for (int narrower : { 150, 270, 330 })
  27434. {
  27435. roll.squeezeToolbarForSnapshot (narrower);
  27436. saveSnapshot (ui, prefix + "-pianoroll-narrow" + juce::String (narrower) + ".png");
  27437. roll.squeezeToolbarForSnapshot (-narrower);
  27438. }
  27439. }
  27440. if (const auto strip = ui.getToolStripAreaForSnapshot (false); ! strip.isEmpty())
  27441. saveArea (ui, strip, prefix + "-pianoroll-tools.png");
  27442. // the editors' mouse feel: the hovered note / clip edge (grip, outline) and its hint in the hint bar
  27443. ui.setHintForSnapshot (ui.getPianoRollForSnapshot().hoverForSnapshot());
  27444. saveSnapshot (ui, prefix + "-pianoroll-hover.png");
  27445. {
  27446. // a pattern with note Chance or a Velocity Range (round 187c): the Piano roll with those lanes
  27447. const auto& song = offline.getSong();
  27448. const auto& notes = song.patterns[(std::size_t) std::clamp (song.currentPattern, 0, (int) song.patterns.size() - 1)].notes;
  27449. if (std::any_of (notes.begin(), notes.end(), [] (const lynx::Note& n) { return n.hasChance(); }))
  27450. {
  27451. auto& roll = ui.getPianoRollForSnapshot();
  27452. ui.setHintForSnapshot ({});
  27453. for (const auto& [lane, name] : { std::pair { lynx::PianoRollComponent::laneChance, "chance" },
  27454. { lynx::PianoRollComponent::laneVelocityRange, "velrange" },
  27455. { lynx::PianoRollComponent::laneVelocity, "velocity" } })
  27456. {
  27457. roll.setLaneForSnapshot (lane);
  27458. offline.dispatchPendingMessages();
  27459. saveSnapshot (ui, prefix + "-pianoroll-" + name + ".png");
  27460. }
  27461. }
  27462. }
  27463. ui.selectTabForSnapshot (2);
  27464. saveSnapshot (ui, prefix + "-playlist.png");
  27465. if (const auto strip = ui.getToolStripAreaForSnapshot (true); ! strip.isEmpty())
  27466. saveArea (ui, strip, prefix + "-playlist-tools.png");
  27467. ui.setHintForSnapshot (ui.getPlaylistForSnapshot().hoverForSnapshot());
  27468. saveSnapshot (ui, prefix + "-playlist-hover.png");
  27469. ui.setHintForSnapshot ({ lynx::tr ("Volume") + " - " + lynx::tr ("drag (Ctrl: fine), wheel, Alt+click resets"), "78%", true, true });
  27470. // the Playlist with a time selection over bars 2-3 (it selects the clips it touches) and the Knife tool
  27471. ui.getPlaylistForSnapshot().setTimeSelectionForSnapshot (1, 3);
  27472. ui.getPlaylistForSnapshot().setToolForSnapshot (lynx::EditTool::knife);
  27473. offline.dispatchPendingMessages();
  27474. saveSnapshot (ui, prefix + "-playlist-timesel.png");
  27475. ui.getPlaylistForSnapshot().setToolForSnapshot (lynx::EditTool::pencil);
  27476. // round 177b: automation lanes on (two lanes under track 2: a volume ramp and a pan wobble)
  27477. {
  27478. const auto before = offline.getSong();
  27479. offline.editSong ([] (lynx::Song& s) {
  27480. s.loopStart = s.loopEnd = 0; // (no time selection in this one)
  27481. const auto bar = s.barTicks();
  27482. const auto vol = lynx::autolanes::addLane (s, 1, { lynx::AutomationTargetKind::mixerVolume, 1, 0, 0 }, "Insert 1 - Volume", 0.3f);
  27483. s.automations[(std::size_t) vol].points = { { 0, 0.3f, 0.0f }, { bar * 2, 0.8f, 0.4f }, { bar * 4, 0.6f, 0.0f } };
  27484. const auto pan = lynx::autolanes::addLane (s, 1, { lynx::AutomationTargetKind::mixerPan, 1, 0, 0 }, "Insert 1 - Pan", 0.5f);
  27485. 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 } };
  27486. }, false);
  27487. lynx::autolanes::setShown (true);
  27488. ui.getPlaylistForSnapshot().resized();
  27489. offline.dispatchPendingMessages();
  27490. saveSnapshot (ui, prefix + "-playlist-lanes.png");
  27491. lynx::autolanes::setShown (false);
  27492. offline.editSong ([before] (lynx::Song& s) { s = before; }, false);
  27493. offline.dispatchPendingMessages();
  27494. }
  27495. // round 104: a folded track group (FL's thin member rows) and the Picker's audio tab
  27496. {
  27497. int header = -1;
  27498. for (int t = 0; t < (int) offline.getSong().playlistTracks.size() && header < 0; ++t)
  27499. if (lynx::noteedit::isGroupHeader (offline.getSong(), t))
  27500. header = t;
  27501. if (header >= 0)
  27502. {
  27503. offline.editSong ([header] (lynx::Song& s) { lynx::noteedit::setGroupCollapsed (s, header, true); }, false);
  27504. offline.dispatchPendingMessages();
  27505. saveSnapshot (ui, prefix + "-playlist-group-folded.png");
  27506. offline.editSong ([header] (lynx::Song& s) { lynx::noteedit::setGroupCollapsed (s, header, false); }, false);
  27507. }
  27508. ui.getPickerForSnapshot().setView (1);
  27509. offline.dispatchPendingMessages();
  27510. saveSnapshot (ui, prefix + "-playlist-picker-audio.png");
  27511. ui.getPickerForSnapshot().setView (0);
  27512. }
  27513. // round 104: the Channel Rack filtered to its first filter group
  27514. if (! offline.getSong().channelGroups.empty())
  27515. {
  27516. ui.selectTabForSnapshot (0);
  27517. ui.getRackForSnapshot().setFilterGroup (0);
  27518. offline.dispatchPendingMessages();
  27519. saveSnapshot (ui, prefix + "-rack-filter.png");
  27520. ui.getRackForSnapshot().setFilterGroup (-1);
  27521. }
  27522. ui.selectTabForSnapshot (3);
  27523. // LYNX_SNAPSHOT_ARRANGE=1 (round 186c): Mixer menu › "Arrange inserts like the Playlist" first
  27524. if (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_ARRANGE", {}) == "1")
  27525. {
  27526. offline.editSong ([] (lynx::Song& s) { lynx::mixerops::arrangeLikePlaylist (s); });
  27527. offline.dispatchPendingMessages();
  27528. }
  27529. // LYNX_SNAPSHOT_TRACK=n: shows the effects of that mixer track
  27530. if (const auto track = juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_TRACK", {}); track.isNotEmpty())
  27531. {
  27532. ui.selectMixerTrackForSnapshot (track.getIntValue(),
  27533. juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SLOT", "-1").getIntValue());
  27534. offline.dispatchPendingMessages();
  27535. }
  27536. saveSnapshot (ui, prefix + "-mixer.png");
  27537. // round 190ir (Discord report, "it isnt picking up my audio input"): an armed insert without an input says so
  27538. // in its input box (record colour)
  27539. // (the first insert no channel plays into: armed without an input, it records silence)
  27540. {
  27541. const auto& song = offline.getSong();
  27542. auto target = -1;
  27543. for (int t = 1; t < (int) song.mixer.size() && target < 0; ++t)
  27544. if (song.mixer[(std::size_t) t].inputChannel < 0
  27545. && std::none_of (song.channels.begin(), song.channels.end(), [t] (const lynx::ChannelDef& c) { return c.mixerTrack == t; }))
  27546. target = t;
  27547. if (target > 0)
  27548. {
  27549. offline.setInsertArmed (target, true);
  27550. ui.selectMixerTrackForSnapshot (target, -1);
  27551. offline.dispatchPendingMessages();
  27552. saveSnapshot (ui, prefix + "-mixer190ir-armed-noinput.png");
  27553. offline.setInsertArmed (target, false);
  27554. offline.dispatchPendingMessages();
  27555. }
  27556. }
  27557. // round 190am: LYNX's two mixer extras, before and after (the demo project leaves most inserts unused). The
  27558. // loudness panel shows a real measurement of 12 s of a test tone (a 1 kHz sine at -14 dBFS after a quieter
  27559. // stretch, pushed through the Master's tap as the audio thread does)
  27560. {
  27561. auto& strips = ui.getMixerForSnapshot().getStripsForSnapshot();
  27562. saveSnapshot (ui, prefix + "-mixer190am-before.png");
  27563. strips.setShowUsedOnly (true);
  27564. offline.dispatchPendingMessages();
  27565. saveSnapshot (ui, prefix + "-mixer190am-usedonly.png");
  27566. strips.setShowUsedOnly (false);
  27567. strips.setShowLoudness (true);
  27568. {
  27569. const double sr = 48000.0;
  27570. std::vector<float> tone (480);
  27571. auto& tap = offline.getMeters().loudness;
  27572. for (int block = 0; block < 1200; ++block)
  27573. {
  27574. const auto gain = std::pow (10.0, (block < 400 ? -20.0 : -14.0) / 20.0);
  27575. for (int i = 0; i < 480; ++i)
  27576. tone[(std::size_t) i] = (float) (gain * std::sin (2.0 * juce::MathConstants<double>::pi * 1000.0 * (block * 480 + i) / sr));
  27577. tap.push (tone.data(), tone.data(), 480, sr);
  27578. }
  27579. }
  27580. strips.refreshLoudnessForSnapshot();
  27581. offline.dispatchPendingMessages();
  27582. saveSnapshot (ui, prefix + "-mixer190am-loudness.png");
  27583. for (const auto l : { lynx::mixerlayout::Layout::compact, lynx::mixerlayout::Layout::extraLarge })
  27584. {
  27585. const auto was = lynx::MixerStrips::layout;
  27586. strips.setLayout (l);
  27587. offline.dispatchPendingMessages();
  27588. saveSnapshot (ui, prefix + "-mixer190am-loudness-" + juce::String ((int) l) + ".png");
  27589. strips.setLayout (was);
  27590. }
  27591. strips.setShowUsedOnly (true);
  27592. offline.dispatchPendingMessages();
  27593. saveSnapshot (ui, prefix + "-mixer190am-both.png");
  27594. strips.setShowUsedOnly (false);
  27595. strips.setShowLoudness (false);
  27596. offline.dispatchPendingMessages();
  27597. }
  27598. // round 168h (issue #52): FL's 8 Mixer layouts
  27599. {
  27600. const auto before = lynx::MixerStrips::layout;
  27601. for (int l = 0; l < lynx::mixerlayout::layoutCount; ++l)
  27602. {
  27603. ui.getMixerForSnapshot().getStripsForSnapshot().setLayout ((lynx::mixerlayout::Layout) l);
  27604. offline.dispatchPendingMessages();
  27605. saveSnapshot (ui, prefix + "-mixer168h-" + juce::String (l) + ".png");
  27606. }
  27607. ui.getMixerForSnapshot().getStripsForSnapshot().setLayout (before);
  27608. offline.dispatchPendingMessages();
  27609. }
  27610. // round 163: the Mixer at short heights (UI zoom 150%+): the EQ folds, then the effects panel scrolls
  27611. {
  27612. const auto size = ui.getBounds();
  27613. for (auto h : { 450, 560, 680, 820 })
  27614. {
  27615. ui.setSize (size.getWidth(), h);
  27616. offline.dispatchPendingMessages();
  27617. saveSnapshot (ui, prefix + "-mixer163-" + juce::String (h) + ".png");
  27618. }
  27619. ui.setBounds (size);
  27620. offline.dispatchPendingMessages();
  27621. }
  27622. // round 170b (Busy Works Beats' review): inserts 1-3 selected and routed together to insert 4, a single effect
  27623. // moved down into slot 2 (FL's slot places), and the plugin menus grouped by category, LYNX SHARE first
  27624. {
  27625. const auto before = offline.getSong();
  27626. offline.editSong ([] (lynx::Song& s) {
  27627. if (s.mixer.size() < 5)
  27628. return;
  27629. s.mixer[1].effects.clear();
  27630. lynx::EffectSlot fx;
  27631. fx.kind = lynx::EffectKind::compressor;
  27632. s.mixer[1].effects.push_back (fx);
  27633. lynx::mixerops::moveEffectBy (s, 1, 0, 1);
  27634. lynx::mixerops::switchSelectedRoute (s, { 1, 2, 3 }, 4, true);
  27635. });
  27636. ui.selectMixerTrackForSnapshot (1);
  27637. ui.getMixerForSnapshot().getStripsForSnapshot().setSelection ({ 1, 2, 3 }, 1);
  27638. offline.dispatchPendingMessages();
  27639. saveSnapshot (ui, prefix + "-mixer170b.png");
  27640. juce::PopupMenu effects, generators;
  27641. lynx::quickpick::addFolderGroups (effects, offline, std::function<void (lynx::EffectSlot)> ([] (lynx::EffectSlot) {}));
  27642. lynx::quickpick::addFolderViewItems (effects, offline);
  27643. lynx::quickpick::addGeneratorMenu (generators, offline, [] (lynx::ChannelDef) {}, {}, nullptr, nullptr);
  27644. lynx::quickpick::addFolderViewItems (generators, offline);
  27645. saveMenus (juce::StringArray { "Mixer slot: add an effect", "Channel Rack: add" }, { effects, generators }, prefix + "-menus170b.png");
  27646. // round 190bf (fl190be Q3): the Channel Rack's "+" menu in FL's three views, with two root entries (plugins
  27647. // at the top of the database, in no folder) and the Categories / Simple / Tree switch at the end
  27648. {
  27649. auto& host = offline.getPluginHost();
  27650. const auto keep = host.databaseFolders();
  27651. auto folders = keep;
  27652. int added = 0;
  27653. for (const auto& e : lynx::quickpick::generatorEntries (offline))
  27654. if (e.folder == 3 && e.available && added < 2) // (installed plugins: FL's root entries are such)
  27655. {
  27656. folders.top.insert (e.key);
  27657. ++added;
  27658. }
  27659. for (const auto& e : lynx::quickpick::generatorEntries (offline))
  27660. if (e.folder != 3 && added < 2)
  27661. {
  27662. folders.top.insert (e.key);
  27663. ++added;
  27664. }
  27665. static const char* const views[] { "categories", "simple", "tree" };
  27666. for (int v = 0; v < 3; ++v)
  27667. {
  27668. folders.view = v;
  27669. host.setDatabaseFolders (folders);
  27670. juce::PopupMenu plus;
  27671. lynx::quickpick::addGeneratorMenu (plus, offline, [] (lynx::ChannelDef) {}, {}, nullptr, nullptr);
  27672. lynx::quickpick::addFolderViewItems (plus, offline);
  27673. saveMenus (juce::StringArray { juce::String ("Channel Rack +: ") + views[v] }, { plus }, prefix + "-menus190bf-" + views[v] + ".png");
  27674. }
  27675. host.setDatabaseFolders (keep);
  27676. }
  27677. offline.setSong (before);
  27678. offline.dispatchPendingMessages();
  27679. }
  27680. // standalone windows, with the theme background
  27681. auto saveWindow = [&prefix] (std::unique_ptr<juce::Component> c, const juce::String& name) {
  27682. juce::Component frame;
  27683. frame.setSize (c->getWidth(), c->getHeight());
  27684. frame.setOpaque (true);
  27685. // an AlertWindow is built on the desktop: shown there first, it would take the foreground from whoever has it
  27686. // (TopLevelWindow::visibilityChanged calls toFront (true)). Off the desktop, its control that showing it would
  27687. // have focused (what grabKeyboardFocus picks) is marked, so the picture keeps that control's focus ring
  27688. if (c->isOnDesktop())
  27689. {
  27690. c->removeFromDesktop();
  27691. auto* focus = c.get();
  27692. for (int depth = 0; focus != nullptr && depth < 32; ++depth)
  27693. {
  27694. if (focus->getWantsKeyboardFocus() && (focus->isEnabled() || focus == c.get()))
  27695. {
  27696. focus->getProperties().set ("lynxSnapshotFocus", true);
  27697. break;
  27698. }
  27699. auto traverser = focus->createKeyboardFocusTraverser();
  27700. focus = traverser != nullptr ? traverser->getDefaultComponent (focus) : nullptr;
  27701. }
  27702. }
  27703. frame.addAndMakeVisible (*c);
  27704. c->setTopLeftPosition (0, 0);
  27705. checkTextFit (*c, name.fromFirstOccurrenceOf ("-", false, false).upToLastOccurrenceOf (".", false, false));
  27706. auto image = lynx::shot::paint (frame, lynx::theme::panel);
  27707. const auto file = lynx::shot::file (juce::File (prefix + name));
  27708. file.deleteFile();
  27709. juce::PNGImageFormat png;
  27710. if (auto out = file.createOutputStream())
  27711. png.writeImageToStream (image, *out);
  27712. };
  27713. saveWindow (lynx::makeExportPanel (offline), "-export.png");
  27714. saveWindow (lynx::makeExportPanel (offline, 1), "-export-mp3.png");
  27715. saveWindow (lynx::makeExportPanel (offline, 3), "-export-flac-stems.png");
  27716. {
  27717. // REA round 165f-mixer: the mixer track's Track latency / routing submenus, Disk recording, PDC, and the
  27718. // Export window for "Render selected tracks to wave file(s)"
  27719. const auto before = offline.getSong();
  27720. offline.editSong ([] (lynx::Song& s) {
  27721. if (s.mixer.size() > 3)
  27722. {
  27723. s.mixer[1].latencyMs = 5.0f;
  27724. s.mixer[1].latencyBypass = lynx::LatencyBypass::whenRecordingOrStopped;
  27725. s.mixer[2].latencyMs = -1.5f;
  27726. }
  27727. });
  27728. offline.dispatchPendingMessages();
  27729. auto& strips = ui.getMixerForSnapshot().getStripsForSnapshot();
  27730. strips.setSelection ({ 1, 2, 3 }, 1);
  27731. const auto menu = strips.buildMenu (1);
  27732. juce::StringArray names { "Mixer track" };
  27733. std::vector<juce::PopupMenu> menus { menu };
  27734. const auto latencyPrefix = lynx::tr ("Track latency: {0}", { juce::String() });
  27735. const juce::String wanted[] = { lynx::tr ("Selected tracks ⇄ this track"), lynx::tr ("Disk recording"),
  27736. lynx::tr ("Plugin delay compensation") };
  27737. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  27738. {
  27739. const auto& item = it.getItem();
  27740. if (item.subMenu != nullptr && (item.text.startsWith (latencyPrefix) || std::find (std::begin (wanted), std::end (wanted), item.text) != std::end (wanted)))
  27741. {
  27742. names.add (item.text.upToFirstOccurrenceOf (":", false, false));
  27743. menus.push_back (*item.subMenu);
  27744. }
  27745. }
  27746. saveMenus (names, menus, prefix + "-menus165-mixer.png");
  27747. saveWindow (lynx::makeExportPanelForTracks (offline, { 1, 2, 3 }), "-export165-tracks.png");
  27748. offline.setSong (before);
  27749. offline.dispatchPendingMessages();
  27750. }
  27751. saveSplashFrames (prefix);
  27752. saveIconSheet (prefix + "-icons.png", 1.0f);
  27753. saveIconSheet (prefix + "-icons-150.png", 1.5f);
  27754. saveStateSheet (prefix + "-states190je.png", 1.0f); // round 190je: the one state rule, per button kind
  27755. saveStateSheet (prefix + "-states190je-z3.png", 3.0f);
  27756. saveWindow (lynx::MainComponent::makeHelpContent(), "-help.png");
  27757. saveWindow (lynx::ui::makeTrackIconGrid (5, {}), "-trackicons168h.png"); // round 168h: the icon picker
  27758. saveWindow (std::make_unique<lynx::toolbar::CustomizePanel> (lynx::toolbarlayout::Layout::makeDefault()), "-customize-toolbar.png");
  27759. // two moved controls: Tools › Last tweaked and Add › Automation for last tweaked parameter show them (REA round 143)
  27760. offline.noteTweaked ({ lynx::AutomationTargetKind::channelVolume, 0 });
  27761. offline.noteTweaked ({ lynx::AutomationTargetKind::mixerVolume, 0 });
  27762. saveMenus (ui, prefix + "-menus.png");
  27763. {
  27764. // the windows' own menus (title bars) and the toolbar's recording menu
  27765. juce::StringArray names;
  27766. std::vector<juce::PopupMenu> menus;
  27767. for (auto [panel, name] : { std::pair { lynx::workspace::Panel::playlist, "Playlist" }, { lynx::workspace::Panel::channelRack, "Channel Rack" },
  27768. { lynx::workspace::Panel::pianoRoll, "Piano Roll" }, { lynx::workspace::Panel::mixer, "Mixer" },
  27769. { lynx::workspace::Panel::browser, "Browser" } })
  27770. {
  27771. names.add (name);
  27772. menus.push_back (ui.getPanelMenuForSnapshot (panel));
  27773. }
  27774. names.add ("Recording");
  27775. menus.push_back (ui.getRecordMenuForSnapshot());
  27776. names.add ("Toolbar");
  27777. menus.push_back (ui.getToolbarMenuForSnapshot());
  27778. saveMenus (names, menus, prefix + "-panel-menus.png");
  27779. }
  27780. // round 189e: the Playlist menu's Edit and Select submenus (FL's items and order) and the header drop question
  27781. saveMenus (juce::StringArray { "Playlist: Edit", "Playlist: Select" },
  27782. std::vector<juce::PopupMenu> { ui.getPlaylistForSnapshot().editMenu(), ui.getPlaylistForSnapshot().selectMenu() },
  27783. prefix + "-playlist-edit189e.png");
  27784. saveWindow (lynx::PlaylistComponent::makeHeaderDropDialog(), "-header-drop189e.png");
  27785. {
  27786. // round 189i: FL's fade handle menu (right-click on an audio clip's fade handle), on the song's first audio
  27787. // clip, or on one added for the shot
  27788. const auto before = offline.getSong();
  27789. auto clipIndex = -1;
  27790. for (std::size_t i = 0; i < before.playlist.size() && clipIndex < 0; ++i)
  27791. if (before.playlist[i].kind == lynx::ClipKind::audio)
  27792. clipIndex = (int) i;
  27793. if (clipIndex < 0)
  27794. {
  27795. auto song = before;
  27796. lynx::ChannelDef channel;
  27797. channel.instrument = lynx::InstrumentKind::audioClip;
  27798. channel.name = "Audio clip";
  27799. song.channels.push_back (channel);
  27800. lynx::Clip clip;
  27801. clip.kind = lynx::ClipKind::audio;
  27802. clip.channel = (int) song.channels.size() - 1;
  27803. clip.length = lynx::ppq * 4;
  27804. song.playlist.push_back (clip);
  27805. clipIndex = (int) song.playlist.size() - 1;
  27806. offline.setSong (song);
  27807. offline.dispatchPendingMessages();
  27808. }
  27809. saveMenus (juce::StringArray { "Fade handle" },
  27810. std::vector<juce::PopupMenu> { ui.getPlaylistForSnapshot().fadeHandleMenu (clipIndex, 1) },
  27811. prefix + "-fade-handle189i.png");
  27812. if (offline.getSong().playlist.size() != before.playlist.size())
  27813. {
  27814. offline.setSong (before);
  27815. offline.dispatchPendingMessages();
  27816. }
  27817. }
  27818. {
  27819. // round 189n: FL's gain handle menu with two overlapping clips selected (Normalize selection individually / as a
  27820. // group) and the later clip's fade in menu (Create crossfade enabled); FL shots in /mnt/e/lynx-work/flgap189n
  27821. const auto before = offline.getSong();
  27822. auto song = before;
  27823. lynx::ChannelDef channel;
  27824. channel.instrument = lynx::InstrumentKind::audioClip;
  27825. channel.name = "Audio clip";
  27826. song.channels.push_back (channel);
  27827. int lane = 0;
  27828. for (const auto& c : song.playlist)
  27829. lane = std::max (lane, c.track + 1);
  27830. for (int k = 0; k < 2; ++k)
  27831. {
  27832. lynx::Clip clip;
  27833. clip.kind = lynx::ClipKind::audio;
  27834. clip.channel = (int) song.channels.size() - 1;
  27835. clip.track = lane;
  27836. clip.start = k * lynx::ppq * 3;
  27837. clip.length = lynx::ppq * 4;
  27838. song.playlist.push_back (clip);
  27839. }
  27840. const auto second = (int) song.playlist.size() - 1;
  27841. song.autoCrossfades = true; // FL's capture: Thief has Automatic crossfades on
  27842. offline.setSong (song);
  27843. offline.dispatchPendingMessages();
  27844. auto& playlist = ui.getPlaylistForSnapshot();
  27845. playlist.selectForSnapshot ({ second - 1, second });
  27846. auto gain = playlist.gainMenu (second);
  27847. auto fadeIn = playlist.fadeHandleMenu (second, 0); // (both selected, as in FL's capture)
  27848. playlist.selectForSnapshot ({});
  27849. saveMenus (juce::StringArray { "Gain handle, 2 selected", "Fade in, overlapping" },
  27850. std::vector<juce::PopupMenu> { gain, fadeIn }, prefix + "-fade-gain189n.png");
  27851. // round 189o: the audio clip menu with both overlapping clips selected (FL's Fades › Crossfade selected
  27852. // shown) and with none selected (hidden)
  27853. playlist.selectForSnapshot ({ second - 1, second });
  27854. auto clipSelected = playlist.getClipMenuForSnapshot (second);
  27855. playlist.selectForSnapshot ({});
  27856. auto clipAlone = playlist.getClipMenuForSnapshot (second);
  27857. saveMenus (juce::StringArray { "Audio clip, 2 selected", "Audio clip, none selected" },
  27858. std::vector<juce::PopupMenu> { clipSelected, clipAlone }, prefix + "-xfadesel189o.png");
  27859. offline.setSong (before);
  27860. offline.dispatchPendingMessages();
  27861. }
  27862. {
  27863. // REA round 143: the piano roll Tools menu, a Playlist track menu and a mixer insert menu (FL's layouts)
  27864. std::vector<juce::PopupMenu> menus { ui.getPianoRollForSnapshot().getToolsMenuForSnapshot(),
  27865. ui.getPlaylistForSnapshot().getTrackMenuForSnapshot (0),
  27866. ui.getMixerForSnapshot().getStripsForSnapshot().buildMenu (1) };
  27867. saveMenus (juce::StringArray { "Piano roll tools", "Playlist track", "Mixer track" }, menus, prefix + "-menus143.png");
  27868. // round 190as: the Piano roll's scripts (FL's Tools › Scripts column) and a script's form
  27869. saveMenus (juce::StringArray { "Piano roll scripts" }, std::vector<juce::PopupMenu> { ui.getPianoRollForSnapshot().getScriptsMenuForSnapshot() },
  27870. prefix + "-prscripts-menu.png");
  27871. {
  27872. lynx::prscript::Score score;
  27873. const auto out = lynx::prscript::run (lynx::prscript::builtins().front().source, score, {});
  27874. if (out.status == lynx::prscript::Outcome::Status::needsForm)
  27875. {
  27876. lynx::ScriptPanel::Options options;
  27877. options.acceptText = lynx::tr ("Accept");
  27878. saveWindow (std::make_unique<lynx::ScriptPanel> (out.form, [] (const lynx::scriptform::Form&) {}, [] (const lynx::scriptform::Form&) {},
  27879. nullptr, options),
  27880. "-prscript-form.png");
  27881. }
  27882. }
  27883. // round 190j (discussion #10): the Piano roll menu's Chord stamp list
  27884. saveMenus (juce::StringArray { "Chord stamp" }, std::vector<juce::PopupMenu> { ui.getPianoRollForSnapshot().getStampMenuForSnapshot() },
  27885. prefix + "-stamp-menu.png");
  27886. // round 167l: the channel menu ("Lock active/mute state")
  27887. if (! offline.getSong().channels.empty())
  27888. saveMenus (juce::StringArray { "Channel" }, std::vector<juce::PopupMenu> { ui.getRackForSnapshot().getChannelMenuForSnapshot (0) }, prefix + "-channel-menu.png");
  27889. // round 163: menu density, compact (default) and comfortable, on a Browser folder menu
  27890. {
  27891. juce::PopupMenu folder;
  27892. folder.addSectionHeader ("Documents");
  27893. folder.addItem (1, "Expand all");
  27894. folder.addItem (2, "Collapse all");
  27895. folder.addSeparator();
  27896. folder.addItem (3, "Refresh");
  27897. folder.addSectionHeader ("System");
  27898. folder.addItem (4, "Open");
  27899. folder.addItem (5, "Copy the file path");
  27900. folder.addSectionHeader ("Tags");
  27901. folder.addItem (6, "Starred", true, true);
  27902. folder.addSeparator();
  27903. folder.addItem (7, "Add folder...");
  27904. const auto wasCompact = lynx::theme::menus::compact();
  27905. lynx::theme::menus::setCompact (true);
  27906. saveMenus (juce::StringArray { "Compact" }, { folder }, prefix + "-menu163-compact.png");
  27907. lynx::theme::menus::setCompact (false);
  27908. saveMenus (juce::StringArray { "Comfortable" }, { folder }, prefix + "-menu163-comfortable.png");
  27909. lynx::theme::menus::setCompact (wasCompact);
  27910. }
  27911. // and the clip menus of the first pattern, audio and automation clips of the project
  27912. juce::StringArray clipNames;
  27913. std::vector<juce::PopupMenu> clipMenus;
  27914. for (auto [kind, name] : { std::pair { lynx::ClipKind::pattern, "Pattern clip" }, { lynx::ClipKind::audio, "Audio clip" },
  27915. { lynx::ClipKind::automation, "Automation clip" } })
  27916. for (int c = 0; c < (int) offline.getSong().playlist.size(); ++c)
  27917. if (offline.getSong().playlist[(std::size_t) c].kind == kind)
  27918. {
  27919. clipNames.add (name);
  27920. clipMenus.push_back (ui.getPlaylistForSnapshot().getClipMenuForSnapshot (c));
  27921. break;
  27922. }
  27923. if (! clipMenus.empty())
  27924. saveMenus (clipNames, clipMenus, prefix + "-menus143-clips.png");
  27925. }
  27926. auto saveAlert = [&] (std::unique_ptr<juce::AlertWindow> alert, const juce::String& name) {
  27927. alert->setOpaque (true);
  27928. saveWindow (std::move (alert), name);
  27929. };
  27930. saveAlert (ui.makeConfirmDiscardWindow(), "-confirm.png");
  27931. saveAlert (lynx::MainComponent::makeAboutWindow(), "-about.png");
  27932. saveAlert (lynx::support::makeSupportWindow(), "-support.png"); // round 190fq: Help › Support LYNX SHARE...
  27933. saveAlert (lynx::makeNameAndColourDialog (lynx::tr ("Rename pattern"), "Pattern 2", lynx::lynxPalette()[6]), "-rename.png");
  27934. saveAlert (lynx::makeRecordChoiceDialog(), "-record-dialog.png");
  27935. // round 190ah: Online Sessions — a guest's "go back in?" at start-up, the host's question at a guest's file limit
  27936. saveAlert (lynx::liveui::makeRejoinDialog ("Ana", juce::Time (2026, 10, 10, 21, 40).toString (true, true, false, true)), "-live-rejoin.png");
  27937. saveAlert (lynx::liveui::makeMediaLimitDialog ("Pedro", (juce::int64) 1010 << 20, (juce::int64) 1 << 30), "-live-media-limit.png");
  27938. saveAlert (lynx::makeSamplePitchDialog (7.25f, true, true), "-sample-pitch.png"); // round 163c
  27939. saveAlert (lynx::makeGradientColourDialog (juce::Colour (0xffe5383b), juce::Colour (0xff3a7bd5), 8), "-gradient.png"); // round 177a
  27940. saveAlert (lynx::makeMidiImportDialog(), "-midi-import-dialog.png"); // File › Import › MIDI file (REA round 143)
  27941. // round 186c: FL's mixer "Delete" questions and its Settings › General › Manage messages menu
  27942. saveAlert (lynx::makeFlMessageDialog ({ lynx::tr ("Delete tracks"), lynx::tr ("This will |delete| {0} selected mixer track(s). Are you sure?", { "1" }),
  27943. { lynx::tr ("Yes"), lynx::tr ("No") }, true }),
  27944. "-delete-tracks.png");
  27945. saveAlert (lynx::makeFlMessageDialog ({ lynx::tr ("Playlist tracks"),
  27946. lynx::tr ("One or more mixer tracks that will be deleted are connected to instrument/audio tracks.") + "\n"
  27947. + lynx::tr ("Do you want to unlink the tracks and channels or delete them?"),
  27948. { lynx::tr ("Delete tracks and channels"), lynx::tr ("Unlink tracks and channels"), lynx::tr ("Cancel") }, false }),
  27949. "-delete-tracks-linked.png");
  27950. saveMenus (juce::StringArray { "Manage messages" }, std::vector<juce::PopupMenu> { lynx::messages::manageMenu() }, prefix + "-manage-messages.png");
  27951. saveWindow (lynx::makeSetupWizardContent (offline, {}, {}), "-setup.png");
  27952. saveWindow (lynx::crashreporter::makeDialogForSnapshot (false), "-crash-report.png"); // round 159
  27953. saveWindow (lynx::crashreporter::makeDialogForSnapshot (true), "-report-problem.png");
  27954. // round 166b: the update bar in its states (available, downloading, failed, ready) and the release notes window
  27955. {
  27956. struct Bars final : juce::Component
  27957. {
  27958. Bars()
  27959. {
  27960. constexpr int h = lynx::updater::UpdateBar::height;
  27961. setSize (1100, 6 * (h + 6));
  27962. for (int state = 0; state < 6; ++state) // (round 190gh: 4 going back, 5 went back)
  27963. {
  27964. bars[state].setBounds (0, state * (h + 6), getWidth(), h);
  27965. bars[state].showForSnapshot (state);
  27966. addAndMakeVisible (bars[state]);
  27967. }
  27968. }
  27969. lynx::updater::UpdateBar bars[6];
  27970. };
  27971. saveWindow (std::make_unique<Bars>(), "-update-bar.png");
  27972. saveWindow (lynx::updater::makeReleaseNotesForSnapshot(), "-update-notes.png");
  27973. // round 190gh (B23): Help › Test audio output... in its states
  27974. for (int state = 0; state < 5; ++state)
  27975. saveWindow (lynx::makeAudioCheckForSnapshot (offline, state), "-audio-check-" + juce::String (state) + ".png");
  27976. }
  27977. saveWindow (lynx::makeMissingFilesPanel (lynx::missingFilesSnapshotInfo(), 0, 1), "-missing-files.png");
  27978. saveWindow (lynx::makeMissingFilesPanel (lynx::missingFilesSnapshotInfo(), 1), "-missing-plugins.png");
  27979. saveWindow (lynx::makeMissingFilesPanel (lynx::missingFilesSnapshotInfo(), 2), "-missing-found.png");
  27980. {
  27981. // the Settings pages, with credits like a project imported from FL would carry
  27982. offline.editSong ([] (lynx::Song& s) {
  27983. s.info = { "Night Drive", "LYNX SHARE demo", "Synthwave", "https://lynx-share.com",
  27984. "Made with LYNX SHARE.\nDrums and bass from the Channel Rack, pads from the Browser.", false };
  27985. }, false);
  27986. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::project), "-settings-project.png");
  27987. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::info), "-settings-info.png");
  27988. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::files), "-settings-files.png");
  27989. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::general), "-settings-general.png");
  27990. {
  27991. // round 189o: the whole General page (the Editing and Plugins sections hold FL's "Monophonic painting in
  27992. // piano roll" and "Limit the number of open plugin editors")
  27993. auto tall = lynx::makeSettingsPanel (offline, lynx::SettingsPage::general);
  27994. tall->setSize (tall->getWidth(), 3200);
  27995. saveWindow (std::move (tall), "-settings-general-tall189o.png");
  27996. }
  27997. {
  27998. // the whole General page (round 186a: the Startup section is below the first screen)
  27999. auto tall = lynx::makeSettingsPanel (offline, lynx::SettingsPage::general);
  28000. tall->setSize (tall->getWidth(), 1500);
  28001. saveWindow (std::move (tall), "-settings-general-tall.png");
  28002. }
  28003. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::theme), "-settings-theme.png");
  28004. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::extras), "-settings-extras.png"); // round 190am
  28005. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::audio), "-settings-audio.png");
  28006. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::midi), "-settings-midi.png");
  28007. {
  28008. // round 190bj (QA): the MIDI page in a small window keeps each row's switch and device name
  28009. auto small = lynx::makeSettingsPanel (offline, lynx::SettingsPage::midi);
  28010. small->setSize (390, 390);
  28011. saveWindow (std::move (small), "-settings-midi-small.png");
  28012. }
  28013. {
  28014. // round 190bj (QA): the Apex Limiter's window content at its default size, as sized before (JUCE's ratio
  28015. // on the whole window: the status row cut off) and now
  28016. lynx::AudioEngine apexEngine (false);
  28017. lynx::Song song;
  28018. song.mixer.resize (2);
  28019. song.mixer[0].name = "Master";
  28020. song.mixer[1].name = "Insert 1";
  28021. song.mixer[1].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::apexLimiter));
  28022. apexEngine.setSong (std::move (song));
  28023. apexEngine.dispatchPendingMessages();
  28024. savePng (lynx::ProEditorWindows::windowContentForSnapshot (apexEngine, 1, 0, true), prefix + "-apex-window-before190bj.png");
  28025. savePng (lynx::ProEditorWindows::windowContentForSnapshot (apexEngine, 1, 0, false), prefix + "-apex-window.png");
  28026. }
  28027. saveWindow (lynx::makePluginManagerPanel (offline, false), "-plugin-manager.png");
  28028. // round 190gg: the crash prompt and a plugin window's crash notice, with "Always run ... in a separate process"
  28029. saveWindow (lynx::PluginWindows::makeCrashPromptPanel ("Serum", false), "-plugin-crash-prompt.png");
  28030. saveWindow (lynx::PluginWindows::makeCrashNoticePanel ("Serum", true), "-plugin-crash-notice.png");
  28031. saveWindow (lynx::makeShortcutManagerPanel (false), "-shortcuts.png");
  28032. }
  28033. {
  28034. // round 84: New project, Clip properties, Arrangements, Plugin performance monitor, Touch keyboard
  28035. saveWindow (lynx::makeNewProjectPanel(), "-new-project.png");
  28036. const auto& clips = offline.getSong().playlist;
  28037. for (int i = 0; i < (int) clips.size(); ++i)
  28038. if (clips[(std::size_t) i].kind == lynx::ClipKind::pattern)
  28039. {
  28040. saveWindow (lynx::makeClipPropertiesPanel (offline, i, { i, (i + 1) % (int) clips.size() }), "-clip-properties.png");
  28041. break;
  28042. }
  28043. for (int i = 0; i < (int) clips.size(); ++i)
  28044. if (clips[(std::size_t) i].kind == lynx::ClipKind::audio)
  28045. {
  28046. saveWindow (lynx::makeClipPropertiesPanel (offline, i, { i }), "-clip-properties-audio.png");
  28047. break;
  28048. }
  28049. if (offline.getSong().arrangements.size() < 2)
  28050. offline.editSong ([] (lynx::Song& s) {
  28051. const auto current = s.currentArrangement;
  28052. s.addArrangement ("Radio edit", true);
  28053. s.addArrangement ("Intro loop");
  28054. s.selectArrangement (current);
  28055. }, false);
  28056. saveWindow (lynx::makeArrangementsPanel (offline), "-arrangements.png");
  28057. saveWindow (lynx::makePluginMonitorPanel (offline), "-plugin-monitor.png");
  28058. saveWindow (lynx::makeTouchKeyboardPanel (offline), "-touch-keyboard.png");
  28059. }
  28060. {
  28061. // round 142: the Newtone / Newtime editors on a synthetic sung line (A3 B3 C4 · E4), one note moved
  28062. const auto wav = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-snapshot-newtone.wav");
  28063. {
  28064. juce::AudioBuffer<float> line (1, 44100 * 2);
  28065. const double hz[] = { 220.0, 246.94, 261.63, 0.0, 329.63 };
  28066. double ph = 0.0;
  28067. for (int i = 0; i < line.getNumSamples(); ++i)
  28068. {
  28069. const auto f0 = hz[std::min (4, i / 17640)];
  28070. 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;
  28071. float v = 0.0f;
  28072. for (int h = 1; f0 > 0.0 && h < 8; ++h)
  28073. v += (float) (0.3 / h * std::sin (h * ph));
  28074. line.setSample (0, i, v);
  28075. }
  28076. wav.deleteFile();
  28077. juce::WavAudioFormat format;
  28078. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  28079. if (auto* w = out != nullptr ? format.createWriterFor (out.get(), 44100.0, 1, 16, {}, 0) : nullptr)
  28080. {
  28081. out.release();
  28082. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  28083. writer->writeFromAudioSampleBuffer (line, 0, line.getNumSamples());
  28084. }
  28085. }
  28086. if (const auto sample = offline.getSampleLibrary().load (wav.getFullPathName()))
  28087. {
  28088. auto notes = lynx::newtonefx::analyseNotes (*sample);
  28089. if (notes.pitches.size() > 1)
  28090. notes.pitches[1].shift = 2.0;
  28091. lynx::newtonefx::WarpMap warp;
  28092. warp.frames = (std::int64_t) sample->frames();
  28093. warp.markers = { { 22050, 33075 } };
  28094. int at = 0;
  28095. offline.editSong ([&] (lynx::Song& song) {
  28096. if (song.mixer.size() < 2)
  28097. song.mixer.resize (2);
  28098. auto& fx = song.mixer[1].effects;
  28099. auto tone = lynx::makeEffectSlot (lynx::EffectKind::newtone);
  28100. tone.samplePath = wav.getFullPathName().toStdString();
  28101. tone.state = lynx::newtonefx::writeNative (notes);
  28102. auto time = lynx::makeEffectSlot (lynx::EffectKind::newtime);
  28103. time.samplePath = tone.samplePath;
  28104. time.state = lynx::newtonefx::writeWarp (warp);
  28105. at = (int) fx.size();
  28106. fx.push_back (tone);
  28107. fx.push_back (time);
  28108. }, false);
  28109. saveWindow (lynx::makeNewtoneEditor (offline, 1, at), "-newtone.png");
  28110. saveWindow (lynx::makeNewtoneEditor (offline, 1, at + 1), "-newtime.png");
  28111. offline.editSong ([at] (lynx::Song& song) {
  28112. auto& fx = song.mixer[1].effects;
  28113. fx.erase (fx.begin() + at, fx.begin() + at + 2);
  28114. }, false);
  28115. }
  28116. }
  28117. if (! offline.getSong().automations.empty())
  28118. {
  28119. auto editor = lynx::makeAutomationEditor (offline, 0);
  28120. editor->setSize (760, 300);
  28121. saveWindow (std::move (editor), "-automation.png");
  28122. // round 177b: the same clip in FL's LFO mode: FL's defaults, then one shaped state (the UI gate pairs)
  28123. const auto before = offline.getSong().automations[0].lfo;
  28124. const auto lfoShot = [&offline, &saveWindow] (std::function<void (lynx::AutomationLfo&)> set, const char* suffix) {
  28125. offline.editSong ([&set] (lynx::Song& song) {
  28126. auto& lfo = song.automations[0].lfo;
  28127. lfo = lynx::AutomationLfo {};
  28128. lfo.on = true;
  28129. set (lfo);
  28130. }, false);
  28131. auto lfoEditor = lynx::makeAutomationEditor (offline, 0);
  28132. lfoEditor->setSize (760, 346);
  28133. saveWindow (std::move (lfoEditor), suffix);
  28134. };
  28135. lfoShot ([] (lynx::AutomationLfo&) {}, "-automation-lfo.png");
  28136. lfoShot ([] (lynx::AutomationLfo& lfo) {
  28137. // the state set through FL's own UI for the UI gate (TNS 50 %, SKEW 25 %, PW 25 %, two points), as FL saved it
  28138. lfo.tension = 64;
  28139. lfo.skew = 32;
  28140. lfo.pulseWidth = 28;
  28141. lfo.amp = { { 0, 0.6716f, 0.0f }, { (std::int64_t) (lynx::ppq * 1.4128), 0.9204f, 0.0f } };
  28142. }, "-automation-lfo-shape.png");
  28143. offline.editSong ([before] (lynx::Song& song) { song.automations[0].lfo = before; }, false);
  28144. }
  28145. // round 177b: LYNX's modulators window, with one routed modulator
  28146. {
  28147. offline.editSong ([] (lynx::Song& song) {
  28148. lynx::Modulator m;
  28149. m.name = "LFO 1";
  28150. m.shape = lynx::ModShape::triangle;
  28151. m.routes = { { { lynx::AutomationTargetKind::mixerVolume, 1, 0, 0 }, 0.25f }, { { lynx::AutomationTargetKind::mixerPan, 1, 0, 0 }, -0.5f } };
  28152. song.modulators.push_back (m);
  28153. lynx::Modulator r;
  28154. r.name = "LFO 2";
  28155. r.shape = lynx::ModShape::smoothRandom;
  28156. r.sync = false;
  28157. r.hz = 0.5;
  28158. song.modulators.push_back (r);
  28159. }, false);
  28160. auto mods = lynx::makeModulatorsPanel (offline);
  28161. mods->setSize (720, 360);
  28162. saveWindow (std::move (mods), "-modulators.png");
  28163. offline.editSong ([] (lynx::Song& song) { song.modulators.clear(); }, false);
  28164. }
  28165. saveWindow (lynx::makeChannelSettingsPanel (offline, 0), "-sampler.png");
  28166. // the channel window frame (REA round 143b): header strip + tabs; the Misc tab of the first channel and of a synth
  28167. saveWindow (lynx::makeChannelFrame (offline, 0), "-channel-frame.png");
  28168. saveWindow (lynx::makeChannelFrame (offline, 0, -1), "-channel-misc.png");
  28169. for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
  28170. if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::synth)
  28171. {
  28172. saveWindow (lynx::makeChannelSettingsPanel (offline, c), "-synth.png");
  28173. saveWindow (lynx::makeChannelModulationPanel (offline, c), "-modulation.png");
  28174. break;
  28175. }
  28176. for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
  28177. if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::controller)
  28178. {
  28179. saveWindow (lynx::makeChannelSettingsPanel (offline, c), "-controller.png");
  28180. break;
  28181. }
  28182. for (const auto kind : { lynx::InstrumentKind::sakura, lynx::InstrumentKind::drumpad })
  28183. for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
  28184. if (offline.getSong().channels[(std::size_t) c].instrument == kind)
  28185. {
  28186. saveWindow (lynx::makeChannelSettingsPanel (offline, c), kind == lynx::InstrumentKind::sakura ? "-sakura.png" : "-drumpad.png");
  28187. break;
  28188. }
  28189. // round 180c: Fruity Slicer's editor
  28190. for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
  28191. if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::fruityslicer)
  28192. {
  28193. saveWindow (lynx::makeChannelSettingsPanel (offline, c), "-fruityslicer.png");
  28194. // rounds 190f / 190m: its Envelope / instrument page, one picture per target
  28195. saveWindow (lynx::makeChannelFrame (offline, c, 1), "-fruityslicer-envelope.png");
  28196. for (const auto& [target, name] : std::vector<std::pair<int, const char*>> { { 0, "panning" }, { 2, "modx" }, { 3, "mody" }, { 4, "pitch" } })
  28197. {
  28198. auto frame = lynx::makeChannelFrame (offline, c, 1);
  28199. lynx::showFlVoiceTarget (*frame, target);
  28200. saveWindow (std::move (frame), juce::String ("-fruityslicer-envelope-") + name + ".png");
  28201. }
  28202. break;
  28203. }
  28204. // round 190r: Slicex's editor
  28205. for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
  28206. if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::slicex)
  28207. {
  28208. saveWindow (lynx::makeChannelSettingsPanel (offline, c), "-slicex.png");
  28209. break;
  28210. }
  28211. // round 190q: FPC's editor
  28212. for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
  28213. if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::fpc)
  28214. {
  28215. saveWindow (lynx::makeChannelSettingsPanel (offline, c), "-fpc.png");
  28216. break;
  28217. }
  28218. // round 190hz: DirectWave's editor
  28219. for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
  28220. if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::directwave)
  28221. {
  28222. saveWindow (lynx::makeChannelSettingsPanel (offline, c), "-directwave.png");
  28223. break;
  28224. }
  28225. // parametric EQ: the one with the most pronounced curve (in an imported .flp, with FL's settings)
  28226. {
  28227. int bestTrack = -1, bestSlot = -1;
  28228. double bestShape = -1.0;
  28229. const auto& mixer = offline.getSong().mixer;
  28230. for (int t = 0; t < (int) mixer.size(); ++t)
  28231. for (int s = 0; s < (int) mixer[(std::size_t) t].effects.size(); ++s)
  28232. if (const auto& fx = mixer[(std::size_t) t].effects[(std::size_t) s]; fx.kind == lynx::EffectKind::parametricEq)
  28233. {
  28234. double shape = 0.0;
  28235. for (double hz = 30.0; hz < 18000.0; hz *= 1.5)
  28236. shape += std::abs (lynx::peq::responseDb (fx.params, 48000.0, hz));
  28237. if (shape > bestShape)
  28238. {
  28239. bestShape = shape;
  28240. bestTrack = t;
  28241. bestSlot = s;
  28242. }
  28243. }
  28244. if (bestTrack >= 0)
  28245. saveWindow (lynx::makeParametricEqEditor (offline, bestTrack, bestSlot), "-peq.png");
  28246. }
  28247. // Note inspector for the Piano Roll's notes (its selection, or all of the channel's notes)
  28248. if (auto inspector = ui.getPianoRollForSnapshot().makeNoteInspectorForSnapshot())
  28249. saveWindow (std::move (inspector), "-noteinspector.png");
  28250. if (auto inspector = ui.getPianoRollForSnapshot().makeNoteInspectorForSnapshot (true))
  28251. saveWindow (std::move (inspector), "-noteinspector-one.png");
  28252. // workflow P2: note tool dialogs (they preview on the pattern; each one puts the notes back when destroyed)
  28253. {
  28254. auto& roll = ui.getPianoRollForSnapshot();
  28255. const std::pair<lynx::NoteTool, const char*> tools[] = { { lynx::NoteTool::strum, "-tool-strum.png" },
  28256. { lynx::NoteTool::arpeggiate, "-tool-arpeggiate.png" },
  28257. { lynx::NoteTool::flip, "-tool-flip.png" },
  28258. { lynx::NoteTool::randomise, "-tool-randomise.png" },
  28259. { lynx::NoteTool::scaleLevels, "-tool-scalelevels.png" },
  28260. { lynx::NoteTool::limit, "-tool-limit.png" },
  28261. { lynx::NoteTool::quantize, "-tool-quantize.png" },
  28262. { lynx::NoteTool::chop, "-tool-chop.png" },
  28263. { lynx::NoteTool::flam, "-tool-flam.png" },
  28264. { lynx::NoteTool::lfo, "-tool-lfo.png" },
  28265. { lynx::NoteTool::claw, "-tool-claw.png" },
  28266. { lynx::NoteTool::articulate, "-tool-articulate.png" },
  28267. { lynx::NoteTool::riffMachine, "-tool-riff.png" },
  28268. { lynx::NoteTool::chordProgression, "-tool-chords.png" } };
  28269. for (const auto& [tool, name] : tools)
  28270. saveWindow (lynx::makeNoteToolPanel (offline, tool, roll.noteIndicesForSnapshot(), roll.gridForSnapshot()), name);
  28271. }
  28272. // round 83: the event editor, with sample events on the selected channel's volume (removed afterwards)
  28273. {
  28274. const lynx::AutomationTarget volume { lynx::AutomationTargetKind::channelVolume, offline.getSelectedChannel() };
  28275. const auto before = offline.getSong().patterns[(std::size_t) offline.getSong().currentPattern].events;
  28276. offline.editSong ([&] (lynx::Song& s) {
  28277. auto& lane = lynx::eventedit::laneFor (s.patterns[(std::size_t) s.currentPattern], volume);
  28278. lynx::eventedit::line (lane, 0, lynx::ppq * 2, 0.2f, 0.9f, lynx::ticksPerStep);
  28279. lynx::prtools::LfoOptions lfo;
  28280. lfo.startSpeed = 7 * 4096; // one beat
  28281. lynx::eventedit::applyLfo (lane, lynx::ppq * 2, lynx::ppq * 4, lfo, lynx::ticksPerStep);
  28282. }, false);
  28283. saveWindow (lynx::makeEventEditor (offline, volume), "-eventeditor.png");
  28284. offline.editSong ([&] (lynx::Song& s) { s.patterns[(std::size_t) s.currentPattern].events = before; }, false);
  28285. // issue #86: the same editor on the Tempo target, with the project's own Tempo events (a sample ramp if none)
  28286. const lynx::AutomationTarget tempo { lynx::AutomationTargetKind::tempo, 0 };
  28287. offline.editSong ([&] (lynx::Song& s) {
  28288. auto& lane = lynx::eventedit::laneFor (s.patterns[(std::size_t) s.currentPattern], tempo);
  28289. if (lane.events.empty())
  28290. lynx::eventedit::line (lane, 0, lynx::ppq * 2, 0.05f, 0.11f, lynx::ticksPerStep);
  28291. }, false);
  28292. saveWindow (lynx::makeEventEditor (offline, tempo), "-eventeditor-tempo.png");
  28293. {
  28294. auto compact = lynx::makeEventEditor (offline, tempo); // the toolbar in a small window
  28295. compact->setSize (640, 300);
  28296. saveWindow (std::move (compact), "-eventeditor-tempo-small.png");
  28297. auto narrowest = lynx::makeEventEditor (offline, tempo); // the tool window's lower limit
  28298. narrowest->setSize (400, 300);
  28299. saveWindow (std::move (narrowest), "-eventeditor-tempo-narrowest.png");
  28300. }
  28301. offline.editSong ([&] (lynx::Song& s) { s.patterns[(std::size_t) s.currentPattern].events = before; }, false);
  28302. }
  28303. // round 86: the audio editor with a synthetic drum loop (markers, a region, a loop), waveform and spectrogram,
  28304. // and its menu items (-audioeditor-menu.txt)
  28305. {
  28306. namespace ae = lynx::audioedit;
  28307. ae::Document d;
  28308. d.title = "Drum loop";
  28309. d.audio.sampleRate = 44100.0;
  28310. const auto frames = (std::size_t) (44100 * 2);
  28311. d.audio.channels.assign (2, std::vector<float> (frames, 0.0f));
  28312. std::uint32_t seed = 7;
  28313. for (int hit = 0; hit < 8; ++hit)
  28314. {
  28315. const auto at = (std::size_t) hit * frames / 8;
  28316. const auto kick = hit % 2 == 0;
  28317. double phase = 0.0;
  28318. for (std::size_t i = 0; i < 12000 && at + i < frames; ++i)
  28319. {
  28320. seed = seed * 1664525u + 1013904223u;
  28321. const auto noise = (float) (seed >> 8) / 16777216.0f - 0.5f;
  28322. const auto t = (double) i / 44100.0;
  28323. phase += 2.0 * 3.141592653589793 * (kick ? 45.0 + 160.0 * std::exp (-t * 30.0) : 190.0) / 44100.0;
  28324. const auto body = (float) std::sin (phase) * (float) std::exp (-t * (kick ? 9.0 : 22.0));
  28325. const auto v = kick ? 0.85f * body : 0.35f * body + 0.6f * noise * (float) std::exp (-t * 18.0);
  28326. d.audio.channels[0][at + i] += v;
  28327. d.audio.channels[1][at + i] += kick ? v : v * 0.8f + 0.1f * noise * (float) std::exp (-t * 30.0);
  28328. }
  28329. }
  28330. ae::addMarker (d, (std::int64_t) frames / 8, "Snare");
  28331. ae::addRegion (d, { (std::int64_t) frames / 2, (std::int64_t) frames * 3 / 4 }, "Fill");
  28332. ae::setLoop (d, { 0, (std::int64_t) frames });
  28333. auto wave = lynx::makeAudioEditorForSnapshot (offline, d, false);
  28334. juce::File (prefix + "-audioeditor-menu.txt").replaceWithText (lynx::audioEditorMenuForSnapshot (*wave).joinIntoString ("\n") + "\n");
  28335. saveWindow (std::move (wave), "-audioeditor.png");
  28336. saveWindow (lynx::makeAudioEditorForSnapshot (offline, d, true), "-audioeditor-spectrum.png");
  28337. }
  28338. // warp markers (round 175a, M3): the audio editor of the first audio clip whose channel has warp markers,
  28339. // opened as the Playlist opens it, with its warp lane
  28340. {
  28341. const auto& song = offline.getSong();
  28342. for (int i = 0; i < (int) song.playlist.size(); ++i)
  28343. {
  28344. const auto& c = song.playlist[(std::size_t) i];
  28345. if (c.kind == lynx::ClipKind::audio && juce::isPositiveAndBelow (c.channel, (int) song.channels.size())
  28346. && song.channels[(std::size_t) c.channel].sampler.warp.size() >= 3)
  28347. {
  28348. if (auto panel = lynx::makeAudioEditorPanel (offline, c.channel, i, true))
  28349. saveWindow (std::move (panel), "-audioeditor-warp.png");
  28350. break;
  28351. }
  28352. }
  28353. }
  28354. // the tempo tapper after five steady taps (round 132)
  28355. saveWindow (lynx::makeTempoTapperForSnapshot (offline, 5, 128.0), "-tempotapper.png");
  28356. // the Channel Rack's piano-roll view (round 132)
  28357. ui.selectTabForSnapshot (0);
  28358. ui.getRackForSnapshot().setPianoRollView (true);
  28359. offline.dispatchPendingMessages();
  28360. saveSnapshot (ui, prefix + "-rack-pianoroll-view.png");
  28361. ui.getRackForSnapshot().setPianoRollView (false);
  28362. // the Channel Rack with the step graph lane (velocity), and the Euclidean fill window
  28363. ui.selectTabForSnapshot (0);
  28364. ui.getRackForSnapshot().setGraphLevelForSnapshot (0);
  28365. offline.dispatchPendingMessages();
  28366. saveSnapshot (ui, prefix + "-rack-graph.png");
  28367. ui.getRackForSnapshot().setGraphLevelForSnapshot (1);
  28368. saveSnapshot (ui, prefix + "-rack-graph-pan.png");
  28369. ui.getRackForSnapshot().toggleGraphLanes();
  28370. saveWindow (ui.getRackForSnapshot().makeEuclideanPanel (0), "-euclidean.png");
  28371. // the Mixer with three inserts selected and one armed for recording
  28372. ui.selectTabForSnapshot (3);
  28373. if (offline.getSong().mixer.size() > 4)
  28374. {
  28375. ui.getMixerForSnapshot().getStripsForSnapshot().setSelection ({ 1, 2, 3 }, 2);
  28376. offline.setInsertArmed (3, true);
  28377. offline.dispatchPendingMessages();
  28378. saveSnapshot (ui, prefix + "-mixer-multi.png");
  28379. // the armed insert with an audio input (its input row in the side panel, the level bar on the strip)
  28380. offline.editSong ([] (lynx::Song& s) { s.mixer[3].inputChannel = 0; });
  28381. ui.getMixerForSnapshot().selectTrack (3);
  28382. offline.dispatchPendingMessages();
  28383. saveSnapshot (ui, prefix + "-mixer-input.png");
  28384. offline.undo();
  28385. offline.setInsertArmed (3, false);
  28386. ui.getMixerForSnapshot().getStripsForSnapshot().setSelection ({}, 0);
  28387. }
  28388. // the Mixer's routing lane: an insert with sends selected (send knobs and wires)
  28389. if (offline.getSong().mixer.size() > 6)
  28390. {
  28391. int source = -1;
  28392. for (int t = 1; t < (int) offline.getSong().mixer.size() && source < 0; ++t)
  28393. if (! offline.getSong().mixer[(std::size_t) t].sends.empty())
  28394. source = t;
  28395. const auto temporary = source < 0;
  28396. if (temporary) // the demo has no sends: add two for the picture
  28397. {
  28398. source = 1;
  28399. 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); });
  28400. }
  28401. ui.getMixerForSnapshot().selectTrack (source);
  28402. offline.dispatchPendingMessages();
  28403. saveSnapshot (ui, prefix + "-mixer-sends.png");
  28404. if (temporary)
  28405. offline.editSong ([] (lynx::Song& s) { s.setRoute (1, 5, false); s.setRoute (1, 6, false); s.setRoute (4, 1, false); });
  28406. ui.getMixerForSnapshot().selectTrack (0);
  28407. }
  28408. // round 190io (issue #154 part 2): the Mixer view that lists each strip's insert effects (a LYNX view, off by
  28409. // default), with an insert selected whose sends light the route arrows
  28410. {
  28411. auto& strips = ui.getMixerForSnapshot().getStripsForSnapshot();
  28412. strips.setShowStripInserts (true);
  28413. offline.dispatchPendingMessages();
  28414. saveSnapshot (ui, prefix + "-mixer190io-inserts.png");
  28415. strips.setShowStripInserts (false);
  28416. offline.dispatchPendingMessages();
  28417. }
  28418. // the Playlist with ripple editing on
  28419. ui.selectTabForSnapshot (2);
  28420. ui.getPlaylistForSnapshot().setRipple (true);
  28421. saveSnapshot (ui, prefix + "-playlist-ripple.png");
  28422. ui.getPlaylistForSnapshot().setRipple (false);
  28423. // FL's legacy Pattern Blocks (round 170f, issue #60): the section under the clip tracks, a row per pattern
  28424. {
  28425. const auto saved = offline.getSong();
  28426. offline.editSong ([] (lynx::Song& s) {
  28427. s.patternBlocksOn = true;
  28428. while (s.patterns.size() < 5) // a few rows to show (Drums, Bass...: copies of the demo's pattern)
  28429. lynx::clonePattern (s, (int) s.patterns.size() - 1);
  28430. const auto rows = juce::jmin (6, (int) s.patterns.size());
  28431. for (int r = 0; r < rows; ++r)
  28432. lynx::patternblocks::paintRange (s, r, (std::int64_t) (r % 3) * 4 * lynx::ppq * 2,
  28433. (std::int64_t) (8 + r * 2) * 4 * lynx::ppq);
  28434. }, false);
  28435. offline.dispatchPendingMessages();
  28436. saveSnapshot (ui, prefix + "-playlist-blocks.png");
  28437. // issue #127 (PR #132 and our follow-up): the Playlist's pencil, brush and eraser on the blocks, driven
  28438. // with real mouse events on the view. One picture per tool, and the gestures' results in
  28439. // <prefix>-playlist-blocks-tools.txt ("OK", or the checks that failed).
  28440. if (auto* blocks = ui.getPlaylistForSnapshot().getBlocksViewForSnapshot())
  28441. {
  28442. juce::StringArray failed;
  28443. const auto expect = [&failed] (bool ok, const char* what) { if (! ok) failed.add (what); };
  28444. const auto bar = offline.getSong().barTicks();
  28445. offline.editSong ([bar] (lynx::Song& s) {
  28446. s.blocks.clear();
  28447. for (std::size_t r = 0; r < 4 && r < s.patterns.size(); ++r)
  28448. s.patterns[r].lengthTicks = r == 1 ? 2 * bar : bar; // row 2 holds a 2-bar pattern
  28449. }, false);
  28450. offline.dispatchPendingMessages();
  28451. const auto source = juce::Desktop::getInstance().getMainMouseSource();
  28452. const juce::ModifierKeys left (juce::ModifierKeys::leftButtonModifier), right (juce::ModifierKeys::rightButtonModifier);
  28453. juce::Point<float> pressedAt;
  28454. const auto event = [&] (int row, std::int64_t tick, juce::ModifierKeys mods) {
  28455. const auto at = blocks->pointForSnapshot (row, tick).toFloat();
  28456. const auto now = juce::Time::getCurrentTime();
  28457. return juce::MouseEvent (source, at, mods, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, blocks, blocks, now, pressedAt, now, 1, false);
  28458. };
  28459. const auto press = [&] (int row, std::int64_t tick, juce::ModifierKeys mods) {
  28460. pressedAt = blocks->pointForSnapshot (row, tick).toFloat();
  28461. blocks->mouseDown (event (row, tick, mods));
  28462. };
  28463. const auto dragTo = [&] (int row, std::int64_t tick, juce::ModifierKeys mods) { blocks->mouseDrag (event (row, tick, mods)); };
  28464. const auto release = [&] (int row, std::int64_t tick) { blocks->mouseUp (event (row, tick, {})); };
  28465. // the starts of row `row`'s blocks, as "0,2,5" (bars from 0)
  28466. const auto rowBars = [&] (int row) {
  28467. juce::StringArray bars;
  28468. for (const auto& b : offline.getSong().blocks)
  28469. if (b.pattern == row)
  28470. bars.add (juce::String (b.start / bar) + (b.start % bar != 0 ? "+" : ""));
  28471. return bars.joinIntoString (",");
  28472. };
  28473. auto& tools = ui.getPlaylistForSnapshot();
  28474. // Pencil: a press on empty space places one block that follows the mouse along its row
  28475. tools.setToolForSnapshot (lynx::EditTool::pencil);
  28476. press (0, 2 * bar + 40, left);
  28477. expect (rowBars (0) == "2", "pencil: a press places one block");
  28478. dragTo (2, 5 * bar + 40, left); // (over another row: the block stays in its own)
  28479. release (2, 5 * bar + 40);
  28480. expect (rowBars (0) == "5" && rowBars (2).isEmpty(), "pencil: the placed block follows the drag in its row");
  28481. // a 2-bar block grabbed by its second bar keeps that bar under the mouse (it used to jump a bar)
  28482. press (1, 1 * bar + 40, left);
  28483. release (1, 1 * bar + 40);
  28484. expect (rowBars (1) == "1", "pencil: a click places the 2-bar block");
  28485. press (1, 2 * bar + 40, left);
  28486. dragTo (1, 2 * bar + bar / 2, left);
  28487. expect (rowBars (1) == "1", "move: a small move on the grabbed bar leaves the block in place");
  28488. dragTo (1, 4 * bar + 40, left);
  28489. release (1, 4 * bar + 40);
  28490. expect (rowBars (1) == "3", "move: the grabbed bar stays under the mouse");
  28491. offline.dispatchPendingMessages();
  28492. saveSnapshot (ui, prefix + "-playlist-blocks-pencil.png");
  28493. // Brush: a drag over empty space paints a run; a press on a block moves it
  28494. tools.setToolForSnapshot (lynx::EditTool::brush);
  28495. press (2, 0, left);
  28496. dragTo (2, 3 * bar + 40, left);
  28497. release (2, 3 * bar + 40);
  28498. expect (rowBars (2) == "0,1,2,3", "brush: a drag paints a run");
  28499. press (2, 3 * bar + 40, left);
  28500. dragTo (2, 6 * bar + 40, left);
  28501. release (2, 6 * bar + 40);
  28502. expect (rowBars (2) == "0,1,2,6", "brush: a press on a block moves it");
  28503. offline.dispatchPendingMessages();
  28504. saveSnapshot (ui, prefix + "-playlist-blocks-brush.png");
  28505. // Eraser, and the right button with any tool: only the blocks under the mouse, row by row
  28506. offline.editSong ([bar] (lynx::Song& s) {
  28507. for (int r = 0; r < 4 && r < (int) s.patterns.size(); ++r)
  28508. lynx::patternblocks::place (s, r, 8 * bar);
  28509. }, false);
  28510. offline.dispatchPendingMessages();
  28511. expect (rowBars (0) == "5,8" && rowBars (3) == "8", "eraser: the column is set up");
  28512. saveSnapshot (ui, prefix + "-playlist-blocks-eraser-before.png");
  28513. tools.setToolForSnapshot (lynx::EditTool::eraser);
  28514. press (0, 8 * bar + 40, left);
  28515. expect (rowBars (0) == "5" && rowBars (1) == "3,8" && rowBars (2) == "0,1,2,6,8" && rowBars (3) == "8",
  28516. "eraser: a click takes only the block under the mouse");
  28517. dragTo (1, 8 * bar + 60, left); // down one row: that row's block goes too, the rows below stay
  28518. release (1, 8 * bar + 60);
  28519. expect (rowBars (1) == "3" && rowBars (2) == "0,1,2,6,8" && rowBars (3) == "8", "eraser: the drag erases the rows it crosses, no others");
  28520. tools.setToolForSnapshot (lynx::EditTool::pencil);
  28521. press (3, 8 * bar + 40, right);
  28522. release (3, 8 * bar + 40);
  28523. expect (rowBars (3).isEmpty() && rowBars (2) == "0,1,2,6,8", "right click: erases only the block under the mouse");
  28524. offline.dispatchPendingMessages();
  28525. saveSnapshot (ui, prefix + "-playlist-blocks-eraser.png");
  28526. juce::File (prefix + "-playlist-blocks-tools.txt").replaceWithText (failed.isEmpty() ? juce::String ("OK\n") : "ERROR\n" + failed.joinIntoString ("\n") + "\n");
  28527. }
  28528. offline.editSong ([saved] (lynx::Song& s) { s = saved; }, false);
  28529. offline.dispatchPendingMessages();
  28530. }
  28531. // quick-add palette, and the Browser searching
  28532. saveWindow (ui.makeQuickAddForSnapshot(), "-quickadd.png");
  28533. ui.showDesktopForSnapshot (false);
  28534. ui.getBrowserForSnapshot().setSearchForSnapshot ("kick");
  28535. offline.dispatchPendingMessages();
  28536. saveSnapshot (ui, prefix + "-browser-search.png");
  28537. ui.getBrowserForSnapshot().setSearchForSnapshot ({});
  28538. ui.getBrowserForSnapshot().selectFirstSampleForSnapshot(); // the tree with a sample selected and its waveform
  28539. offline.dispatchPendingMessages();
  28540. saveSnapshot (ui, prefix + "-browser-tree.png");
  28541. // the Browser's PROJECT tab: the patterns, generators and audio files of the project in their colours
  28542. ui.getBrowserForSnapshot().showProjectForSnapshot();
  28543. offline.dispatchPendingMessages();
  28544. saveSnapshot (ui, prefix + "-browser-project.png");
  28545. ui.getBrowserForSnapshot().showPluginDatabaseForSnapshot(); // round 142: the Plugin database's FL engines
  28546. offline.dispatchPendingMessages();
  28547. saveSnapshot (ui, prefix + "-browser-plugins.png");
  28548. // round 190bf (fl190be Q1): the Plugin database's right-click menus, a folder's and an entry's (FL's System group)
  28549. saveMenus (juce::StringArray { "Plugin database: folder", "Plugin database: entry" }, ui.getBrowserForSnapshot().pluginDatabaseMenusForSnapshot(),
  28550. prefix + "-browser190bf-menus.png");
  28551. ui.getBrowserForSnapshot().setTab (lynx::BrowserComponent::allTab);
  28552. saveWindow (ui.getBrowserForSnapshot().makeFoldersPanelForSnapshot(), "-browser-folders.png"); // round 164
  28553. {
  28554. // round 164: the content filter leaves out the folders with nothing to list (a small library)
  28555. const auto lib = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-snapshot-library");
  28556. lib.deleteRecursively();
  28557. for (const auto* path : { "Drums/Kicks/kick 1.wav", "Drums/Kicks/kick 2.wav", "Drums/snare.wav", "Keys/pad.sf2", "Presets/Synth/lead.fst",
  28558. "Projects/beat.flp", "Projects/MIDI/chords.mid", "Notes/readme.txt", "Empty/Nothing/.keep" })
  28559. lib.getChildFile (path).create();
  28560. ui.showDesktopForSnapshot (false);
  28561. ui.getBrowserForSnapshot().showFilterForSnapshot (lib, lynx::browserview::ContentFilter::all);
  28562. offline.dispatchPendingMessages();
  28563. saveSnapshot (ui, prefix + "-browser164-all.png");
  28564. ui.getBrowserForSnapshot().showFilterForSnapshot (lib, lynx::browserview::ContentFilter::samples);
  28565. offline.dispatchPendingMessages();
  28566. saveSnapshot (ui, prefix + "-browser164-samples.png");
  28567. ui.getBrowserForSnapshot().showFilterForSnapshot (lib, lynx::browserview::ContentFilter::projects);
  28568. offline.dispatchPendingMessages();
  28569. saveSnapshot (ui, prefix + "-browser164-projects.png");
  28570. lib.deleteRecursively();
  28571. ui.getBrowserForSnapshot().resetViewForSnapshot();
  28572. }
  28573. {
  28574. // round 190as: "Find similar samples" on a small library of kicks, hats and pads (LYNX_SNAPSHOT_SIMILAR =
  28575. // "<folder>|<file>" lists a real folder instead)
  28576. auto lib = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-snapshot-similar");
  28577. auto query = lib.getChildFile ("Drums/Kicks/Kick 2.wav");
  28578. const auto real = juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIMILAR", {});
  28579. const auto made = real.isEmpty();
  28580. if (made)
  28581. {
  28582. lib.deleteRecursively();
  28583. juce::Random random (190);
  28584. const auto write = [&] (const juce::String& path, char kind, int v) {
  28585. const auto rate = 44100.0;
  28586. const auto frames = (int) (rate * (kind == 'k' ? 0.35 : kind == 'h' ? 0.09 : 2.5));
  28587. juce::AudioBuffer<float> audio (1, frames);
  28588. double phase = 0.0;
  28589. float last = 0.0f;
  28590. for (int i = 0; i < frames; ++i)
  28591. {
  28592. const auto t = i / rate;
  28593. float x = 0.0f;
  28594. if (kind == 'k')
  28595. {
  28596. phase += juce::MathConstants<double>::twoPi * ((46.0 + 3.0 * v) + 150.0 * std::exp (-t * 35.0)) / rate;
  28597. x = (float) (std::sin (phase) * std::exp (-t * (8.0 + v)));
  28598. }
  28599. else if (kind == 'h')
  28600. {
  28601. const auto n = random.nextFloat() * 2.0f - 1.0f;
  28602. x = (n - last) * 0.5f * (float) std::exp (-t * (50.0 + 12.0 * v));
  28603. last = n;
  28604. }
  28605. else
  28606. {
  28607. const auto base = 220.0 * std::pow (2.0, v / 12.0);
  28608. x = (float) (0.25 * std::min (1.0, t / 0.4) * std::min (1.0, (2.5 - t) / 0.5)
  28609. * (std::sin (juce::MathConstants<double>::twoPi * base * t) + std::sin (juce::MathConstants<double>::twoPi * base * 1.5 * t)));
  28610. }
  28611. audio.setSample (0, i, 0.8f * x);
  28612. }
  28613. const auto file = lib.getChildFile (path);
  28614. file.getParentDirectory().createDirectory();
  28615. juce::WavAudioFormat wav;
  28616. if (auto out = file.createOutputStream())
  28617. if (auto writer = std::unique_ptr<juce::AudioFormatWriter> (wav.createWriterFor (out.release(), rate, 1, 16, {}, 0)))
  28618. writer->writeFromAudioSampleBuffer (audio, 0, frames);
  28619. };
  28620. for (int v = 1; v <= 5; ++v)
  28621. {
  28622. write ("Drums/Kicks/Kick " + juce::String (v) + ".wav", 'k', v);
  28623. write ("Drums/Hats/Hat " + juce::String (v) + ".wav", 'h', v);
  28624. write ("Keys/Pad " + juce::String (v) + ".wav", 'p', v);
  28625. }
  28626. }
  28627. else
  28628. {
  28629. lib = juce::File (real.upToFirstOccurrenceOf ("|", false, false));
  28630. query = juce::File (real.fromFirstOccurrenceOf ("|", false, false));
  28631. }
  28632. ui.showDesktopForSnapshot (false);
  28633. ui.getBrowserForSnapshot().showFilterForSnapshot (lib, lynx::browserview::ContentFilter::all);
  28634. ui.getBrowserForSnapshot().findSimilarForSnapshot (query, lib);
  28635. offline.dispatchPendingMessages();
  28636. saveSnapshot (ui, prefix + "-browser-similar.png");
  28637. ui.getBrowserForSnapshot().setSearchForSnapshot ({});
  28638. if (made)
  28639. lib.deleteRecursively();
  28640. ui.getBrowserForSnapshot().resetViewForSnapshot();
  28641. }
  28642. // the undo history after a few edits
  28643. offline.editSong ([] (lynx::Song& s) { s.bpm += 1.0; });
  28644. offline.editSong ([] (lynx::Song& s) { if (! s.channels.empty()) s.channels[0].muted = ! s.channels[0].muted; });
  28645. offline.editSong ([] (lynx::Song& s) { if (! s.patterns.empty()) s.patterns[(std::size_t) s.currentPattern].notes.push_back ({}); });
  28646. offline.undo();
  28647. saveWindow (lynx::makeHistoryPanel (offline), "-history.png");
  28648. // spectral waveforms: a synthetic beat (kick, hats, a chord, a noise riser) as audio clips in spectral
  28649. // colours, zoomed in, classic and stereo; the same file in the Sampler editor and the Browser preview
  28650. {
  28651. const juce::File wav (prefix + "-wavedemo.wav");
  28652. writeWaveDemo (wav, offline.getSong().bpm);
  28653. const auto path = wav.getFullPathName();
  28654. const auto pathUtf8 = path.toStdString();
  28655. int samplerChannel = -1, firstTrack = 0;
  28656. offline.editSong ([&] (lynx::Song& s) {
  28657. for (const auto& clip : s.playlist)
  28658. firstTrack = std::max (firstTrack, clip.track + 1);
  28659. lynx::ChannelDef audio;
  28660. audio.name = "Beat (audio)";
  28661. audio.instrument = lynx::InstrumentKind::audioClip;
  28662. audio.samplePath = pathUtf8;
  28663. s.channels.push_back (audio);
  28664. const auto audioChannel = (int) s.channels.size() - 1;
  28665. lynx::ChannelDef sampler = audio;
  28666. sampler.name = "Beat (sampler)";
  28667. sampler.instrument = lynx::InstrumentKind::sampler;
  28668. sampler.sampler.regionStart = 0.06f;
  28669. sampler.sampler.regionEnd = 0.94f;
  28670. s.channels.push_back (sampler);
  28671. samplerChannel = (int) s.channels.size() - 1;
  28672. const auto bar = s.barTicks();
  28673. const auto whole = (std::int64_t) std::llround (8.0 * s.bpm / 60.0 * lynx::ppq);
  28674. lynx::Clip clip;
  28675. clip.kind = lynx::ClipKind::audio;
  28676. clip.channel = audioChannel;
  28677. clip.track = firstTrack;
  28678. clip.length = whole;
  28679. s.playlist.push_back (clip);
  28680. clip.track = firstTrack + 1; // a slice of it, later in the song
  28681. clip.start = bar;
  28682. clip.offset = bar;
  28683. clip.length = 2 * bar;
  28684. s.playlist.push_back (clip);
  28685. // taller rows for the audio (tracks can be resized: P18)
  28686. if ((int) s.playlistTracks.size() < firstTrack + 2)
  28687. s.playlistTracks.resize ((std::size_t) firstTrack + 2);
  28688. s.playlistTracks[(std::size_t) firstTrack].height = 80;
  28689. s.playlistTracks[(std::size_t) firstTrack + 1].height = 60;
  28690. });
  28691. offline.dispatchPendingMessages();
  28692. auto& cache = *lynx::ui::WaveformCache::getInstance();
  28693. cache.find (path, [&offline, path] { return offline.getSampleLibrary().load (path); });
  28694. cache.waitUntilIdle (30000);
  28695. ui.selectTabForSnapshot (2);
  28696. auto& playlist = ui.getPlaylistForSnapshot();
  28697. playlist.setTimeSelectionForSnapshot (0, 0);
  28698. {
  28699. // the Playlist alone (the floating Channel Rack would cover the clips)
  28700. auto saveSnapshot = [&playlist] (juce::Component&, const juce::String& file) { saveArea (playlist, playlist.getLocalBounds(), file); };
  28701. playlist.setViewForSnapshot (180.0, 0, std::max (0, firstTrack - 3));
  28702. saveSnapshot (ui, prefix + "-playlist-audio.png");
  28703. playlist.setViewForSnapshot (1400.0, 0, std::max (0, firstTrack - 3));
  28704. saveSnapshot (ui, prefix + "-playlist-audio-zoom.png");
  28705. lynx::ui::WaveformCache::stereo = true;
  28706. saveSnapshot (ui, prefix + "-playlist-audio-stereo.png");
  28707. lynx::ui::WaveformCache::stereo = false;
  28708. lynx::ui::WaveformCache::spectral = true;
  28709. playlist.setViewForSnapshot (180.0, 0, std::max (0, firstTrack - 3));
  28710. saveSnapshot (ui, prefix + "-playlist-audio-spectral.png");
  28711. lynx::ui::WaveformCache::spectral = false;
  28712. playlist.setViewForSnapshot (40.0, 0, 0);
  28713. saveSnapshot (ui, prefix + "-playlist-audio-far.png");
  28714. // LYNX_SNAPSHOT_AUDIO=a.wav;b.wav...: real audio as clips (default-height tracks, one tall,
  28715. // a fade, a reversed copy), at three zoom levels
  28716. if (const auto files = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_AUDIO", {}), ";", "");
  28717. ! files.isEmpty())
  28718. {
  28719. const auto realTrack = firstTrack + 2;
  28720. std::vector<juce::String> paths;
  28721. for (const auto& f : files)
  28722. if (juce::File (f.trim()).existsAsFile())
  28723. paths.push_back (f.trim());
  28724. offline.editSong ([&] (lynx::Song& s) {
  28725. const auto bar = s.barTicks();
  28726. const std::uint32_t colours[] = { 0, 0xffd9a441, 0xff6fb36a, 0xffb06fd0, 0xff5fb7c9, 0xffd06f6f };
  28727. for (std::size_t i = 0; i < paths.size(); ++i)
  28728. {
  28729. lynx::ChannelDef audio;
  28730. audio.name = juce::File (paths[i]).getFileNameWithoutExtension().toStdString();
  28731. audio.instrument = lynx::InstrumentKind::audioClip;
  28732. audio.samplePath = paths[i].toStdString();
  28733. audio.colour = colours[i % 6];
  28734. audio.sampler.stretchBeats = i % 2 == 0 ? 16.0f : 0.0f; // fitted to 4 bars, or as recorded
  28735. audio.sampler.keepPitch = true;
  28736. s.channels.push_back (audio);
  28737. lynx::Clip clip;
  28738. clip.kind = lynx::ClipKind::audio;
  28739. clip.channel = (int) s.channels.size() - 1;
  28740. clip.track = realTrack + (int) i;
  28741. clip.length = 4 * bar;
  28742. clip.fadeIn = i == 1 ? bar / 2 : 0;
  28743. s.playlist.push_back (clip);
  28744. clip.start = 4 * bar;
  28745. clip.fadeIn = 0;
  28746. clip.fadeOut = i == 0 ? bar : 0;
  28747. s.playlist.push_back (clip);
  28748. }
  28749. if ((int) s.playlistTracks.size() < realTrack + (int) paths.size())
  28750. s.playlistTracks.resize ((std::size_t) realTrack + paths.size());
  28751. if (! paths.empty())
  28752. s.playlistTracks[(std::size_t) realTrack].height = 90;
  28753. });
  28754. offline.dispatchPendingMessages();
  28755. for (const auto& path2 : paths)
  28756. cache.find (path2, [&offline, path2] { return offline.getSampleLibrary().load (path2); });
  28757. cache.waitUntilIdle (60000);
  28758. playlist.setViewForSnapshot (160.0, 0, std::max (0, realTrack - 4));
  28759. saveSnapshot (ui, prefix + "-playlist-real.png");
  28760. playlist.setViewForSnapshot (700.0, 0, std::max (0, realTrack - 1));
  28761. saveSnapshot (ui, prefix + "-playlist-real-zoom.png");
  28762. playlist.setViewForSnapshot (2400.0, 0, std::max (0, realTrack - 1));
  28763. saveSnapshot (ui, prefix + "-playlist-real-close.png");
  28764. playlist.setViewForSnapshot (50.0, 0, std::max (0, realTrack - 4));
  28765. saveSnapshot (ui, prefix + "-playlist-real-far.png");
  28766. // the clip menu of the first real clip
  28767. if (const auto menu = playlist.getClipMenuForSnapshot ((int) offline.getSong().playlist.size() - (int) paths.size() * 2); menu.getNumItems() > 0)
  28768. saveMenus (juce::StringArray { "Audio clip" }, std::vector<juce::PopupMenu> { menu }, prefix + "-clip-menu-audio.png");
  28769. if (const auto menu = playlist.getClipMenuForSnapshot (0); menu.getNumItems() > 0)
  28770. saveMenus (juce::StringArray { "Pattern clip" }, std::vector<juce::PopupMenu> { menu }, prefix + "-clip-menu-pattern.png");
  28771. // the clip menu's actions, run through the menu itself; results in -clip-actions.txt
  28772. {
  28773. juce::StringArray log;
  28774. auto clipOf = [&offline] (const std::string& channelName, int nth) {
  28775. const auto& sg = offline.getSong();
  28776. for (int i = 0; i < (int) sg.playlist.size(); ++i)
  28777. {
  28778. const auto& c = sg.playlist[(std::size_t) i];
  28779. if (c.kind == lynx::ClipKind::audio && c.channel >= 0 && sg.channels[(std::size_t) c.channel].name == channelName && nth-- == 0)
  28780. return i;
  28781. }
  28782. return -1;
  28783. };
  28784. std::function<bool (const juce::PopupMenu&, const juce::String&)> run = [&run] (const juce::PopupMenu& m, const juce::String& text) {
  28785. for (juce::PopupMenu::MenuItemIterator it (m); it.next();)
  28786. {
  28787. auto& item = it.getItem();
  28788. if (item.subMenu != nullptr && run (*item.subMenu, text))
  28789. return true;
  28790. // (without the menu mnemonic's mark: FL's underlined letters, round 190dz)
  28791. if (item.text.removeCharacters (juce::String::charToString (1)).startsWith (text) && item.isEnabled && item.action)
  28792. {
  28793. item.action();
  28794. return true;
  28795. }
  28796. }
  28797. return false;
  28798. };
  28799. auto act = [&] (const std::string& name, int nth, const juce::String& text) {
  28800. const auto clip = clipOf (name, nth);
  28801. const auto ok = clip >= 0 && run (playlist.getClipMenuForSnapshot (clip), text);
  28802. offline.dispatchPendingMessages();
  28803. return ok;
  28804. };
  28805. auto channelOf = [&] (const std::string& name) -> const lynx::ChannelDef* {
  28806. for (const auto& c : offline.getSong().channels)
  28807. if (c.name == name)
  28808. return &c;
  28809. return nullptr;
  28810. };
  28811. auto check = [&log] (const juce::String& what, bool ok) { log.add ((ok ? "OK " : "FAIL ") + what); };
  28812. const auto names = [&] { std::vector<std::string> n; for (auto& p2 : paths) n.push_back (juce::File (p2).getFileNameWithoutExtension().toStdString()); return n; }();
  28813. if (names.size() >= 4)
  28814. {
  28815. const auto channelsBefore = offline.getSong().channels.size();
  28816. check ("Reverse", act (names[2], 0, lynx::tr ("Reverse")) && channelOf (names[2])->sampler.reverse);
  28817. offline.undo();
  28818. offline.dispatchPendingMessages();
  28819. check ("Reverse undone", ! channelOf (names[2])->sampler.reverse);
  28820. act (names[2], 0, lynx::tr ("Reverse"));
  28821. check ("Make unique", act (names[3], 1, lynx::tr ("Make unique")) && offline.getSong().channels.size() == channelsBefore + 1
  28822. && channelOf (names[3] + " #2") != nullptr);
  28823. check ("Fit to tempo, resample", act (names[1], 0, lynx::tr ("Fit to tempo, resample ({0})", { juce::String() }).upToFirstOccurrenceOf ("(", false, false))
  28824. && channelOf (names[1])->sampler.stretchBeats > 0.0f && ! channelOf (names[1])->sampler.keepPitch);
  28825. const auto gainBefore = offline.getSong().playlist[(std::size_t) clipOf (names[0], 1)].gain;
  28826. check ("Normalize", act (names[0], 1, lynx::tr ("Normalize"))
  28827. && offline.getSong().playlist[(std::size_t) clipOf (names[0], 1)].gain != gainBefore);
  28828. const auto clipsBefore = offline.getSong().playlist.size();
  28829. check ("Split here", act (names[3], 0, lynx::tr ("Split here")) && offline.getSong().playlist.size() == clipsBefore + 1);
  28830. check ("Mute", act (names[0], 0, lynx::tr ("Mute")) && offline.getSong().playlist[(std::size_t) clipOf (names[0], 0)].muted);
  28831. check ("Copy + Paste here", act (names[0], 0, lynx::tr ("Copy")) && act (names[0], 1, lynx::tr ("Paste here"))
  28832. && offline.getSong().playlist.size() == clipsBefore + 2);
  28833. check ("Delete", act (names[0], 2, lynx::tr ("Delete")) && offline.getSong().playlist.size() == clipsBefore + 1);
  28834. check ("Chop to grid", act (names[3], 0, lynx::tr ("Chop to grid")) && offline.getSong().playlist.size() > clipsBefore + 1);
  28835. }
  28836. playlist.setViewForSnapshot (160.0, 0, std::max (0, realTrack - 4));
  28837. saveSnapshot (ui, prefix + "-playlist-real-actions.png");
  28838. juce::File (prefix + "-clip-actions.txt").replaceWithText (log.joinIntoString ("\n") + "\n");
  28839. }
  28840. }
  28841. }
  28842. saveWindow (lynx::makeChannelSettingsPanel (offline, samplerChannel), "-sampler-wave.png");
  28843. ui.showDesktopForSnapshot (false);
  28844. ui.getBrowserForSnapshot().showPreviewForSnapshot (wav);
  28845. saveSnapshot (ui, prefix + "-browser-preview.png");
  28846. }
  28847. }
  28848. // round 165o: every Label / button / tick box whose text the drawing squeezes below its minimum scale or cuts
  28849. // (an ellipsis), per language: `LYNX --lang de --snapshot shots/de` -> shots/de-textfit.txt
  28850. juce::File (prefix + "-textfit.txt").replaceWithText (textFitLog().joinIntoString ("\n") + "\n");
  28851. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  28852. quit();
  28853. }
  28854. // --snapshot: 8 s of a synthetic stereo beat whose parts sit in different bands (kick = low, chord = mid,
  28855. // hats and the noise riser = high), to show the spectral waveform colours
  28856. static void writeWaveDemo (const juce::File& file, double bpm)
  28857. {
  28858. constexpr double rate = 44100.0;
  28859. const auto frames = (int) (8.0 * rate);
  28860. juce::AudioBuffer<float> buffer (2, frames);
  28861. buffer.clear();
  28862. auto* l = buffer.getWritePointer (0);
  28863. auto* r = buffer.getWritePointer (1);
  28864. const auto beat = 60.0 / juce::jlimit (40.0, 300.0, bpm);
  28865. std::uint32_t noise = 0x9e3779b9u;
  28866. auto white = [&noise] {
  28867. noise ^= noise << 13;
  28868. noise ^= noise >> 17;
  28869. noise ^= noise << 5;
  28870. return (float) (noise & 0xffffff) / (float) 0x800000 - 1.0f;
  28871. };
  28872. float previous = 0.0f;
  28873. for (int i = 0; i < frames; ++i)
  28874. {
  28875. const auto t = i / rate;
  28876. const auto inBeat = std::fmod (t, beat);
  28877. const auto bar = (int) (t / (beat * 4.0));
  28878. float left = 0.0f, right = 0.0f;
  28879. // kick on every beat: a falling sine
  28880. {
  28881. const auto phase = 2.0 * juce::MathConstants<double>::pi * (48.0 * inBeat + 4.0 * (1.0 - std::exp (-inBeat * 30.0)));
  28882. const auto k = (float) (std::sin (phase) * std::exp (-inBeat * 7.0)) * 0.85f;
  28883. left += k;
  28884. right += k;
  28885. }
  28886. // hats on the off-beats: high-passed noise bursts, a little to the right
  28887. {
  28888. const auto h = std::fmod (t + beat * 0.5, beat);
  28889. const auto n = white();
  28890. const auto hp = (n - previous) * 0.5f;
  28891. previous = n;
  28892. const auto hat = hp * (float) std::exp (-h * 45.0) * 0.55f;
  28893. left += hat * 0.6f;
  28894. right += hat;
  28895. }
  28896. // a chord in the second and third bars (mid band)
  28897. if (bar == 1 || bar == 2)
  28898. {
  28899. const auto env = (float) std::min (1.0, std::min (t - beat * 4.0, beat * 12.0 - t) * 8.0);
  28900. float chord = 0.0f;
  28901. for (const auto hz : { 523.25, 659.25, 783.99 })
  28902. chord += (float) (std::sin (2.0 * juce::MathConstants<double>::pi * hz * t) + 0.3 * std::sin (4.0 * juce::MathConstants<double>::pi * hz * t));
  28903. left += chord * 0.09f * std::max (0.0f, env);
  28904. right += chord * 0.09f * std::max (0.0f, env);
  28905. }
  28906. // a white-noise riser over the last two seconds (high band)
  28907. if (t > 6.0)
  28908. {
  28909. const auto rise = (float) ((t - 6.0) / 2.0);
  28910. left += white() * 0.4f * rise * rise;
  28911. right += white() * 0.4f * rise * rise;
  28912. }
  28913. l[i] = left;
  28914. r[i] = right;
  28915. }
  28916. buffer.applyGain (0.9f / juce::jmax (1.0e-6f, buffer.getMagnitude (0, frames)));
  28917. file.deleteFile();
  28918. juce::WavAudioFormat wav;
  28919. if (std::unique_ptr<juce::AudioFormatWriter> writer { wav.createWriterFor (file.createOutputStream().release(), rate, 2, 24, {}, 0) })
  28920. writer->writeFromAudioSampleBuffer (buffer, 0, frames);
  28921. }
  28922. // the menu bar's menus side by side, drawn with the LookAndFeel as they appear when opened
  28923. static void saveMenus (lynx::MainComponent& ui, const juce::String& path)
  28924. {
  28925. const auto names = ui.getMenuNamesForSnapshot();
  28926. std::vector<juce::PopupMenu> source;
  28927. for (int m = 0; m < names.size(); ++m)
  28928. source.push_back (ui.getMenuForSnapshot (m));
  28929. saveMenus (names, source, path);
  28930. }
  28931. // menus side by side, each under its name
  28932. static void saveMenus (const juce::StringArray& names, const std::vector<juce::PopupMenu>& source, const juce::String& path)
  28933. {
  28934. auto& lf = juce::LookAndFeel::getDefaultLookAndFeel();
  28935. struct Laid
  28936. {
  28937. juce::PopupMenu menu;
  28938. int width = 0, height = 0;
  28939. };
  28940. std::vector<Laid> menus;
  28941. const auto border = lf.getPopupMenuBorderSize();
  28942. for (int m = 0; m < names.size(); ++m)
  28943. {
  28944. Laid laid { source[(std::size_t) m] };
  28945. int width = 160, height = 2 * border;
  28946. for (juce::PopupMenu::MenuItemIterator it (laid.menu); it.next();)
  28947. {
  28948. const auto& item = it.getItem();
  28949. int w = 0, h = 0;
  28950. lf.getIdealPopupMenuItemSize (item.text, item.isSeparator, item.isSectionHeader ? -1 : 0, w, h);
  28951. if (item.isSectionHeader) h += h / 2; // as JUCE does
  28952. if (item.shortcutKeyDescription.isNotEmpty() || item.text.containsChar ('\t'))
  28953. w += 90;
  28954. width = juce::jmax (width, w + 10);
  28955. height += h;
  28956. }
  28957. laid.width = width;
  28958. laid.height = height;
  28959. menus.push_back (std::move (laid));
  28960. }
  28961. int totalWidth = 16, totalHeight = 0;
  28962. for (const auto& l : menus)
  28963. {
  28964. totalWidth += l.width + 16;
  28965. totalHeight = juce::jmax (totalHeight, l.height + 32);
  28966. }
  28967. auto image = lynx::shot::canvas (totalWidth, totalHeight);
  28968. {
  28969. juce::Graphics g (image);
  28970. lynx::shot::logical (g);
  28971. g.fillAll (lynx::theme::colour::bg1);
  28972. int x = 16;
  28973. for (int m = 0; m < (int) menus.size(); ++m)
  28974. {
  28975. const auto& l = menus[(std::size_t) m];
  28976. g.setColour (lynx::theme::colour::textSecondary);
  28977. g.setFont (lynx::theme::font (lynx::theme::type::small, true));
  28978. g.drawText (names[m], x, 0, l.width, 24, juce::Justification::centredLeft);
  28979. {
  28980. juce::Graphics::ScopedSaveState state (g);
  28981. g.reduceClipRegion (x, 24, l.width, l.height);
  28982. g.setOrigin (x, 24);
  28983. lf.drawPopupMenuBackground (g, l.width, l.height);
  28984. int y = border;
  28985. bool first = true;
  28986. for (juce::PopupMenu::MenuItemIterator it (l.menu); it.next();)
  28987. {
  28988. const auto& item = it.getItem();
  28989. int w = 0, h = 0;
  28990. lf.getIdealPopupMenuItemSize (item.text, item.isSeparator, item.isSectionHeader ? -1 : 0, w, h);
  28991. if (item.isSectionHeader) h += h / 2; // as JUCE does
  28992. const juce::Rectangle<int> r (0, y, l.width, h);
  28993. auto text = item.text, shortcut = item.shortcutKeyDescription;
  28994. if (text.containsChar ('\t'))
  28995. {
  28996. shortcut = text.fromFirstOccurrenceOf ("\t", false, false);
  28997. text = text.upToFirstOccurrenceOf ("\t", false, false);
  28998. }
  28999. if (item.isSectionHeader)
  29000. lf.drawPopupMenuSectionHeader (g, r, text);
  29001. else
  29002. lf.drawPopupMenuItem (g, r, item.isSeparator, item.isEnabled, first && ! item.isSeparator && m == 0, item.isTicked,
  29003. item.subMenu != nullptr, text, shortcut, item.image.get(), nullptr);
  29004. first = false;
  29005. y += h;
  29006. }
  29007. }
  29008. x += l.width + 16;
  29009. }
  29010. }
  29011. const auto file = lynx::shot::file (juce::File (path));
  29012. file.deleteFile();
  29013. juce::PNGImageFormat png;
  29014. if (auto out = file.createOutputStream())
  29015. png.writeImageToStream (image, *out);
  29016. }
  29017. static void writePng (const juce::Image& image, const juce::String& path)
  29018. {
  29019. const auto file = lynx::shot::file (juce::File (path));
  29020. file.deleteFile();
  29021. juce::PNGImageFormat png;
  29022. if (auto out = file.createOutputStream())
  29023. png.writeImageToStream (image, *out);
  29024. }
  29025. // the splash screen: one settled frame, and a strip of frames through its animation
  29026. static void saveSplashFrames (const juce::String& prefix)
  29027. {
  29028. lynx::SplashScreen splash;
  29029. splash.setStatus (lynx::tr ("Loading the workspace..."));
  29030. splash.setTimeForSnapshot (1.6);
  29031. writePng (lynx::shot::snapshot (splash), prefix + "-splash.png");
  29032. const double times[] = { 0.10, 0.22, 0.29, 0.40, 0.58, 0.75, 1.00, 1.30 };
  29033. const auto w = lynx::SplashScreen::width / 2, h = lynx::SplashScreen::height / 2;
  29034. auto strip = lynx::shot::canvas (4 * (w + 8) + 8, 2 * (h + 8) + 8);
  29035. {
  29036. juce::Graphics g (strip);
  29037. lynx::shot::logical (g);
  29038. g.fillAll (lynx::theme::colour::bg1);
  29039. for (int i = 0; i < 8; ++i)
  29040. {
  29041. splash.setTimeForSnapshot (times[i]);
  29042. const auto frame = lynx::shot::snapshot (splash);
  29043. g.drawImage (frame, 8 + (i % 4) * (w + 8), 8 + (i / 4) * (h + 8), w, h, 0, 0, frame.getWidth(), frame.getHeight());
  29044. }
  29045. }
  29046. writePng (strip, prefix + "-splash-frames.png");
  29047. }
  29048. // every icon at 16, 20 and 24 px (at `scale`, e.g. 1.5 for a 150% display), in the toolbar's
  29049. // colours: at rest, hovered and switched on
  29050. // round 190je (design190ia G1): one state sheet per button kind: idle, hover, pressed, on, disabled, as the one state rule
  29051. // draws them (core/ThemePalette.h buttonLook)
  29052. static void saveStateSheet (const juce::String& path, float scale)
  29053. {
  29054. using namespace lynx;
  29055. scale *= shot::scale();
  29056. auto& lf = juce::LookAndFeel::getDefaultLookAndFeel();
  29057. const int labelWidth = 220, cellW = 120, cellH = 40, columns = 5;
  29058. const juce::String heads[] = { "idle", "hover", "pressed", "on", "disabled" };
  29059. enum Kind { text, iconFilled, iconOnce, iconSwitch, iconSwitchOwn, tick, radio, combo, tab, kinds };
  29060. const char* names[] = { "Text button", "Icon button (filled)", "Toolbar icon (acts once)", "Toolbar switch", "Toolbar switch (own colours)",
  29061. "Tick box", "Radio choice", "Combo box", "Tab" };
  29062. const auto w = labelWidth + columns * cellW + 16, h = 30 + kinds * cellH + 16;
  29063. juce::Image image (juce::Image::ARGB, juce::roundToInt ((float) w * scale), juce::roundToInt ((float) h * scale), true);
  29064. {
  29065. juce::Graphics g (image);
  29066. g.addTransform (juce::AffineTransform::scale (scale));
  29067. g.fillAll (theme::colour::bg3);
  29068. g.setFont (theme::font (theme::type::small, true));
  29069. g.setColour (theme::colour::textSecondary);
  29070. for (int c = 0; c < columns; ++c)
  29071. g.drawText (heads[c], labelWidth + c * cellW, 6, cellW, 20, juce::Justification::centred);
  29072. for (int k = 0; k < kinds; ++k)
  29073. {
  29074. const auto y = 30 + k * cellH;
  29075. g.setFont (theme::font (theme::type::small));
  29076. g.setColour (theme::colour::textPrimary);
  29077. g.drawText (names[k], 8, y, labelWidth - 12, cellH, juce::Justification::centredLeft);
  29078. for (int c = 0; c < columns; ++c)
  29079. {
  29080. const auto hover = c == 1, down = c == 2, on = c == 3, disabled = c == 4;
  29081. const juce::Rectangle<int> cell (labelWidth + c * cellW, y, cellW, cellH);
  29082. juce::Graphics::ScopedSaveState state (g);
  29083. g.reduceClipRegion (cell);
  29084. switch (k)
  29085. {
  29086. case text:
  29087. {
  29088. juce::TextButton b ("Export");
  29089. b.setSize (96, 26);
  29090. b.setToggleState (on, juce::dontSendNotification);
  29091. b.setEnabled (! disabled);
  29092. g.setOrigin (cell.getX() + 12, cell.getY() + 7);
  29093. lf.drawButtonBackground (g, b, b.findColour (on ? juce::TextButton::buttonOnColourId : juce::TextButton::buttonColourId), hover, down);
  29094. lf.drawButtonText (g, b, hover, down);
  29095. break;
  29096. }
  29097. case iconFilled:
  29098. case iconOnce:
  29099. case iconSwitch:
  29100. case iconSwitchOwn:
  29101. {
  29102. IconButton b ("state", k == iconFilled ? Icon::plus : k == iconOnce ? Icon::save : Icon::metronome);
  29103. b.setFlat (k != iconFilled);
  29104. if (k == iconSwitch)
  29105. b.setToggleLook (true);
  29106. if (k == iconSwitchOwn)
  29107. {
  29108. b.setOnColour (theme::colour::bg6);
  29109. b.setIconColourWhenOn (theme::colour::accent);
  29110. }
  29111. b.setSize (k == iconFilled ? 34 : 30, 30);
  29112. b.setToggleState (on, juce::dontSendNotification);
  29113. b.setEnabled (! disabled);
  29114. g.setOrigin (cell.getX() + 12, cell.getY() + 5);
  29115. b.paintButton (g, hover, down);
  29116. break;
  29117. }
  29118. case tick:
  29119. case radio:
  29120. {
  29121. juce::ToggleButton b (k == tick ? "Snap to grid" : "Pattern");
  29122. if (k == radio)
  29123. b.getProperties().set ("lynxRadio", true);
  29124. b.setSize (110, 24);
  29125. b.setToggleState (on, juce::dontSendNotification);
  29126. b.setEnabled (! disabled);
  29127. g.setOrigin (cell.getX() + 6, cell.getY() + 8);
  29128. lf.drawToggleButton (g, b, hover, down);
  29129. break;
  29130. }
  29131. case combo:
  29132. {
  29133. if (hover || down || on) // (a combo box's hover comes from the mouse itself: --uitest covers it)
  29134. break;
  29135. juce::ComboBox b;
  29136. b.setSize (100, 24);
  29137. b.setEnabled (! disabled);
  29138. g.setOrigin (cell.getX() + 10, cell.getY() + 8);
  29139. lf.drawComboBox (g, 100, 24, false, 0, 0, 0, 0, b);
  29140. g.setColour (disabled ? theme::colour::textDisabled : theme::colour::textPrimary);
  29141. g.setFont (lf.getComboBoxFont (b));
  29142. g.drawText ("1/16 step", 6, 0, 70, 24, juce::Justification::centredLeft);
  29143. break;
  29144. }
  29145. case tab:
  29146. {
  29147. if (disabled)
  29148. break;
  29149. juce::TabbedButtonBar bar (juce::TabbedButtonBar::TabsAtTop);
  29150. bar.setSize (220, 32);
  29151. bar.addTab ("Audio", theme::colour::bg2, -1);
  29152. bar.addTab ("MIDI", theme::colour::bg2, -1);
  29153. bar.setCurrentTabIndex (on ? 1 : 0, false);
  29154. auto* tabButton = bar.getTabButton (1);
  29155. tabButton->setBounds (0, 0, 100, 32);
  29156. g.setOrigin (cell.getX() + 10, cell.getY() + 4);
  29157. g.setColour (theme::colour::bg1);
  29158. g.fillRect (0, 0, 100, 32);
  29159. lf.drawTabButton (*tabButton, g, hover, down);
  29160. break;
  29161. }
  29162. default:
  29163. break;
  29164. }
  29165. }
  29166. }
  29167. }
  29168. writePng (image, path);
  29169. }
  29170. static void saveIconSheet (const juce::String& path, float scale)
  29171. {
  29172. scale *= lynx::shot::scale();
  29173. const int sizes[] = { 16, 20, 24 };
  29174. const int cell = 34, columns = 3 * 3, labelWidth = 110;
  29175. const auto w = labelWidth + columns * cell + 16, h = lynx::iconCount * cell + 16;
  29176. juce::Image image (juce::Image::ARGB, juce::roundToInt ((float) w * scale), juce::roundToInt ((float) h * scale), true);
  29177. {
  29178. juce::Graphics g (image); // (drawing is flushed when it goes out of scope)
  29179. g.addTransform (juce::AffineTransform::scale (scale));
  29180. g.fillAll (lynx::theme::colour::bg3);
  29181. g.setFont (lynx::theme::font (lynx::theme::type::small));
  29182. for (int i = 1; i < lynx::iconCount; ++i)
  29183. {
  29184. const auto y = 8 + (i - 1) * cell;
  29185. g.setColour (lynx::theme::colour::textDisabled);
  29186. g.drawText (juce::String (i), 8, y, labelWidth - 8, cell, juce::Justification::centredLeft);
  29187. for (int v = 0; v < 3; ++v)
  29188. for (int s = 0; s < 3; ++s)
  29189. {
  29190. const juce::Rectangle<float> box ((float) (labelWidth + (v * 3 + s) * cell), (float) y, (float) cell, (float) cell);
  29191. const auto bg = v == 2 ? lynx::theme::colour::accent : v == 1 ? lynx::theme::colour::bg5 : lynx::theme::colour::bg3;
  29192. g.setColour (bg);
  29193. g.fillRoundedRectangle (box.reduced (2.0f), 4.0f);
  29194. const auto fg = v == 2 ? lynx::theme::colour::onAccent : v == 1 ? lynx::theme::colour::textPrimary
  29195. : lynx::theme::colour::textSecondary.brighter (0.25f);
  29196. lynx::icons::draw (g, (lynx::Icon) i, box.withSizeKeepingCentre ((float) sizes[s], (float) sizes[s]), fg);
  29197. }
  29198. }
  29199. }
  29200. writePng (image, path);
  29201. }
  29202. // a part of a component (e.g. the main toolbar)
  29203. static void saveArea (juce::Component& c, juce::Rectangle<int> area, const juce::String& path)
  29204. {
  29205. const auto file = lynx::shot::file (juce::File (path));
  29206. file.deleteFile();
  29207. juce::PNGImageFormat png;
  29208. if (auto out = file.createOutputStream())
  29209. png.writeImageToStream (lynx::shot::snapshot (c, area), *out);
  29210. }
  29211. static void savePng (const juce::Image& image, const juce::String& path)
  29212. {
  29213. const auto file = lynx::shot::file (juce::File (path));
  29214. file.deleteFile();
  29215. juce::PNGImageFormat png;
  29216. if (auto out = file.createOutputStream())
  29217. png.writeImageToStream (image, *out);
  29218. }
  29219. // -toolbar-tips.png: the top of the window with the bubbles of a few controls as they appear under the
  29220. // mouse; -tips-sheet.png: every quick tip of the window, to check names, shortcuts and translations
  29221. static void saveQuickTips (lynx::MainComponent& ui, const juce::String& prefix)
  29222. {
  29223. const auto tips = ui.getQuickTipsForSnapshot();
  29224. const auto top = juce::Rectangle<int> (0, 0, ui.getWidth(), juce::jmin (ui.getHeight(), ui.getToolbarBoundsForSnapshot().getHeight() + 72));
  29225. auto image = lynx::shot::snapshot (ui, top);
  29226. {
  29227. juce::Graphics g (image);
  29228. lynx::shot::logical (g);
  29229. const juce::String shown[] = { lynx::tr ("Pattern mode"), lynx::tr ("Play"), lynx::tr ("Metronome"), lynx::tr ("Mixer"), lynx::tr ("Save project"),
  29230. lynx::tr ("Window options"), lynx::tr ("Close") };
  29231. std::vector<juce::Rectangle<int>> used;
  29232. for (const auto& [area, tip] : tips)
  29233. {
  29234. const auto name = tip.upToFirstOccurrenceOf ("\t", false, false);
  29235. if (std::find (std::begin (shown), std::end (shown), name) == std::end (shown))
  29236. continue;
  29237. const auto bubble = lynx::ui::quickTipBounds (tip, area, top);
  29238. if (std::any_of (used.begin(), used.end(), [&] (const auto& r) { return r.intersects (bubble); }))
  29239. continue;
  29240. used.push_back (bubble);
  29241. g.setColour (juce::Colours::white.withAlpha (0.075f)); // the hovered control
  29242. g.fillRoundedRectangle (area.toFloat().reduced (0.5f), lynx::theme::radius::md);
  29243. lynx::ui::paintQuickTip (g, bubble.toFloat(), tip);
  29244. }
  29245. }
  29246. savePng (image, prefix + "-toolbar-tips.png");
  29247. // the sheet: bubbles in rows
  29248. const int width = 900;
  29249. int x = 12, y = 12;
  29250. std::vector<std::pair<juce::Rectangle<int>, juce::String>> placed;
  29251. for (const auto& [area, tip] : tips)
  29252. {
  29253. auto r = lynx::ui::quickTipSize (tip);
  29254. if (x + r.getWidth() > width - 12)
  29255. {
  29256. x = 12;
  29257. y += r.getHeight() + 10;
  29258. }
  29259. placed.emplace_back (r.withPosition (x, y), tip);
  29260. x += r.getWidth() + 10;
  29261. }
  29262. auto sheet = lynx::shot::canvas (width, y + 20 + 12);
  29263. {
  29264. juce::Graphics g (sheet);
  29265. lynx::shot::logical (g);
  29266. g.fillAll (lynx::theme::colour::bg3);
  29267. for (const auto& [r, tip] : placed)
  29268. lynx::ui::paintQuickTip (g, r.toFloat(), tip);
  29269. }
  29270. savePng (sheet, prefix + "-tips-sheet.png");
  29271. }
  29272. static juce::StringArray& textFitLog()
  29273. {
  29274. static juce::StringArray log;
  29275. return log;
  29276. }
  29277. // drawFittedText would shrink `text` below `minScale` or cut it: fewer visible glyphs than the text has
  29278. static bool textIsCut (const juce::Font& font, const juce::String& text, juce::Rectangle<int> area, int maxLines, float minScale)
  29279. {
  29280. if (text.trim().isEmpty() || area.getWidth() <= 4 || area.getHeight() <= 4)
  29281. return false;
  29282. auto visible = [] (juce::GlyphArrangement& ga) {
  29283. int n = 0;
  29284. for (int i = 0; i < ga.getNumGlyphs(); ++i)
  29285. n += ga.getGlyph (i).isWhitespace() ? 0 : 1;
  29286. return n;
  29287. };
  29288. juce::GlyphArrangement fitted, full;
  29289. fitted.addFittedText (font, text, 0.0f, 0.0f, (float) area.getWidth(), (float) area.getHeight(), juce::Justification::centredLeft,
  29290. juce::jmax (1, maxLines), minScale);
  29291. full.addLineOfText (font, text, 0.0f, 0.0f);
  29292. return visible (fitted) < visible (full);
  29293. }
  29294. // walks the visible components under `root` and logs the texts that don't fit (labels, text buttons, tick boxes)
  29295. static void checkTextFit (juce::Component& root, const juce::String& where)
  29296. {
  29297. std::function<void (juce::Component&)> visit = [&] (juce::Component& c) {
  29298. if (! c.isVisible() || c.getWidth() <= 0 || c.getHeight() <= 0)
  29299. return;
  29300. juce::String text;
  29301. bool cut = false;
  29302. if (auto* label = dynamic_cast<juce::Label*> (&c); label != nullptr && ! label->isBeingEdited())
  29303. {
  29304. const auto font = label->getLookAndFeel().getLabelFont (*label);
  29305. const auto area = label->getBorderSize().subtractedFrom (label->getLocalBounds());
  29306. text = label->getText();
  29307. cut = textIsCut (font, text, area, juce::jmax (1, (int) ((float) area.getHeight() / font.getHeight())),
  29308. label->getMinimumHorizontalScale());
  29309. }
  29310. else if (auto* toggle = dynamic_cast<juce::ToggleButton*> (&c))
  29311. {
  29312. const auto tick = juce::jmin (16.0f, (float) c.getHeight() - 4.0f);
  29313. text = toggle->getButtonText();
  29314. cut = textIsCut (juce::Font (lynx::theme::font (juce::jmin ((float) lynx::theme::type::body, (float) c.getHeight() * 0.75f))), text,
  29315. c.getLocalBounds().withTrimmedLeft (juce::roundToInt (tick) + 8).withTrimmedRight (2), 2, 0.85f);
  29316. }
  29317. else if (auto* button = dynamic_cast<juce::TextButton*> (&c);
  29318. button != nullptr && (int) button->getProperties().getWithDefault (lynx::theme::LookAndFeel::iconProperty, 0) == 0)
  29319. {
  29320. text = button->getButtonText();
  29321. cut = textIsCut (button->getLookAndFeel().getTextButtonFont (*button, button->getHeight()), text,
  29322. button->getLocalBounds().reduced (juce::jmin (8, button->getWidth() / 6), 0), 2, 0.85f);
  29323. }
  29324. if (cut)
  29325. {
  29326. juce::String path;
  29327. for (auto* p = &c; p != nullptr && p != &root; p = p->getParentComponent())
  29328. if (p->getName().isNotEmpty())
  29329. path = p->getName() + (path.isEmpty() ? "" : "/") + path;
  29330. const auto line = where + " | " + juce::String (c.getWidth()) + "x" + juce::String (c.getHeight()) + " | " + text.replace ("\n", "\\n")
  29331. + (path.isEmpty() ? juce::String() : " | " + path);
  29332. textFitLog().addIfNotAlreadyThere (line);
  29333. }
  29334. for (auto* child : c.getChildren())
  29335. visit (*child);
  29336. };
  29337. visit (root);
  29338. }
  29339. static void saveSnapshot (juce::Component& c, const juce::String& path)
  29340. {
  29341. checkTextFit (c, juce::File (path).getFileNameWithoutExtension());
  29342. const auto file = lynx::shot::file (juce::File (path));
  29343. file.deleteFile();
  29344. juce::PNGImageFormat png;
  29345. if (auto out = file.createOutputStream())
  29346. png.writeImageToStream (lynx::shot::snapshot (c), *out);
  29347. }
  29348. class MainWindow final : public juce::DocumentWindow
  29349. {
  29350. public:
  29351. MainWindow (const juce::String& name, lynx::AudioEngine& engine)
  29352. : DocumentWindow (name, lynx::theme::window, DocumentWindow::allButtons, false)
  29353. {
  29354. probeEngine = &engine;
  29355. // (round 190hd) one desktop window, made with the native title bar: before, JUCE made one with its own title
  29356. // bar and setUsingNativeTitleBar made it again (~20-35 ms each, the Direct2D context included)
  29357. setUsingNativeTitleBar (true);
  29358. addToDesktop();
  29359. setIcon (lynx::logoImage());
  29360. startupTrace.mark (" window: its desktop window (native title bar), icon");
  29361. content = new lynx::MainComponent (engine);
  29362. setContentOwned (content, true);
  29363. startupTrace.mark (" window: content set");
  29364. setResizable (true, true);
  29365. setResizeLimits (800, 400, 10000, 10000);
  29366. // ~88% of the main display's usable area (at least the UI's design size, but never larger than the
  29367. // display: the AppImage catalog test runs on an 800x600 screen)
  29368. if (const auto* display = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay())
  29369. {
  29370. const auto area = display->userArea;
  29371. const auto fit = [] (int design, int available) {
  29372. return juce::jmin (available, juce::jmax (design, (int) (available * 0.88)));
  29373. };
  29374. setSize (fit (getWidth(), area.getWidth()), fit (getHeight(), area.getHeight()));
  29375. }
  29376. centreWithSize (getWidth(), getHeight());
  29377. // where it was last time (round 167v); the first start opens maximized, the Playlist filling the screen
  29378. // with the Browser at the left and the Channel Rack above it, like FL Studio's first start
  29379. const auto saved = stateFile().loadFileAsString().trim();
  29380. // (LYNX_TEST_MODE keeps the fixed-size window scripted checks expect, unless LYNX_TEST_MAXIMIZE=1)
  29381. const auto firstStart = saved.isEmpty()
  29382. && (! lynx::platform::testMode() || juce::SystemStats::getEnvironmentVariable ("LYNX_TEST_MAXIMIZE", {}) == "1");
  29383. maximiseOnReveal = firstStart || saved.startsWithIgnoreCase ("fs");
  29384. if (saved.isNotEmpty())
  29385. restoreWindowStateFromString (saved.startsWithIgnoreCase ("fs") ? saved.substring (2).trim() : saved);
  29386. }
  29387. // Shows the window (built hidden while the splash screen is up).
  29388. void reveal()
  29389. {
  29390. if (lynx::uitrace::enabled()) // LYNX_TRACE_UI: the frames per second and the longest gap in ui.log (round 173f)
  29391. watchFrames ({});
  29392. setVisible (true);
  29393. // LYNX_LOCATOR_PROBE=1 (round 190ip, measurements): a floating window with a locator moving 30 times a second
  29394. if (juce::SystemStats::getEnvironmentVariable ("LYNX_LOCATOR_PROBE", {}) == "1")
  29395. juce::Timer::callAfterDelay (1500, [e = probeEngine] {
  29396. lynx::ui::openLocatorProbe ([e] {
  29397. const auto& transport = e->getTransport();
  29398. const auto bar = (double) juce::jmax<std::int64_t> (1, e->getSong().barTicks());
  29399. return transport.playing.load() ? std::fmod (transport.positionTicks.load(), bar) / bar : -1.0;
  29400. });
  29401. });
  29402. lynx::applyWindowChrome (*this);
  29403. lynx::fitWindowOnScreen (*this); // a size saved at another UI zoom still fits (round 163)
  29404. if (maximiseOnReveal)
  29405. setFullScreen (true); // (a title-bar window: maximized, the taskbar stays)
  29406. toFront (true);
  29407. content->grabKeyboardFocus();
  29408. // issue #62: the detached panels restored with the layout (built before this window was shown): their saved
  29409. // place and above it, once the window manager has placed this one
  29410. juce::Timer::callAfterDelay (250, [safe = juce::Component::SafePointer<MainWindow> (this)] {
  29411. if (safe != nullptr)
  29412. safe->content->restoreDetachedWindows();
  29413. });
  29414. }
  29415. // Runs `then` once, right after the window's next frame (round 190go: the audio device opens behind the
  29416. // window's first frame, not before it); at the latest after 300 ms (a window that paints nothing: minimised).
  29417. void whenPainted (std::function<void()> then)
  29418. {
  29419. afterPaint = std::move (then);
  29420. afterPaintPosted = false;
  29421. repaint();
  29422. juce::Timer::callAfterDelay (300, [safe = juce::Component::SafePointer<MainWindow> (this)] {
  29423. if (safe != nullptr)
  29424. safe->runAfterPaint();
  29425. });
  29426. }
  29427. void runAfterPaint()
  29428. {
  29429. if (auto then = std::exchange (afterPaint, nullptr))
  29430. then();
  29431. }
  29432. // The window's place and maximized state for the next start (main-window.txt in the settings folder).
  29433. void saveState() { stateFile().replaceWithText (getWindowStateAsString()); }
  29434. static juce::File stateFile() { return lynx::PluginHost::settingsFolder().getChildFile ("main-window.txt"); }
  29435. void openFile (const juce::File& file) { content->openFile (file); }
  29436. lynx::MainComponent& getContent() { return *content; }
  29437. void showSetupWizard() { content->showSetupWizard(); }
  29438. void confirmDiscard (std::function<void()> then) { content->confirmDiscard (std::move (then)); }
  29439. void closeButtonPressed() override { JUCEApplication::getInstance()->systemRequestedQuit(); }
  29440. // Every frame the window paints, with its dirty area (ui/FrameProbe.h; --uiperf, LYNX_TRACE_UI). The trace keeps
  29441. // counting when --uiperf watches too.
  29442. void watchFrames (std::function<void (double, juce::Rectangle<int>)> callback)
  29443. {
  29444. if (probe == nullptr)
  29445. {
  29446. probe = std::make_unique<lynx::ui::FrameProbe>();
  29447. Component::addAndMakeVisible (*probe); // (ResizableWindow hides the plain overload)
  29448. probe->setBounds (getLocalBounds());
  29449. }
  29450. probe->onFrame = [callback = std::move (callback)] (double now, juce::Rectangle<int> area) {
  29451. if (lynx::uitrace::enabled())
  29452. lynx::uitrace::frame (now);
  29453. if (callback)
  29454. callback (now, area);
  29455. };
  29456. }
  29457. void resized() override
  29458. {
  29459. DocumentWindow::resized();
  29460. if (probe != nullptr)
  29461. probe->setBounds (getLocalBounds());
  29462. }
  29463. // --uiperf: the time of each frame the window paints (its own paint, then every child's, up to the last)
  29464. std::function<void (double)> onFrame;
  29465. void paint (juce::Graphics& g) override
  29466. {
  29467. if (onFrame)
  29468. frameStart = juce::Time::getMillisecondCounterHiRes();
  29469. DocumentWindow::paint (g);
  29470. }
  29471. void paintOverChildren (juce::Graphics& g) override
  29472. {
  29473. DocumentWindow::paintOverChildren (g);
  29474. if (afterPaint != nullptr && ! std::exchange (afterPaintPosted, true)) // (the frame is presented first)
  29475. juce::MessageManager::callAsync ([safe = juce::Component::SafePointer<MainWindow> (this)] {
  29476. if (safe != nullptr)
  29477. safe->runAfterPaint();
  29478. });
  29479. if (onFrame && frameStart > 0.0)
  29480. onFrame (juce::Time::getMillisecondCounterHiRes() - frameStart);
  29481. frameStart = 0.0;
  29482. }
  29483. private:
  29484. lynx::MainComponent* content = nullptr; // owned by the window
  29485. std::unique_ptr<lynx::ui::FrameProbe> probe; // (on top of the content; see watchFrames)
  29486. double frameStart = 0.0;
  29487. bool maximiseOnReveal = false;
  29488. std::function<void()> afterPaint; // (whenPainted)
  29489. lynx::AudioEngine* probeEngine = nullptr; // (LYNX_LOCATOR_PROBE)
  29490. bool afterPaintPosted = false;
  29491. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MainWindow)
  29492. };
  29493. lynx::theme::LookAndFeel lookAndFeel;
  29494. std::unique_ptr<lynx::AudioEngine> engine;
  29495. std::unique_ptr<lynx::RemoteControl> remoteControl;
  29496. std::unique_ptr<juce::XmlElement> savedDeviceState; // --rtstress: the user's device before this run's --type/--buffer
  29497. // Hidden test mode --asiodll "<driver.dll>[|{CLSID}]" (REA round 97): an ASIO driver loaded straight from its file,
  29498. // without registering it, listed as the driver type "ASIO driver file". True when one was added.
  29499. bool addDriverFileDeviceType()
  29500. {
  29501. const auto args = juce::JUCEApplication::getCommandLineParameterArray();
  29502. const auto i = args.indexOf ("--asiodll");
  29503. if (i < 0 || i + 1 >= args.size() || engine == nullptr)
  29504. return false;
  29505. auto& devices = engine->getDeviceManager();
  29506. devices.getAvailableDeviceTypes(); // creates the standard types first
  29507. for (auto* t : devices.getAvailableDeviceTypes())
  29508. if (t->getTypeName() == lynx::dllAsioTypeName)
  29509. return true;
  29510. auto type = lynx::makeDllAsioDeviceType (args[i + 1].unquoted());
  29511. if (type == nullptr)
  29512. return false;
  29513. devices.addAudioDeviceType (std::move (type));
  29514. return true;
  29515. }
  29516. void restoreSavedDeviceState()
  29517. {
  29518. if (engine != nullptr)
  29519. engine->restoreAudioDeviceState (savedDeviceState.get());
  29520. }
  29521. std::unique_ptr<MainWindow> mainWindow;
  29522. std::unique_ptr<juce::Timer> perf; // --uiperf
  29523. std::unique_ptr<lynx::StartupSplash> splash;
  29524. static constexpr double landingSeconds = 1.05; // the logo's drop (SplashScreen::remainingDuration's `landing`)
  29525. std::shared_future<std::pair<juce::Image, double>> graphicsDeviceJob; // (round 190hd) holds the graphics device
  29526. bool graphicsDeviceMarked = false, windowRevealed = false;
  29527. std::future<std::shared_ptr<const lynx::SampleData>> startupSampleJob; // (round 190go: the built-in start-up sound)
  29528. bool startedAfterWindow = false, startupSoundPlayed = false;
  29529. double splashDuration = lynx::SplashScreen::minimumDuration; // seconds of its clock (round 121: from the process start)
  29530. lynx::StartupOptions startupOptions;
  29531. juce::File fileToOpen;
  29532. bool startupFileHandled = false;
  29533. bool startWithoutPlugins = false; // --no-plugins project.lynx (round 190ap)
  29534. juce::File openTimeReport; // --opentime
  29535. int openTimeIdleSeconds = 10;
  29536. };
  29537. START_JUCE_APPLICATION (LynxApplication)