Main.cpp 2.0 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826
  1. #include <juce_gui_basics/juce_gui_basics.h>
  2. #include "engine/FileSort.h"
  3. #include "platform/Paths.h"
  4. #include "core/GrooveAudio.h"
  5. #include "core/EditorScale.h"
  6. #include "core/SimplePads.h"
  7. #include "core/ClipEnvelope.h"
  8. #include "core/ClipWarp.h"
  9. #include "core/KeyGuess.h"
  10. #include "core/EditorPolish.h"
  11. #include "core/FlpExport.h"
  12. #include "core/FruityBasicFx.h" // (round 190my: Fruity Balance in --details190myshot)
  13. #include "core/Groove.h"
  14. #include "core/DrawMode.h"
  15. #include "core/SessionOps.h"
  16. #include "ui/ClipGridComponent.h"
  17. #include "ui/ArticulatorTools.h"
  18. #include "ui/ExternalDrag.h"
  19. #include "ui/LabelFont.h"
  20. #include "ui/SessionMixer.h"
  21. #include "core/FlSamplers.h"
  22. #include "core/ArrangeOps.h"
  23. #include "core/ClipSample.h"
  24. #include "core/WarpModes.h"
  25. #include "ui/ClipAudioPanel.h"
  26. #include "core/DetailChain.h"
  27. #include "core/SessionMixer.h"
  28. #include "core/PlaylistOps.h"
  29. #include "core/LastTweaked.h"
  30. #include "core/ClipOps.h"
  31. #include "core/TransportEdit.h" // (round 190jz: --issueshot190jz)
  32. #include "core/SamplerPage.h"
  33. #include "core/FlTrackMenus.h"
  34. #include "core/FlClipMenu.h"
  35. #include "core/OneClickRec.h"
  36. #include "core/WarpTools.h"
  37. #include "core/Comping.h"
  38. #include "core/Drumaxx.h"
  39. #include "core/PatternBlocks.h"
  40. #include "core/LoadTrace.h"
  41. #include "core/ProjectSafety.h"
  42. #include "core/Patcher.h"
  43. #include "core/Rack.h"
  44. #include "ui/RackEditor.h"
  45. #include "ui/HelixEditor.h"
  46. #include "core/AlsDevices.h"
  47. #include "core/XmlLite.h"
  48. #include "ui/DrumRackShot.h"
  49. #include "ui/GroovePoolComponent.h"
  50. #include "core/Patcherize.h"
  51. #include "core/Performance.h"
  52. #include "core/VideoPlayer.h"
  53. #include "core/Effects.h"
  54. #include "core/MixSuite.h"
  55. #include "core/HardwareInsert.h"
  56. #include "core/EchoSuite.h"
  57. #include "core/LuxeVerb.h"
  58. #include "core/LynxVerbs.h"
  59. #include "core/LynxTune.h"
  60. #include "core/FlEffects.h"
  61. #include "core/FlpImport.h"
  62. #include "core/NoteEdit.h"
  63. #include "core/PlaylistTrackOps.h" // round 190jf (FoldersShot190jf.inc)
  64. #include "ui/DawProjectExport.h" // round 190jf (--dawprojcheck190jf)
  65. #include "core/NoteNames.h"
  66. #include "core/MaximusFx.h"
  67. #include "core/ChainPresets.h"
  68. #include "core/GoalKnobs.h"
  69. #include "core/MasterLooks.h"
  70. #include "core/Harmor.h"
  71. #include "flp/Flp.h"
  72. #include "core/DemoSongs.h"
  73. #include "core/FirstSongTour.h"
  74. #include "core/PerfProjects.h"
  75. #include "core/ShowcaseSong.h"
  76. #include "core/RenderAhead.h"
  77. #include "core/SynthPresets.h"
  78. #include "core/FlWrapper.h"
  79. #include "engine/AudioEngine.h"
  80. #include "engine/ProjectDowngrade.h"
  81. #include "core/ClipLauncher.h"
  82. #include "core/SimpleSteps.h"
  83. #include "core/DirectWaveState.h"
  84. #include "core/MixSnapshots.h"
  85. #include "core/VoiceShift.h"
  86. #include "core/TempoMarkers.h"
  87. #include "engine/RemoteControl.h"
  88. #include "engine/RemoteError.h"
  89. #include "ui/RemoteControlSettings.h"
  90. #include "engine/PreviewPlayer.h"
  91. #include "engine/Metronome.h"
  92. #include "engine/AudioLogger.h"
  93. #include "engine/DllAsioDevice.h"
  94. #include "engine/PipeWireDevice.h"
  95. #include "platform/LinuxRealtime.h"
  96. #include "engine/PowerHints.h"
  97. #include "engine/Exporter.h"
  98. #include "engine/AacEncoder.h"
  99. #include "engine/FlStudioExport.h"
  100. #include "engine/MidiFileIo.h"
  101. #include "engine/PluginHost.h"
  102. #include "engine/Vst3NoteTuning.h"
  103. #include "engine/PluginSandbox.h"
  104. #include "engine/Bridge32Test.h"
  105. #include "engine/ClapFormat.h"
  106. #include "engine/ClapTeardownTest.h"
  107. #include "engine/HostingTests.h"
  108. #include "core/EdisonFx.h"
  109. #include "engine/ProjectFile.h"
  110. #include "ui/RemoteControl.h"
  111. #include "core/FlControlMenus.h"
  112. #include "core/PlaylistOps.h"
  113. #include "core/Sha256.h"
  114. #include "engine/SessionPack.h"
  115. #include "engine/LiveTest.h"
  116. #include "engine/ShortExportTest.h"
  117. #include "core/SessionIds.h"
  118. #include "core/SessionParts.h"
  119. #include "engine/SampleLibrary.h"
  120. #include "engine/Text.h"
  121. #include "platform/FileTypes.h"
  122. #include "platform/Package.h"
  123. #include "core/AlsExport.h"
  124. #include "core/AlsImport.h"
  125. #include "core/PianoRollScript.h"
  126. #include "ui/ScriptPanel.h"
  127. #include "ui/AlsExportDialog.h"
  128. #include "ui/LiveRemoteUi.h"
  129. #include "ui/GamepadInput.h"
  130. #include "ui/SettingsPages.h"
  131. #include "ui/ExtendedHintPanel.h"
  132. #include "core/FlSettings.h"
  133. #include "ui/OtherAppsExport.h"
  134. #include "ui/TimerWhileShowing.h"
  135. #include "ui/MixerBasicsCheck.h"
  136. #include "ui/VideoPlayerView.h"
  137. #include "ui/VideoMedia.h"
  138. #include "ui/VideoTracks.h"
  139. #include "ui/AdrWindow.h"
  140. #include "ui/PlaylistComponent.h"
  141. #include "ui/PictureCheck.h"
  142. #include "ui/PatternBlocksView.h"
  143. #include "ui/PaintAB.h"
  144. #include <typeinfo>
  145. #include "ui/PatcherEditor.h"
  146. #include "ui/VisualEditors.h"
  147. #include "ui/FlExtraEditors.h"
  148. #include "ui/VisualGl.h"
  149. #include "ui/DanceView.h"
  150. #include "ui/PluginPresetMenu.h"
  151. #include "ui/GeneratorPresetMenu.h"
  152. #include "core/GeneratorPresets.h"
  153. #include "ui/PluginWindow.h"
  154. #include "ui/Motion.h"
  155. #include "ui/ShotShowing.h"
  156. #include "ui/SimpleLook.h"
  157. #include "ui/NativeChild.h"
  158. #include "ui/DockPaintCheck.h"
  159. #include "ui/Workspace.h"
  160. #include "ui/PluginThumbs.h"
  161. #include "ui/ClipProperties.h"
  162. #include "ui/NewProjectDialog.h"
  163. #include "ui/PluginMonitorWindow.h"
  164. #include "ui/TouchKeyboard.h"
  165. #include "ui/AutomationUi.h"
  166. #include "core/GrossBeatLocator.h"
  167. #include "ui/PluginSkin.h"
  168. #include "ui/ChannelSettings.h"
  169. #include "ui/TempoDetectionDialog.h"
  170. #include "ui/AudioClipboard.h"
  171. #include "ui/FlVoicePanel.h"
  172. #include "ui/SlicexEditor.h"
  173. #include "ui/DirectWaveEditor.h"
  174. #include "ui/FruitySlicerEditor.h"
  175. #include "core/GrossBeat.h"
  176. #include "core/LynxBanks.h"
  177. #include "core/NativeEngines.h"
  178. #include "ui/ControllerEditors.h"
  179. #include "ui/NewtoneEditor.h"
  180. #include "core/NewtoneFx.h"
  181. #include "core/FormulaController.h"
  182. #include "core/MidiControls.h"
  183. #include "core/FlSynths.h"
  184. #include "core/SoundFont.h"
  185. #include "core/Sfz.h"
  186. #include "core/Slicex.h"
  187. #include "ui/Dialogs.h"
  188. #include "ui/DialogFrame.h"
  189. #include "ui/FileChoosers.h"
  190. #include "ui/TrackIcons.h"
  191. #include "core/MeterScale.h"
  192. #include "core/RackOps.h"
  193. #include "core/Layer.h"
  194. #include "core/XyController.h"
  195. #include "core/FlCurve.h"
  196. #include "core/ControlSurface.h"
  197. #include "core/VoltageController.h"
  198. #include "ui/Controllers164.h"
  199. #include "core/StandIns.h"
  200. #include "ui/ExportDialog.h"
  201. #include "ui/QuickAddPalette.h"
  202. #include "ui/I18n.h"
  203. #include "ui/MainComponent.h"
  204. #include "ui/SimpleDock.h"
  205. #include "core/ScaleKeys.h"
  206. #include "core/KeyFollow.h"
  207. #include "core/SoundLibrary.h"
  208. #include "ui/MidiToolsPanel.h"
  209. #include "ui/FrameProbe.h"
  210. #include "ui/MotionOverlay.h"
  211. #include "ui/UiTrace.h"
  212. #include "core/MixerOps.h"
  213. #include "ui/QuickPick.h"
  214. #include "core/FolderWatcher.h"
  215. #include "core/FruityDynamics.h"
  216. #include "core/PluginDbFolder.h"
  217. #include "core/NoteTools.h"
  218. #include "engine/ProjectPackage.h"
  219. #include "ui/SetupWizard.h"
  220. #include "engine/FlStudio.h"
  221. #include "ui/HistoryPanel.h"
  222. #include "ui/VersionsPanel.h"
  223. #include "ui/CleanVoiceMenu.h"
  224. #include "ui/LyricsPanel.h"
  225. #include "ui/ReferenceMatchPanel.h"
  226. #include "ui/StartFromPanel.h"
  227. #include "ui/FirstSongTour.h"
  228. #include "ui/PluginsOffPanel.h"
  229. #include "ui/MissingFilesDialog.h"
  230. #include "ui/SettingsDialog.h"
  231. #include "ui/PluginManager.h"
  232. #include "ui/ShortcutManager.h"
  233. #include "ui/NoteToolDialogs.h"
  234. #include "ui/ChordStripView.h" // round 190kd (--prchord190kd)
  235. #include "ui/EventEditor.h"
  236. #include "ui/AudioEditor.h"
  237. #include "ui/SampleProperties.h"
  238. #include "ui/TempoTapper.h"
  239. #include "ui/ProjectPickerView.h" // (round 190my)
  240. #include "core/EventEdit.h"
  241. #include "core/FacetEq.h"
  242. #include "ui/FacetEqEditor.h"
  243. #include "core/RackRenderer.h"
  244. #include "ui/ProEditors.h"
  245. #include "ui/ParametricEqEditor.h"
  246. #include "ui/PluginEditors.h"
  247. #include "core/PluginLayout.h"
  248. #include "core/EffectPresets.h"
  249. #include "ui/PluginHeader.h"
  250. #include "core/Vfx.h"
  251. #include "core/TransistorBass.h"
  252. #include "ui/Splash.h"
  253. #include "ui/Theme.h"
  254. #include "ui/ThemeSettings.h"
  255. #include "ui/WaveformView.h"
  256. #include "ui/WindowOwner.h"
  257. #include "ui/PluginKeysTest.h"
  258. #include "ui/Toolbar.h"
  259. #include "ui/ToolWindow.h"
  260. #include "core/Details190mv.h" // (round 190mv)
  261. #include "platform/CrashGuard.h"
  262. #include "ui/CrashReporter.h"
  263. #include "ui/Updater.h"
  264. #include "ui/AudioCheck.h"
  265. #include "ui/StemExtract.h"
  266. #include "core/RegionLoop.h" // round 190jr: --bandlab190jrshot
  267. #include "core/FactoryContent.h" // round 190ke: --simplegb190keshot
  268. #include "core/SongFade.h"
  269. #include "core/SoundLibrary.h"
  270. #include "core/SynthParams.h"
  271. #include "core/GoalKnobs.h"
  272. #include "core/DetailChain.h"
  273. #include "ui/FinishDock.h"
  274. #include "ui/SimpleDock.h"
  275. #include "ui/SimpleTuner.h"
  276. #include "ui/AudioToMidi.h"
  277. #include "ui/ShotScale.h"
  278. #include "core/LaneView.h" // round 190iu
  279. #include "core/PlaylistTrackOps.h"
  280. #include "core/MidiDrop.h"
  281. #include "core/TakeCleanup.h"
  282. #include "core/TrackOnly.h"
  283. #include "core/WheelZones.h"
  284. #include "ui/WorkflowExtras.h"
  285. #include "core/Links.h"
  286. #include <algorithm>
  287. #include <set> // (round 190jf: --dawprojcheck190jf)
  288. #include <atomic>
  289. #include <exception>
  290. #include <chrono>
  291. #include <cstdio>
  292. #include <ctime>
  293. #include <cstdlib>
  294. #include <future>
  295. #include <mutex>
  296. #include <thread>
  297. namespace
  298. {
  299. lynx::AudioEngine* crashEngine = nullptr;
  300. // Startup trace (REA round 116): with LYNX_TRACE_STARTUP set, the time of each startup step since the C++ runtime
  301. // started is written to %APPDATA%\LYNX\startup.log (the loader's own time before that is not included).
  302. struct StartupTrace
  303. {
  304. using clock = std::chrono::steady_clock;
  305. const clock::time_point t0 = clock::now(); // static initialisation: no JUCE yet, standard library only
  306. const std::chrono::system_clock::time_point t0System = std::chrono::system_clock::now(); // (round 190hd: vs the process's creation)
  307. // (round 190go: always kept, as a field-readable start-up timeline; written to startup.log 5 s and 15 s after the
  308. // window — with LYNX_TRACE_STARTUP set, at every step as before, so a start that hangs still leaves its last step)
  309. const bool on = true;
  310. const bool eachStep = std::getenv ("LYNX_TRACE_STARTUP") != nullptr;
  311. juce::String text;
  312. clock::time_point last = t0;
  313. std::int64_t lastPrivate = 0;
  314. double seconds() const { return std::chrono::duration<double> (clock::now() - t0).count(); } // since the process started
  315. void mark (const char* step)
  316. {
  317. if (! on)
  318. return;
  319. const auto now = clock::now();
  320. const auto ms = [] (clock::duration d) { return std::chrono::duration<double, std::milli> (d).count(); };
  321. // (round 190gd: the process's memory after each step too, so the log says where the megabytes of a start go)
  322. const auto mb = [] (std::int64_t bytes) { return juce::String ((double) bytes / 1048576.0, 1).paddedLeft (' ', 7); };
  323. const auto priv = lynx::toolbar::PerformanceMeter::processPrivateBytes();
  324. const auto ws = lynx::toolbar::PerformanceMeter::processMemoryBytes();
  325. text << juce::String (ms (now - t0), 1).paddedLeft (' ', 8) << " ms +" << juce::String (ms (now - last), 1).paddedLeft (' ', 7)
  326. << " private " << mb (priv) << " MB (+" << mb (priv - lastPrivate).trim() << ") ws " << mb (ws) << " MB " << step << "\n";
  327. lastPrivate = priv;
  328. last = now;
  329. if (eachStep)
  330. write();
  331. }
  332. void write() const { lynx::platform::settingsFile ("startup.log").replaceWithText (text); }
  333. };
  334. StartupTrace startupTrace;
  335. void startupMarkHook (const char* step) { startupTrace.mark (step); }
  336. juce::File crashFolderForTest; // --faulttest: where the crash file goes instead of the settings' autosave folder
  337. // Crashed: try to save the project and write the backtrace (like FL's "emergency save").
  338. void onCrash (void* exceptionPointers)
  339. {
  340. // (round 190ci: once. The hook for stacks Windows cannot walk, crashguard::setUnwalkableFaultHandler, may have run
  341. // this before the top-level filter does)
  342. static std::atomic<bool> reported { false };
  343. if (reported.exchange (true))
  344. return;
  345. const auto folder = crashFolderForTest != juce::File() ? crashFolderForTest : lynx::platform::settingsFile ("autosave");
  346. folder.createDirectory();
  347. const auto stamp = juce::Time::getCurrentTime().formatted ("%Y-%m-%d %H-%M-%S");
  348. // JUCE's backtrace (named frames only), then every frame of the faulting thread as module+offset (round 157a: a
  349. // release LYNX.exe has no symbols, so its own frames were missing from the file)
  350. folder.getChildFile ("crash " + stamp + ".txt").replaceWithText (juce::SystemStats::getStackBacktrace() + "\n--- frames (module+offset)\n"
  351. + juce::String::fromUTF8 (lynx::crashguard::exceptionBacktrace (exceptionPointers).c_str()));
  352. lynx::crashguard::note (("crashed: backtrace in autosave\\crash " + stamp + ".txt").toStdString());
  353. if (crashEngine != nullptr)
  354. {
  355. juce::String error;
  356. lynx::ProjectFile::save (crashEngine->getSong(), folder.getChildFile ("recovered " + stamp + lynx::ProjectFile::extension), error);
  357. }
  358. }
  359. juce::File sessionsFolder()
  360. {
  361. return lynx::PluginHost::settingsFolder().getChildFile ("sessions");
  362. }
  363. // Sessions of earlier runs whose process is gone without closing (a fail-fast, a crash, a forced end): each is appended
  364. // to %APPDATA%\LYNX\crash-history.log and its file removed. Returns the last step of the newest one ("" when none).
  365. juce::StringArray uncleanSteps; // the newest unclean session's steps (without their times)
  366. juce::String uncleanSessionText; // the newest unclean session's whole file (round 159: the crash report reads it)
  367. // What the newest unclean session tells (round 157a): the plugin whose editor was opening / shown when it ended, and
  368. // whether its crash file blames a graphics driver
  369. struct UncleanCause
  370. {
  371. juce::String editorPlugin; // the last steps were that plugin's editor
  372. bool gpuDriver = false; // the crash file's top frames are in a GPU driver / Direct3D / Direct2D module
  373. juce::String driverModule;
  374. };
  375. UncleanCause uncleanCause()
  376. {
  377. UncleanCause cause;
  378. juce::File crashFile;
  379. for (int i = uncleanSteps.size(); --i >= 0 && i >= uncleanSteps.size() - 4;)
  380. {
  381. const auto& step = uncleanSteps[i];
  382. if (step.startsWith ("crashed: backtrace in "))
  383. crashFile = lynx::platform::settingsFolder().getChildFile (step.fromFirstOccurrenceOf ("backtrace in ", false, false).replaceCharacter ('\\', '/'));
  384. for (const auto* prefix : { "opening the editor of ", "editor open: ", "editor shown: " })
  385. if (cause.editorPlugin.isEmpty() && step.startsWith (prefix))
  386. cause.editorPlugin = step.fromFirstOccurrenceOf (prefix, false, false).trim();
  387. if (step.startsWith ("closing the editor of ") || step.startsWith ("loaded plugin") || step.startsWith ("opening project"))
  388. break; // older steps than these did not end the session
  389. }
  390. // issue #32 (round 174a): a plugin whose editor already faulted in this session (caught, LYNX went on) is the
  391. // likely cause when the session then ended without a word: offer it a separate process too
  392. for (int i = uncleanSteps.size(); --i >= 0 && cause.editorPlugin.isEmpty();)
  393. if (const auto editor = lynx::crashreport::parseEditorCrashStep (uncleanSteps[i].toStdString()); ! editor.plugin.empty())
  394. cause.editorPlugin = juce::String::fromUTF8 (editor.plugin.c_str());
  395. if (crashFile.existsAsFile())
  396. {
  397. // the first frames after the crash handler's own (the "--- frames" part lists the faulting thread)
  398. auto text = crashFile.loadFileAsString();
  399. if (text.contains ("--- frames"))
  400. text = text.fromFirstOccurrenceOf ("--- frames", false, false);
  401. auto lines = juce::StringArray::fromLines (text);
  402. int looked = 0;
  403. for (const auto& line : lines)
  404. {
  405. const auto module = line.fromFirstOccurrenceOf (": ", false, false).upToFirstOccurrenceOf ("+", false, false).trim().toLowerCase();
  406. if (module.isEmpty() || ! module.endsWith (".dll"))
  407. continue;
  408. if (++looked > 12)
  409. break;
  410. for (const auto* driver : { "igd", "ig9icd", "ig7icd", "igxelp", "nvwgf2um", "nvoglv", "nvd3dum", "atidxx", "atio6axx", "amdxx", "aticfx",
  411. "d3d11.dll", "d3d10warp", "dxgi.dll", "d2d1.dll", "opengl32.dll", "dcomp.dll" })
  412. if (module.startsWith (driver))
  413. {
  414. cause.gpuDriver = true;
  415. cause.driverModule = module;
  416. break;
  417. }
  418. if (cause.gpuDriver)
  419. break;
  420. }
  421. }
  422. return cause;
  423. }
  424. juce::String collectUncleanSessions()
  425. {
  426. juce::String lastStep;
  427. juce::Time newest;
  428. for (const auto& file : sessionsFolder().findChildFiles (juce::File::findFiles, false, "session-*.txt"))
  429. {
  430. const auto text = file.loadFileAsString();
  431. juce::StringPairArray values;
  432. juce::StringArray steps;
  433. for (const auto& line : juce::StringArray::fromLines (text))
  434. {
  435. if (line.startsWith ("step="))
  436. steps.add (line.fromFirstOccurrenceOf ("=", false, false));
  437. else if (line.contains ("="))
  438. values.set (line.upToFirstOccurrenceOf ("=", false, false), line.fromFirstOccurrenceOf ("=", false, false));
  439. }
  440. const auto pid = (std::uint32_t) values["pid"].getLargeIntValue();
  441. const auto start = (std::uint64_t) values["start"].getLargeIntValue();
  442. if (pid == lynx::crashguard::processId() || lynx::crashguard::processRunning (pid, start))
  443. continue; // this run, or another LYNX window still open
  444. lynx::PluginHost::settingsFolder().getChildFile ("crash-history.log")
  445. .appendText (juce::Time::getCurrentTime().toISO8601 (true) + " previous session ended without closing\n" + text + "\n");
  446. file.deleteFile();
  447. if (const auto modified = file.getLastModificationTime(); lastStep.isEmpty() || modified > newest)
  448. {
  449. newest = modified;
  450. lastStep = steps.isEmpty() ? juce::String ("start-up") : steps[steps.size() - 1].fromFirstOccurrenceOf (" ", false, false);
  451. uncleanSessionText = text;
  452. uncleanSteps.clear();
  453. for (const auto& step : steps)
  454. uncleanSteps.add (step.fromFirstOccurrenceOf (" ", false, false));
  455. }
  456. }
  457. return lastStep;
  458. }
  459. } // namespace
  460. // --uiperf (round 173f, discussion #10): a mixer fader dragged up and down with the mouse while the pattern plays. A
  461. // high-resolution timer delivers 125 moves a second to the message thread through the window's own mouse path
  462. // (ComponentPeer::handleMouseEvent), at most one waiting at a time as Windows does with WM_MOUSEMOVE; every frame the
  463. // window paints tells whether it covered the fader. Measured: how long a move waited for the message thread, the time
  464. // from a move to the first frame that shows the fader after it (input → paint), and whether the value stays put when
  465. // the mouse is released.
  466. #if JUCE_WINDOWS
  467. namespace juce
  468. {
  469. extern int lynxD2DPresents; // (cmake/LynxPatchJuce.cmake, round 190gv: every Direct2D window present)
  470. }
  471. #endif
  472. // round 190jy: --uiperf's presents per second (190kb's cycles line reads it too)
  473. static int uiPerfPresents()
  474. {
  475. #if JUCE_WINDOWS
  476. return juce::lynxD2DPresents;
  477. #else
  478. return 0;
  479. #endif
  480. }
  481. struct UiPerfDrag final : public std::enable_shared_from_this<UiPerfDrag>,
  482. private juce::HighResolutionTimer
  483. {
  484. ~UiPerfDrag() override { stopTimer(); }
  485. void start (juce::Component& windowIn, juce::Component& strips, juce::Rectangle<int> rail, lynx::AudioEngine* engineIn, int trackIn)
  486. {
  487. window = &windowIn;
  488. engine = engineIn;
  489. track = trackIn;
  490. railInWindow = window->getLocalArea (&strips, rail);
  491. watch = railInWindow.expanded (6, 40); // the cap, its tip above and the dB read-out below
  492. visible = strips.isShowing() && window->getLocalArea (&strips, strips.getLocalBounds()).contains (railInWindow.getCentre());
  493. const auto volume = engine->getSong().mixer[(std::size_t) track].volume;
  494. x = (float) railInWindow.getCentreX();
  495. startY = (float) railInWindow.getBottom() - volume * (float) railInWindow.getHeight(); // on the cap: no jump
  496. amplitude = 0.4f * (float) railInWindow.getHeight();
  497. centreY = juce::jlimit ((float) railInWindow.getY() + amplitude, (float) railInWindow.getBottom() - amplitude, startY);
  498. t0 = juce::Time::getMillisecondCounterHiRes();
  499. inject (x, startY, false);
  500. juce::ModifierKeys::currentModifiers = juce::ModifierKeys (juce::ModifierKeys::leftButtonModifier);
  501. inject (x, startY, true);
  502. active = true;
  503. startTimer (8);
  504. }
  505. // message thread
  506. void framePainted (double now, juce::Rectangle<int> area)
  507. {
  508. if (pending.empty() || ! area.intersects (watch))
  509. return;
  510. for (const auto t : pending)
  511. latencies.push_back (now - t);
  512. pending.clear();
  513. ++framesOverFader;
  514. }
  515. // the moves end; as in the reporter's clip, the song is stopped while the button is still down
  516. juce::String stop()
  517. {
  518. stopTimer();
  519. active = false;
  520. valueAtRelease = engine->getSong().mixer[(std::size_t) track].volume;
  521. engine->stop();
  522. juce::String text;
  523. text << " drag of insert " << track << "'s fader" << (visible ? "" : " (NOT VISIBLE)") << ": " << moves << " moves handled, " << dropped
  524. << " folded into the next (the message thread still busy with the previous one)\n"
  525. << " move waited for the message thread: " << describe (queueDelays) << "\n"
  526. << " input -> paint (move to the first frame over the fader): " << describe (latencies) << ", " << framesOverFader
  527. << " frames over the fader\n";
  528. return text;
  529. }
  530. juce::String release()
  531. {
  532. const auto now = engine->getSong().mixer[(std::size_t) track].volume;
  533. juce::ModifierKeys::currentModifiers = {};
  534. inject (x, lastY, false);
  535. return " song stopped, button still down: fader " + juce::String (now, 4) + " (" + juce::String (valueAtRelease, 4) + " at the last move) "
  536. + (std::abs (now - valueAtRelease) < 1.0e-4f ? "kept" : "CHANGED") + "\n";
  537. }
  538. juce::String released() const
  539. {
  540. const auto now = engine->getSong().mixer[(std::size_t) track].volume;
  541. return " after the release: fader " + juce::String (now, 4) + " (" + juce::String (valueAtRelease, 4) + " when released) "
  542. + (std::abs (now - valueAtRelease) < 1.0e-4f ? "kept" : "CHANGED") + "\n";
  543. }
  544. private:
  545. juce::Component* window = nullptr;
  546. lynx::AudioEngine* engine = nullptr;
  547. int track = 1;
  548. juce::Rectangle<int> railInWindow, watch;
  549. bool visible = false;
  550. float x = 0.0f, startY = 0.0f, centreY = 0.0f, amplitude = 0.0f, lastY = 0.0f;
  551. double t0 = 0.0;
  552. std::atomic<bool> active { false }, posted { false };
  553. std::atomic<int> dropped { 0 };
  554. int moves = 0, framesOverFader = 0;
  555. float valueAtRelease = 0.0f;
  556. std::vector<double> pending, latencies, queueDelays;
  557. static juce::String describe (std::vector<double> v)
  558. {
  559. if (v.empty())
  560. return "none";
  561. std::sort (v.begin(), v.end());
  562. const auto at = [&v] (double q) { return v[std::min (v.size() - 1, (std::size_t) (q * (double) v.size()))]; };
  563. return "p50 " + juce::String (at (0.5), 1) + " / p95 " + juce::String (at (0.95), 1) + " / p99 " + juce::String (at (0.99), 1) + " / max "
  564. + juce::String (v.back(), 1) + " ms";
  565. }
  566. void inject (float px, float py, bool down)
  567. {
  568. lastY = py;
  569. if (auto* peer = window != nullptr ? window->getPeer() : nullptr)
  570. {
  571. const auto local = peer->globalToLocal (window->localPointToGlobal (juce::Point<float> (px, py)));
  572. peer->handleMouseEvent (juce::MouseInputSource::InputSourceType::mouse, local,
  573. down ? juce::ModifierKeys (juce::ModifierKeys::leftButtonModifier) : juce::ModifierKeys(),
  574. juce::MouseInputSource::defaultPressure, juce::MouseInputSource::defaultOrientation,
  575. juce::Time::currentTimeMillis());
  576. }
  577. }
  578. void hiResTimerCallback() override
  579. {
  580. if (! active.load())
  581. return;
  582. if (posted.exchange (true))
  583. {
  584. ++dropped;
  585. return;
  586. }
  587. const auto postedAt = juce::Time::getMillisecondCounterHiRes();
  588. juce::MessageManager::callAsync ([self = shared_from_this(), postedAt] {
  589. self->posted = false;
  590. if (! self->active.load())
  591. return;
  592. const auto now = juce::Time::getMillisecondCounterHiRes();
  593. self->queueDelays.push_back (now - postedAt);
  594. // up and down ~1.3 times a second, like the reporter's hand
  595. const auto y = self->centreY + self->amplitude * (float) std::sin (2.0 * juce::MathConstants<double>::pi * 1.3 * (now - self->t0) / 1000.0);
  596. self->inject (self->x, y, true);
  597. self->pending.push_back (postedAt);
  598. ++self->moves;
  599. });
  600. }
  601. };
  602. class LynxApplication final : public juce::JUCEApplication
  603. {
  604. public:
  605. const juce::String getApplicationName() override { return JUCE_APPLICATION_NAME_STRING; }
  606. const juce::String getApplicationVersion() override { return JUCE_APPLICATION_VERSION_STRING; }
  607. // the plugin scan runs copies of LYNX as child processes
  608. bool moreThanOneInstanceAllowed() override { return true; }
  609. // A file handed to the running application. macOS does this for every Finder double-click, "Open With" and Dock drop,
  610. // also the one that starts LYNX (its argv has no file). On Windows and Linux a second start is a second process
  611. // (moreThanOneInstanceAllowed) with the file as an argument, so this is not called there. Only the first file of a
  612. // multiple selection opens: a project replaces the one before it. (D#92, round 180a)
  613. void anotherInstanceStarted (const juce::String& commandLine) override
  614. {
  615. const auto files = lynx::safety::filesInCommandLine (commandLine.toStdString());
  616. if (files.empty())
  617. return;
  618. const auto file = juce::File::getCurrentWorkingDirectory().getChildFile (juce::String::fromUTF8 (files.front().c_str()));
  619. if (! startupFileHandled) // still starting: openStartupFile takes it, nothing to ask about yet
  620. {
  621. fileToOpen = file;
  622. return;
  623. }
  624. if (mainWindow != nullptr)
  625. {
  626. mainWindow->toFront (true);
  627. mainWindow->getContent().openFileRequest (file);
  628. }
  629. }
  630. void initialise (const juce::String& commandLine) override
  631. {
  632. // round 166b: the copy of LYNX.exe that installs an update (ui/Updater.h) waits, installs, starts LYNX again
  633. if (commandLine.contains ("--apply-update") && lynx::updater::runApplyHelper (juce::StringArray::fromTokens (commandLine, true)))
  634. {
  635. updateHelper = true;
  636. quit();
  637. return;
  638. }
  639. // Windows, LYNX.exe in a folder with accents: run again from its ASCII short path (Waves editors crash otherwise)
  640. if (int code = 0; lynx::platform::relaunchFromAsciiPath (code))
  641. {
  642. relaunched = true;
  643. setApplicationReturnValue (code);
  644. quit();
  645. return;
  646. }
  647. // a crash in any mode (UI, command line) writes its backtrace to %APPDATA%\LYNX\autosave
  648. juce::SystemStats::setApplicationCrashHandler (onCrash);
  649. // rollup 0.1.28 (REA 190hb action 4, FL's "Init DWM"): the compositor on MMCSS, steadier frames under CPU load
  650. // (Windows; LYNX_DWM_MMCSS=0 leaves it off)
  651. lynx::powerhints::enableCompositorMmcss();
  652. // round als190ka (issue #193): a video's sound track for the sample library (a Live set's video clips)
  653. lynx::SampleLibrary::setVideoSoundDecoder ([] (const juce::File& video) { return lynx::videotracks::soundTrackWav (video); });
  654. // round 190ci: also for a fault on a stack Windows cannot walk, which never reaches that handler (Windows)
  655. lynx::crashguard::setUnwalkableFaultHandler (onCrash);
  656. if (const auto args = juce::StringArray::fromTokens (commandLine, true); args.contains ("--faulttest"))
  657. {
  658. // LYNX.exe --faulttest plain|unwalkable <folder> (round 190ci): ends by an access violation on purpose,
  659. // before any window, so that --selftest can check that the crash file gets written (into <folder>)
  660. const auto i = args.indexOf ("--faulttest");
  661. crashFolderForTest = juce::File (args[i + 2].unquoted());
  662. lynx::crashguard::quietCrashReports();
  663. // round 190dt: guarded / guarded-libc = LYNX's own fault inside a guarded plugin call (Linux / macOS): it must
  664. // reach the crash handler like any other; a return means the guard swallowed it
  665. // round 190gg: thread / thread-libc = a fault on a thread of LYNX's own, with LYNX's executable watched as
  666. // a plugin's module: it must not be parked as a plugin's thread
  667. if (args[i + 1].startsWith ("thread"))
  668. {
  669. lynx::crashguard::faultOnOwnThreadForTest (args[i + 1] == "thread-libc");
  670. crashFolderForTest.getChildFile ("swallowed.txt").replaceWithText ("parked");
  671. lynx::crashguard::exitNow (4);
  672. }
  673. if (args[i + 1].startsWith ("guarded"))
  674. {
  675. const auto code = lynx::crashguard::faultInGuardedCallForTest (args[i + 1] == "guarded-libc");
  676. crashFolderForTest.getChildFile ("swallowed.txt").replaceWithText (lynx::crashguard::describe (code));
  677. lynx::crashguard::exitNow (4);
  678. }
  679. lynx::crashguard::faultForTest (args[i + 1] == "unwalkable");
  680. }
  681. lynx::crashguard::hardenSignals(); // issue #115: stack overflows and SIGTERM / SIGHUP leave a trace (Linux / macOS)
  682. // SFZ instruments (round 167o): their FLAC / OGG / AIFF / MP3 samples through JUCE's readers
  683. lynx::sfz::setDecoder ([] (const std::string& path, lynx::sfz::Audio& out) {
  684. juce::AudioFormatManager formats;
  685. formats.registerBasicFormats();
  686. std::unique_ptr<juce::AudioFormatReader> reader (formats.createReaderFor (juce::File (juce::String::fromUTF8 (path.c_str()))));
  687. if (reader == nullptr || reader->lengthInSamples <= 0 || reader->lengthInSamples > (1 << 28) || reader->numChannels == 0)
  688. return false;
  689. const auto frames = (int) reader->lengthInSamples;
  690. juce::AudioBuffer<float> buffer ((int) std::min (2u, reader->numChannels), frames);
  691. if (! reader->read (&buffer, 0, frames, 0, true, buffer.getNumChannels() > 1))
  692. return false;
  693. out.channels.clear();
  694. for (int ch = 0; ch < buffer.getNumChannels(); ++ch)
  695. out.channels.emplace_back (buffer.getReadPointer (ch), buffer.getReadPointer (ch) + frames);
  696. out.sampleRate = reader->sampleRate;
  697. out.loopStart = out.loopEnd = -1;
  698. return true;
  699. });
  700. // child process of a sandboxed plugin: no window or audio of its own
  701. if (lynx::runPluginSandboxWorker (commandLine))
  702. {
  703. lynx::crashguard::quietCrashReports();
  704. sandboxChild = true;
  705. return;
  706. }
  707. // --shot-scale <v> / --shot-suffix <text> (round 190bi, ui/ShotScale.h): the pixel scale and file-name suffix of every
  708. // picture route, taken out here so the routes' own arguments keep their places
  709. const auto args = lynx::shot::takeArguments (juce::StringArray::fromTokens (commandLine, true));
  710. // interface language: saved in %APPDATA%\LYNX\language.txt; --lang pt-BR overrides it for this run
  711. lynx::i18n::initialise (args);
  712. // interface font: saved in Settings › General; --uifont "Name" overrides it for this run
  713. const auto uiFontArg = args.indexOf ("--uifont");
  714. lookAndFeel.applyInterfaceFont (lynx::i18n::current(), uiFontArg >= 0 ? args[uiFontArg + 1].unquoted() : juce::String());
  715. // text size (issue #189): saved in Settings › General; --textsize 125 overrides it for this run
  716. const auto textSizeArg = args.indexOf ("--textsize");
  717. lynx::theme::setTextSize (textSizeArg >= 0 ? args[textSizeArg + 1].getIntValue() : lynx::theme::savedTextSize());
  718. // bold text (round 190jp): saved in Settings › General; --boldtext 1 (labels) or 2 (all) overrides it for this run
  719. const auto boldTextArg = args.indexOf ("--boldtext");
  720. lynx::theme::setBoldText (boldTextArg >= 0 ? args[boldTextArg + 1].getIntValue() : lynx::theme::savedBoldText());
  721. // round 190je: FL-style condensed labels (Settings › General); --condensedlabels for one run. --menustyle flClassic: FL's
  722. // light menus for one run (Settings › Theme keeps the saved choice)
  723. lynx::theme::setCondensedLabels (args.contains ("--condensedlabels") || lynx::theme::savedCondensedLabels());
  724. if (const auto menuStyleArg = args.indexOf ("--menustyle"); menuStyleArg >= 0)
  725. {
  726. lynx::theme::menus::setStyle (lynx::themes::menuStyleFromId (args[menuStyleArg + 1].unquoted().toStdString()));
  727. lookAndFeel.refreshColours();
  728. }
  729. if (args.contains ("--showcase"))
  730. {
  731. // LYNX's own demo project (README screenshots): --showcase output.lynx [pattern]
  732. const auto i = args.indexOf ("--showcase");
  733. runShowcase (args[i + 1].unquoted(), args[i + 2].getIntValue());
  734. return;
  735. }
  736. if (args.contains ("--demosongs"))
  737. {
  738. // round 190dv: LYNX's two short genre demos (core/DemoSongs.h) as .lynx files: --demosongs <folder>
  739. // (resources/demos/ in the repository)
  740. const auto i = args.indexOf ("--demosongs");
  741. runDemoSongs (args[i + 1].unquoted());
  742. return;
  743. }
  744. if (args.contains ("--perfgen"))
  745. {
  746. // round perfgate190id: the big-project performance gate's synthetic projects (core/PerfProjects.h) as .lynx
  747. // files with their WAVs: --perfgen <folder> [report.txt] [name,name...]; the save and load times in the report
  748. const auto i = args.indexOf ("--perfgen");
  749. const auto report = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  750. const auto only = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  751. runPerfGen (args[i + 1].unquoted(), report, only);
  752. return;
  753. }
  754. if (args.contains ("--sandboxtest"))
  755. {
  756. const auto i = args.indexOf ("--sandboxtest");
  757. runSandboxTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  758. return;
  759. }
  760. // round 190jg (BUILD-LIST 11 + 18, engine/HostingTests.h): grouped plugin processes, CLAP extensions, timing
  761. if (args.contains ("--sandboxgrouptest") || args.contains ("--sandboxbench") || args.contains ("--clapext")
  762. || args.contains ("--automationtimingtest"))
  763. {
  764. const auto value = [&args] (const char* name, int fallback) {
  765. return args.contains (name) ? args[args.indexOf (name) + 1].getIntValue() : fallback;
  766. };
  767. auto code = 1;
  768. if (const auto i = args.indexOf ("--sandboxgrouptest"); i >= 0)
  769. code = lynx::runSandboxGroupTest (args[i + 1].unquoted(), args[i + 2].unquoted(),
  770. args.contains ("--crash") ? args[args.indexOf ("--crash") + 1].unquoted() : juce::String());
  771. else if (const auto b = args.indexOf ("--sandboxbench"); b >= 0)
  772. code = lynx::runSandboxBench (args[b + 1].unquoted(), args[b + 2].unquoted(), value ("--plugins", 8), value ("--block", 256),
  773. args.contains ("--seconds") ? args[args.indexOf ("--seconds") + 1].getDoubleValue() : 5.0);
  774. else if (const auto c = args.indexOf ("--clapext"); c >= 0)
  775. code = lynx::runClapExtTest (args[c + 1].unquoted(), args[c + 2].unquoted());
  776. else if (const auto t = args.indexOf ("--automationtimingtest"); t >= 0)
  777. code = lynx::runAutomationTimingTest (args[t + 1].unquoted(), args[t + 2].unquoted());
  778. setApplicationReturnValue (code);
  779. quit();
  780. return;
  781. }
  782. if (args.contains ("--bridge32test"))
  783. {
  784. // LYNX.exe --bridge32test "LYNX Test Synth 32.dll" report.txt [--compare "LYNX Test Synth.dll"] (round 176a):
  785. // the 32-bit plugin bridge (engine/Bridge32Test.cpp)
  786. const auto i = args.indexOf ("--bridge32test");
  787. const auto compare = args.contains ("--compare") ? args[args.indexOf ("--compare") + 1].unquoted() : juce::String();
  788. setApplicationReturnValue (lynx::runBridge32Test (args[i + 1].unquoted(), args[i + 2].unquoted(), compare));
  789. quit();
  790. return;
  791. }
  792. if (args.contains ("--rtstress"))
  793. {
  794. // LYNX.exe --rtstress project.(flp|lynx) report.txt [seconds] [--buffer N] [--type "driver type"] [--device "output"]
  795. // [--no-window] [--record take.wav]: the real app (window, audio device) plays the project and reports the callbacks
  796. // that missed their deadline (REA round 87); --type/--device pick another driver for this run only (round 97);
  797. // --record also records the input during the run, like Rec + Play, and moves the take to take.wav (round 106)
  798. const auto i = args.indexOf ("--rtstress");
  799. const auto seconds = args[i + 3].getDoubleValue();
  800. const auto buffer = args.contains ("--buffer") ? args[args.indexOf ("--buffer") + 1].getIntValue() : 0;
  801. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  802. const auto option = [&args] (const char* name) { return args.contains (name) ? args[args.indexOf (name) + 1].unquoted() : juce::String(); };
  803. runRealtimeStress (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()), seconds > 0.0 ? seconds : 30.0, buffer,
  804. option ("--type"), option ("--device"), option ("--record"));
  805. return;
  806. }
  807. if (args.contains ("--renderaheadtest"))
  808. {
  809. // LYNX --renderaheadtest report.txt [project.flp|.lynx ...] [--buffer N] [--seconds S] (round 190gq): the engine's
  810. // own device callback (a stand-in device driven block by block, as --cliplooptest) plays the showcase song (from
  811. // the start, round a loop region that wraps mid-block, in Pattern mode) and each project with Options › Audio
  812. // settings › "Render ahead" off, then on. The two outputs must be the same to the bit, nothing rendered ahead
  813. // may be dropped, and most blocks must come from the ring. No window, no audio device.
  814. const auto i = args.indexOf ("--renderaheadtest");
  815. juce::StringArray projects;
  816. for (int k = i + 2; k < args.size() && ! args[k].startsWith ("--"); ++k)
  817. projects.add (args[k].unquoted());
  818. const auto buffer = args.contains ("--buffer") ? args[args.indexOf ("--buffer") + 1].getIntValue() : 128;
  819. const auto seconds = args.contains ("--seconds") ? args[args.indexOf ("--seconds") + 1].getDoubleValue() : 12.0;
  820. runRenderAheadTest (juce::File (args[i + 1].unquoted()), projects, juce::jlimit (16, 2048, buffer), seconds > 0.0 ? seconds : 12.0);
  821. return;
  822. }
  823. if (args.contains ("--cliplooptest"))
  824. {
  825. // LYNX --cliplooptest report.txt [export.wav] (round 167q, issue #25: 0.1.21 drew the repeats of a stretched
  826. // pattern clip but played the pattern once). The real engine's device callback (a stand-in device, driven
  827. // block by block) plays a synth's 1-bar pattern in a 4-bar clip: every repeat must sound as bar 1, also
  828. // starting inside a repeat, after a jump mid-clip and in a loop region; the WAV export (written to
  829. // export.wav and read back) the same. With the LYNX extra off, bars 2-4 must be silent (FL's behaviour).
  830. const auto i = args.indexOf ("--cliplooptest");
  831. runClipLoopTest (juce::File (args[i + 1].unquoted()), args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? juce::File (args[i + 2].unquoted()) : juce::File());
  832. return;
  833. }
  834. if (args.contains ("--devicechangetest"))
  835. {
  836. // LYNX --devicechangetest report.txt [switches] [--plugin file]... (round 190c, issue #134: changing the
  837. // output device with a project open crashed LYNX). The engine plays a project of every instrument and effect
  838. // it can make here on stand-in devices with real callback threads, while the output device, its sample
  839. // rate and its buffer size change the way Settings > Audio changes them (8 kHz mono to 192 kHz, buffers of
  840. // 32 to 16384 samples, a device plugged in, the open one unplugged, one that refuses to open). After every
  841. // change the song must sound, finite, at the new rate. No window, no real audio or MIDI device.
  842. const auto i = args.indexOf ("--devicechangetest");
  843. const juce::File report (args[i + 1].unquoted());
  844. const auto switches = args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? args[i + 2].getIntValue() : 0;
  845. juce::StringArray plugins;
  846. for (int k = 0; k + 1 < args.size(); ++k)
  847. if (args[k] == "--plugin")
  848. plugins.add (args[k + 1].unquoted());
  849. auto text = std::make_shared<juce::String>();
  850. // --quick: the selftest's handful of instruments and effects instead of every one
  851. const auto result = lynx::AudioEngine::deviceChangeSelfTest (switches > 0 ? switches : 40, ! args.contains ("--quick"), plugins, [report, text] (const juce::String& line) {
  852. *text << line << "\n";
  853. report.replaceWithText (*text + "(running)\n"); // what was reached, if it crashes
  854. });
  855. *text << "device_change=" << result << "\nresult=" << (result.startsWith ("OK") ? "OK" : "FAILED") << "\n";
  856. report.replaceWithText (*text);
  857. setApplicationReturnValue (result.startsWith ("OK") ? 0 : 1);
  858. quit();
  859. return;
  860. }
  861. if (args.contains ("--exportlivetest"))
  862. {
  863. // LYNX --exportlivetest report.txt [--plugin file]... (round 190jb): exports with the live plugin instances (as
  864. // FL renders) against playback on a stand-in device, the plugins given back afterwards. No window.
  865. const auto i = args.indexOf ("--exportlivetest");
  866. const juce::File report (args[i + 1].unquoted());
  867. juce::StringArray files;
  868. for (int k = 0; k + 1 < args.size(); ++k)
  869. if (args[k] == "--plugin")
  870. files.add (args[k + 1].unquoted());
  871. juce::String text;
  872. const auto result = lynx::AudioEngine::exportLiveSelfTest ([&text] (const juce::String& line) { text << line << "\n"; }, files);
  873. text << "export_live=" << result << "\nresult=" << (result.startsWith ("OK") ? "OK" : "FAILED") << "\n";
  874. report.replaceWithText (text);
  875. setApplicationReturnValue (result.startsWith ("OK") ? 0 : 1);
  876. quit();
  877. return;
  878. }
  879. if (args.contains ("--midiouttest"))
  880. {
  881. // LYNX --midiouttest report.txt (round 190jl): MIDI Out channels to the hardware MIDI outputs on their port
  882. // (the sender's dry run and the live engine on a stand-in device). No window.
  883. const auto i = args.indexOf ("--midiouttest");
  884. const auto result = lynx::AudioEngine::midiOutPortSelfTest();
  885. juce::File (args[i + 1].unquoted()).replaceWithText ("midi_out_ports=" + result + "\nresult=" + (result.startsWith ("OK") ? "OK" : "FAILED") + "\n");
  886. setApplicationReturnValue (result.startsWith ("OK") ? 0 : 1);
  887. quit();
  888. return;
  889. }
  890. if (args.contains ("--exportparitytest") || args.contains ("--midihotplugtest"))
  891. {
  892. // LYNX --exportparitytest report.txt (round 190gh, B7): the export against playback through a stand-in audio
  893. // device, stems adding up to the mix with one length, the PDC trim. LYNX --midihotplugtest report.txt (B8):
  894. // MIDI devices plugged in and out (stand-in device lists) while messages arrive. No window.
  895. const auto parity = args.contains ("--exportparitytest");
  896. const auto i = args.indexOf (parity ? "--exportparitytest" : "--midihotplugtest");
  897. const juce::File report (args[i + 1].unquoted());
  898. juce::String text;
  899. const auto result = parity ? lynx::AudioEngine::exportParitySelfTest ([&text] (const juce::String& line) { text << line << "\n"; })
  900. : lynx::AudioEngine::midiHotplugSelfTest();
  901. text << (parity ? "export_parity=" : "midi_hotplug=") << result << "\nresult=" << (result.startsWith ("OK") ? "OK" : "FAILED") << "\n";
  902. report.replaceWithText (text);
  903. setApplicationReturnValue (result.startsWith ("OK") ? 0 : 1);
  904. quit();
  905. return;
  906. }
  907. if (args.contains ("--shortexportstress"))
  908. {
  909. // LYNX --shortexportstress report.txt [count] [--seed N] [--no-realtime] [--plugin file] (round 190hn, issue #138): `count`
  910. // random export settings over short sounds at the very start of the song, each exported again a bar later; a
  911. // file that comes out silent or quieter fails (engine/ShortExportTest.h). No window.
  912. const auto i = args.indexOf ("--shortexportstress");
  913. const juce::File report (args[i + 1].unquoted());
  914. const auto count = args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? args[i + 2].getIntValue() : 200;
  915. const auto s = args.indexOf ("--seed");
  916. const auto seed = s >= 0 && s + 1 < args.size() ? args[s + 1].getLargeIntValue() : juce::Time::currentTimeMillis();
  917. auto text = std::make_shared<juce::String>();
  918. const auto pl = args.indexOf ("--plugin");
  919. lynx::shortexport::stress (count, seed, ! args.contains ("--no-realtime"), pl >= 0 && pl + 1 < args.size() ? args[pl + 1].unquoted() : juce::String(),
  920. [report, text] (const juce::String& line) {
  921. *text << line << "\n";
  922. report.replaceWithText (*text + "(running)\n");
  923. },
  924. [this, report, text] (juce::String result) {
  925. *text << "short_export_stress=" << result << "\nresult=" << (result.startsWith ("OK") ? "OK" : "FAILED") << "\n";
  926. report.replaceWithText (*text);
  927. setApplicationReturnValue (result.startsWith ("OK") ? 0 : 1);
  928. quit();
  929. });
  930. return;
  931. }
  932. if (args.contains ("--shortexporttest"))
  933. {
  934. // LYNX --shortexporttest report.txt [repeats] [--plugin file]... (round 190c, issue #138: a short note at
  935. // the very start of the Playlist exported quiet). Every instrument LYNX can make here, and a synth with
  936. // effects, tail modes, normalising and other rates, exported through the Export window's path (the job
  937. // made on the message thread, run on its own thread, the message loop running) with a 2-second note at
  938. // tick 0 and again with it at bar 2: the note must come out the same. No window.
  939. const auto i = args.indexOf ("--shortexporttest");
  940. const juce::File report (args[i + 1].unquoted());
  941. const auto repeats = args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? args[i + 2].getIntValue() : 0;
  942. juce::StringArray plugins;
  943. for (int k = 0; k + 1 < args.size(); ++k)
  944. if (args[k] == "--plugin")
  945. plugins.add (args[k + 1].unquoted());
  946. auto text = std::make_shared<juce::String>();
  947. lynx::shortexport::run (! args.contains ("--quick"), repeats > 0 ? repeats : 3, plugins, // (--quick: a handful of instruments, round 190hn)
  948. [report, text] (const juce::String& line) {
  949. *text << line << "\n";
  950. report.replaceWithText (*text + "(running)\n");
  951. },
  952. [this, report, text] (juce::String result) {
  953. *text << "short_export=" << result << "\nresult=" << (result.startsWith ("OK") ? "OK" : "FAILED") << "\n";
  954. report.replaceWithText (*text);
  955. setApplicationReturnValue (result.startsWith ("OK") ? 0 : 1);
  956. quit();
  957. });
  958. return;
  959. }
  960. if (args.contains ("--slicexedittest"))
  961. {
  962. // LYNX --slicexedittest project script.txt report.txt [png-prefix] (round 190aj): the Slicex editor of the
  963. // project's first Slicex channel, off screen, driven by the script's commands (ui/SlicexEditor.h; mouse
  964. // gestures at fractions of the deck's width, the menu entries, shortcuts). The report holds each command
  965. // and what the state held after it; "shot <name>" writes <png-prefix><name>.png.
  966. const auto i = args.indexOf ("--slicexedittest");
  967. runSlicexEditTest (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()), juce::File (args[i + 3].unquoted()),
  968. args.size() > i + 4 ? args[i + 4].unquoted() : juce::String());
  969. return;
  970. }
  971. if (args.contains ("--dwedittest"))
  972. {
  973. // LYNX --dwedittest project script.txt report.txt [png-prefix] (round 190hz): the DirectWave editor of the
  974. // project's first DirectWave channel, off screen, driven by the script's commands (ui/DirectWaveEditor.h);
  975. // "shot <name>" writes <png-prefix><name>.png. A project path "new" makes a new DirectWave channel.
  976. const auto i = args.indexOf ("--dwedittest");
  977. runDirectWaveEditTest (args[i + 1].unquoted(), juce::File (args[i + 2].unquoted()), juce::File (args[i + 3].unquoted()),
  978. args.size() > i + 4 ? args[i + 4].unquoted() : juce::String());
  979. return;
  980. }
  981. if (args.contains ("--slicexkeytest"))
  982. {
  983. // LYNX --slicexkeytest report.txt (round 190ac): what a click on the Slicex editor's keyboard sends
  984. // (AudioEngine::sendLiveNote on the channel, velocity 100/128) through the real engine's device callback
  985. // (a stand-in device, driven block by block): the key's region must sound, on the channel's mixer meter
  986. // too, another key must play another region, and the note-off must end it.
  987. runSlicexKeyTest (juce::File (args[args.indexOf ("--slicexkeytest") + 1].unquoted()));
  988. return;
  989. }
  990. if (args.contains ("--countinrectest"))
  991. {
  992. // LYNX --countinrectest report.txt (round 170d, the Busy Works video: the chord on the downbeat after the
  993. // pre-count was lost). The real engine's device callback (a stand-in device: 48 kHz, blocks of 512, 256
  994. // samples of output latency) records a Song-mode take from bar 3 with a 1-bar count-in. Pass 1 finds where
  995. // the metronome's bar-3 click is heard; pass 2 plays MIDI notes stamped at the times they are heard around
  996. // 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
  997. // LYNX's MIDI input. Every note must land on the tick it was heard at (the chord on bar 3).
  998. const auto i = args.indexOf ("--countinrectest");
  999. runCountInRecordTest (juce::File (args[i + 1].unquoted()));
  1000. return;
  1001. }
  1002. if (args.contains ("--bendrectest"))
  1003. {
  1004. // LYNX --bendrectest report.txt [song|pattern] (round 167a, issue #12): pitch bend recording end to end. A
  1005. // controller's pitch wheel is injected into LYNX's MIDI input (as a device would send it) while recording
  1006. // plays: a held note and a wheel sweep 0 → full up → full down → centre. The recorded lane (pattern mode) or
  1007. // automation clip (song mode) of the channel's pitch bend must follow the sweep.
  1008. const auto i = args.indexOf ("--bendrectest");
  1009. const auto songMode = args.size() > i + 2 && args[i + 2] == "song";
  1010. runBendRecordTest (juce::File (args[i + 1].unquoted()), songMode);
  1011. return;
  1012. }
  1013. if (args.contains ("--rectest"))
  1014. {
  1015. // LYNX --rectest report.txt [seconds] [--type T] [--device D] [--input I] [--loop] [--buffer N]
  1016. // (round 163): records a click track through a loopback (cable, interface loopback or PipeWire's
  1017. // pw-loopback): pings the round trip, plays a click on every beat from an audio clip, records it on Insert 1,
  1018. // stops, and checks every recorded click's song position on the Playlist against its beat (samples).
  1019. // --loop: loop recording over bars 2-4 (take lanes). --punch: punch in/out on bars 3-4 with 1 bar of pre-roll
  1020. // and 1 of post-roll (playback stops by itself after the post-roll).
  1021. const auto i = args.indexOf ("--rectest");
  1022. const auto option = [&args] (const char* name) { return args.contains (name) ? args[args.indexOf (name) + 1].unquoted() : juce::String(); };
  1023. const auto seconds = args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? args[i + 2].getDoubleValue() : 20.0;
  1024. runRecordTest (juce::File (args[i + 1].unquoted()), seconds > 0.0 ? seconds : 20.0, option ("--type"), option ("--device"), option ("--input"),
  1025. args.contains ("--loop") ? 1 : args.contains ("--punch") ? 2 : 0, option ("--pdc").getIntValue(), option ("--buffer").getIntValue());
  1026. return;
  1027. }
  1028. if (args.contains ("--hwinserttest"))
  1029. {
  1030. // LYNX --hwinserttest report.txt [seconds] [--type T] [--device D] [--input I] [--buffer N] (round 164d): a
  1031. // hardware insert through a loopback cable (output pair 1-2 -> input pair 1-2; the Master plays nowhere, so
  1032. // the cable carries the send only). The same click track plays on two inserts: Insert 1 through the
  1033. // hardware insert (panned left), Insert 2 dry (panned right). The insert's own ping measures the round
  1034. // trip, PDC delays the dry path by it, and every click of the Master's left side must sit on the same
  1035. // sample as the right side's.
  1036. const auto i = args.indexOf ("--hwinserttest");
  1037. const auto option = [&args] (const char* name) { return args.contains (name) ? args[args.indexOf (name) + 1].unquoted() : juce::String(); };
  1038. const auto seconds = args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? args[i + 2].getDoubleValue() : 10.0;
  1039. // round 165c: --patcher puts the insert inside a Patcher on Insert 1; --bounce file.wav then exports the song in real
  1040. // time through the device (Export › "Render through the hardware in real time") and offline, and compares them
  1041. runHwInsertTest (juce::File (args[i + 1].unquoted()), seconds > 0.0 ? seconds : 10.0, option ("--type"), option ("--device"), option ("--input"),
  1042. option ("--buffer").getIntValue(), args.contains ("--patcher"),
  1043. args.contains ("--bounce") ? juce::File (option ("--bounce")) : juce::File());
  1044. return;
  1045. }
  1046. if (args.contains ("--uiperf"))
  1047. {
  1048. // LYNX --uiperf project.(flp|lynx) report.txt: the heavy UI cases in the real window, every frame timed (round 161)
  1049. const auto i = args.indexOf ("--uiperf");
  1050. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1051. runUiPerf (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()));
  1052. return;
  1053. }
  1054. if (args.contains ("--cachetest"))
  1055. {
  1056. // LYNX --cachetest project.(flp|lynx) report.txt (round 174f): the Playlist's cached picture against exact
  1057. // paints after zooms, scrolls and repaints, off screen (no window)
  1058. const auto i = args.indexOf ("--cachetest");
  1059. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1060. runCacheTest (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()));
  1061. return;
  1062. }
  1063. if (args.contains ("--picturetest"))
  1064. {
  1065. // LYNX --picturetest report.txt [project.(flp|lynx)] (round 190bm): the Playlist and the Mixer drawn through
  1066. // their cached pictures at 100-300 %, into native and software targets, against straight paints; off
  1067. // screen (no window)
  1068. const auto i = args.indexOf ("--picturetest");
  1069. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1070. runPictureTest (juce::File (args[i + 1].unquoted()), i + 2 < args.size() ? juce::File (args[i + 2].unquoted()) : juce::File());
  1071. return;
  1072. }
  1073. if (args.contains ("--timertest"))
  1074. {
  1075. // LYNX --timertest report.txt (round 174f): ui::TimerWhileShowing through hide / show / minimise (opens a small window)
  1076. runTimerTest (juce::File (args[args.indexOf ("--timertest") + 1].unquoted()));
  1077. return;
  1078. }
  1079. if (args.contains ("--livepeer"))
  1080. {
  1081. // LYNX --livepeer host|guest|rejoin <folder> [--relay URL] [--code CODE|@file]: one computer's side of a live
  1082. // session between two real computers, no window (round 190ah)
  1083. setApplicationReturnValue (lynx::livetest::runPeer (args));
  1084. quit();
  1085. return;
  1086. }
  1087. if (args.contains ("--livetest"))
  1088. {
  1089. // LYNX --livetest report.txt [--relay URL]: a live session of four peers over the relay (round 169b)
  1090. setApplicationReturnValue (lynx::livetest::run (args));
  1091. quit();
  1092. return;
  1093. }
  1094. if (args.contains ("--selftest"))
  1095. {
  1096. const auto i = args.indexOf ("--selftest");
  1097. runSelfTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  1098. return;
  1099. }
  1100. if (args.contains ("--scan-one"))
  1101. {
  1102. // child process of the plugin scan (see PluginHost::scan)
  1103. const auto i = args.indexOf ("--scan-one");
  1104. // no crash dialogs from the plugin being examined; and once the result is written, the process ends without
  1105. // unloading it: a Waves shell crashed in its own teardown at exit (Intel GPU driver fail-fast, 0xC0000409),
  1106. // which showed Windows' crash dialog and made the scan reject the whole shell (round 111)
  1107. lynx::crashguard::quietCrashReports();
  1108. lynx::PluginHost::scanOneFile (args[i + 1].unquoted(), args[i + 2].unquoted(), juce::File (args[i + 3].unquoted()));
  1109. lynx::crashguard::exitNow (0);
  1110. }
  1111. if (args.contains ("--splashshot"))
  1112. {
  1113. // LYNX --splashshot <folder> (round 190hd): the splash card drawn as the JUCE card is and as the card on its own
  1114. // thread is (ui/Splash.h), side by side; no window
  1115. const auto shots = lynx::writeSplashShots (juce::File (args[args.indexOf ("--splashshot") + 1].unquoted()));
  1116. setApplicationReturnValue (shots.size() == 20 ? 0 : 1);
  1117. quit();
  1118. return;
  1119. }
  1120. if (args.contains ("--browser-indexer"))
  1121. {
  1122. // round 190hd: the Browser's indexer, a low-priority child of the LYNX window (BrowserComponent.h): no window,
  1123. // no session, no audio; it ends with its parent
  1124. lynx::crashguard::quietCrashReports();
  1125. lynx::crashguard::exitNow (lynx::BrowserComponent::runIndexerProcess (args));
  1126. }
  1127. if (args.contains ("--packageinfo"))
  1128. {
  1129. // round 165n: the Microsoft Store (MSIX) build's identity and folders (platform/Package.h); the release
  1130. // workflow runs it inside the installed test package
  1131. juce::File (args[args.indexOf ("--packageinfo") + 1].unquoted()).replaceWithText (lynx::platform::packageReport());
  1132. quit();
  1133. return;
  1134. }
  1135. if (args.contains ("--paths"))
  1136. {
  1137. // diagnostics: folders LYNX searches
  1138. const auto programs = juce::File::getSpecialLocation (juce::File::globalApplicationsDirectory);
  1139. juce::String report;
  1140. report << "programs=" << programs.getFullPathName() << "\n";
  1141. for (const auto& dir : programs.getChildFile ("Image-Line").findChildFiles (juce::File::findDirectories, false, "FL Studio*"))
  1142. report << "fl=" << dir.getFullPathName() << " packs=" << (int) dir.getChildFile ("Data").getChildFile ("Patches").getChildFile ("Packs").isDirectory() << "\n";
  1143. juce::File (args[args.indexOf ("--paths") + 1].unquoted()).replaceWithText (report);
  1144. quit();
  1145. return;
  1146. }
  1147. if (args.contains ("--fldb"))
  1148. {
  1149. // diagnostics: LYNX.exe --fldb report.txt [project.flp]: the FL Studio installation, its plugin database,
  1150. // the suggested plugin folders and, for a project, how each of its plugins resolves (read-only)
  1151. const auto i = args.indexOf ("--fldb");
  1152. const auto fl = lynx::findFlStudio();
  1153. lynx::PluginHost host (false);
  1154. juce::String report;
  1155. report << "install=" << fl.installDir.getFullPathName() << "\nuserdata=" << fl.userData.getFullPathName() << "\n";
  1156. for (const auto& f : fl.vstFolders)
  1157. report << "flvstfolder=" << f << "\n";
  1158. report << "dbfiles=" << host.flPluginDatabaseFiles() << " entries=" << (int) host.flPluginDatabase().entries().size() << "\n";
  1159. for (const auto& e : host.flPluginDatabase().entries())
  1160. report << " entry: " << juce::String::fromUTF8 (e.name.c_str()) << " | " << juce::String::fromUTF8 (e.path.c_str()) << " | role=" << e.role << "\n";
  1161. const auto suggested = host.suggestedFolders();
  1162. for (int k = 0; k < suggested.getNumPaths(); ++k)
  1163. report << "folder=" << suggested[k].getFullPathName() << "\n";
  1164. if (const juce::File project (args[i + 2].unquoted()); project.existsAsFile())
  1165. {
  1166. juce::MemoryBlock data;
  1167. project.loadFileAsData (data);
  1168. try
  1169. {
  1170. for (const auto& use : lynx::flpForeignPlugins (flp::parseProject ({ static_cast<const std::uint8_t*> (data.getData()), data.getSize() })))
  1171. {
  1172. juce::String how;
  1173. const auto d = host.findForeign (use.plugin, use.instrument, &how);
  1174. const auto* entry = host.flPluginDatabase().match (use.plugin, use.instrument);
  1175. report << "plugin: " << juce::String::fromUTF8 (use.plugin.name.c_str()) << " -> "
  1176. << (d ? d->fileOrIdentifier + " (" + how + ")" : juce::String ("not known"))
  1177. << (entry != nullptr ? " | fl db: " + juce::String::fromUTF8 (entry->path.c_str()) : juce::String()) << "\n";
  1178. }
  1179. const auto uses = lynx::flpForeignPlugins (flp::parseProject ({ static_cast<const std::uint8_t*> (data.getData()), data.getSize() }));
  1180. const auto candidates = host.filesToScanFor (uses);
  1181. report << "scan_candidates=" << candidates.joinIntoString (";") << "\n";
  1182. if (args.contains ("--scan"))
  1183. {
  1184. // the targeted scan an open would run (child processes; the user's plugin list is not touched)
  1185. report << "scanned_new=" << host.scanFiles (candidates, {}) << "\n";
  1186. for (const auto& use : uses)
  1187. {
  1188. juce::String how;
  1189. const auto d = host.findForeign (use.plugin, use.instrument, &how);
  1190. report << "after_scan: " << juce::String::fromUTF8 (use.plugin.name.c_str()) << " -> "
  1191. << (d ? d->fileOrIdentifier + " (" + how + ")" : juce::String ("not known")) << "\n";
  1192. }
  1193. }
  1194. }
  1195. catch (const flp::Error& e)
  1196. {
  1197. report << "error=" << e.what() << "\n";
  1198. }
  1199. }
  1200. juce::File (args[i + 1].unquoted()).replaceWithText (report);
  1201. quit();
  1202. return;
  1203. }
  1204. if (args.contains ("--midisync-test"))
  1205. {
  1206. // LYNX --midisync-test report.txt ["output device"] ["input device"] (round 165f): MIDI clock timing
  1207. const auto i = args.indexOf ("--midisync-test");
  1208. const auto out = args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  1209. const auto in = args.size() > i + 3 && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  1210. juce::File (args[i + 1].unquoted()).replaceWithText (lynx::MidiSyncIo::selfTest (out, in));
  1211. quit();
  1212. return;
  1213. }
  1214. if (args.contains ("--linktest"))
  1215. {
  1216. // LYNX --linktest report.txt [seconds] [peer] (round 190gl): Ableton Link with simulated audio callbacks; with
  1217. // "peer" a second Link peer in this process, else a peer on the network (Ableton's LinkHut) is expected
  1218. const auto i = args.indexOf ("--linktest");
  1219. const auto seconds = args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? args[i + 2].getDoubleValue() : 20.0;
  1220. const auto ownPeer = args.contains ("peer");
  1221. juce::File (args[i + 1].unquoted()).replaceWithText (juce::String (lynx::AbletonLink::selfTest (seconds > 0.0 ? seconds : 20.0, ownPeer)));
  1222. quit();
  1223. return;
  1224. }
  1225. if (args.contains ("--devices") || args.contains ("--dispositivos")) // --dispositivos: legacy alias
  1226. {
  1227. // diagnostics: driver types and output devices JUCE offers (without opening any)
  1228. juce::AudioDeviceManager manager;
  1229. juce::String report;
  1230. manager.getAvailableDeviceTypes();
  1231. if (auto pipeWire = lynx::makePipeWireDeviceType()) // Linux: LYNX's own PipeWire client (round 161)
  1232. manager.addAudioDeviceType (std::move (pipeWire));
  1233. #if JUCE_LINUX
  1234. report << lynx::describePipeWire() << "\n";
  1235. #endif
  1236. for (auto* type : manager.getAvailableDeviceTypes())
  1237. {
  1238. type->scanForDevices();
  1239. report << "type=" << type->getTypeName() << "\n";
  1240. for (const auto& name : type->getDeviceNames (false))
  1241. report << " output=" << name << "\n";
  1242. for (const auto& name : type->getDeviceNames (true))
  1243. report << " input=" << name << "\n";
  1244. }
  1245. for (const auto& d : juce::MidiInput::getAvailableDevices())
  1246. report << "midi-in=" << d.name << "\n";
  1247. for (const auto& d : juce::MidiOutput::getAvailableDevices())
  1248. report << "midi-out=" << d.name << "\n";
  1249. const auto flag = args.contains ("--devices") ? args.indexOf ("--devices") : args.indexOf ("--dispositivos");
  1250. juce::File (args[flag + 1].unquoted()).replaceWithText (report);
  1251. quit();
  1252. return;
  1253. }
  1254. if (args.contains ("--devicetest"))
  1255. {
  1256. // LYNX.exe --devicetest "type" "device" report.txt ["input device"] [--buffer N] [--roundtrip]: opens that output device (and, with the
  1257. // 4th argument, an input: "*" = the same device / the driver's default input), receives 1 s of callbacks
  1258. // writing silence, closes it and reports rate, block size, latency, callbacks and the input channels with
  1259. // their peak level (driver check, no sound). --roundtrip: clicks out, found again on input 1 through a loopback
  1260. // cable / PipeWire link: the round-trip latency (3 s)
  1261. const auto i = args.indexOf ("--devicetest");
  1262. const auto typeName = args[i + 1].unquoted(), deviceName = args[i + 2].unquoted();
  1263. auto inputName = args.size() > i + 4 && ! args[i + 4].startsWith ("--") ? args[i + 4].unquoted() : juce::String();
  1264. const auto wantInput = inputName.isNotEmpty();
  1265. juce::String report;
  1266. const juce::File reportFile (args[i + 3].unquoted());
  1267. auto step = [&] (const juce::String& line) { report << line << "\n"; reportFile.replaceWithText (report); }; // progress survives a driver that ends the process
  1268. step ("step=start");
  1269. juce::AudioDeviceManager manager;
  1270. manager.getAvailableDeviceTypes();
  1271. if (auto pipeWire = lynx::makePipeWireDeviceType())
  1272. manager.addAudioDeviceType (std::move (pipeWire));
  1273. std::unique_ptr<juce::AudioIODevice> device;
  1274. for (auto* type : manager.getAvailableDeviceTypes())
  1275. if (type->getTypeName() == typeName)
  1276. {
  1277. type->scanForDevices();
  1278. if (wantInput && type->hasSeparateInputsAndOutputs())
  1279. {
  1280. const auto inputs = type->getDeviceNames (true);
  1281. if (inputName == "*" || ! inputs.contains (inputName))
  1282. {
  1283. const auto index = type->getDefaultDeviceIndex (true);
  1284. inputName = juce::isPositiveAndBelow (index, inputs.size()) ? inputs[index] : juce::String();
  1285. }
  1286. for (const auto& n : inputs)
  1287. step ("input_device=" + n);
  1288. step ("input_chosen=" + inputName);
  1289. }
  1290. else if (wantInput)
  1291. inputName = deviceName;
  1292. step ("step=create");
  1293. device.reset (type->createDevice (deviceName, type->hasSeparateInputsAndOutputs() ? inputName : juce::String()));
  1294. step ("step=created");
  1295. }
  1296. struct Silence final : juce::AudioIODeviceCallback
  1297. {
  1298. std::atomic<int> calls { 0 }, inputs { 0 };
  1299. std::array<std::atomic<float>, 64> peaks {};
  1300. // --roundtrip (round 161): a click every quarter second on the outputs, found again on input 1 through a
  1301. // loopback; the delays in samples
  1302. bool roundtrip = false;
  1303. int period = 12000;
  1304. std::int64_t position = 0, lastClick = -1;
  1305. std::vector<int> delays;
  1306. void audioDeviceIOCallbackWithContext (const float* const* in, int numIn, float* const* out, int channels, int n,
  1307. const juce::AudioIODeviceCallbackContext&) override
  1308. {
  1309. for (int c = 0; c < channels; ++c)
  1310. if (out[c] != nullptr)
  1311. juce::FloatVectorOperations::clear (out[c], n);
  1312. if (roundtrip)
  1313. {
  1314. for (int i = 0; i < n; ++i)
  1315. {
  1316. if (numIn > 0 && in[0] != nullptr && lastClick >= 0 && std::abs (in[0][i]) > 0.5f)
  1317. {
  1318. if (delays.size() < delays.capacity())
  1319. delays.push_back ((int) (position + i - lastClick));
  1320. lastClick = -1;
  1321. }
  1322. if ((position + i) % period == 0 && position + i > 0)
  1323. {
  1324. for (int c = 0; c < channels; ++c)
  1325. if (out[c] != nullptr)
  1326. out[c][i] = 0.9f;
  1327. lastClick = position + i;
  1328. }
  1329. }
  1330. position += n;
  1331. }
  1332. inputs.store (numIn);
  1333. for (int c = 0; c < juce::jmin (numIn, 64); ++c)
  1334. if (in[c] != nullptr)
  1335. {
  1336. const auto range = juce::FloatVectorOperations::findMinAndMax (in[c], n);
  1337. const auto peak = juce::jmax (std::abs (range.getStart()), std::abs (range.getEnd()));
  1338. if (peak > peaks[(std::size_t) c].load())
  1339. peaks[(std::size_t) c].store (peak);
  1340. }
  1341. ++calls;
  1342. }
  1343. void audioDeviceAboutToStart (juce::AudioIODevice*) override {}
  1344. void audioDeviceStopped() override {}
  1345. } silence;
  1346. bool ok = false;
  1347. if (device == nullptr)
  1348. step ("error=device not found");
  1349. else
  1350. {
  1351. step ("step=open");
  1352. juce::BigInteger outputs;
  1353. outputs.setRange (0, 2, true);
  1354. const auto rates = device->getAvailableSampleRates();
  1355. const auto rate = device->getCurrentSampleRate() > 0 ? device->getCurrentSampleRate()
  1356. : rates.contains (48000.0) ? 48000.0 : rates.isEmpty() ? 44100.0 : rates[0];
  1357. step ("rates=" + juce::String (rates.size()) + " chosen=" + juce::String (rate) + " default_block=" + juce::String (device->getDefaultBufferSize()));
  1358. juce::BigInteger inputs;
  1359. if (wantInput)
  1360. {
  1361. const auto names = device->getInputChannelNames();
  1362. step ("input_channels=" + juce::String (names.size()));
  1363. for (int c = 0; c < names.size(); ++c)
  1364. step (" in" + juce::String (c + 1) + "=" + names[c]);
  1365. inputs.setRange (0, juce::jmin (64, names.size()), true);
  1366. }
  1367. // --buffer N: ask for that block size (REA round 97 latency survey); default: the driver's default
  1368. const auto wantedBlock = args.contains ("--buffer") ? args[args.indexOf ("--buffer") + 1].getIntValue() : 0;
  1369. const auto error = device->open (inputs, outputs, rate, wantedBlock > 0 ? wantedBlock : device->getDefaultBufferSize());
  1370. if (error.isNotEmpty())
  1371. step ("error=" + error);
  1372. else
  1373. {
  1374. step ("step=start_callbacks");
  1375. silence.roundtrip = args.contains ("--roundtrip");
  1376. silence.period = juce::jmax (1, (int) (rate / 4));
  1377. silence.delays.reserve (64);
  1378. device->start (&silence);
  1379. juce::Thread::sleep (silence.roundtrip ? 3000 : 1000);
  1380. device->stop();
  1381. if (silence.roundtrip)
  1382. {
  1383. auto d = silence.delays;
  1384. std::sort (d.begin(), d.end());
  1385. report << "roundtrip_clicks=" << (int) d.size() << "\n";
  1386. if (! d.empty())
  1387. report << "roundtrip_samples=min " << d.front() << " median " << d[d.size() / 2] << " max " << d.back() << "\n"
  1388. << "roundtrip_ms=" << juce::String (1000.0 * d[d.size() / 2] / device->getCurrentSampleRate(), 2) << "\n";
  1389. }
  1390. report << "rate=" << device->getCurrentSampleRate() << "\n"
  1391. << "block=" << device->getCurrentBufferSizeSamples() << "\n"
  1392. << "output_latency=" << device->getOutputLatencyInSamples() << "\n"
  1393. << "callbacks=" << silence.calls.load() << "\n";
  1394. if (wantInput)
  1395. {
  1396. report << "input_latency=" << device->getInputLatencyInSamples() << "\n"
  1397. << "active_inputs=" << device->getActiveInputChannels().countNumberOfSetBits() << "\n"
  1398. << "callback_inputs=" << silence.inputs.load() << "\n";
  1399. for (int c = 0; c < juce::jmin (64, silence.inputs.load()); ++c)
  1400. report << " peak_in" << (c + 1) << "=" << juce::Decibels::gainToDecibels (silence.peaks[(std::size_t) c].load(), -150.0f) << " dB\n";
  1401. }
  1402. ok = silence.calls.load() > 0 && (! wantInput || silence.inputs.load() > 0);
  1403. device->close();
  1404. }
  1405. }
  1406. step (juce::String ("result=") + (ok ? "OK" : "FAILED"));
  1407. setApplicationReturnValue (ok ? 0 : 1);
  1408. quit();
  1409. return;
  1410. }
  1411. if (args.contains ("--plusmenutime"))
  1412. {
  1413. // LYNX --plusmenutime report.txt [watched] (round 190mf): the Channel rack "+" menu's build time (as
  1414. // showAddChannelMenu builds it, without showing it) with the profile's plugin list and Plugin database
  1415. // folder: the first one, then each one after the old two-second throttle ran out; then one after the
  1416. // folder was marked changed. "watched": as the app (a folder watcher), else as before round 190mf.
  1417. const auto i = args.indexOf ("--plusmenutime");
  1418. const auto watched = i + 2 < args.size() && args[i + 2] == "watched";
  1419. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1420. lynx::AudioEngine offline (false);
  1421. lynx::quickpick::installPluginDatabase (offline);
  1422. std::unique_ptr<lynx::folderwatch::Watcher> watcher;
  1423. if (watched)
  1424. {
  1425. const auto root = lynx::quickpick::pluginDatabaseFolder();
  1426. watcher = std::make_unique<lynx::folderwatch::Watcher> (
  1427. std::vector<std::string> { root.getChildFile ("Effects").getFullPathName().toStdString(), root.getChildFile ("Generators").getFullPathName().toStdString() },
  1428. [] { juce::MessageManager::callAsync ([] { lynx::quickpick::markPluginDatabaseChanged(); }); });
  1429. lynx::quickpick::setPluginDatabaseWatched (true);
  1430. }
  1431. juce::String report;
  1432. report << "types=" << offline.getPluginHost().getKnownPlugins().getNumTypes() << " watched=" << (watched ? 1 : 0) << "\n";
  1433. auto build = [&offline] (int& items) {
  1434. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  1435. juce::PopupMenu menu;
  1436. auto picks = lynx::quickpick::renamedGenerators (offline, [] (lynx::ChannelDef) {});
  1437. lynx::quickpick::addPicks (menu, picks);
  1438. lynx::quickpick::addGeneratorMenu (menu, offline, [] (lynx::ChannelDef) {}, [] {}, nullptr, nullptr);
  1439. lynx::quickpick::addFolderViewItems (menu, offline);
  1440. items = menu.getNumItems();
  1441. return juce::Time::getMillisecondCounterHiRes() - t0;
  1442. };
  1443. auto line = [&report, &build] (const juce::String& what) {
  1444. const auto readsBefore = lynx::quickpick::lastRefreshTimes().reads;
  1445. int items = 0;
  1446. const auto ms = build (items);
  1447. const auto t = lynx::quickpick::lastRefreshTimes();
  1448. const auto read = t.reads != readsBefore;
  1449. report << what << " menu_ms=" << juce::String (ms, 2) << " items=" << items << " folder_read=" << (read ? 1 : 0);
  1450. if (read)
  1451. report << " list_ms=" << juce::String (t.listMs, 2) << " read_ms=" << juce::String (t.readMs, 2);
  1452. report << "\n";
  1453. };
  1454. line ("first");
  1455. for (int k = 1; k <= 5; ++k)
  1456. {
  1457. juce::Thread::sleep (2100);
  1458. line ("again" + juce::String (k));
  1459. }
  1460. for (int k = 1; k <= 3; ++k)
  1461. line ("quick" + juce::String (k));
  1462. lynx::quickpick::markPluginDatabaseChanged();
  1463. line ("marked");
  1464. line ("after");
  1465. lynx::quickpick::setPluginDatabaseWatched (false);
  1466. watcher.reset();
  1467. lynx::plugindb::finishInstalledWrites();
  1468. juce::File (args[i + 1].unquoted()).replaceWithText (report);
  1469. setApplicationReturnValue (0);
  1470. quit();
  1471. return;
  1472. }
  1473. if (args.contains ("--scantest"))
  1474. {
  1475. // LYNX.exe --scantest folder report.txt: scan (in child processes) without touching the user's list
  1476. const auto i = args.indexOf ("--scantest");
  1477. lynx::PluginHost host (false);
  1478. const auto found = host.scan (juce::FileSearchPath (args[i + 1].unquoted()), {});
  1479. juce::String report;
  1480. report << "found=" << found << "\n";
  1481. for (const auto& t : host.getKnownPlugins().getTypes())
  1482. report << " " << (t.isInstrument ? "instrument: " : "effect: ") << t.name << "\n";
  1483. for (const auto& f : host.getKnownPlugins().getBlacklistedFiles())
  1484. report << " blacklisted: " << f << "\n";
  1485. juce::File (args[i + 2].unquoted()).replaceWithText (report);
  1486. setApplicationReturnValue (found > 0 ? 0 : 1);
  1487. quit();
  1488. return;
  1489. }
  1490. if (args.contains ("--wrappermiditest"))
  1491. {
  1492. // LYNX.exe --wrappermiditest plugin.dll report.txt (round 181c), with LYNX_TEST_VST2_MIDILOG set: what a
  1493. // hosted plugin receives after a wrapper MIDI option changes while it runs
  1494. const auto i = args.indexOf ("--wrappermiditest");
  1495. runWrapperMidiTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  1496. return;
  1497. }
  1498. if (args.contains ("--wrappershot"))
  1499. {
  1500. const auto i = args.indexOf ("--wrappershot");
  1501. runWrapperShot (args[i + 1].unquoted(), args[i + 2].unquoted());
  1502. return;
  1503. }
  1504. if (args.contains ("--multiouttest"))
  1505. {
  1506. const auto i = args.indexOf ("--multiouttest");
  1507. runMultiOutTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  1508. return;
  1509. }
  1510. if (args.contains ("--vstitest"))
  1511. {
  1512. // LYNX --vstitest plugin folder [project.lynx] (round 190fw, issue #162): an instrument plugin (Image-Line's
  1513. // "FL Studio VSTi") on a channel: notes in, audio out, its state through a saved project, its outputs and
  1514. // the host tempo it follows. See runVstiTest.
  1515. const auto i = args.indexOf ("--vstitest");
  1516. const auto project = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  1517. runVstiTest (args[i + 1].unquoted(), args[i + 2].unquoted(), project);
  1518. return;
  1519. }
  1520. if (args.contains ("--vst2test"))
  1521. {
  1522. const auto i = args.indexOf ("--vst2test");
  1523. runVst2Test (args[i + 1].unquoted(), args[i + 2].unquoted());
  1524. return;
  1525. }
  1526. if (args.contains ("--vst3noteidtest"))
  1527. {
  1528. const auto i = args.indexOf ("--vst3noteidtest");
  1529. runVst3NoteIdTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  1530. return;
  1531. }
  1532. if (args.contains ("--lv2scantest"))
  1533. {
  1534. runLv2ScanTest (args[args.indexOf ("--lv2scantest") + 1].unquoted());
  1535. return;
  1536. }
  1537. if (args.contains ("--wrappertest"))
  1538. {
  1539. const auto i = args.indexOf ("--wrappertest");
  1540. runWrapperTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  1541. return;
  1542. }
  1543. if (args.contains ("--plugintest"))
  1544. {
  1545. const auto i = args.indexOf ("--plugintest");
  1546. // optional 3rd argument: the plugin's name inside a shell (e.g. "CLA-2A Stereo" in a WaveShell)
  1547. const auto only = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  1548. runPluginTest (args[i + 1].unquoted(), args[i + 2].unquoted(), only);
  1549. return;
  1550. }
  1551. if (args.contains ("--crashguardtest"))
  1552. {
  1553. // LYNX --crashguardtest "LYNX Test Crash.vst3|.clap" report.txt [process|memcpy] (round 190dt,
  1554. // tools/testplugin/lynx_test_crash*.{c,cpp}): the plugin crashes in its 40th block on insert 1; LYNX must
  1555. // catch it, mark the slot, keep playing the other inserts, save the project, reload the plugin; then the
  1556. // saved project opens with the plugin crashing on its state; and LYNX's own faults are still crashes
  1557. const auto i = args.indexOf ("--crashguardtest");
  1558. runCrashGuardTest (args[i + 1].unquoted(), args[i + 2].unquoted(),
  1559. i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String ("process"));
  1560. return;
  1561. }
  1562. if (args.contains ("--claprestarttest"))
  1563. {
  1564. // LYNX.exe --claprestarttest "LYNX Test Restart.clap" report.txt (tools/testplugin/lynx_test_restart.c)
  1565. const auto i = args.indexOf ("--claprestarttest");
  1566. runClapRestartTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  1567. return;
  1568. }
  1569. if (args.contains ("--clapteardowntest"))
  1570. {
  1571. // LYNX.exe --clapteardowntest "LYNX Test Restart.clap" report.txt (round 190az, engine/ClapTeardownTest.cpp)
  1572. const auto i = args.indexOf ("--clapteardowntest");
  1573. lynx::runClapTeardownTest (args[i + 1].unquoted(), args[i + 2].unquoted(), [this] (int code) {
  1574. setApplicationReturnValue (code);
  1575. quit();
  1576. });
  1577. return;
  1578. }
  1579. if (args.contains ("--mpetest"))
  1580. {
  1581. // LYNX.exe --mpetest "LYNX Test MPE.clap" report.txt (tools/testplugin/lynx_test_mpe.c, issue #108)
  1582. const auto i = args.indexOf ("--mpetest");
  1583. runMpeTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  1584. return;
  1585. }
  1586. if (args.contains ("--mpeplaytest190hy"))
  1587. {
  1588. // LYNX --mpeplaytest190hy plugin.(clap|vst3) report.txt (round 190hy, issue #108): a song note with a pitch
  1589. // curve played by a hosted plugin with MPE on, through the whole song path (scheduler, renderer, the wrapper's
  1590. // MPE / CLAP note expressions), rendered offline; the pitch heard is measured (report.txt, report.wav)
  1591. const auto i = args.indexOf ("--mpeplaytest190hy");
  1592. runMpePlayTest190hy (args[i + 1].unquoted(), args[i + 2].unquoted());
  1593. return;
  1594. }
  1595. if (args.contains ("--editortest"))
  1596. {
  1597. // LYNX.exe --editortest plugin.vst3 report.txt ["name"]: opens the plugin's own editor in a window for a few
  1598. // seconds, then closes it (a plugin whose UI crashes the host ends the process before the report says OK)
  1599. const auto i = args.indexOf ("--editortest");
  1600. const auto only = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  1601. runEditorTest (args[i + 1].unquoted(), args[i + 2].unquoted(), only);
  1602. return;
  1603. }
  1604. if (args.contains ("--editorcrashtest"))
  1605. {
  1606. // LYNX.exe --editorcrashtest "LYNX Test Crash.clap" report.txt (issue #32, round 174a; Windows): the test
  1607. // plugin's editor faults in its own window procedure (LYNX_TEST_CRASH=editor). LYNX must catch it, close
  1608. // that editor, record the trace and keep running its message loop.
  1609. const auto i = args.indexOf ("--editorcrashtest");
  1610. runEditorCrashTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  1611. return;
  1612. }
  1613. if (args.contains ("--reloadtest"))
  1614. {
  1615. // LYNX --reloadtest plugin report.txt [shots folder] [--wait-kill]: round 190ao (reload a crashed plugin).
  1616. // Hosts the plugin in a separate process (a channel for an instrument, insert 1 for an effect) in an offline
  1617. // engine, crashes its process (--wait-kill: writes <report>.pid and waits for the process to be killed
  1618. // from outside), checks that nothing reloads by itself, reloads it on request and checks the new process,
  1619. // the state captured last, the untouched song and undo history; twice. With a shots folder: PNGs of the
  1620. // plugin window's crash notice and of the prompt.
  1621. const auto i = args.indexOf ("--reloadtest");
  1622. runReloadTest (args[i + 1].unquoted(), args[i + 2].unquoted(),
  1623. i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String(), args.contains ("--wait-kill"));
  1624. return;
  1625. }
  1626. if (args.contains ("--pluginoptionstest"))
  1627. {
  1628. // LYNX --pluginoptionstest plugin report.txt [shots folder]: round 190ao. Hosts the plugin inside LYNX (a
  1629. // channel for an instrument, insert 1 for an effect) in an offline engine, opens its window and checks
  1630. // LYNX's own plugin-window options: Pin on top (set, kept above another window, saved with the plugin,
  1631. // back when the window opens again). With a shots folder: PNGs of each state. The window is on screen.
  1632. const auto i = args.indexOf ("--pluginoptionstest");
  1633. runPluginOptionsTest (args[i + 1].unquoted(), args[i + 2].unquoted(),
  1634. i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String());
  1635. return;
  1636. }
  1637. if (args.contains ("--plugwintest"))
  1638. {
  1639. // LYNX --plugwintest plugin report.txt ["name"] [seconds]: round 162d. Puts the plugin in a channel (an
  1640. // instrument) or on insert 1 (an effect) of an offline engine, opens its plugin window (wrapper header,
  1641. // presets), checks a preset round trip, keeps the window `seconds` on screen (default 15: time for xdotool /
  1642. // screenshots), then removes the plugin from the song and reports whether its window closed by itself.
  1643. const auto i = args.indexOf ("--plugwintest");
  1644. const auto only = i + 3 < args.size() && ! args[i + 3].startsWith ("--") && ! args[i + 3].containsOnly ("0123456789") ? args[i + 3].unquoted() : juce::String();
  1645. auto seconds = 15;
  1646. for (int k = i + 3; k < juce::jmin (args.size(), i + 5); ++k)
  1647. if (args[k].containsOnly ("0123456789"))
  1648. seconds = args[k].getIntValue();
  1649. runPlugWinTest (args[i + 1].unquoted(), args[i + 2].unquoted(), only, seconds);
  1650. return;
  1651. }
  1652. if (args.contains ("--fittest"))
  1653. {
  1654. // LYNX.exe --fittest report.txt [percent]: round 163 — at that UI zoom (default 150) a window taller than
  1655. // the screen and a big resizable window that grows with a zoom change keep their title bar and close
  1656. // button on the screen. The windows show for about two seconds.
  1657. const auto i = args.indexOf ("--fittest");
  1658. runFitTest (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].getIntValue() : 150);
  1659. return;
  1660. }
  1661. if (args.contains ("--windowtest"))
  1662. {
  1663. // LYNX.exe --windowtest report.txt: opens the Quick-add palette, the Audio editor, a plugin-like window and a name dialog
  1664. // over the main window and checks that each one stays in front, owned by the main window, with the
  1665. // keyboard focus (issue #4). The windows appear on screen for a few seconds.
  1666. runWindowTest (args[args.indexOf ("--windowtest") + 1].unquoted());
  1667. return;
  1668. }
  1669. if (args.contains ("--minimizeclicktest"))
  1670. {
  1671. // LYNX --minimizeclicktest report.txt (issue #188, round 190ir): a tool window over the main window is
  1672. // minimised (through the window manager), the main window comes to the front, and a click where the tool
  1673. // window was must reach the main window's component. Run it under a window manager (openbox on a private
  1674. // Xvfb); exit code 0 = OK.
  1675. runMinimizeClickTest (args[args.indexOf ("--minimizeclicktest") + 1].unquoted());
  1676. return;
  1677. }
  1678. if (args.contains ("--focustest"))
  1679. {
  1680. // LYNX --focustest report.txt (issue #161): the main window with the Playlist and the Piano roll (native
  1681. // child windows with docking on). For each: LYNX goes to the background (the main window loses the focus),
  1682. // the user comes back with a click in the panel, then presses Space: playback must start. Also: a text
  1683. // field's focus comes back with the window, and inside the active window the click's answer is unchanged.
  1684. // Shows a window (takes the foreground on Windows: GUI lock); exit code 0 = OK.
  1685. runFocusTest (args[args.indexOf ("--focustest") + 1].unquoted());
  1686. return;
  1687. }
  1688. if (args.contains ("--simplekeytest"))
  1689. {
  1690. // LYNX --simplekeytest report.txt (round 190fc, 0.1.27 RC H2): the main window in the Simple layout; after a
  1691. // demo opened from Welcome › Start from and after clicks in the dock, its tabs, the Lyrics button, a track
  1692. // header and the grid, Space must start playback (a text field clicked into keeps its typing keys). Shows a
  1693. // window (takes the foreground on Windows: GUI lock); exit code 0 = OK.
  1694. runSimpleKeyTest (args[args.indexOf ("--simplekeytest") + 1].unquoted());
  1695. return;
  1696. }
  1697. if (args.contains ("--pluginstyle")) // round 126: force one style for this run (glow, neon, hardware, vivid; auto = per plugin)
  1698. {
  1699. const auto i = args.indexOf ("--pluginstyle");
  1700. if (i + 1 < args.size())
  1701. {
  1702. const auto name = args[i + 1].unquoted();
  1703. lynx::skin::setForcedStyle (name.equalsIgnoreCase ("auto") ? -1 : (int) lynx::skin::styleFromName (name));
  1704. }
  1705. }
  1706. if (args.contains ("--gfxprobe"))
  1707. {
  1708. // LYNX.exe --gfxprobe report.txt (round 170c, issue #11): renderer checks on this platform's native images —
  1709. // text drawn with a gradient fill (a word with a space in it) and an empty path filled with a gradient must
  1710. // stay inside their shapes. JUCE 8.0.4's CoreGraphics renderer (macOS) clipped to an empty glyph or path as
  1711. // "no clip" and flooded the whole component (Facet EQ's blank pink window).
  1712. const auto i = args.indexOf ("--gfxprobe");
  1713. juce::File (args[i + 1].unquoted()).replaceWithText (lynx::skin::rendererProbeReport());
  1714. quit();
  1715. return;
  1716. }
  1717. if (args.contains ("--steppertest"))
  1718. {
  1719. // LYNX.exe --steppertest <report.txt>: round 170c (#14) — every value stepper of every generated effect editor
  1720. // driven by synthetic input (arrows, click on the value, drag, wheel, trackpad); ends with result=OK / FAIL
  1721. const auto i = args.indexOf ("--steppertest");
  1722. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1723. juce::String report;
  1724. int fails = 0, count = 0, skips = 0;
  1725. {
  1726. lynx::AudioEngine offline (false);
  1727. auto kinds = lynx::plugui::flLayoutKinds();
  1728. for (const auto own : lynx::plugui::ownLayoutKinds())
  1729. kinds.push_back (own);
  1730. // FL's Default preset when the installation has one (the state-backed controls need FL's state)
  1731. const auto roots = lynx::findFlStudioRoots();
  1732. const auto presets = juce::File (juce::String::fromUTF8 (roots.data.c_str())).getChildFile ("Patches/Plugin presets/Effects");
  1733. for (const auto kind : kinds)
  1734. {
  1735. auto fx = lynx::makeEffectSlot (kind);
  1736. for (const auto& plugin : lynx::flPluginsForEffect (kind))
  1737. {
  1738. juce::MemoryBlock data;
  1739. const auto file = presets.getChildFile (juce::String::fromUTF8 (plugin.c_str())).getChildFile ("Default.fst");
  1740. if (file.existsAsFile() && file.loadFileAsData (data))
  1741. {
  1742. const auto* bytes = static_cast<const std::uint8_t*> (data.getData());
  1743. 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)
  1744. fx = *loaded;
  1745. }
  1746. break;
  1747. }
  1748. lynx::Song song;
  1749. song.mixer.resize (2);
  1750. song.mixer[0].name = "Master";
  1751. song.mixer[1].name = "Insert 1";
  1752. song.mixer[1].effects.push_back (fx);
  1753. offline.setSong (std::move (song));
  1754. offline.dispatchPendingMessages();
  1755. const auto lines = lynx::stepperSelfTest (offline, 1, 0, (int) lynx::plugui::layoutFor (kind).pages.size());
  1756. for (const auto& line : juce::StringArray::fromLines (lines))
  1757. if (line.isNotEmpty())
  1758. {
  1759. ++count;
  1760. fails += line.contains (": FAIL") ? 1 : 0;
  1761. skips += line.contains (": SKIP") ? 1 : 0;
  1762. }
  1763. report << lines;
  1764. juce::PopupMenu::dismissAllActiveMenus();
  1765. offline.dispatchPendingMessages();
  1766. }
  1767. }
  1768. report << "steppers=" << count << " failures=" << fails << " skipped=" << skips << "\nresult=" << (fails == 0 && count > 0 ? "OK" : "FAIL") << "\n";
  1769. juce::File (args[i + 1].unquoted()).replaceWithText (report);
  1770. quit();
  1771. return;
  1772. }
  1773. if (args.contains ("--design190inshot"))
  1774. {
  1775. // LYNX --design190inshot prefix [project.flp]: round 190in off screen (no desktop window, no audio device) —
  1776. // the channel window as it shows docked (FL's ▸, two-tone title, presets in the title bar, the 46 px strip
  1777. // with icon tabs, LED, knobs, RANGE / TRACK badges) on each tab, the floating strip, and FL's ▸ menu
  1778. const auto i = args.indexOf ("--design190inshot");
  1779. runDesign190inShot (args[i + 1].unquoted(), i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String());
  1780. quit();
  1781. return;
  1782. }
  1783. if (args.contains ("--plugui"))
  1784. {
  1785. // LYNX.exe --plugui <folder>: the native effect editors at FL's size (one PNG per editor and page), each
  1786. // loaded with the FL plugin's Default preset when the FL installation has one
  1787. const auto i = args.indexOf ("--plugui");
  1788. runPluginEditorSnapshots (args[i + 1].unquoted());
  1789. return;
  1790. }
  1791. if (args.contains ("--parityshot"))
  1792. {
  1793. // LYNX.exe --parityshot <out.png> <effect name> [<params file>]: one built-in effect's editor with the given
  1794. // parameters ("index value" lines, tools/fxrender --dump), its displays fed by the demo song — the LYNX side
  1795. // of the third-party parity pictures (round tp172b)
  1796. const auto i = args.indexOf ("--parityshot");
  1797. runParityShot (args[i + 1].unquoted(), args[i + 2].unquoted(), i + 3 < args.size() ? args[i + 3].unquoted() : juce::String());
  1798. if (parityShotFailed)
  1799. setApplicationReturnValue (2);
  1800. if (parityShow == nullptr)
  1801. quit();
  1802. return;
  1803. }
  1804. if (args.contains ("--design168rshot"))
  1805. {
  1806. // LYNX.exe --design168rshot <folder>: round 168r's editors (FL effects that had a generated page and LYNX's own
  1807. // simple built-ins) at 100 % and 200 %, with their default settings and, when they have one, the first
  1808. // preset of LYNX's own bank. "--design168rshot <folder> generated": the generated pages they had before
  1809. const auto i = args.indexOf ("--design168rshot");
  1810. if (i + 2 < args.size() && args[i + 2] == "generated")
  1811. lynx::plugui::showGeneratedLayoutsOnly (true);
  1812. runDesign168rShots (args[i + 1].unquoted());
  1813. quit();
  1814. return;
  1815. }
  1816. if (args.contains ("--eq166fshot"))
  1817. {
  1818. // LYNX.exe --eq166fshot <folder>: round 166f's pictures (issue #16) — Parametric EQ 2's spectrum and heatmap
  1819. // (flat, a +12 dB band, a -12 dB band, Top position) and Facet EQ's comparative EQ (listening to the target,
  1820. // its spectrum over the source's), each fed by the demo song rendered offline
  1821. const auto i = args.indexOf ("--eq166fshot");
  1822. runEq166fShots (args[i + 1].unquoted());
  1823. quit();
  1824. return;
  1825. }
  1826. if (args.contains ("--editorcpu"))
  1827. {
  1828. // LYNX.exe --editorcpu report.txt: opens built-in plugin editors one at a time in a small window (no audio
  1829. // device: a silent, idle editor) and writes the process CPU each costs while idle and while its display
  1830. // animates (demo signal) — round 122's check that an idle editor burns no CPU
  1831. const auto i = args.indexOf ("--editorcpu");
  1832. runEditorCpu (args[i + 1].unquoted());
  1833. return;
  1834. }
  1835. if (args.contains ("--precomputeshot"))
  1836. {
  1837. // LYNX.exe --precomputeshot project.(flp|lynx) <prefix>: round 167h — <prefix>-precompute.png (channel 1's
  1838. // Precomputed effects panel) and <prefix>-project.png (Options › Project with "Fast declick for cut groups")
  1839. const auto i = args.indexOf ("--precomputeshot");
  1840. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1841. lynx::AudioEngine shotEngine (false);
  1842. const juce::File input (args[i + 1].unquoted());
  1843. const auto prefix = args[i + 2].unquoted();
  1844. juce::String error;
  1845. bool ok = false;
  1846. if (input.hasFileExtension ("flp"))
  1847. ok = shotEngine.importFlpFile (input, error);
  1848. else if (auto song = lynx::ProjectFile::load (input, error))
  1849. shotEngine.setSong (std::move (*song)), ok = true;
  1850. shotEngine.dispatchPendingMessages();
  1851. auto shoot = [&] (std::unique_ptr<juce::Component> c, const juce::String& name) {
  1852. if (c == nullptr)
  1853. return false;
  1854. if (c->getWidth() <= 0)
  1855. c->setSize (520, 600);
  1856. savePng (lynx::shot::snapshot (*c), prefix + name);
  1857. return true;
  1858. };
  1859. ok = ok && shoot (lynx::makeChannelPrecomputePanel (shotEngine, 0), "-precompute.png");
  1860. ok = ok && shoot (lynx::makeSettingsPanel (shotEngine, lynx::SettingsPage::project), "-project.png");
  1861. setApplicationReturnValue (ok ? 0 : 1);
  1862. quit();
  1863. return;
  1864. }
  1865. if (args.contains ("--pluginthumbs"))
  1866. {
  1867. // LYNX.exe --pluginthumbs <folder> [key,key...]: the Plugin picker's pictures of LYNX's own plugins (round 171c,
  1868. // ui/PluginThumbs.h), each editor drawn off-screen and kept as <folder>/<name>.png; the picker starts this in
  1869. // the background when pictures are missing. One line per plugin on stdout.
  1870. const auto i = args.indexOf ("--pluginthumbs");
  1871. lynx::crashguard::quietCrashReports();
  1872. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1873. juce::StringArray only;
  1874. if (i + 2 < args.size() && ! args[i + 2].startsWith ("--"))
  1875. only.addTokens (args[i + 2].unquoted(), ",", "");
  1876. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  1877. // round 190bi: with --shot-scale / LYNX_SHOT_SCALE each plugin's whole editor at that scale, not the picker's
  1878. // small thumbnail (never for the picker's own cache folder, whatever the environment says)
  1879. const juce::File folder (args[i + 1].unquoted());
  1880. const auto full = lynx::shot::given() && folder != lynx::pluginthumbs::nativeFolder() ? lynx::shot::scale() : 0.0f;
  1881. const auto drawn = lynx::pluginthumbs::renderNative (folder, only, [] (const juce::String& line) {
  1882. std::printf ("%s\n", line.toRawUTF8());
  1883. std::fflush (stdout);
  1884. }, full);
  1885. std::printf ("drawn %d in %.0f ms\n", drawn, juce::Time::getMillisecondCounterHiRes() - t0);
  1886. setApplicationReturnValue (0);
  1887. quit();
  1888. return;
  1889. }
  1890. if (args.contains ("--jsonroundtrip"))
  1891. {
  1892. // LYNX.exe --jsonroundtrip <folder>: round 183c's finding — a project saved, loaded and saved again: both texts
  1893. // (a.json, b.json) and the first lines that differ (diff.txt) for the default song, with and without a Patcher
  1894. const auto i = args.indexOf ("--jsonroundtrip");
  1895. const juce::File out (args[i + 1].unquoted());
  1896. out.createDirectory();
  1897. juce::String report;
  1898. auto check = [&] (const lynx::Song& song, const juce::String& name) {
  1899. const auto a = lynx::ProjectFile::toJson (song);
  1900. juce::String error;
  1901. const auto back = lynx::ProjectFile::fromJson (a, error);
  1902. const auto b = back ? lynx::ProjectFile::toJson (*back) : juce::String ("(not loaded: " + error + ")");
  1903. out.getChildFile (name + "-a.json").replaceWithText (a);
  1904. out.getChildFile (name + "-b.json").replaceWithText (b);
  1905. juce::StringArray la, lb;
  1906. la.addLines (a);
  1907. lb.addLines (b);
  1908. report << name << ": " << (a == b ? "stable" : "DIFFERS") << " (" << la.size() << " / " << lb.size() << " lines)\n";
  1909. int shown = 0;
  1910. for (int k = 0; k < juce::jmax (la.size(), lb.size()) && shown < 12; ++k)
  1911. if (la[k] != lb[k])
  1912. {
  1913. report << " line " << (k + 1) << "\n a: " << la[k].trim().substring (0, 200) << "\n b: " << lb[k].trim().substring (0, 200) << "\n";
  1914. ++shown;
  1915. }
  1916. };
  1917. auto song = lynx::Song::makeDefault();
  1918. check (song, "default");
  1919. song.mixer.resize (3);
  1920. song.mixer[1].effects = { lynx::makeEffectSlot (lynx::EffectKind::patcher) };
  1921. check (song, "patcher");
  1922. song.mixer[1].effects = { lynx::rack::makeRackSlot (lynx::RackDoc::Kind::audioEffect) };
  1923. check (song, "rack");
  1924. out.getChildFile ("diff.txt").replaceWithText (report);
  1925. setApplicationReturnValue (0);
  1926. quit();
  1927. return;
  1928. }
  1929. // --prshot190jv <folder> (round 190jv: Piano roll › Scale highlighting › Automatic): src/PrShot190jv.inc
  1930. if (args.contains ("--prshot190jv"))
  1931. {
  1932. setApplicationReturnValue (runPrShot190jv (juce::File (args[args.indexOf ("--prshot190jv") + 1].unquoted())) ? 0 : 1);
  1933. quit();
  1934. return;
  1935. }
  1936. // --prchord190kd <folder> (round 190kd: FL's chord tool strip, scale shading, rack name alignment): src/PrChordShot190kd.inc
  1937. if (args.contains ("--prchord190kd"))
  1938. {
  1939. setApplicationReturnValue (runPrChordShot190kd (juce::File (args[args.indexOf ("--prchord190kd") + 1].unquoted())) ? 0 : 1);
  1940. quit();
  1941. return;
  1942. }
  1943. // --trimshot190jv <folder> (round 190jv: Mixer menu › Trim unused tracks): src/TrimShot190jv.inc
  1944. if (args.contains ("--trimshot190jv"))
  1945. {
  1946. setApplicationReturnValue (runTrimShot190jv (juce::File (args[args.indexOf ("--trimshot190jv") + 1].unquoted())) ? 0 : 1);
  1947. quit();
  1948. return;
  1949. }
  1950. // --undogesture190jv <report.txt> (round 190jv, queue item 73: one undo step per drag): src/UndoGesture190jv.inc
  1951. if (args.contains ("--undogesture190jv"))
  1952. {
  1953. setApplicationReturnValue (runUndoGesture190jv (juce::File (args[args.indexOf ("--undogesture190jv") + 1].unquoted())) ? 0 : 1);
  1954. quit();
  1955. return;
  1956. }
  1957. // --simplegb190keshot <folder> (round 190ke: tuner, fade-out, Controls tab, LYNX content): src/SimpleGbShot190ke.inc
  1958. if (args.contains ("--simplegb190keshot"))
  1959. {
  1960. setApplicationReturnValue (runSimpleGbShot190ke (juce::File (args[args.indexOf ("--simplegb190keshot") + 1].unquoted())) ? 0 : 1);
  1961. quit();
  1962. return;
  1963. }
  1964. // --browsershot190iz <folder> (round 190iz: FL's tabs, tags, Live's browser): src/BrowserShot190iz.inc
  1965. // --loopshot190kf <folder> (round gaps190kf: the Loop Browser): src/LoopShot190kf.inc
  1966. if (args.contains ("--loopshot190kf"))
  1967. {
  1968. setApplicationReturnValue (runLoopShot190kf (juce::File (args[args.indexOf ("--loopshot190kf") + 1].unquoted())) ? 0 : 1);
  1969. quit();
  1970. return;
  1971. }
  1972. if (args.contains ("--browsershot190iz"))
  1973. {
  1974. setApplicationReturnValue (runBrowserShot190iz (juce::File (args[args.indexOf ("--browsershot190iz") + 1].unquoted())) ? 0 : 1);
  1975. quit();
  1976. return;
  1977. }
  1978. if (args.contains ("--rackshot"))
  1979. {
  1980. // LYNX.exe --rackshot <folder>: round 183c's Rack view drawn off-screen (no window), for the LYNX | Live pairs:
  1981. // rack-deviceview.png (an Audio Effect Rack laid out as in Live's reference shot), rack-mapmode.png (Map mode
  1982. // with the mapping list), rack-instrument.png (an Instrument Rack with its key zones)
  1983. const auto i = args.indexOf ("--rackshot");
  1984. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1985. const auto set = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  1986. setApplicationReturnValue (runRackShots (juce::File (args[i + 1].unquoted()), set) ? 0 : 1);
  1987. quit();
  1988. return;
  1989. }
  1990. if (args.contains ("--artshot"))
  1991. {
  1992. // LYNX.exe --artshot <folder> [before|after] [name,name...]: every editor with art of its own (round 170j/170k: the
  1993. // Themed style; or only the named ones, e.g. "sakura,facet-eq") drawn off-screen at 100 % and 200 % as
  1994. // <folder>/<plugin>-<before|after>-<scale>.png. "before" draws each in the style it had before the Themed style
  1995. const auto i = args.indexOf ("--artshot");
  1996. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1997. const auto mode = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String ("after");
  1998. if (i + 3 < args.size() && ! args[i + 3].startsWith ("--")) // [name,name...]: only these arts
  1999. artOnly().addTokens (args[i + 3].unquoted(), ",", "");
  2000. setApplicationReturnValue (runArtShots (juce::File (args[i + 1].unquoted()), mode == "before") ? 0 : 1);
  2001. quit();
  2002. return;
  2003. }
  2004. if (args.contains ("--artgui"))
  2005. {
  2006. // LYNX.exe --artgui <folder> [before|after|still] [name,name...]: the same editors in REAL windows on the desktop, one at a
  2007. // time (always on top, no focus taken), each held while an outside script screenshots it (it writes
  2008. // <folder>/<plugin>.ready with the window's bounds and waits up to 10 s for <folder>/<plugin>.done), then the
  2009. // process CPU it costs over 6 s is written to <folder>/cpu-<mode>.txt. "still": Themed with the motion off
  2010. const auto i = args.indexOf ("--artgui");
  2011. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  2012. const auto mode = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String ("after");
  2013. if (i + 3 < args.size() && ! args[i + 3].startsWith ("--")) // [name,name...]: only these arts
  2014. artOnly().addTokens (args[i + 3].unquoted(), ",", "");
  2015. runArtGui (juce::File (args[i + 1].unquoted()), mode);
  2016. return;
  2017. }
  2018. if (args.contains ("--instrumentshot"))
  2019. {
  2020. // LYNX.exe --instrumentshot <folder> <engine,engine...|banks> [lynx|fl]: round 168n — the channel window of
  2021. // each engine (its Plugin tab) at 100 %, 150 % and 200 %, as <folder>/<engine>-<source>-<scale>.png. Source
  2022. // "lynx" starts from the engine's LYNX bank (what a PC without FL gets), "fl" from FL's Default preset.
  2023. const auto i = args.indexOf ("--instrumentshot");
  2024. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  2025. const auto source = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String ("lynx");
  2026. setApplicationReturnValue (runInstrumentShots (juce::File (args[i + 1].unquoted()), args[i + 2].unquoted(), source) ? 0 : 1);
  2027. quit();
  2028. return;
  2029. }
  2030. if (args.contains ("--flextrashot"))
  2031. {
  2032. // LYNX.exe --flextrashot <folder>: pictures of the editors of round 165g (Big Clock, Tuner, HTML NoteBook, Mute 2, Scratcher, Transmitter) + round 167n Transporter
  2033. const auto i = args.indexOf ("--flextrashot");
  2034. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  2035. lynx::AudioEngine shotEngine (false);
  2036. const auto ok = lynx::runFlExtraShots (shotEngine, juce::File (args[i + 1].unquoted()));
  2037. setApplicationReturnValue (ok ? 0 : 1);
  2038. quit();
  2039. return;
  2040. }
  2041. if (args.contains ("--visualtest"))
  2042. {
  2043. // LYNX.exe --visualtest <folder> [project.flp]: the visual plugins (round 164c) — the audio path's CPU, every
  2044. // Wave Candy mode and Visualizer scene drawn from a test signal (PNG + the editor's CPU each), and the video
  2045. // export of a project (default: FL's first ZGameEditor demo) with ffmpeg and as images. Writes report.txt.
  2046. const auto i = args.indexOf ("--visualtest");
  2047. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  2048. const auto project = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? juce::File (args[i + 2].unquoted()) : juce::File();
  2049. lynx::runVisualTest (juce::File (args[i + 1].unquoted()), project, [this] (bool ok) {
  2050. setApplicationReturnValue (ok ? 0 : 1);
  2051. quit();
  2052. });
  2053. return;
  2054. }
  2055. if (args.contains ("--menu-entry"))
  2056. {
  2057. // LYNX.AppImage --menu-entry on|off: puts the AppImage in the applications menu (and .lynx files on it) or
  2058. // takes it out again, without opening a window; the same as the switch in Options › General (round 161)
  2059. const auto i = args.indexOf ("--menu-entry");
  2060. const auto on = args[i + 1].unquoted() != "off";
  2061. const auto ok = lynx::runningAsAppImage() && lynx::setAppImageMenuEntry (on);
  2062. std::fprintf (ok ? stdout : stderr, "%s\n", ok ? (on ? "LYNX SHARE added to the applications menu" : "LYNX SHARE removed from the applications menu")
  2063. : "only the LYNX SHARE AppImage on Linux can do this");
  2064. setApplicationReturnValue (ok ? 0 : 1);
  2065. quit();
  2066. return;
  2067. }
  2068. if (args.contains ("--send-test-report"))
  2069. {
  2070. // LYNX.exe --send-test-report out.txt [--dry]: builds a crash report marked "test" from the newest crash /
  2071. // hang file and this computer's facts, writes its JSON to out.txt.json and (without --dry) sends it to
  2072. // lynx-share.com (LYNX_CRASH_ENDPOINT overrides); out.txt gets "id=…" and "result=OK" or the error (round 159)
  2073. const auto i = args.indexOf ("--send-test-report");
  2074. const juce::File out (args[i + 1].unquoted());
  2075. lynx::crashreporter::Session session;
  2076. session.version = getApplicationVersion();
  2077. for (const auto* pattern : { "crash *.txt", "hang *.txt" })
  2078. {
  2079. auto files = lynx::platform::settingsFile ("autosave").findChildFiles (juce::File::findFiles, false, pattern);
  2080. lynx::filesort::byTime (files, lynx::filesort::By::modificationTime, true);
  2081. if (! files.isEmpty())
  2082. (juce::String (pattern).startsWith ("crash") ? session.crashFile : session.hangFile) = files[0];
  2083. }
  2084. session.steps = { "00:00:01 test report (LYNX.exe --send-test-report)", "00:00:02 opening project " + out.getFileName() };
  2085. auto input = lynx::crashreporter::makeInput (session, session.crashFile.existsAsFile() ? "crash" : "manual", nullptr);
  2086. input.test = true;
  2087. const auto json = lynx::crashreporter::buildJson (input, false);
  2088. out.withFileExtension (out.getFileExtension() + ".json").replaceWithText (json);
  2089. const auto error = args.contains ("--dry") ? juce::String() : lynx::crashreporter::sendNow (json);
  2090. out.replaceWithText ("id=" + juce::String::fromUTF8 (input.id.c_str()) + "\nendpoint=" + lynx::crashreporter::endpoint() + "\nbytes="
  2091. + juce::String (json.getNumBytesAsUTF8()) + "\nresult=" + (error.isEmpty() ? juce::String ("OK") : error) + "\n");
  2092. setApplicationReturnValue (error.isEmpty() ? 0 : 1);
  2093. quit();
  2094. return;
  2095. }
  2096. if (args.contains ("--symbolize"))
  2097. {
  2098. // LYNX.exe --symbolize "crash … .txt" out.txt: names the LYNX.exe+offset frames of a user's crash / hang file
  2099. // (needs this build's LYNX.pdb next to LYNX.exe — the release's "LYNX-symbols" CI artifact; round 157a)
  2100. const auto i = args.indexOf ("--symbolize");
  2101. const auto text = juce::File (args[i + 1].unquoted()).loadFileAsString();
  2102. juce::File (args[i + 2].unquoted()).replaceWithText (juce::String::fromUTF8 (lynx::crashguard::symbolizeOwnFrames (text.toStdString()).c_str()));
  2103. quit();
  2104. return;
  2105. }
  2106. if (args.contains ("--opentest"))
  2107. {
  2108. // LYNX.exe --opentest report.txt [--visible]: every built-in effect and instrument window opened as the mixer /
  2109. // Channel rack open them, with default, extreme, random and old-project states; a watchdog fails the test on
  2110. // a hang (round 157a: opening the Parametric EQ froze LYNX). Windows stay off-screen without --visible.
  2111. const auto i = args.indexOf ("--opentest");
  2112. runOpenTest (args[i + 1].unquoted(), args.contains ("--visible"), [this] (bool ok) {
  2113. setApplicationReturnValue (ok ? 0 : 1);
  2114. quit();
  2115. });
  2116. return;
  2117. }
  2118. if (args.contains ("--fxfuzz"))
  2119. {
  2120. // LYNX.exe --fxfuzz report.txt [rounds] [--drags]: every built-in effect in its editor, parameters swept (and
  2121. // dragged with the mouse), audio rendered at several rates; a crash ends the process (round 111)
  2122. const auto i = args.indexOf ("--fxfuzz");
  2123. const auto rounds = args.size() > i + 2 ? juce::jmax (1, args[i + 2].getIntValue()) : 6;
  2124. // --drags: also mouse drags over the editors (their menus may flash on screen: not for the selftest)
  2125. const auto ok = runEffectFuzz (rounds, args[i + 1].unquoted(), args.contains ("--drags"));
  2126. setApplicationReturnValue (ok ? 0 : 1);
  2127. quit();
  2128. return;
  2129. }
  2130. if (args.contains ("--controllershot"))
  2131. {
  2132. // LYNX.exe --controllershot prefix: the built-in controllers' editors (round 133) as PNGs
  2133. const auto i = args.indexOf ("--controllershot");
  2134. runControllerShot (args[i + 1].unquoted());
  2135. quit();
  2136. return;
  2137. }
  2138. if (args.contains ("--edisonshot"))
  2139. {
  2140. // LYNX.exe --edisonshot prefix [audio.wav]: the audio editor's Edison tool windows (round 165l) and the
  2141. // editor before / after some of them, as PNGs (a synthetic drum loop without a file)
  2142. const auto i = args.indexOf ("--edisonshot");
  2143. runEdisonShot (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String());
  2144. quit();
  2145. return;
  2146. }
  2147. if (args.contains ("--newtoneshot"))
  2148. {
  2149. // LYNX --newtoneshot prefix audio.wav (round natives190kj): FL's Newtone window with the sample analysed, in a
  2150. // few states (-plain, -selected, -advanced, -cut, -timesel, -moved) and the paint time of the FL look against
  2151. // the round-165g layout (-paint.txt)
  2152. const auto i = args.indexOf ("--newtoneshot");
  2153. runNewtoneShot (args[i + 1].unquoted(), args[i + 2].unquoted());
  2154. quit();
  2155. return;
  2156. }
  2157. if (args.contains ("--edisonslottest"))
  2158. {
  2159. // LYNX.exe --edisonslottest folder [project.flp]: round 190cd — the audio editor as a mixer-slot plugin through
  2160. // the engine and the project file (report.txt: one "name=ok|FAIL" per check), its window as slot-*.png, and
  2161. // the Edison slots of an FL project (what was read of each)
  2162. const auto i = args.indexOf ("--edisonslottest");
  2163. const auto ok = runEdisonSlotTest (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String());
  2164. setApplicationReturnValue (ok ? 0 : 1);
  2165. quit();
  2166. return;
  2167. }
  2168. if (args.contains ("--danceshot"))
  2169. {
  2170. // LYNX.exe --danceshot prefix: LYNX Dance (round 165e) — every move as a contact sheet, the channel's editor,
  2171. // and a demo project with two dance channels (for --snapshot)
  2172. const auto i = args.indexOf ("--danceshot");
  2173. runDanceShot (args[i + 1].unquoted());
  2174. quit();
  2175. return;
  2176. }
  2177. if (args.contains ("--videoshot") && args.indexOf ("--videoshot") + 2 < args.size())
  2178. {
  2179. // LYNX.exe --videoshot prefix video: the Video Player's editor (round 165g) at a few song positions, with
  2180. // the user's ffmpeg, as PNGs + report.txt (frames decoded, the sound track)
  2181. const auto i = args.indexOf ("--videoshot");
  2182. runVideoShot (args[i + 1].unquoted(), args[i + 2].unquoted());
  2183. return;
  2184. }
  2185. if (args.contains ("--videotrackshot") && args.indexOf ("--videotrackshot") + 2 < args.size())
  2186. {
  2187. // LYNX.exe --videotrackshot prefix video [video2]: round 174d — the Playlist with video tracks (filmstrips,
  2188. // timecode row) and the video window at a few song positions, as PNGs + report.txt (the decoder, the
  2189. // frame shown for each wanted time: frame accuracy, frames dropped)
  2190. const auto i = args.indexOf ("--videotrackshot");
  2191. runVideoTrackShot (args[i + 1].unquoted(), args[i + 2].unquoted(), i + 3 < args.size() ? args[i + 3].unquoted() : juce::String());
  2192. return;
  2193. }
  2194. if (args.contains ("--vfxshot"))
  2195. {
  2196. // LYNX.exe --vfxshot prefix: the VFX note effects' editors (round 164b), on channels and in a Patcher, as PNGs
  2197. const auto i = args.indexOf ("--vfxshot");
  2198. runVfxShot (args[i + 1].unquoted());
  2199. quit();
  2200. return;
  2201. }
  2202. if (args.contains ("--patchershot"))
  2203. {
  2204. // LYNX.exe --patchershot prefix [project]: every Patcher's editor (round 141) as PNGs (a demo one without a project)
  2205. const auto i = args.indexOf ("--patchershot");
  2206. runPatcherShot (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String());
  2207. quit();
  2208. return;
  2209. }
  2210. if (args.contains ("--audioxshot"))
  2211. {
  2212. // LYNX.exe --audioxshot prefix (round 190aq): the pre-fader send, the "Low latency while recording" mark on a
  2213. // bypassed slot and the Browser's "Preview in time", drawn off-screen
  2214. runAudioXShot (args[args.indexOf ("--audioxshot") + 1].unquoted());
  2215. quit();
  2216. return;
  2217. }
  2218. if (args.contains ("--comp177shot"))
  2219. {
  2220. // LYNX.exe --comp177shot prefix project (round 177c): a project of loop takes in the maximised
  2221. // Playlist as it opened; every group after "Comp these takes", with a swipe on the first; the track and record menus
  2222. const auto i = args.indexOf ("--comp177shot");
  2223. runComp177Shot (args[i + 1].unquoted(), args[i + 2].unquoted());
  2224. quit();
  2225. return;
  2226. }
  2227. if (args.contains ("--evpaneshot"))
  2228. {
  2229. // LYNX --evpaneshot prefix [project] (round 190fz): the Piano roll's event editor divider driven with the mouse
  2230. // handlers (drag, right-click = alternate size and back, middle-click = default, a drag into the snap zone),
  2231. // a picture of each state and prefix-report.txt with the heights and the remembered settings file
  2232. const auto i = args.indexOf ("--evpaneshot");
  2233. setApplicationReturnValue (runEvPaneShot (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String()) ? 0 : 1);
  2234. quit();
  2235. return;
  2236. }
  2237. if (args.contains ("--feat166shot"))
  2238. {
  2239. // LYNX.exe --feat166shot prefix [project]: round 166d (issue #14) — the Piano Roll with a scale, folded to
  2240. // it, with one ghost channel, the ghost channels menu, and the Mixer filled to 500 inserts (its start and
  2241. // its end, and the time a full repaint takes)
  2242. const auto i = args.indexOf ("--feat166shot");
  2243. runFeat166Shot (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String());
  2244. quit();
  2245. return;
  2246. }
  2247. if (args.contains ("--pickerdropshot"))
  2248. {
  2249. // LYNX --pickerdropshot prefix: round 190hm (issue #177) — Picker panel entries dropped on the Playlist as FL
  2250. // places them (plain drop: one track per entry at the snapped time; Shift: one after another), off-screen,
  2251. // with <prefix>-checks.txt (OK / FAIL per placement)
  2252. setApplicationReturnValue (runPickerDropShot (args[args.indexOf ("--pickerdropshot") + 1].unquoted()) ? 0 : 1);
  2253. quit();
  2254. return;
  2255. }
  2256. if (args.contains ("--trackmodeshot"))
  2257. {
  2258. // LYNX --trackmodeshot prefix: rollup 190cv (UI gate of PR #151) — Playlist track header › Track mode › Audio
  2259. // track, off-screen, in three states of FL's live check 190cu (q1-01 fresh, q1-02 one insert linked
  2260. // elsewhere and one renamed, q1-07 the full state), plus a report that compares each list with FL's
  2261. setApplicationReturnValue (runTrackModeShot (args[args.indexOf ("--trackmodeshot") + 1].unquoted()) ? 0 : 1);
  2262. quit();
  2263. return;
  2264. }
  2265. if (args.contains ("--curveshot"))
  2266. {
  2267. // LYNX.exe --curveshot prefix: round 190bw — an automation clip with one segment per FL curve mode in the
  2268. // point editor and in the Playlist, and FL's point menu, off-screen
  2269. runCurveShot (args[args.indexOf ("--curveshot") + 1].unquoted());
  2270. quit();
  2271. return;
  2272. }
  2273. if (args.contains ("--remoteshot"))
  2274. {
  2275. // LYNX.exe --remoteshot prefix: Online Sessions P5-A1 (round 190ai) — the host's "Share plugins with guests"
  2276. // list and a guest's parameter editor of a plugin the host plays, off-screen with sample data
  2277. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  2278. lynx::liveui::saveRemoteShots (args[args.indexOf ("--remoteshot") + 1].unquoted());
  2279. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  2280. quit();
  2281. return;
  2282. }
  2283. if (args.contains ("--settingsshot") && ! args.contains ("--rtstress")) // (--rtstress has its own --settingsshot file.png option, round 161)
  2284. {
  2285. // LYNX.exe --settingsshot prefix: round 190bx — every Settings page off-screen at the window's size, in a
  2286. // small window (390 x 390) and, for the long pages, whole (see runSettingsShot)
  2287. runSettingsShot (args[args.indexOf ("--settingsshot") + 1].unquoted());
  2288. quit();
  2289. return;
  2290. }
  2291. if (args.contains ("--perfshot"))
  2292. {
  2293. // LYNX.exe --perfshot prefix project: the Playlist in Performance mode with a few clips launched and waiting,
  2294. // then the project patcherized (every insert's effects, the first channels) saved as prefix-patcherized.lynx
  2295. // for --patchershot (round 165m)
  2296. const auto i = args.indexOf ("--perfshot");
  2297. runPerfShot (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String());
  2298. quit();
  2299. return;
  2300. }
  2301. if (args.contains ("--freezetest"))
  2302. {
  2303. // LYNX.exe --freezetest prefix [project]: round 190ay's Freeze end to end, off-screen (see runFreezeTest)
  2304. const auto i = args.indexOf ("--freezetest");
  2305. const auto project = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  2306. // a word after the project: "keep" = freeze, save prefix-frozen.lynx and stop (the audio stays);
  2307. // "measure" = only load and render the project, for the memory and time of a process of its own
  2308. const auto mode = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  2309. setApplicationReturnValue (runFreezeTest (args[i + 1].unquoted(), project, mode) ? 0 : 1);
  2310. quit();
  2311. return;
  2312. }
  2313. if (args.contains ("--trackfreezetest"))
  2314. {
  2315. // LYNX --trackfreezetest prefix: round 190ff's Freeze Track, Flatten / Bounce Track in Place, Bounce to New
  2316. // Track and Consolidate end to end in the Clip-launch workflow, off-screen (see runTrackFreezeTest)
  2317. const auto i = args.indexOf ("--trackfreezetest");
  2318. setApplicationReturnValue (runTrackFreezeTest (args[i + 1].unquoted()) ? 0 : 1);
  2319. quit();
  2320. return;
  2321. }
  2322. if (args.contains ("--details190ihshot"))
  2323. {
  2324. // LYNX --details190ihshot prefix: round 190ih's live states off screen (no window, no audio device) — Gross
  2325. // Beat's locator and slots from its real engine, the rack's activity light, Play / Pause, the Record blink,
  2326. // the "Note on" hint, the save reminder, the Simple dock's input level, the Envelope Controller's key line
  2327. const auto i = args.indexOf ("--details190ihshot");
  2328. runDetails190ihShot (args[i + 1].unquoted());
  2329. quit();
  2330. return;
  2331. }
  2332. if (args.contains ("--paintbench"))
  2333. {
  2334. // LYNX --paintbench project.(flp|lynx|als) report.txt (round 190ge): each main view drawn off screen, whole, many
  2335. // times (the message thread's CPU per frame), with the playhead mid-song; no window, no audio device
  2336. const auto i = args.indexOf ("--paintbench");
  2337. runPaintBench (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()));
  2338. quit();
  2339. return;
  2340. }
  2341. if (args.contains ("--design190igshot"))
  2342. {
  2343. // LYNX --design190igshot prefix project.flp: round 190ig off-screen (design190ia slice 3) — the Pattern layout's
  2344. // 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),
  2345. // at FL's "zoom 17" (50 px tracks, 39.75 px a bar), and playing (the activity column), as FL's reference shots
  2346. const auto i = args.indexOf ("--design190igshot");
  2347. runDesign190igShot (args[i + 1].unquoted(), args[i + 2].unquoted());
  2348. quit();
  2349. return;
  2350. }
  2351. if (args.contains ("--cliplaunch190kcshot"))
  2352. {
  2353. // LYNX --cliplaunch190kcshot prefix set.als: round 190kc off screen (Live's return tracks, Sends rows, Pre / Post,
  2354. // the crossfader, the map modes' crossfader positions and relative strip, Commit / Extract on audio); prefix-checks.txt
  2355. const auto i = args.indexOf ("--cliplaunch190kcshot");
  2356. const auto set = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  2357. runClipLaunch190kcShot (args[i + 1].unquoted(), set);
  2358. quit();
  2359. return;
  2360. }
  2361. if (args.contains ("--livelook190jnshot"))
  2362. {
  2363. // LYNX --livelook190jnshot prefix [set.als]: round 190jn off screen (design190ia slices 13, 17, 18, 19, 25: the
  2364. // Clip-launch layout in Live's look, and the classic look); prefix-checks.txt
  2365. const auto i = args.indexOf ("--livelook190jnshot");
  2366. const auto set = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  2367. runLiveLook190jnShot (args[i + 1].unquoted(), set);
  2368. quit();
  2369. return;
  2370. }
  2371. if (args.contains ("--fllook190joshot"))
  2372. {
  2373. // LYNX --fllook190joshot prefix project.flp: round 190jo off screen (design190ia slices 12, 21, 23): the Pattern
  2374. // toolbar's tiles in every state, time / tempo / hint / menu bar, at 1920 / 1600 / 1366 / 1280; the Piano roll
  2375. // (FL's rows, notes, keys, grid, ghosts); the audio editor in Edison's layout with FL's "DL Breaker.wav";
  2376. // prefix-checks.txt (note label contrast)
  2377. const auto i = args.indexOf ("--fllook190joshot");
  2378. runFllook190joShot (args[i + 1].unquoted(), i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String());
  2379. quit();
  2380. return;
  2381. }
  2382. if (args.contains ("--capfix190jjshot"))
  2383. {
  2384. // LYNX --capfix190jjshot prefix project.flp [set.als]: round 190jj off screen (capture190ji's changes: Simple
  2385. // capsule states, master meter, pads press, held keys, drop lane ghosts; Live's control bar; FL's C-11 drop ghost
  2386. // and the picker's playing mark); prefix-checks.txt
  2387. const auto i = args.indexOf ("--capfix190jjshot");
  2388. const auto set = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  2389. runCapfix190jjShot (args[i + 1].unquoted(), args[i + 2].unquoted(), set);
  2390. quit();
  2391. return;
  2392. }
  2393. if (args.contains ("--details190myshot"))
  2394. {
  2395. // LYNX --details190myshot prefix project.flp: round 190my off screen (src/DetailsShot190my.inc)
  2396. const auto i = args.indexOf ("--details190myshot");
  2397. setApplicationReturnValue (runDetailsShot190my (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String()) ? 0 : 1);
  2398. quit();
  2399. return;
  2400. }
  2401. if (args.contains ("--details190mvshot"))
  2402. {
  2403. // LYNX --details190mvshot prefix project.flp: round 190mv off screen (src/DetailsShot190mv.inc)
  2404. const auto i = args.indexOf ("--details190mvshot");
  2405. setApplicationReturnValue (runDetailsShot190mv (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String()) ? 0 : 1);
  2406. quit();
  2407. return;
  2408. }
  2409. if (args.contains ("--details190mrshot"))
  2410. {
  2411. // LYNX --details190mrshot prefix project.flp: round 190mr off screen (src/DetailsShot190mr.inc)
  2412. const auto i = args.indexOf ("--details190mrshot");
  2413. setApplicationReturnValue (runDetailsShot190mr (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String()) ? 0 : 1);
  2414. quit();
  2415. return;
  2416. }
  2417. if (args.contains ("--details190mpshot"))
  2418. {
  2419. // LYNX --details190mpshot prefix project.flp: round 190mp off screen (src/DetailsShot190mp.inc)
  2420. const auto i = args.indexOf ("--details190mpshot");
  2421. setApplicationReturnValue (runDetailsShot190mp (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String()) ? 0 : 1);
  2422. quit();
  2423. return;
  2424. }
  2425. if (args.contains ("--details190mkshot"))
  2426. {
  2427. // LYNX --details190mkshot prefix project.flp: round 190mk off screen (src/DetailsShot190mk.inc)
  2428. const auto i = args.indexOf ("--details190mkshot");
  2429. setApplicationReturnValue (runDetailsShot190mk (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String()) ? 0 : 1);
  2430. quit();
  2431. return;
  2432. }
  2433. if (args.contains ("--details190mfshot"))
  2434. {
  2435. // LYNX --details190mfshot prefix project.flp: round 190mf off screen (src/DetailsShot190mf.inc)
  2436. const auto i = args.indexOf ("--details190mfshot");
  2437. setApplicationReturnValue (runDetailsShot190mf (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String()) ? 0 : 1);
  2438. quit();
  2439. return;
  2440. }
  2441. if (args.contains ("--details190lxshot"))
  2442. {
  2443. // LYNX --details190lxshot prefix project.flp [set.als]: round 190lx off screen (src/DetailsShot190lx.inc)
  2444. const auto i = args.indexOf ("--details190lxshot");
  2445. const auto set = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  2446. setApplicationReturnValue (runDetailsShot190lx (args[i + 1].unquoted(), args[i + 2].unquoted(), set) ? 0 : 1);
  2447. quit();
  2448. return;
  2449. }
  2450. if (args.contains ("--details190lrshot"))
  2451. {
  2452. // LYNX --details190lrshot prefix project.flp [set.als]: round 190lr off screen (src/DetailsShot190lr.inc)
  2453. const auto i = args.indexOf ("--details190lrshot");
  2454. const auto set = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  2455. setApplicationReturnValue (runDetailsShot190lr (args[i + 1].unquoted(), args[i + 2].unquoted(), set) ? 0 : 1);
  2456. quit();
  2457. return;
  2458. }
  2459. if (args.contains ("--details190ldshot"))
  2460. {
  2461. // LYNX --details190ldshot prefix project.flp [set.als]: round 190ld off screen (src/DetailsShot190ld.inc)
  2462. const auto i = args.indexOf ("--details190ldshot");
  2463. const auto set = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  2464. setApplicationReturnValue (runDetailsShot190ld (args[i + 1].unquoted(), args[i + 2].unquoted(), set) ? 0 : 1);
  2465. quit();
  2466. return;
  2467. }
  2468. if (args.contains ("--details190knshot"))
  2469. {
  2470. // LYNX --details190knshot prefix project.flp [set.als]: round 190kn off screen (src/DetailsShot190kn.inc)
  2471. const auto i = args.indexOf ("--details190knshot");
  2472. const auto set = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  2473. setApplicationReturnValue (runDetailsShot190kn (args[i + 1].unquoted(), args[i + 2].unquoted(), set) ? 0 : 1);
  2474. quit();
  2475. return;
  2476. }
  2477. if (args.contains ("--details190imshot"))
  2478. {
  2479. // LYNX --details190imshot prefix project.flp [set.als]: round 190im off-screen (details190if R1, R5, R6, R11, R12,
  2480. // R13, R15) — the automation hints, the Playlist playing (picker marks, glow, overview, activity levels), a drop
  2481. // preview, Follow's pause, the Sampler's handles, and with the Live set the grid's one-shot / follow / queued
  2482. // scene / deactivated clip / hints and the Clip View's launched position; prefix-checks.txt
  2483. const auto i = args.indexOf ("--details190imshot");
  2484. const auto set = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  2485. runDetails190imShot (args[i + 1].unquoted(), args[i + 2].unquoted(), set);
  2486. quit();
  2487. return;
  2488. }
  2489. if (args.contains ("--toolbarshot190iv"))
  2490. {
  2491. // LYNX --toolbarshot190iv prefix [project.als]: round 190iv off screen — the toolbar of each layout style (Pattern,
  2492. // Simple, Clip-launch) at 1920 / 1366 / 1280, the Simple transport capsule idle / hover / pressed / playing /
  2493. // recording, the "Last saved" status in its four states, Live's control bar with every button idle / hover /
  2494. // pressed / lit, the "⋯" menus, and a report of the parts' bounds
  2495. const auto i = args.indexOf ("--toolbarshot190iv");
  2496. const auto project = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  2497. runToolbarShot190iv (args[i + 1].unquoted(), project);
  2498. quit();
  2499. return;
  2500. }
  2501. if (args.contains ("--gridshot"))
  2502. {
  2503. // LYNX.exe --gridshot prefix [project]: the Clip-launch workflow's layout off-screen, with a grid of sample
  2504. // clips, some playing and waiting, at the size of LYNX_SNAPSHOT_SIZE (round 181a); with a project (.lynx,
  2505. // .flp, .als), that project's grid instead (round 181c: a Live set's Session view as LYNX imports it)
  2506. const auto i = args.indexOf ("--gridshot");
  2507. const auto project = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  2508. runGridShot (args[i + 1].unquoted(), project);
  2509. quit();
  2510. return;
  2511. }
  2512. if (args.contains ("--tour190dvshot"))
  2513. {
  2514. // LYNX.exe --tour190dvshot prefix: round 190dv off-screen — the Simple workflow's Welcome screen, every step of
  2515. // the first-song tour done with its "Do it for me" (a loop dropped for the loop step), the end card, Back /
  2516. // Next / close, the Help menu, the chooser's tour button, Start from with the three demo songs, a demo
  2517. // opened in Simple — and a text report of the checks (incl. resources/demos/*.lynx = the generated songs)
  2518. const auto i = args.indexOf ("--tour190dvshot");
  2519. runTour190dvShot (args[i + 1].unquoted());
  2520. quit();
  2521. return;
  2522. }
  2523. if (args.contains ("--donateshot"))
  2524. {
  2525. // LYNX --donateshot prefix: round 190fq off-screen (no window) — Help › Support LYNX SHARE... in the three
  2526. // layouts, the Support window, the About window's Support button, the start-up support note in the main
  2527. // window, and the note's rules end to end on its saved state (run it with LYNX_PROFILE_DIR: it writes
  2528. // support-note.txt there, and puts the old one back at the end); report prefix-report.txt, exit 0 = OK
  2529. const auto i = args.indexOf ("--donateshot");
  2530. setApplicationReturnValue (runDonateShot (args[i + 1].unquoted()) ? 0 : 1);
  2531. quit();
  2532. return;
  2533. }
  2534. if (args.contains ("--simpleclosetest"))
  2535. {
  2536. // LYNX --simpleclosetest <report.txt>: round 190fc off-screen (no window) — the main window in the Simple
  2537. // layout with Welcome, the tour, Start from, a demo, the dock's tabs, Finish and Lyrics open, then closed as at
  2538. // shutdown (the 0.1.27 RC crashed on every such close); exit code 0 = OK
  2539. const auto i = args.indexOf ("--simpleclosetest");
  2540. setApplicationReturnValue (runSimpleCloseTest (args[i + 1].unquoted()) ? 0 : 1);
  2541. quit();
  2542. return;
  2543. }
  2544. if (args.contains ("--patterns190ea"))
  2545. {
  2546. // LYNX --patterns190ea <report.txt>: round 190ea off-screen (no window) — a song with no pattern at all
  2547. // reaching the engine in every layout (the Simple dock's Editor tab, the Piano roll panel of the Pattern
  2548. // layout, the Clip-launch layout), the last pattern deleted, all patterns cleared by an edit, undo / redo,
  2549. // a live session's remote song and an out-of-range current pattern; each must leave one pattern and not crash
  2550. const auto i = args.indexOf ("--patterns190ea");
  2551. setApplicationReturnValue (runPatterns190ea (args[i + 1].unquoted()) ? 0 : 1);
  2552. quit();
  2553. return;
  2554. }
  2555. if (args.contains ("--reabl190foshot"))
  2556. {
  2557. // LYNX --reabl190foshot prefix: round 190fo off-screen — the Simple Sampler track's 16 pads in the dock, its
  2558. // menus and kits, the typing keys, the .lynx round trip, a folder of stems and MIDI files — and a report
  2559. const auto i = args.indexOf ("--reabl190foshot");
  2560. runReabl190foShot (args[i + 1].unquoted());
  2561. quit();
  2562. return;
  2563. }
  2564. if (args.contains ("--simple190dsshot"))
  2565. {
  2566. // LYNX.exe --simple190dsshot prefix: round 190ds off-screen, at 1x and 2x — loops dropped in the Simple
  2567. // workflow following the project key (the dock's switch, the clip menu), the docked Piano roll in the Editor
  2568. // tab, the keyboard's modes Keys / Scale keys / Chord pad with the scale selector — and a text report
  2569. const auto i = args.indexOf ("--simple190dsshot");
  2570. runSimple190dsShot (args[i + 1].unquoted());
  2571. quit();
  2572. return;
  2573. }
  2574. if (args.contains ("--simple190dgshot"))
  2575. {
  2576. // LYNX.exe --simple190dgshot prefix: round 190dg's additions to the Simple dock off-screen, at 1x and 2x —
  2577. // the Effects tab with all eight one-knob cards and each card alone, a chain preset with Blend, the
  2578. // favourites in the Preset menu, the sound picker (a search, My plugins with a made-up plugin list) — and a
  2579. // text report of the checks
  2580. const auto i = args.indexOf ("--simple190dgshot");
  2581. runSimple190dgShot (args[i + 1].unquoted());
  2582. quit();
  2583. return;
  2584. }
  2585. if (args.contains ("--simplefxshot"))
  2586. {
  2587. // LYNX.exe --simplefxshot prefix: round 190bu's track dock of the Simple workflow off-screen, at 1x and 2x —
  2588. // the Instrument tab (LYNX sounds, My SoundFonts), the Effects tab (empty, a preset, its menus), and a text
  2589. // report: the dock's edits, a user preset saved and loaded, the same slots in the Pattern workflow's Mixer
  2590. const auto i = args.indexOf ("--simplefxshot");
  2591. runSimpleFxShot (args[i + 1].unquoted());
  2592. quit();
  2593. return;
  2594. }
  2595. if (args.contains ("--simple190jcshot"))
  2596. {
  2597. // LYNX.exe --simple190jcshot prefix: round 190jc's Simple layout look (design190ia slices 5, 14, 15, 22, 24 and
  2598. // Large controls) off-screen, at 1x and 2x, with a text report
  2599. const auto i = args.indexOf ("--simple190jcshot");
  2600. runSimple190jcShot (args[i + 1].unquoted());
  2601. quit();
  2602. return;
  2603. }
  2604. if (args.contains ("--simpleshot"))
  2605. {
  2606. // LYNX.exe --simpleshot prefix: round 184a's Simple workflow off-screen — View › Layout style with each style
  2607. // chosen, Settings › General (Pattern, then Simple selected) with its style list, the window in Pattern, then
  2608. // Simple, then Pattern again, and how many Simple workflow objects existed before and after (0 before)
  2609. const auto i = args.indexOf ("--simpleshot");
  2610. runSimpleShot (args[i + 1].unquoted());
  2611. quit();
  2612. return;
  2613. }
  2614. // --versionsshot <prefix> (round 190ap): the Versions panel, File's new items, a project opened without its
  2615. // third-party plugins (window, list, File menu) and the Export window's additions, offscreen
  2616. if (args.contains ("--versionsshot"))
  2617. {
  2618. runVersionsShot (args[args.indexOf ("--versionsshot") + 1].unquoted());
  2619. quit();
  2620. return;
  2621. }
  2622. // --linkshot <prefix> (round 190bt): FL's Remote control settings / Global link settings windows, the control
  2623. // menu with "Link to controller...", the formula presets and controller menus and the Multilink items,
  2624. // offscreen; prefix-checks.txt holds the round's checks of the engine, the project file and the settings
  2625. if (args.contains ("--linkshot"))
  2626. {
  2627. setApplicationReturnValue (runLinkShot (args[args.indexOf ("--linkshot") + 1].unquoted()) ? 0 : 1);
  2628. quit();
  2629. return;
  2630. }
  2631. // --flctlshot <prefix> (round 190df): FL's multilink menu (on / off), the plugin menu's A/B and "Link all
  2632. // parameters...", the sampler's File row with its Sample history, and the Envelope / instrument page of a sampler
  2633. // running FL's voice with its envelope presets, offscreen; prefix-checks.txt holds the checks
  2634. if (args.contains ("--flctlshot"))
  2635. {
  2636. setApplicationReturnValue (runFlCtlShot (args[args.indexOf ("--flctlshot") + 1].unquoted()) ? 0 : 1);
  2637. quit();
  2638. return;
  2639. }
  2640. // --samplerpageshot <prefix> (round 190dh): FL's Sampler page offscreen (shots and checks in prefix-checks.txt)
  2641. if (args.contains ("--samplerpageshot"))
  2642. {
  2643. setApplicationReturnValue (runSamplerPageShot (args[args.indexOf ("--samplerpageshot") + 1].unquoted()) ? 0 : 1);
  2644. quit();
  2645. return;
  2646. }
  2647. // --flplshot <prefix> (round 190dx): the audio clip menu (Preview, Automate › Panning / Volume), the Playlist's "+"
  2648. // and its menu, Track mode › Instrument track, the Channel rack's "Assign to new instrument track", Tools › One-click
  2649. // audio recording and Mixer › Disk recording › Latency compensation, offscreen; prefix-checks.txt holds the checks
  2650. // --hdrshot190ft <prefix> (round 190ft, issues #163 / #164): FL's track-header selection and resize rules driven
  2651. // with synthetic mouse events on the Playlist headers and the mixer strips, offscreen; prefix-checks.txt
  2652. if (args.contains ("--hdrshot190ft"))
  2653. {
  2654. setApplicationReturnValue (runHdrShot190ft (args[args.indexOf ("--hdrshot190ft") + 1].unquoted()) ? 0 : 1);
  2655. quit();
  2656. return;
  2657. }
  2658. // --dawprojcheck190jf <prefix> <project> (round 190jf, slice B22): export to DAWproject and open it again
  2659. if (args.contains ("--dawprojcheck190jf") && args.indexOf ("--dawprojcheck190jf") + 2 < args.size())
  2660. {
  2661. const auto at = args.indexOf ("--dawprojcheck190jf");
  2662. setApplicationReturnValue (runDawProjectCheck190jf (args[at + 1].unquoted(), juce::File (args[at + 2].unquoted())) ? 0 : 1);
  2663. quit();
  2664. return;
  2665. }
  2666. // --foldersshot190jf <prefix> <thief.flp> (round 190jf, slice B17): the Playlist's folders; prefix-checks.txt
  2667. if (args.contains ("--foldersshot190jf") && args.indexOf ("--foldersshot190jf") + 2 < args.size())
  2668. {
  2669. const auto at = args.indexOf ("--foldersshot190jf");
  2670. setApplicationReturnValue (runFoldersShot190jf (args[at + 1].unquoted(), juce::File (args[at + 2].unquoted())) ? 0 : 1);
  2671. quit();
  2672. return;
  2673. }
  2674. // --userfixshot190ib <prefix> (round 190ib): issue #182's type-to-jump in a real popup menu (the Playlist's Edit menu
  2675. // of the issue's screenshot, typed into), #183's Piano roll item, #181's Ctrl+, through the main window's keys;
  2676. // prefix-checks.txt
  2677. if (args.contains ("--userfixshot190ib"))
  2678. {
  2679. setApplicationReturnValue (runUserFixShot190ib (args[args.indexOf ("--userfixshot190ib") + 1].unquoted()) ? 0 : 1);
  2680. quit();
  2681. return;
  2682. }
  2683. // --issuesshot190ht <prefix> (round 190ht): issue #127's other tools on Pattern Blocks (Mute, Select + group move,
  2684. // Slice, Zoom) and issue #154's insert effects list on linked headers, driven with synthetic mouse events,
  2685. // offscreen; prefix-checks.txt and pictures
  2686. if (args.contains ("--issuesshot190ht"))
  2687. {
  2688. setApplicationReturnValue (runIssuesShot190ht (args[args.indexOf ("--issuesshot190ht") + 1].unquoted()) ? 0 : 1);
  2689. quit();
  2690. return;
  2691. }
  2692. // --playlistshot190jq <prefix> (round 190jq, issues #164 and #191): src/PlaylistShot190jq.inc
  2693. if (args.contains ("--playlistshot190jq"))
  2694. {
  2695. setApplicationReturnValue (runPlaylistShot190jq (args[args.indexOf ("--playlistshot190jq") + 1].unquoted()) ? 0 : 1);
  2696. quit();
  2697. return;
  2698. }
  2699. // --issueshot190jz <prefix> (round 190jz, issues #192, #194, #195): src/IssuesShot190jz.inc
  2700. if (args.contains ("--issueshot190jz"))
  2701. {
  2702. setApplicationReturnValue (runIssuesShot190jz (args[args.indexOf ("--issueshot190jz") + 1].unquoted()) ? 0 : 1);
  2703. quit();
  2704. return;
  2705. }
  2706. // --workflowshot190iu <prefix> (round 190iu, issues #186 and #191): src/WorkflowShot190iu.inc
  2707. if (args.contains ("--workflowshot190iu"))
  2708. {
  2709. setApplicationReturnValue (runWorkflowShot190iu (args[args.indexOf ("--workflowshot190iu") + 1].unquoted()) ? 0 : 1);
  2710. quit();
  2711. return;
  2712. }
  2713. // --trackautoshot190gz <prefix> (round 190gz, issue #170): LYNX's "Link Playlist tracks to mixer tracks" — the
  2714. // switch, the linked headers' M / S / volume / pan driven with synthetic mouse events, row sizes, undo and the
  2715. // .lynx round trip, offscreen; prefix-checks.txt
  2716. if (args.contains ("--trackautoshot190gz"))
  2717. {
  2718. setApplicationReturnValue (runTrackAutoShot190gz (args[args.indexOf ("--trackautoshot190gz") + 1].unquoted()) ? 0 : 1);
  2719. quit();
  2720. return;
  2721. }
  2722. if (args.contains ("--flplshot"))
  2723. {
  2724. setApplicationReturnValue (runFlPlShot (args[args.indexOf ("--flplshot") + 1].unquoted()) ? 0 : 1);
  2725. quit();
  2726. return;
  2727. }
  2728. // --genpresetshot <prefix> (round 190fs): the channel window's preset box with the user's own presets (Save
  2729. // preset..., Your presets, Delete preset, Show the presets folder) for Fruity DX10, 3x Osc and LYNX's synth, the
  2730. // name box, a load (one undo step) and the Browser's new channel, offscreen; prefix-checks.txt holds the checks
  2731. if (args.contains ("--genpresetshot"))
  2732. {
  2733. setApplicationReturnValue (runGenPresetShot (args[args.indexOf ("--genpresetshot") + 1].unquoted()) ? 0 : 1);
  2734. quit();
  2735. return;
  2736. }
  2737. // --flfixshot <prefix> (round 190ey): what the live FL session 190ew found different (the Sampler page, the
  2738. // Multilink menu, the Playlist, issue #152's question), offscreen; prefix-checks.txt holds the checks
  2739. if (args.contains ("--flfixshot"))
  2740. {
  2741. setApplicationReturnValue (runFlFixShot (args[args.indexOf ("--flfixshot") + 1].unquoted()) ? 0 : 1);
  2742. quit();
  2743. return;
  2744. }
  2745. // --flclipshot <prefix> (round 190dz): FL's audio clip menu layout (two columns, FL's sections, LYNX's own items at
  2746. // the end) and the channel's Misc › Levels adjustment, offscreen; prefix-checks.txt holds the checks
  2747. if (args.contains ("--flclipshot"))
  2748. {
  2749. setApplicationReturnValue (runFlClipShot (args[args.indexOf ("--flclipshot") + 1].unquoted()) ? 0 : 1);
  2750. quit();
  2751. return;
  2752. }
  2753. if (args.contains ("--warpshot"))
  2754. {
  2755. // LYNX.exe --warpshot prefix: round 190cg's pictures (warp commands in the audio editor, the Clip page's
  2756. // Audio panel, the arrangement with the loop switched off, a folded track, signature changes), off-screen
  2757. const auto i = args.indexOf ("--warpshot");
  2758. runWarpShot (args[i + 1].unquoted());
  2759. quit();
  2760. return;
  2761. }
  2762. // --bandlab190jrshot <prefix> (round 190jr): a .blx imported as Simple tracks, the region loop handle, the Simple
  2763. // automation view and its menu, the Extract stems form; <prefix>-report.txt with ok / FAIL lines
  2764. if (args.contains ("--bandlab190jrshot"))
  2765. {
  2766. runBandlab190jrShot (args[args.indexOf ("--bandlab190jrshot") + 1].unquoted());
  2767. quit();
  2768. return;
  2769. }
  2770. // --bandlabshot <prefix> (round 190ch): Lyrics / Notes, Reference match, Start from and Clean voice, offscreen
  2771. if (args.contains ("--bandlabshot"))
  2772. {
  2773. runBandlabShot (args[args.indexOf ("--bandlabshot") + 1].unquoted());
  2774. quit();
  2775. return;
  2776. }
  2777. if (args.contains ("--mpeshot190hy"))
  2778. {
  2779. // LYNX --mpeshot190hy prefix: round 190hy (issue #108, MPE stage 2) off-screen: the Piano roll's MPE lanes (pitch
  2780. // bend, slide, pressure) over notes with curves in Pattern workflow, then the Clip-launch layout's Clip page with
  2781. // its Notes and MPE tabs. Writes prefix-checks.txt.
  2782. runMpeShot190hy (args[args.indexOf ("--mpeshot190hy") + 1].unquoted());
  2783. quit();
  2784. return;
  2785. }
  2786. if (args.contains ("--detailshot"))
  2787. {
  2788. // LYNX.exe --detailshot prefix: the Clip-launch workflow's detail view off-screen (round 183a): a track's chain
  2789. // (instrument, effects, one off, one folded), its clip page, and Pattern workflow before / after, at
  2790. // LYNX_SNAPSHOT_SIZE. Writes prefix-counts.txt with what the chain shows.
  2791. const auto i = args.indexOf ("--detailshot");
  2792. runDetailShot (args[i + 1].unquoted());
  2793. quit();
  2794. return;
  2795. }
  2796. if (args.contains ("--livedevshot190kk"))
  2797. {
  2798. // LYNX.exe --livedevshot190kk prefix: round 190kk off-screen, in the Clip-launch layout: a track whose insert holds
  2799. // what Live's Erosion, Vinyl Distortion and Corpus (Core Library presets) import onto — Corrode, Platter,
  2800. // Soundboard — on the Device View as ordinary effect cards. Writes prefix-devices.png and prefix-checks.txt.
  2801. runLiveDevShot190kk (args[args.indexOf ("--livedevshot190kk") + 1].unquoted());
  2802. quit();
  2803. return;
  2804. }
  2805. if (args.contains ("--liverackshot190hr"))
  2806. {
  2807. // LYNX.exe --liverackshot190hr prefix: round 190hr off-screen, in the Ableton-style layout: the Device View's
  2808. // instrument menu with Group / Ungroup, an instrument grouped into an Instrument Rack and back, a rack's Save
  2809. // Preset button and drop area (a device dropped in, an instrument refused), Live's own .adg presets opened
  2810. // with their chains, and a saved .adg read back. Writes prefix-checks.txt.
  2811. runLiveRackShot190hr (args[args.indexOf ("--liverackshot190hr") + 1].unquoted());
  2812. quit();
  2813. return;
  2814. }
  2815. if (args.contains ("--helixshot190ja"))
  2816. {
  2817. // LYNX --helixshot190ja prefix [Wavetable preset .adv]: round 190ja off-screen, the Clip-launch layout's Device
  2818. // View with a Helix track (the preset's values imported as a Live set would bring them, else Helix's defaults):
  2819. // the device and its pages (Matrix, MIDI, MPE, Env 2, LFO 1, Osc 2), then the Pattern layout's channel window.
  2820. const auto i = args.indexOf ("--helixshot190ja");
  2821. runHelixShot190ja (args[i + 1].unquoted(), i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String());
  2822. quit();
  2823. return;
  2824. }
  2825. if (args.contains ("--liveshot190ce"))
  2826. {
  2827. // LYNX.exe --liveshot190ce prefix: round 190ce off-screen, in the Ableton-style layout: the Device View's cards
  2828. // with their hot-swap and save buttons, a device's menu, hot-swap on (the Browser's bar, the lit button), a
  2829. // swap and its undo, a duplicate, and the Browser's collections (STARRED tab, the Collections menu, a search
  2830. // by a collection's name). Writes prefix-checks.txt.
  2831. runLiveShot190ce (args[args.indexOf ("--liveshot190ce") + 1].unquoted());
  2832. quit();
  2833. return;
  2834. }
  2835. if (args.contains ("--missingsearchshot190eo"))
  2836. {
  2837. // LYNX --missingsearchshot190eo prefix folder...: round 190eo (integration of issue #159's fix) off-screen: the
  2838. // Missing files window's Samples page while a real search of the folders runs (matches streamed in, Stop
  2839. // shown, Apply usable). Writes prefix-searching.png and prefix-checks.txt; the search is let go at the end.
  2840. const auto i = args.indexOf ("--missingsearchshot190eo");
  2841. const auto prefix = args[i + 1].unquoted();
  2842. juce::StringArray folders;
  2843. for (int k = i + 2; k < args.size(); ++k)
  2844. folders.add (args[k].unquoted());
  2845. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  2846. std::shared_ptr<juce::Component> panel = lynx::makeMissingFilesPanelSearching (lynx::missingFilesSnapshotInfo(), folders);
  2847. juce::Timer::callAfterDelay (700, [this, panel, prefix] {
  2848. juce::String status;
  2849. bool stopShown = false, applyEnabled = false;
  2850. const auto searching = lynx::missingFilesSearchState (*panel, status, stopShown, applyEnabled);
  2851. auto image = lynx::shot::paint (*panel, lynx::theme::panel);
  2852. const auto file = juce::File (prefix + "-searching.png");
  2853. file.deleteFile();
  2854. if (auto out = file.createOutputStream())
  2855. juce::PNGImageFormat().writeImageToStream (image, *out);
  2856. juce::String checks;
  2857. auto check = [&checks] (const char* name, bool ok, const juce::String& detail) {
  2858. checks << name << "=" << (ok ? "OK" : "FAIL") << " " << detail << "\n";
  2859. };
  2860. check ("still_searching_at_the_shot", searching, {});
  2861. check ("status_shows_the_walk", status.contains (lynx::tr ("Searching {0}... {1} files looked at").upToFirstOccurrenceOf ("{0}", false, false)), status);
  2862. check ("stop_shown", stopShown, {});
  2863. check ("apply_usable_during_the_search", applyEnabled, {});
  2864. lynx::stopMissingFilesSearch (*panel);
  2865. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  2866. quit();
  2867. });
  2868. return;
  2869. }
  2870. // --grooveshot190fm <prefix> (round 190fm): a Playlist pattern clip's menu with its Groove items (the chooser, Commit,
  2871. // Extract) and the "Classic swing" folder, and a Groove Pool holding classic swing grooves, offscreen;
  2872. // prefix-checks.txt holds the checks (also the .lynx round trip of a Playlist clip's groove)
  2873. if (args.contains ("--grooveshot190fm"))
  2874. {
  2875. setApplicationReturnValue (runGrooveShot190fm (args[args.indexOf ("--grooveshot190fm") + 1].unquoted()) ? 0 : 1);
  2876. quit();
  2877. return;
  2878. }
  2879. if (args.contains ("--mtshot190fm"))
  2880. {
  2881. // LYNX --mtshot190fm prefix: round 190fm off-screen: the MIDI Tools panel's Generate tab with each generator
  2882. // (prefix-generate-rhythm.png … -euclidean.png), the five side by side as Live's picture shows them
  2883. // (prefix-generate-panels.png; Live's: ableton190o/shots/live-04-generate-panels.png), then each generator
  2884. // written into a one-bar pattern and undone again: prefix-checks.txt.
  2885. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  2886. runMtShot190fm (args[args.indexOf ("--mtshot190fm") + 1].unquoted());
  2887. quit();
  2888. return;
  2889. }
  2890. if (args.contains ("--drumshot190ec"))
  2891. {
  2892. // LYNX.exe --drumshot190ec prefix: round 190ec off-screen: a demo Drum Rack's pad view (default and scrolled), its
  2893. // chain list with I-O, sends and return chains, a new empty Drum Rack and the Piano roll's pad names. Writes
  2894. // prefix-checks.txt (hit tests: C1 bottom-left, overview scroll, a pad dragged onto another swaps them).
  2895. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  2896. lynx::drumshot::run (args[args.indexOf ("--drumshot190ec") + 1].unquoted());
  2897. quit();
  2898. return;
  2899. }
  2900. if (args.contains ("--linkshot190gl"))
  2901. {
  2902. // LYNX --linkshot190gl prefix (round 190gl): Ableton Link off-screen with a second Link peer in this process —
  2903. // the toolbar in FL's Pattern layout (hidden by default, then shown, off and on) and in the Clip-launch layout
  2904. // ("1 Link", the position display's progress bar, Play waiting), Settings › Ableton Link, the toggle's
  2905. // drop-down and the Options menu. Writes prefix-checks.txt.
  2906. runLinkShot190gl (args[args.indexOf ("--linkshot190gl") + 1].unquoted());
  2907. quit();
  2908. return;
  2909. }
  2910. if (args.contains ("--communityshot190hp"))
  2911. {
  2912. // LYNX --communityshot190hp prefix (round 190hp): global MIDI mappings, Mix snapshots and Split at silence
  2913. // off-screen; writes prefix-checks.txt
  2914. runCommunityShot190hp (args[args.indexOf ("--communityshot190hp") + 1].unquoted());
  2915. quit();
  2916. return;
  2917. }
  2918. if (args.contains ("--mapshot190ef"))
  2919. {
  2920. // LYNX.exe --mapshot190ef prefix: round 190ef's map modes off-screen, in the Clip-launch workflow: MIDI Map Mode
  2921. // (the overlay over the grid, the Session mixer, the Device View and the transport; the Mapping Browser with
  2922. // Min / Max), Key Map Mode, the row menu, the title bar's Draw / Key / MIDI switches, Ctrl+M / Ctrl+K and the
  2923. // Pattern layout keeping Ctrl+M. Writes prefix-checks.txt.
  2924. runMapShot190ef (args[args.indexOf ("--mapshot190ef") + 1].unquoted());
  2925. quit();
  2926. return;
  2927. }
  2928. if (args.contains ("--sceneshot190ef"))
  2929. {
  2930. // LYNX.exe --sceneshot190ef prefix: round 190ef's scene work off-screen, in the Clip-launch workflow: the scene
  2931. // column with its tempo / time signature fields, the scene menu, a scene field's menu, the column title's menu
  2932. // (Rename, colours), a duplicated scene and a captured scene. Writes prefix-checks.txt.
  2933. runSceneShot190ef (args[args.indexOf ("--sceneshot190ef") + 1].unquoted());
  2934. quit();
  2935. return;
  2936. }
  2937. if (args.contains ("--drawshot190ef"))
  2938. {
  2939. // LYNX.exe --drawshot190ef prefix: round 190ef off-screen, in the Clip-launch workflow: Draw Mode in an
  2940. // automation lane, steps at the grid width and an Alt (no grid) freehand stroke drawn through the Playlist's
  2941. // own mouse handlers, and the Options menu with "Draw Mode". Writes prefix-checks.txt.
  2942. runDrawShot190ef (args[args.indexOf ("--drawshot190ef") + 1].unquoted());
  2943. quit();
  2944. return;
  2945. }
  2946. if (args.contains ("--clipenvshot190gi"))
  2947. {
  2948. // LYNX.exe --clipenvshot190gi prefix: round 190gi off-screen: audio clip envelopes on the Playlist (volume and
  2949. // pan lanes, edited through the Playlist's own mouse handlers), the clip menu's LYNX extras (Clip envelope ›,
  2950. // Auto-warp, Quantize audio, run from the menu), warp flags added on the flag strip and moved with Alt + drag,
  2951. // and the Clip-launch Clip View's Envelopes tab (Clip › Gain, Mixer › Track Panning). Writes prefix-checks.txt.
  2952. runClipEnvShot190gi (args[args.indexOf ("--clipenvshot190gi") + 1].unquoted());
  2953. quit();
  2954. return;
  2955. }
  2956. if (args.contains ("--gapsshot190kf"))
  2957. {
  2958. // LYNX.exe --gapsshot190kf prefix [file.wav]: round gaps190kf off-screen: the Clip View's warp time line (Live's
  2959. // loop brace and Start / End markers under the beat-time ruler, the seconds ruler of an unwarped clip) on the
  2960. // probe of gaps190kf/live/cv-clipview.als (voice.wav, warp markers at 30 % / 55 %, Loop 1.3 … 3.3, Start 1.4).
  2961. const auto i = args.indexOf ("--gapsshot190kf");
  2962. runGapsShot190kf (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String());
  2963. quit();
  2964. return;
  2965. }
  2966. if (args.contains ("--livefactsshot190gx"))
  2967. {
  2968. // LYNX.exe --livefactsshot190gx prefix: round 190gx off-screen: the Clip page's Audio panel in Live's 190gu
  2969. // layout (Beats: Preserve label + chooser, the loop-mode icon chooser beside the Transient Envelope box;
  2970. // Tones / Texture: Grain Size [+ Flux]; Complex [Pro]), the Envelopes tab with a Clip Gain staircase on Live's
  2971. // axis, choosers at the bottom left, and an unwarped clip without the Envelopes tab. Writes prefix-checks.txt.
  2972. runLiveFactsShot190gx (args[args.indexOf ("--livefactsshot190gx") + 1].unquoted());
  2973. quit();
  2974. return;
  2975. }
  2976. if (args.contains ("--dvshot190hr"))
  2977. {
  2978. // LYNX.exe --dvshot190hr prefix: round 190hr off-screen, the Clip-launch Clip View: a MIDI clip whose Start
  2979. // marker sits inside its loop, with its own scale and a follow action (Launch panel controls), the docked
  2980. // editor's grid value and menu, Ctrl+1 / Ctrl+3 / Ctrl+U on it, the Quantize Settings panel, and an audio clip
  2981. // transposed past ±12. Writes prefix-checks.txt.
  2982. runDvShot190hr (args[args.indexOf ("--dvshot190hr") + 1].unquoted());
  2983. quit();
  2984. return;
  2985. }
  2986. if (args.contains ("--warpshot190fm"))
  2987. {
  2988. // LYNX.exe --warpshot190fm prefix: round 190fm off-screen: the Clip page's Audio panel of a grid audio clip in
  2989. // Beats (Preserve, Transient Loop Mode, Envelope), Tones and Texture (Grain Size), Complex (none), and the clip
  2990. // made unique by a mode change while another clip shares its channel (O16). Writes prefix-checks.txt.
  2991. runWarpShot190fm (args[args.indexOf ("--warpshot190fm") + 1].unquoted());
  2992. quit();
  2993. return;
  2994. }
  2995. if (args.contains ("--liveshot190dr"))
  2996. {
  2997. // LYNX.exe --liveshot190dr prefix: round 190dr off-screen, in the Clip-launch workflow: the Session mixer
  2998. // under the clip grid (default sections, Track Options, Volume only, hidden, its View menu), the Clip page's
  2999. // Sample panel of an audio clip (Warp on / off, the Set buttons while it plays, the sample's title) and a
  3000. // device dragged from one track's Device View to another track. Writes prefix-checks.txt.
  3001. runLiveShot190dr (args[args.indexOf ("--liveshot190dr") + 1].unquoted());
  3002. quit();
  3003. return;
  3004. }
  3005. if (args.contains ("--design190igs4shot"))
  3006. {
  3007. // LYNX.exe --design190igs4shot prefix [set.als]: round 190ig slice 4 off-screen, in the Clip-launch layout with the
  3008. // set imported there (Live's colours, CL-6): the Session grid in Live's look idle, then the launch states —
  3009. // playing, a launch waiting (both blink phases), a stop waiting, recording, the status pie at 25 / 50 / 75 % —
  3010. // and the same with Animations off, then round 181a's look (the option); prefix-checks.txt
  3011. const auto i = args.indexOf ("--design190igs4shot");
  3012. const auto project = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  3013. runDesign190igS4Shot (args[i + 1].unquoted(), project);
  3014. quit();
  3015. return;
  3016. }
  3017. if (args.contains ("--typeaheadtest"))
  3018. {
  3019. // LYNX.exe --typeaheadtest out.txt: issue #64 — a real popup menu (headings, a submenu) driven by key presses
  3020. // through its window's peer, as the OS delivers them; writes what got the highlight and what was picked
  3021. const auto i = args.indexOf ("--typeaheadtest");
  3022. runTypeAheadTest (juce::File (args[i + 1].unquoted()));
  3023. return;
  3024. }
  3025. if (args.contains ("--choosertest"))
  3026. {
  3027. // LYNX --choosertest out.txt file: issue #72 — opens LYNX's file chooser as the UI does (makeFileChooser +
  3028. // launchChooser) and reports which dialog came up and what reached the callback. A built-in dialog is shot
  3029. // (out.txt.png), `file` typed into it and confirmed; a native one (zenity / kdialog) is left to answer.
  3030. const auto i = args.indexOf ("--choosertest");
  3031. runChooserTest (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()));
  3032. return;
  3033. }
  3034. if (args.contains ("--stabilityshot"))
  3035. {
  3036. // LYNX --stabilityshot <folder> (round 190gg): offscreen PNGs of the crash prompt, the plugin window's crash
  3037. // notice, the Plugin manager's "Separate process" column and the monitor's dropout line (no window opens)
  3038. const auto i = args.indexOf ("--stabilityshot");
  3039. runStabilityShot (args[i + 1].unquoted());
  3040. return;
  3041. }
  3042. if (args.contains ("--snapshot"))
  3043. {
  3044. const auto i = args.indexOf ("--snapshot");
  3045. runSnapshot (args[i + 1].unquoted(), args[i + 2].unquoted());
  3046. return;
  3047. }
  3048. if (args.contains ("--stemsplit"))
  3049. {
  3050. // LYNX.exe --stemsplit input.wav folder ["stems=111100 model=2 ..."]: the stem separation of the clip menu,
  3051. // without the window (round 190jr: the options as the settings file writes them; none = every stem, Standard)
  3052. const auto i = args.indexOf ("--stemsplit");
  3053. lynx::AudioEngine loader (false);
  3054. const auto options = i + 3 < args.size() && args[i + 3].unquoted().containsChar ('=') ? lynx::stemsplit::optionsFromText (args[i + 3].unquoted().toStdString())
  3055. : lynx::stemsplit::Options {};
  3056. const auto started = juce::Time::getMillisecondCounterHiRes();
  3057. const auto error = lynx::extractStemsToFolder (loader, juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()), options);
  3058. std::fprintf (stderr, "stemsplit: %.0f ms\n", juce::Time::getMillisecondCounterHiRes() - started);
  3059. juce::File (args[i + 2].unquoted()).getSiblingFile ("stemsplit.txt").replaceWithText (error.isEmpty() ? "result=OK\n" : "result=FAIL " + error + "\n");
  3060. setApplicationReturnValue (error.isEmpty() ? 0 : 1);
  3061. quit();
  3062. return;
  3063. }
  3064. if (args.contains ("--audio2midi"))
  3065. {
  3066. // LYNX.exe --audio2midi input.wav melody|harmony|drums notes.csv: the clip menu's Convert to MIDI, without the
  3067. // window (round a2m189b's measurements)
  3068. const auto i = args.indexOf ("--audio2midi");
  3069. const auto mode = args[i + 2] == "drums" ? lynx::a2m::Mode::drums : args[i + 2] == "harmony" ? lynx::a2m::Mode::harmony : lynx::a2m::Mode::melody;
  3070. lynx::AudioEngine loader (false);
  3071. const juce::File csv (args[i + 3].unquoted());
  3072. const auto error = lynx::convertFileToMidiCsv (loader, juce::File (args[i + 1].unquoted()), mode, csv);
  3073. csv.getSiblingFile ("audio2midi.txt").replaceWithText (error.isEmpty() ? "result=OK\n" : "result=FAIL " + error + "\n");
  3074. setApplicationReturnValue (error.isEmpty() ? 0 : 1);
  3075. quit();
  3076. return;
  3077. }
  3078. if (args.contains ("--stems") || args.contains ("--stemexport"))
  3079. {
  3080. // LYNX.exe --stems project.(flp|als|lynx) base.wav [--separate]: one WAV per insert that has sound (like
  3081. // "Export stems"), in one render of the song (round 190gj; --separate: one render per insert, as before).
  3082. // LYNX.exe --stemexport project base.ext options.txt [--separate]: what the Export window writes with these
  3083. // options (exportopts::toText lines: stems, sections, the full mix, formats...), the same code.
  3084. // Both write <base>.txt: the files with their peaks, the renders, the wall and CPU time.
  3085. const auto full = args.contains ("--stemexport");
  3086. const auto i = args.indexOf (full ? "--stemexport" : "--stems");
  3087. const auto separate = args.contains ("--separate");
  3088. juce::String error, report;
  3089. int written = 0;
  3090. {
  3091. lynx::AudioEngine loader (false);
  3092. const juce::File input (args[i + 1].unquoted()), base (args[i + 2].unquoted());
  3093. // an .flp or a Live set (.als) opens through the import, as File › Open does (round 182b)
  3094. auto ok = input.hasFileExtension ("flp;als") ? loader.importFlpFile (input, error) : false;
  3095. if (! input.hasFileExtension ("flp;als"))
  3096. if (auto song = lynx::ProjectFile::load (input, error))
  3097. {
  3098. loader.setSong (std::move (*song));
  3099. ok = true;
  3100. }
  3101. const auto& song = loader.getSong();
  3102. lynx::StemPlan plan;
  3103. if (full && ok)
  3104. plan = lynx::planStemExport (song, lynx::exportopts::fromText (juce::File (args[i + 3].unquoted()).loadFileAsString().toStdString()), base);
  3105. else if (ok)
  3106. {
  3107. // every insert a channel goes to, as "<base> - <insert>.wav", 24-bit, 6 s of tail at most
  3108. lynx::ExportSettings settings;
  3109. plan.sets.push_back ({ song, settings.toOptions() });
  3110. for (int t = 1; t < (int) song.mixer.size(); ++t)
  3111. if (std::any_of (song.channels.begin(), song.channels.end(), [t] (const lynx::ChannelDef& c) { return c.mixerTrack == t; }))
  3112. plan.items.push_back ({ juce::String (t), base.getSiblingFile (base.getFileNameWithoutExtension() + " - " + juce::String (t) + ".wav"), 0, t,
  3113. lynx::makeBounceSong (song, t), settings.toOptions() });
  3114. }
  3115. const auto wallStart = juce::Time::getMillisecondCounterHiRes();
  3116. const auto cpuStart = std::clock();
  3117. lynx::StemRunStats stats;
  3118. std::vector<juce::String> lines (plan.items.size());
  3119. auto previous = wallStart; // (one render per file: the time since the file before is its render's)
  3120. written = lynx::runStemExport (
  3121. plan, [] (std::function<void()> f) { f(); }, {}, {}, {},
  3122. [&] (std::size_t k, bool done, float peak) {
  3123. const auto now = juce::Time::getMillisecondCounterHiRes();
  3124. if (done)
  3125. lines[k] = plan.items[k].file.getFileName() + " peak=" + juce::String (peak) + " ms=" + juce::String (now - previous, 0) + "\n";
  3126. previous = now;
  3127. },
  3128. separate, full, &stats);
  3129. const auto wallMs = juce::Time::getMillisecondCounterHiRes() - wallStart;
  3130. const auto cpuMs = 1000.0 * (double) (std::clock() - cpuStart) / (double) CLOCKS_PER_SEC;
  3131. for (const auto& line : lines)
  3132. report << line;
  3133. report << "renders=" << (stats.passes + stats.alone) << " shared=" << stats.passes << " inshared=" << stats.inPass
  3134. << " alone=" << stats.alone << "\n";
  3135. for (const auto& why : stats.why)
  3136. report << "alone: " << why << "\n";
  3137. report << "wall_ms=" << juce::String (wallMs, 0) << " cpu_ms=" << juce::String (cpuMs, 0) << " make_ms=" << juce::String (stats.makeMs, 0)
  3138. << " render_ms=" << juce::String (stats.renderMs, 0) << "\n";
  3139. }
  3140. report << "stems=" << written << "\n";
  3141. juce::File (args[i + 2].unquoted() + ".txt").replaceWithText (report);
  3142. setApplicationReturnValue (written > 0 ? 0 : 1);
  3143. quit();
  3144. return;
  3145. }
  3146. // --export-als <in.lynx|.flp|.als> <folder> [--live11] [--reference] [--scan]: "<folder>/<name> Project/<name>.als" (round 175a)
  3147. if (args.contains ("--export-als"))
  3148. {
  3149. const auto i = args.indexOf ("--export-als");
  3150. runAlsExport (args[i + 1].unquoted(), args[i + 2].unquoted(), args.contains ("--live11"), args.contains ("--reference"));
  3151. return;
  3152. }
  3153. // --gamepadshot <prefix> (round 184a, S16): the game controller's hints overlay and the MIDI settings page with
  3154. // the option on, offscreen, plus the poller fed fake pad states ("<prefix>-gamepad.txt")
  3155. if (args.contains ("--gamepadshot"))
  3156. {
  3157. runGamepadShot (args[args.indexOf ("--gamepadshot") + 1].unquoted());
  3158. return;
  3159. }
  3160. // --midioutshot <prefix> [--shot-scale 1.5] (round 190jl): Settings › MIDI with the output devices' Port boxes
  3161. // (the snapshot's sample devices: the volca on port 1 of its own, the drum machine with master sync), offscreen
  3162. if (args.contains ("--midioutshot"))
  3163. {
  3164. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  3165. {
  3166. lynx::AudioEngine engine (false);
  3167. auto page = lynx::makeMidiPage (engine, {}, false);
  3168. page->setSize (1000, 1300);
  3169. savePng (lynx::shot::snapshot (*page), args[args.indexOf ("--midioutshot") + 1].unquoted() + "-settings-midi.png");
  3170. }
  3171. setApplicationReturnValue (0);
  3172. quit();
  3173. return;
  3174. }
  3175. // --export-bundle <in.lynx|.flp|.als> <folder> [--zip] [--no-mixdown] [--shot <prefix>] (round 184a, S9): File ›
  3176. // Export › "For other apps..." without the window; the report goes to "<folder>/export-bundle.txt"
  3177. if (args.contains ("--export-bundle"))
  3178. {
  3179. const auto i = args.indexOf ("--export-bundle");
  3180. runBundleExport (args[i + 1].unquoted(), args[i + 2].unquoted(), args.contains ("--zip"), ! args.contains ("--no-mixdown"),
  3181. args.contains ("--shot") ? args[args.indexOf ("--shot") + 1].unquoted() : juce::String());
  3182. return;
  3183. }
  3184. if (args.contains ("--export-flp"))
  3185. {
  3186. const auto i = args.indexOf ("--export-flp");
  3187. runFlExport (args[i + 1].unquoted(), args[i + 2].unquoted(), args.contains ("--substitute"));
  3188. return;
  3189. }
  3190. if (args.contains ("--export"))
  3191. {
  3192. const auto i = args.indexOf ("--export");
  3193. const auto insert = args.contains ("--insert") ? args[args.indexOf ("--insert") + 1].getIntValue() : 0;
  3194. runExport (args[i + 1].unquoted(), args[i + 2].unquoted(), args.contains ("--pattern"), insert);
  3195. return;
  3196. }
  3197. if (args.contains ("--tempomarkershot"))
  3198. {
  3199. // LYNX --tempomarkershot <prefix> <project.lynx> (round 190hq): the Playlist of the project with its tempo
  3200. // markers on the ruler (-playlist.png) and the "Save a copy for an older LYNX" window for each release
  3201. // (-savecopy-<release>.png); no window, nothing saved
  3202. const auto i = args.indexOf ("--tempomarkershot");
  3203. const auto prefix = args[i + 1].unquoted();
  3204. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  3205. lynx::AudioEngine shotEngine (false);
  3206. juce::String error;
  3207. auto ok = false;
  3208. if (auto song = lynx::ProjectFile::load (juce::File (args[i + 2].unquoted()), error))
  3209. shotEngine.setSong (std::move (*song)), ok = true;
  3210. if (ok)
  3211. {
  3212. {
  3213. lynx::PlaylistComponent playlist (shotEngine);
  3214. playlist.setBounds (0, 0, 1400, 420);
  3215. playlist.setVisible (true);
  3216. playlist.setViewForSnapshot (70.0, 0, 0);
  3217. shotEngine.dispatchPendingMessages();
  3218. saveSnapshot (playlist, prefix + "-playlist.png");
  3219. }
  3220. auto list = std::make_shared<juce::TextEditor>();
  3221. std::unique_ptr<juce::AlertWindow> w (lynx::MainComponent::buildSaveCopyWindow (lynx::ProjectFile::toJson (shotEngine.getSong()), list));
  3222. const auto releases = lynx::olderlynx::releases();
  3223. for (int k = 0; k < releases.size(); ++k)
  3224. {
  3225. w->getComboBoxComponent ("release")->setSelectedItemIndex (k, juce::sendNotificationSync);
  3226. saveSnapshot (*w, prefix + "-savecopy-" + releases[k] + ".png");
  3227. }
  3228. }
  3229. setApplicationReturnValue (ok ? 0 : 1);
  3230. quit();
  3231. return;
  3232. }
  3233. if (args.contains ("--savecopyfor"))
  3234. {
  3235. // LYNX --savecopyfor <in.lynx> <release> <out.lynx> (round 190hq, B20): File › "Save a copy for an older
  3236. // LYNX..." without the window; what the copy loses goes to <out.lynx>.txt (English), then result=OK
  3237. const auto i = args.indexOf ("--savecopyfor");
  3238. const juce::File input (args[i + 1].unquoted()), output (args[i + 3].unquoted());
  3239. const auto release = args[i + 2].unquoted();
  3240. juce::String report, error;
  3241. auto ok = false;
  3242. if (const auto song = lynx::ProjectFile::load (input, error))
  3243. {
  3244. const auto copy = lynx::olderlynx::forRelease (*song, release);
  3245. for (const auto& l : copy.lost)
  3246. report << (l.sound ? "sound: " : "view: ") << juce::String::fromUTF8 (l.text).replace ("{0}", l.detail) << "\n";
  3247. ok = copy.ok && output.replaceWithText (copy.json, false, false, nullptr);
  3248. if (! copy.ok)
  3249. error = copy.error;
  3250. }
  3251. report << "result=" << (ok ? juce::String ("OK") : "ERROR " + error) << "\n";
  3252. juce::File (output.getFullPathName() + ".txt").replaceWithText (report);
  3253. setApplicationReturnValue (ok ? 0 : 1);
  3254. quit();
  3255. return;
  3256. }
  3257. if (args.contains ("--render"))
  3258. {
  3259. const auto i = args.indexOf ("--render");
  3260. runRender (args[i + 1].unquoted(), args[i + 2].unquoted(), args[i + 3].getDoubleValue());
  3261. return;
  3262. }
  3263. // session breadcrumb: a fail-fast (no crash handler runs) still leaves the last steps behind (round 111)
  3264. uncleanLastStep = collectUncleanSessions();
  3265. sessionsFolder().createDirectory();
  3266. lynx::crashguard::beginSession (
  3267. sessionsFolder().getChildFile ("session-" + juce::String (lynx::crashguard::processId()) + ".txt").getFullPathName().toStdString(),
  3268. ("LYNX session\nversion=" + getApplicationVersion() + "\npid=" + juce::String (lynx::crashguard::processId())
  3269. + "\nstart=" + juce::String ((juce::int64) lynx::crashguard::processStartTime())
  3270. + "\nstarted=" + juce::Time::getCurrentTime().toISO8601 (true) + "\n").toStdString());
  3271. startHangWatch();
  3272. // LYNX_PROFILE_MAIN=<file> (round 174f): the message thread sampled every millisecond, 5-second windows
  3273. if (const auto profile = juce::SystemStats::getEnvironmentVariable ("LYNX_PROFILE_MAIN", {}); profile.isNotEmpty())
  3274. lynx::crashguard::startMainProfiler (profile.toStdString());
  3275. startupTrace.mark ("initialise (normal start)");
  3276. // (round 190hd, Windows) how long before the trace's 0 the process was made: the loader (the exe, its DLLs,
  3277. // relocations) and the static initialisers that ran before this file's
  3278. if (const auto created = lynx::crashguard::processStartTime(); created != 0)
  3279. {
  3280. const auto t0 = (std::uint64_t) std::chrono::duration_cast<std::chrono::microseconds> (startupTrace.t0System.time_since_epoch()).count() * 10u
  3281. + 116444736000000000ull; // (FILETIME: 100 ns since 1601)
  3282. if (t0 > created)
  3283. startupTrace.mark ((" (the process was made " + juce::String ((double) (t0 - created) / 10000.0, 1)
  3284. + " ms before this trace's 0: the loader, the DLLs, the first static initialisers)").toRawUTF8());
  3285. }
  3286. prepareGraphicsDevice();
  3287. if (startupTrace.on)
  3288. lynx::startupMark = startupMarkHook;
  3289. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  3290. lynx::themeui::loadSaved(); // the user's theme (Options › Theme, round 162d)
  3291. startupOptions = lynx::StartupOptions::load();
  3292. lynx::registerFileTypes();
  3293. startupTrace.mark ("options + file types");
  3294. // Double-clicking a .lynx/.flp opens LYNX with the file as an argument; a path typed in a terminal may be relative
  3295. // (D#92, round 180a: it was ignored, leaving the blank project with no message). A missing file gets "Could not open".
  3296. if (args.size() > 0 && lynx::safety::isFileArgument (args[0].unquoted().toStdString()))
  3297. fileToOpen = juce::File::getCurrentWorkingDirectory().getChildFile (args[0].unquoted());
  3298. // LYNX --no-plugins project.lynx (round 190ap): File › "Open without third-party plugins..." from the command
  3299. // line, for a project a plugin keeps from opening — no hosted plugin is created, each keeps its settings
  3300. if (const auto i = args.indexOf ("--no-plugins"); i >= 0)
  3301. {
  3302. if (i + 1 < args.size() && lynx::safety::isFileArgument (args[i + 1].unquoted().toStdString()))
  3303. fileToOpen = juce::File::getCurrentWorkingDirectory().getChildFile (args[i + 1].unquoted());
  3304. startWithoutPlugins = fileToOpen.hasFileExtension ("lynx");
  3305. }
  3306. // LYNX_TEST_MODE=1 LYNX --open-event-test <ms> <file>: the file arrives the way macOS's Finder delivers it (a Linux
  3307. // or Windows run can exercise that path): 0 ms = at once, before the window exists
  3308. if (lynx::platform::testMode() && args[0] == "--open-event-test" && args.size() > 2)
  3309. {
  3310. const auto file = args[2].unquoted().quoted();
  3311. if (args[1].getIntValue() == 0)
  3312. anotherInstanceStarted (file);
  3313. else
  3314. juce::Timer::callAfterDelay (args[1].getIntValue(), [this, file] { anotherInstanceStarted (file); });
  3315. }
  3316. // LYNX --opentime project.(flp|lynx)|- report.txt [idle seconds] (round 165i): the normal start-up (splash, audio
  3317. // device, window) opens the project, waits until it is loaded and LYNX has gone quiet, measures the idle CPU and
  3318. // memory, writes the times and quits normally (a benchmark that killed LYNX left "closed unexpectedly" behind)
  3319. if (args.contains ("--opentime"))
  3320. {
  3321. const auto i = args.indexOf ("--opentime");
  3322. const auto project = args[i + 1].unquoted();
  3323. fileToOpen = project != "-" && juce::File::isAbsolutePath (project) ? juce::File (project) : juce::File();
  3324. openTimeReport = juce::File (args[i + 2].unquoted());
  3325. if (args.size() > i + 3 && ! args[i + 3].startsWith ("--"))
  3326. openTimeIdleSeconds = juce::jlimit (1, 120, args[i + 3].getIntValue());
  3327. }
  3328. // round 190go: the ASIO device of the last session is made and opened from now on, while the splash and the
  3329. // window come up (see below)
  3330. lynx::AudioEngine::prewarmAudioDevice();
  3331. // round 190go: the built-in start-up sound is made while the splash and the window come up (pure maths)
  3332. if (startupOptions.sound && lynx::themeui::current().startupSound.empty())
  3333. startupSampleJob = std::async (std::launch::async, [] { return lynx::makeStartupSample(); });
  3334. // Round 190go (start-up faster than FL Studio): the main window is built first, with the engine ready but no
  3335. // audio device open; the device opens after it. An ASIO device of the last session was made and opened ahead,
  3336. // on a worker, while the window was built (AudioEngine::prewarmAudioDevice; the driver itself only ever runs on
  3337. // JUCE's ASIO thread, as COM wants). Play pressed before the device is open starts with it.
  3338. if (! startupOptions.splash)
  3339. {
  3340. startEngine();
  3341. createMainWindow();
  3342. mainWindow->reveal();
  3343. startupTrace.mark ("window revealed");
  3344. // the device (and the start-up sound) once the window's first frame is on screen
  3345. mainWindow->whenPainted ([this] {
  3346. openAudioDevice();
  3347. openMidiDevices();
  3348. startAfterWindow (false);
  3349. });
  3350. return;
  3351. }
  3352. // the splash first; the main window is built behind its card (still: the logo has not started to drop; building
  3353. // it during the drop would stop the animation, both run on the message thread), then the audio device opens
  3354. // (the start-up sound needs it), and the drop starts with its sound. The window shows the moment the logo has
  3355. // landed (round 190go, A4: before, the window was built only after the drop: the drop, then ~0.6 s of build).
  3356. // Round 190hd (Windows): the card draws on a thread of its own, so the main window is built DURING the drop
  3357. // (startOnItsOwnThread below).
  3358. splash = lynx::makeStartupSplash();
  3359. startupTrace.mark ("splash made");
  3360. splash->showOnDesktop();
  3361. startupTrace.mark ("splash on the desktop");
  3362. if (splash->drawsOnItsOwnThread())
  3363. {
  3364. startWithThreadedSplash();
  3365. return;
  3366. }
  3367. // the rest once the card's first frame is on the screen (round 190go: before, a fixed 40 ms), at the latest
  3368. // after 40 ms
  3369. const auto goOn = [this, started = std::make_shared<bool> (false)] {
  3370. if (std::exchange (*started, true) || splash == nullptr) // (once; or quit meanwhile)
  3371. return;
  3372. startEngine();
  3373. if (splash == nullptr) // quit meanwhile
  3374. return;
  3375. createMainWindow();
  3376. if (splash == nullptr || mainWindow == nullptr)
  3377. return;
  3378. if (startupOptions.sound)
  3379. openAudioDevice (false); // (else after the splash: nothing waits for it)
  3380. // one turn of the message loop before the drop: what fell due while the window was built (JUCE's timers,
  3381. // the window's own async work) runs now, on the still card, not in the drop's first frames
  3382. juce::MessageManager::callAsync ([this] { startDrop(); });
  3383. };
  3384. splash->onFirstFrame = goOn;
  3385. juce::Timer::callAfterDelay (40, goOn);
  3386. }
  3387. // Round 190hd (start-up faster than FL Studio, Windows): the card draws on a thread of its own (ui/Splash.cpp), so
  3388. // nothing the message thread does stops the drop. The card shows at once (no Direct2D device is made for it); the
  3389. // engine starts and the audio device opens behind the still card (an ASIO device of the last session was made and
  3390. // opened ahead on its own thread meanwhile), the drop starts with its sound, and the main window is built while
  3391. // 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
  3392. // fades the moment the logo has landed. The card stays for the drop only (the JUCE card's
  3393. // 2.1 s from the process start was there to keep a fast start from flashing; the drop alone is 1.05 s).
  3394. void startWithThreadedSplash()
  3395. {
  3396. splash->onFirstFrame = [this] {
  3397. if (splash != nullptr && startupTrace.on)
  3398. startupTrace.mark ((" splash: first frame on the screen at "
  3399. + juce::String (std::chrono::duration<double, std::milli> (splash->getFirstFrameTime() - startupTrace.t0).count(), 1) + " ms (its own thread)")
  3400. .toRawUTF8());
  3401. };
  3402. juce::MessageManager::callAsync ([this] {
  3403. if (splash == nullptr) // (quit meanwhile)
  3404. return;
  3405. startEngine();
  3406. if (splash == nullptr)
  3407. return;
  3408. if (startupOptions.sound)
  3409. openAudioDevice (false); // (else after the splash: nothing waits for it)
  3410. startDrop();
  3411. // the main window while the logo drops (one more message, so the drop's start is not held by it)
  3412. juce::MessageManager::callAsync ([this] {
  3413. if (splash == nullptr || mainWindow != nullptr || engine == nullptr)
  3414. return;
  3415. createMainWindow();
  3416. // shown as soon as it is built, behind the card: the logo goes on dropping above it and the card fades at
  3417. // the landing as before (LYNX_REVEAL_AT_LANDING=1: the window shows at the landing, as in round 190go)
  3418. if (mainWindow != nullptr && splash != nullptr
  3419. && juce::SystemStats::getEnvironmentVariable ("LYNX_REVEAL_AT_LANDING", {}) != "1")
  3420. {
  3421. mainWindow->reveal();
  3422. windowRevealed = true;
  3423. startupTrace.mark ("window revealed (behind the card, while the logo drops)");
  3424. splash->raise();
  3425. }
  3426. });
  3427. });
  3428. }
  3429. // the logo's drop and the start-up sound together; the window shows the moment the logo has landed
  3430. void startDrop()
  3431. {
  3432. const auto ownThread = splash != nullptr && splash->drawsOnItsOwnThread(); // (the window is built during the drop)
  3433. if (splash == nullptr || (mainWindow == nullptr && ! ownThread) || engine == nullptr)
  3434. return;
  3435. if (startupOptions.sound)
  3436. playStartupSound();
  3437. splash->setStatus (lynx::tr ("Loading the workspace..."));
  3438. splash->startClock();
  3439. // the minimum counts from the process start (the window and the audio device took part of it already); a card
  3440. // on its own thread stays for the drop (round 190hd)
  3441. splashDuration = ownThread ? landingSeconds : lynx::SplashScreen::remainingDuration (startupTrace.seconds());
  3442. splash->setBarDuration (splashDuration);
  3443. splash->whenLanded (splashDuration, [this] {
  3444. if (splash == nullptr || mainWindow == nullptr)
  3445. return;
  3446. if (startupTrace.on)
  3447. startupTrace.mark (("splash: the drop in " + juce::String (splash->getDropFrames()) + " frames, longest gap "
  3448. + juce::String (splash->getLongestDropGapMs(), 1) + " ms"
  3449. + (splash->getLongestDropGapAt() >= 0.0 ? " (at " + juce::String (splash->getLongestDropGapAt(), 3) + " s of its clock; the frame before: "
  3450. + splash->getLongestDropGapDetail() + ")"
  3451. : juce::String()))
  3452. .toRawUTF8());
  3453. if (! std::exchange (windowRevealed, true))
  3454. {
  3455. mainWindow->reveal();
  3456. startupTrace.mark ("window revealed (after the splash)");
  3457. }
  3458. splash->raise();
  3459. const auto deviceOpen = ! engine->isAudioDeviceOpenPending();
  3460. splash->finish ([this, deviceOpen] {
  3461. splash = nullptr;
  3462. // without the start-up sound the device opens now, once the card has faded (the window is up)
  3463. if (! deviceOpen)
  3464. openAudioDevice();
  3465. openMidiDevices();
  3466. if (! deviceOpen)
  3467. startAfterWindow (true);
  3468. });
  3469. if (deviceOpen)
  3470. mainWindow->whenPainted ([this] { startAfterWindow (true); });
  3471. });
  3472. }
  3473. // what follows the window's first frame (the audio device is open): the notice of an unclean end, the start-up
  3474. // project, the probes and the update check; on a first run (with the splash) the setup wizard
  3475. void startAfterWindow (bool offerSetupWizard)
  3476. {
  3477. if (std::exchange (startedAfterWindow, true) || mainWindow == nullptr)
  3478. return;
  3479. // (round 190go) each step after the window is a timed line of the start-up trace
  3480. showUncleanNotice();
  3481. startupTrace.mark ("after the window: unclean-session notice");
  3482. openStartupFile();
  3483. startupTrace.mark ("startup file opened");
  3484. startOpenTimeProbe();
  3485. startUpdateCheck();
  3486. startSupportNote(); // (round 190fq)
  3487. startupTrace.mark ("after the window: probes, update check scheduled");
  3488. juce::MessageManager::callAsync ([] { startupTrace.mark ("first message loop turn"); });
  3489. markSettled(); // (round 190gd)
  3490. // first run: language, audio, plugin folders (FL Studio's included) and a background scan
  3491. if (! offerSetupWizard)
  3492. return;
  3493. if (! lynx::setupWizardDone() && lynx::platform::testMode())
  3494. lynx::platform::testModeLog ("setup wizard");
  3495. else if (! lynx::setupWizardDone())
  3496. {
  3497. mainWindow->showSetupWizard();
  3498. startupTrace.mark ("after the window: setup wizard shown");
  3499. }
  3500. }
  3501. // round 190fq: the start-up support note (ui/SupportLynx.h) counts this start and, from the 10th on, may show its
  3502. // card once at a quiet moment. Only here, on the normal start path (the command-line modes returned earlier); test
  3503. // mode and CI machines neither count nor show it.
  3504. void startSupportNote()
  3505. {
  3506. if (mainWindow == nullptr)
  3507. return;
  3508. const auto env = [] (const char* name) { return juce::SystemStats::getEnvironmentVariable (name, {}).toStdString(); };
  3509. const auto quiet = lynx::supportnote::quietEnvironment (lynx::platform::testMode(), env ("CI"), env ("GITHUB_ACTIONS"), env ("LYNX_NO_SUPPORT_NOTE"));
  3510. if (quiet && lynx::platform::testMode())
  3511. lynx::platform::testModeLog ("support note: not counted (test mode)");
  3512. mainWindow->getContent().startSupportNote (quiet);
  3513. }
  3514. // the start-up trace's last lines: what the first seconds after the window add (lazy work, caches, the first paints)
  3515. static void markSettled()
  3516. {
  3517. if (! startupTrace.on)
  3518. return;
  3519. juce::Timer::callAfterDelay (5000, [] { startupTrace.mark ("5 s after the window"); startupTrace.write(); });
  3520. juce::Timer::callAfterDelay (15000, [] { startupTrace.mark ("15 s after the window"); startupTrace.write(); });
  3521. }
  3522. // Round 190hd (Windows): the Direct3D 11 + Direct2D device (~0.35 s: the graphics driver loads) is made once, on a
  3523. // worker, while the splash card, the engine and the audio device come up, and kept until LYNX closes: a 1 x 1
  3524. // Direct2D image holds JUCE's shared DirectX object (its devices), so the main window finds them made and nothing
  3525. // makes them again (before, every holder going away -- the splash's logo, a temporary one -- could mean a new device
  3526. // at its next use). Other systems: nothing to do.
  3527. void prepareGraphicsDevice()
  3528. {
  3529. #if JUCE_WINDOWS
  3530. if (juce::SystemStats::getEnvironmentVariable ("LYNX_GPU_PREWARM", {}) == "0")
  3531. return;
  3532. graphicsDeviceJob = std::async (std::launch::async, [] {
  3533. const auto from = std::chrono::steady_clock::now();
  3534. juce::Image holder (juce::Image::ARGB, 1, 1, false); // (NativeImageType: Direct2D, the shared device)
  3535. return std::make_pair (holder, std::chrono::duration<double, std::milli> (std::chrono::steady_clock::now() - from).count());
  3536. });
  3537. #endif
  3538. }
  3539. void markGraphicsDevice()
  3540. {
  3541. if (! graphicsDeviceJob.valid() || ! startupTrace.on || std::exchange (graphicsDeviceMarked, true))
  3542. return;
  3543. const auto ready = graphicsDeviceJob.wait_for (std::chrono::seconds (0)) == std::future_status::ready;
  3544. startupTrace.mark (ready ? (" graphics device made on a worker in " + juce::String (graphicsDeviceJob.get().second, 1) + " ms").toRawUTF8()
  3545. : " graphics device: still being made on its worker");
  3546. }
  3547. void startEngine()
  3548. {
  3549. startupTrace.mark ("before the audio engine");
  3550. lynx::BrowserComponent::allowIndexerProcess = true; // (round 190hd: the normal window only)
  3551. // (round 190go) ready to play, no device open yet: see openAudioDevice
  3552. engine = std::make_unique<lynx::AudioEngine> (true, -1, true, true);
  3553. lynx::videoview::install (*engine); // (Fruity Video Player channels: their sound tracks)
  3554. startupTrace.mark ("audio engine (no device yet)");
  3555. crashEngine = engine.get();
  3556. lynx::crashreporter::watchAudioDevice (engine->getDeviceManager()); // (the session file names the device: crash reports)
  3557. // a project given on the command line: its slow plugin modules (a Waves shell) start now, on their own
  3558. // thread, while the splash and the main window come up (round 121)
  3559. if (fileToOpen.hasFileExtension ("flp"))
  3560. if (juce::MemoryBlock data; fileToOpen.loadFileAsData (data))
  3561. try
  3562. {
  3563. engine->getPluginHost().startModulesFor (lynx::flpForeignPlugins (flp::parseProject ({ static_cast<const std::uint8_t*> (data.getData()), data.getSize() })));
  3564. startupTrace.mark ("plugin modules started ahead");
  3565. }
  3566. catch (const flp::Error&)
  3567. {
  3568. }
  3569. }
  3570. // The audio device of the last session, then (withSound) the start-up sound on it (once; message thread)
  3571. void openAudioDevice (bool withSound = true)
  3572. {
  3573. if (engine == nullptr || ! engine->isAudioDeviceOpenPending())
  3574. return;
  3575. engine->openAudioDevice();
  3576. if (const auto prewarmed = lynx::asioPrewarmReport(); prewarmed.isNotEmpty() && startupTrace.on)
  3577. startupTrace.mark ((" " + prewarmed).toRawUTF8());
  3578. startupTrace.mark ("audio device opened");
  3579. addDriverFileDeviceType();
  3580. if (withSound)
  3581. playStartupSound();
  3582. }
  3583. void playStartupSound()
  3584. {
  3585. if (startupOptions.sound && ! std::exchange (startupSoundPlayed, true) && engine != nullptr)
  3586. {
  3587. // Options › Theme › Startup sound (issue #12): the user's file, else (or when it can't be read) LYNX's own
  3588. std::shared_ptr<const lynx::SampleData> sound;
  3589. if (const auto& own = lynx::themeui::current().startupSound; ! own.empty() && juce::File (juce::String::fromUTF8 (own.c_str())).existsAsFile())
  3590. sound = engine->getSampleLibrary().load (juce::String::fromUTF8 (own.c_str()));
  3591. if (sound == nullptr && startupSampleJob.valid())
  3592. sound = startupSampleJob.get();
  3593. engine->previewSample (sound != nullptr ? sound : lynx::makeStartupSample());
  3594. }
  3595. startupTrace.mark ("startup sound");
  3596. }
  3597. void openMidiDevices()
  3598. {
  3599. if (engine != nullptr)
  3600. engine->openMidiDevices(); // (its own line in the start-up trace: "engine: MIDI inputs")
  3601. }
  3602. void createMainWindow()
  3603. {
  3604. mainWindow = std::make_unique<MainWindow> ("LYNX SHARE", *engine); // the brand; getApplicationName() stays "LYNX" (an id: instance lock, X11 WM_CLASS, ALSA client)
  3605. lynx::setMainWindowForOwnership (mainWindow.get());
  3606. lynx::applyRenderingChoice (*mainWindow); // (GPU rendering off: GDI; round 157a)
  3607. lynx::startRenderingWatch();
  3608. startupTrace.mark ("main window built");
  3609. lynx::remoteui::install ([this] (bool enabled) {
  3610. remoteControl = nullptr;
  3611. if (enabled)
  3612. remoteControl = lynx::RemoteControl::create (*engine, true, [this] {
  3613. const auto title = mainWindow != nullptr ? mainWindow->getName() : juce::String ("Untitled");
  3614. const auto separator = title.indexOf (" - ");
  3615. return separator >= 0 ? title.substring (separator + 3) : title;
  3616. }, [this] {
  3617. const auto file = mainWindow != nullptr ? mainWindow->getContent().getCurrentProjectFile() : juce::File();
  3618. return file == juce::File() ? juce::String() : file.getFullPathName();
  3619. });
  3620. lynx::remoteui::setRuntimeStatus (remoteControl != nullptr && remoteControl->active());
  3621. });
  3622. markGraphicsDevice();
  3623. }
  3624. // the previous run ended without closing (see collectUncleanSessions): say so once, with its last step — and, as
  3625. // Settings › General › "Crash reports" says (round 159), ask whether to send a report, send it unasked, or not
  3626. void showUncleanNotice()
  3627. {
  3628. if (lynx::platform::testMode()) // LYNX_TEST_MODE: no prompt, no report sent (written to test-mode.log)
  3629. {
  3630. if (uncleanLastStep.isNotEmpty())
  3631. lynx::platform::testModeLog ("\"closed unexpectedly\" notice (last step: " + uncleanLastStep + ")");
  3632. return;
  3633. }
  3634. if (uncleanLastStep.isEmpty())
  3635. {
  3636. lynx::crashreporter::retryPending(); // (reports an earlier run could not send: once more)
  3637. return;
  3638. }
  3639. auto message = lynx::tr ("The last session ended without closing normally. Last step: {0}. Backup copies of your project are in "
  3640. "LYNX SHARE's autosave folder; details in crash-history.log.",
  3641. { uncleanLastStep });
  3642. uncleanLastStep.clear();
  3643. const auto cause = uncleanCause();
  3644. // round 157a: a plugin's editor was opening — it crashed (often in the graphics driver, inside the plugin's own
  3645. // OpenGL window): offer to keep that plugin in its own process, where a crash takes only the plugin down
  3646. juce::String separatePlugin;
  3647. if (cause.editorPlugin.isNotEmpty() && ! lynx::pluginSandboxEnabled() && ! lynx::pluginAlwaysSeparate (cause.editorPlugin))
  3648. separatePlugin = cause.editorPlugin;
  3649. // LYNX's own drawing crashed in the graphics driver (Direct2D / Direct3D): draw with the CPU from now on
  3650. else if (cause.gpuDriver && lynx::gpuRenderingEnabled())
  3651. {
  3652. lynx::setGpuRenderingEnabled (false);
  3653. message << "\n\n"
  3654. << lynx::tr ("The crash was in the graphics driver ({0}). LYNX SHARE now draws its windows without the GPU; you can turn GPU "
  3655. "rendering back on in Options > General settings (after a driver update, for example).",
  3656. { cause.driverModule });
  3657. }
  3658. // round 165e: the Visualizer's GPU view was drawing when the session ended (a driver crash, a hang, the machine
  3659. // going down): the Visualizer draws with the 2D renderer from now on (its GPU button turns it back on)
  3660. for (int i = uncleanSteps.size(); --i >= 0;)
  3661. {
  3662. if (uncleanSteps[i].contains (lynx::visualgl::stopNote))
  3663. break;
  3664. if (uncleanSteps[i].contains (lynx::visualgl::startNote))
  3665. {
  3666. if (lynx::visualgl::enabled())
  3667. {
  3668. lynx::visualgl::setEnabled (false);
  3669. message << "\n\n"
  3670. << lynx::tr ("The Visualizer was drawing with the GPU (OpenGL) when it happened. It now draws without the GPU; its GPU "
  3671. "button turns it back on.");
  3672. }
  3673. break;
  3674. }
  3675. }
  3676. const auto session = lynx::crashreporter::parseSession (uncleanSessionText);
  3677. auto* devices = engine != nullptr ? &engine->getDeviceManager() : nullptr;
  3678. const auto action = lynx::crashreport::actionFor (lynx::crashreporter::consent());
  3679. lynx::crashreporter::retryPending();
  3680. if (action == lynx::crashreport::Action::askUser)
  3681. {
  3682. if (separatePlugin.isNotEmpty())
  3683. message << "\n\n"
  3684. << lynx::tr ("It happened while the window of {0} was opening{1}.",
  3685. { separatePlugin, cause.gpuDriver ? lynx::tr (" (in the graphics driver, {0})", { cause.driverModule }) : juce::String() });
  3686. lynx::crashreporter::showStartupDialog (session, message, separatePlugin, [separatePlugin] { lynx::setPluginAlwaysSeparate (separatePlugin, true); },
  3687. devices);
  3688. return;
  3689. }
  3690. if (action == lynx::crashreport::Action::sendSilently)
  3691. {
  3692. const auto input = lynx::crashreporter::makeInput (session, session.kind(), devices);
  3693. lynx::crashreporter::send (lynx::crashreporter::buildJson (input, false), juce::String::fromUTF8 (input.id.c_str()));
  3694. message << "\n\n" << lynx::tr ("A crash report is being sent to help fix it (Options > General settings > Crash reports).");
  3695. }
  3696. if (separatePlugin.isNotEmpty())
  3697. {
  3698. juce::AlertWindow::showOkCancelBox (
  3699. juce::MessageBoxIconType::WarningIcon, lynx::tr ("LYNX SHARE closed unexpectedly"),
  3700. message + "\n\n"
  3701. + lynx::tr ("It happened while the window of {0} was opening{1}. Run {0} in a separate process from now on? If it "
  3702. "crashes again, only the plugin stops and LYNX SHARE keeps running (Plugin wrapper menu: \"Always run in a "
  3703. "separate process\").",
  3704. { separatePlugin, cause.gpuDriver ? lynx::tr (" (in the graphics driver, {0})", { cause.driverModule }) : juce::String() }),
  3705. lynx::tr ("Run separately"), lynx::tr ("No"), nullptr,
  3706. juce::ModalCallbackFunction::create ([separatePlugin] (int result) {
  3707. if (result != 0)
  3708. lynx::setPluginAlwaysSeparate (separatePlugin, true);
  3709. }));
  3710. return;
  3711. }
  3712. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, lynx::tr ("LYNX SHARE closed unexpectedly"), message);
  3713. }
  3714. // --opentime: after the start-up file was handed to the window
  3715. void startOpenTimeProbe()
  3716. {
  3717. if (openTimeReport == juce::File())
  3718. return;
  3719. struct Probe final : juce::Timer
  3720. {
  3721. LynxApplication& app;
  3722. juce::File report, project;
  3723. int idleSeconds;
  3724. int phase = 0; // 0 loading, 1 settling, 2 idle measurement
  3725. double revealedS = 0.0, loadedS = -1.0, settledS = -1.0, cpuAtLoaded = 0.0;
  3726. double lastCpu = 0.0, lastT = 0.0, quietSince = -1.0, idleCpu0 = 0.0, idleT0 = 0.0;
  3727. Probe (LynxApplication& a, juce::File r, juce::File p, int idle)
  3728. : app (a), report (std::move (r)), project (std::move (p)), idleSeconds (idle)
  3729. {
  3730. revealedS = startupTrace.seconds();
  3731. startTimer (250);
  3732. }
  3733. bool loaded() const
  3734. {
  3735. if (project == juce::File())
  3736. return true;
  3737. return app.mainWindow != nullptr
  3738. && app.mainWindow->getName().containsIgnoreCase (project.getFileNameWithoutExtension());
  3739. }
  3740. void finish (const juce::String& result)
  3741. {
  3742. stopTimer();
  3743. const auto now = startupTrace.seconds();
  3744. const auto cpu = lynx::processCpuSeconds();
  3745. juce::String text;
  3746. text << "project=" << (project == juce::File() ? juce::String ("-") : project.getFullPathName()) << "\n"
  3747. << "window_s=" << juce::String (revealedS, 3) << "\n"
  3748. << "loaded_s=" << juce::String (loadedS, 3) << "\n"
  3749. << "settled_s=" << juce::String (settledS, 3) << "\n"
  3750. << "cpu_at_loaded_s=" << juce::String (cpuAtLoaded, 3) << "\n"
  3751. << "idle_s=" << juce::String (now - idleT0, 2) << "\n"
  3752. << "idle_cpu_pct=" << juce::String (phase == 2 && now > idleT0 ? 100.0 * (cpu - idleCpu0) / (now - idleT0) : -1.0, 1) << "\n"
  3753. << "working_set_mb=" << juce::String ((double) lynx::toolbar::PerformanceMeter::processMemoryBytes() / 1048576.0, 0) << "\n"
  3754. << "cpu_total_s=" << juce::String (cpu, 3) << "\n"
  3755. << "result=" << result << "\n";
  3756. report.replaceWithText (text);
  3757. app.setApplicationReturnValue (result == "OK" ? 0 : 1);
  3758. app.quit();
  3759. }
  3760. void timerCallback() override
  3761. {
  3762. const auto now = startupTrace.seconds();
  3763. const auto cpu = lynx::processCpuSeconds();
  3764. if (phase == 0)
  3765. {
  3766. if (loaded())
  3767. {
  3768. loadedS = now;
  3769. cpuAtLoaded = cpu;
  3770. phase = 1;
  3771. lastCpu = cpu;
  3772. lastT = now;
  3773. }
  3774. else if (now - revealedS > 240.0)
  3775. finish ("TIMEOUT loading");
  3776. return;
  3777. }
  3778. if (phase == 1)
  3779. {
  3780. // quiet = under 10 % of one core for 1.5 s (the harness's rule), at most 30 s after loading
  3781. const auto use = now > lastT ? 100.0 * (cpu - lastCpu) / (now - lastT) : 0.0;
  3782. lastCpu = cpu;
  3783. lastT = now;
  3784. if (use < 10.0)
  3785. {
  3786. if (quietSince < 0.0)
  3787. quietSince = now - 0.25;
  3788. if (now - quietSince >= 1.5)
  3789. settledS = quietSince;
  3790. }
  3791. else
  3792. quietSince = -1.0;
  3793. if (settledS >= 0.0 || now - loadedS > 30.0)
  3794. {
  3795. phase = 2;
  3796. idleCpu0 = cpu;
  3797. idleT0 = now;
  3798. }
  3799. return;
  3800. }
  3801. if (now - idleT0 >= (double) idleSeconds)
  3802. finish ("OK");
  3803. }
  3804. };
  3805. perf = std::make_unique<Probe> (*this, openTimeReport, fileToOpen, openTimeIdleSeconds);
  3806. }
  3807. // round 166b: the update check of a normal start (never in --opentime and the other command-line modes), a few
  3808. // seconds after the window is up so it never competes with the start-up; and the result of an update just installed
  3809. void startUpdateCheck()
  3810. {
  3811. if (openTimeReport != juce::File())
  3812. return;
  3813. lynx::updater::afterStart();
  3814. juce::Timer::callAfterDelay (3000, [] { lynx::updater::startAutomaticCheck(); });
  3815. }
  3816. void openStartupFile()
  3817. {
  3818. startupFileHandled = true;
  3819. if (fileToOpen != juce::File() && mainWindow != nullptr)
  3820. {
  3821. if (std::exchange (startWithoutPlugins, false)) // --no-plugins (round 190ap)
  3822. mainWindow->getContent().openNextWithoutPlugins (true);
  3823. mainWindow->openFile (fileToOpen);
  3824. mainWindow->getContent().openNextWithoutPlugins (false); // (a file that did not open leaves nothing behind)
  3825. }
  3826. else if (mainWindow != nullptr && openTimeReport == juce::File())
  3827. mainWindow->getContent().openStartupProject(); // issue #123 (FL's Startup project)
  3828. }
  3829. void shutdown() override
  3830. {
  3831. parityShow.reset(); // (LYNX_PARITYSHOT_SHOW's window, before the engine it shows)
  3832. if (relaunched || updateHelper)
  3833. return; // the copy that ran owns the session (its crash notes stay for the next start)
  3834. lynx::crashguard::note ("closing");
  3835. lynx::shutdownPluginSandboxWorker();
  3836. splash = nullptr;
  3837. lynx::shutdownStemExtraction(); // (a separation in flight stops before its window and the engine go)
  3838. lynx::shutdownAudioToMidi(); // (the same for a conversion to MIDI)
  3839. if (mainWindow != nullptr && mainWindow->isVisible())
  3840. mainWindow->saveState();
  3841. lynx::remoteui::shutdown();
  3842. remoteControl = nullptr; // cancels queued control work before its engine and UI go
  3843. mainWindow = nullptr; // the UI goes before the engine
  3844. graphicsDeviceJob = {}; // (round 190hd: the graphics device's holder, after every window)
  3845. lynx::updater::shutdown(); // (a check or download in flight stops)
  3846. crashEngine = nullptr;
  3847. engine = nullptr;
  3848. // separate-process plugins end on threads of their own (issue #159): a moment for them, never the 10 s a dead
  3849. // child's pipe can take
  3850. lynx::finishSandboxTeardowns (2000);
  3851. // CLAP plugins whose instance another thread deleted while this one was busy: deactivated and destroyed now
  3852. lynx::ClapPluginFormat::finishPendingTeardowns();
  3853. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  3854. heartbeat.stopTimer();
  3855. lynx::crashreporter::shutdown(); // (an upload in flight gets a moment, never long)
  3856. lynx::crashguard::stopHangWatch();
  3857. lynx::crashguard::stopMainProfiler();
  3858. lynx::crashguard::endSession(); // a clean exit: no breadcrumb left behind
  3859. // everything is saved and closed: a process that loaded third-party plugins ends here, before the DLLs' own
  3860. // teardown runs (some crash in it at exit, round 111)
  3861. if (sandboxChild || lynx::PluginHost::pluginsWereLoaded())
  3862. lynx::crashguard::exitNow (getApplicationReturnValue());
  3863. }
  3864. void systemRequestedQuit() override
  3865. {
  3866. if (mainWindow != nullptr)
  3867. mainWindow->confirmDiscard ([] { juce::JUCEApplication::quit(); });
  3868. else
  3869. quit();
  3870. }
  3871. private:
  3872. // round 157a: a frozen UI (Windows' "not responding") writes the message thread's stack to autosave\hang <time>.txt
  3873. // and a session step, so a freeze can be told apart from a crash and located. The timer is the heartbeat.
  3874. struct Heartbeat final : juce::Timer
  3875. {
  3876. void timerCallback() override { lynx::crashguard::heartbeat(); }
  3877. } heartbeat;
  3878. void startHangWatch()
  3879. {
  3880. const auto folder = lynx::platform::settingsFile ("autosave");
  3881. folder.createDirectory();
  3882. // keep the newest hang files only
  3883. auto old = folder.findChildFiles (juce::File::findFiles, false, "hang *.txt");
  3884. lynx::filesort::byTime (old, lynx::filesort::By::modificationTime, true);
  3885. for (int i = 20; i < old.size(); ++i)
  3886. old.getReference (i).deleteFile();
  3887. lynx::crashguard::startHangWatch (folder.getFullPathName().replaceCharacter ('\\', '/').toStdString());
  3888. heartbeat.startTimerHz (5);
  3889. }
  3890. bool sandboxChild = false;
  3891. bool relaunched = false; // relaunchFromAsciiPath ran LYNX from its short path: this process only waited
  3892. bool updateHelper = false; // --apply-update (round 166b)
  3893. juce::String uncleanLastStep; // last step of a previous run that ended without closing
  3894. // LYNX_PROFILE_DIR=<folder> LYNX --lv2scantest report.txt (Linux, issue #85): the LV2 scan's promise, with real child
  3895. // processes. A new PluginHost per step, as every start of LYNX has. The LV2 folders of the machine are read too.
  3896. void runLv2ScanTest (const juce::String& reportPath)
  3897. {
  3898. juce::String report;
  3899. auto ok = lynx::platform::profileOverride() != juce::File();
  3900. #if JUCE_LINUX
  3901. const auto folder = lynx::platform::profileOverride().getChildFile ("lv2-test");
  3902. const juce::FileSearchPath paths (folder.getFullPathName());
  3903. const auto check = [&] (const juce::String& name, bool passed) {
  3904. report << name << "=" << (passed ? "ok" : "FAILED") << "\n";
  3905. ok = ok && passed;
  3906. };
  3907. const auto install = [&] (const juce::String& name) {
  3908. const auto bundle = folder.getChildFile (name + ".lv2");
  3909. bundle.createDirectory();
  3910. bundle.getChildFile ("manifest.ttl").replaceWithText ("@prefix lv2: <http://lv2plug.in/ns/lv2core#> .\n@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n"
  3911. "<urn:lynx-test:" + name + "> a lv2:Plugin ; lv2:binary <" + name + ".so> ; rdfs:seeAlso <plugin.ttl> .\n");
  3912. bundle.getChildFile ("plugin.ttl").replaceWithText ("@prefix doap: <http://usefulinc.com/ns/doap#> .\n<urn:lynx-test:" + name + "> doap:name \"" + name + "\" .\n");
  3913. };
  3914. auto date = juce::Time::getCurrentTime();
  3915. const auto touch = [&] { // the next date, whatever the file system's date resolution
  3916. date += juce::RelativeTime::seconds (2.0);
  3917. folder.getChildFile ("a.lv2/plugin.ttl").setLastModificationTime (date);
  3918. };
  3919. const auto listed = [] (lynx::PluginHost& host, const juce::String& name) {
  3920. for (const auto& d : host.getKnownPlugins().getTypes())
  3921. if (d.fileOrIdentifier == "urn:lynx-test:" + name)
  3922. return true;
  3923. return false;
  3924. };
  3925. const auto step = [&] (const juce::String& name, int children, const std::function<void (lynx::PluginHost&)>& prepare = {}) {
  3926. lynx::PluginHost host (true);
  3927. if (prepare)
  3928. prepare (host);
  3929. host.scan (paths, {});
  3930. check (name, host.scanChildrenStarted() == children && listed (host, "a"));
  3931. };
  3932. install ("a");
  3933. step ("first_scan_one_child", 1);
  3934. step ("nothing_changed_no_child", 0);
  3935. touch();
  3936. step ("ttl_updated", 1);
  3937. install ("b");
  3938. step ("bundle_installed", 1);
  3939. step ("forget_file", 1, [] (lynx::PluginHost& host) { host.forgetFile ("urn:lynx-test:a"); });
  3940. step ("forget_all", 1, [] (lynx::PluginHost& host) { host.forgetAll(); });
  3941. lynx::platform::settingsFile ("plugins.xml").deleteFile();
  3942. step ("list_lost", 1);
  3943. step ("nothing_changed_again", 0);
  3944. // cancelled while the child works: stopped at once, and nothing is taken for done
  3945. touch();
  3946. setenv ("LYNX_TEST_CRASH", "lv2-batch-hang", 1);
  3947. {
  3948. lynx::PluginHost host (true);
  3949. const auto started = juce::Time::getMillisecondCounter();
  3950. host.scan (paths, [] (float, const juce::String&) { return false; });
  3951. check ("cancel_stops_the_child", host.scanChildrenStarted() == 1 && juce::Time::getMillisecondCounter() - started < 20000);
  3952. }
  3953. unsetenv ("LYNX_TEST_CRASH");
  3954. step ("described_after_cancel", 1);
  3955. // the child dies: plugin by plugin takes over (stopped after two of them: a machine may have hundreds)
  3956. touch();
  3957. setenv ("LYNX_TEST_CRASH", "lv2-batch", 1);
  3958. {
  3959. lynx::PluginHost host (true);
  3960. host.scan (paths, [&host] (float, const juce::String&) { return host.scanChildrenStarted() < 3; });
  3961. check ("crash_falls_back_plugin_by_plugin", host.scanChildrenStarted() == 3);
  3962. auto blamed = false;
  3963. for (const auto& file : host.getKnownPlugins().getBlacklistedFiles())
  3964. blamed = blamed || file.startsWith ("lv2-folders:");
  3965. check ("crash_blacklists_nothing", ! blamed);
  3966. }
  3967. unsetenv ("LYNX_TEST_CRASH");
  3968. step ("described_after_crash", 1);
  3969. // round 190fw: past the first limit, a child that still works is waited for (FL Studio's own VST plugin boots
  3970. // the FL engine), one that sits still is killed as before, and a busy one only up to the cap. Limits are
  3971. // shortened for the test: 2 s first limit, 2 s without work, 8 s cap (real: 30 s, 30 s, 5 min).
  3972. setenv ("LYNX_TEST_SCAN_MS", "2000,2000,8000", 1);
  3973. const auto timed = [&] (const char* fault, const std::function<bool (lynx::PluginHost&)>& progress) {
  3974. touch();
  3975. setenv ("LYNX_TEST_CRASH", fault, 1);
  3976. lynx::PluginHost host (true);
  3977. const auto started = juce::Time::getMillisecondCounter();
  3978. host.scan (paths, [&] (float, const juce::String&) { return ! progress || progress (host); });
  3979. unsetenv ("LYNX_TEST_CRASH");
  3980. const auto took = (int) (juce::Time::getMillisecondCounter() - started);
  3981. report << " " << fault << ": " << took << " ms, children " << host.scanChildrenStarted() << "\n";
  3982. return std::make_pair (took, host.scanChildrenStarted());
  3983. };
  3984. // (after a failed batch, one plugin-by-plugin child and no more: it describes quickly)
  3985. const auto stopAfterBatch = [] (lynx::PluginHost& host) { return host.scanChildrenStarted() < 2; };
  3986. {
  3987. const auto [took, children] = timed ("lv2-batch-busy:5000", {});
  3988. check ("busy_child_is_waited_for", children == 1 && took >= 4500);
  3989. }
  3990. {
  3991. const auto [took, children] = timed ("lv2-batch-hang", stopAfterBatch);
  3992. check ("idle_child_ends_near_the_first_limit", children == 2 && took >= 1900 && took < 9000);
  3993. }
  3994. {
  3995. const auto [took, children] = timed ("lv2-batch-busy:60000", stopAfterBatch);
  3996. check ("busy_child_ends_at_the_cap", children == 2 && took >= 7500 && took < 20000);
  3997. }
  3998. unsetenv ("LYNX_TEST_SCAN_MS");
  3999. step ("described_after_slow_children", 1);
  4000. #endif
  4001. juce::File (reportPath).replaceWithText (report + "result=" + (ok ? "OK" : "FAILED") + "\n");
  4002. setApplicationReturnValue (ok ? 0 : 1);
  4003. quit();
  4004. }
  4005. // LYNX.exe --selftest report.txt: renders 2 s without a sound card and writes the result.
  4006. // Exit code 0 = audio came out, 1 = silence.
  4007. // --selftest (round 190ci): two more copies of LYNX end by a fault on purpose (--faulttest), one on a normal stack
  4008. // (the top-level filter) and one on a stack Windows cannot walk (the first-chance hook); each must leave
  4009. // "crash <time>.txt" with the access violation in the folder it is given.
  4010. // Round 190dt (Linux / macOS): a plain fault, and LYNX's own fault inside a guarded plugin call (in its code, and in
  4011. // the C library called from its code), must each leave the crash file with the signal: the plugin guard passes
  4012. // LYNX's own faults on to the crash handler instead of swallowing them ("swallowed.txt" = it did).
  4013. // Round 190gj (P9): the inserts' stems from one render are the files each stem's own render writes, byte for byte
  4014. // (a short song with a bus, a send return, delay compensation, a channel on the Master, an automated insert and a
  4015. // side-chained insert), streamed (24-bit WAV with the full mix) and buffered (normalised float).
  4016. static juce::String stemsSinglePassSelfTest()
  4017. {
  4018. auto s = lynx::Song::makeDefault();
  4019. s.mixer = lynx::Song::defaultMixer (7);
  4020. for (std::size_t c = 0; c < s.channels.size(); ++c)
  4021. s.channels[c].mixerTrack = (int) c + 1;
  4022. auto onMaster = s.channels[2];
  4023. onMaster.mixerTrack = 0;
  4024. onMaster.pan = -0.4f;
  4025. s.channels.push_back (onMaster);
  4026. for (int step : { 1, 5, 9, 13 })
  4027. s.patterns[0].toggleStep ((int) s.channels.size() - 1, step);
  4028. for (int step : { 4, 12 })
  4029. s.patterns[0].toggleStep (3, step); // the snare
  4030. for (int k = 0; k < 4; ++k) // the synth under the kick (its compressor listens to it)
  4031. s.patterns[0].notes.push_back ({ (std::int64_t) k * lynx::ppq, lynx::ppq - 60, 4, 57 + 3 * k, 0.9f });
  4032. s.patterns[0].sortNotes();
  4033. s.mixer[0].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::limiter));
  4034. s.mixer[1].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::compressor));
  4035. s.mixer[2].toMaster = false;
  4036. s.mixer[2].sends = { lynx::MixerSend { 6, 1.0f } };
  4037. s.mixer[3].sends = { lynx::MixerSend { 7, 0.5f } };
  4038. s.mixer[3].latencyMs = 3.0f;
  4039. s.mixer[4].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::delay));
  4040. s.mixer[4].latencyMs = 5.0f;
  4041. s.mixer[4].sends = { lynx::MixerSend { 6, 0.7f } };
  4042. s.mixer[4].masterLevel = 0.8f;
  4043. auto keyed = lynx::makeEffectSlot (lynx::EffectKind::compressor);
  4044. keyed.params[0] = 0.5f; // (−30 dB: the kick's hits pull the synth down)
  4045. keyed.sidechain = 1;
  4046. s.mixer[5].effects.push_back (keyed);
  4047. s.mixer[6].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::distortion));
  4048. s.mixer[7].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::reverb));
  4049. lynx::Automation a;
  4050. a.target = { lynx::AutomationTargetKind::mixerPan, 3 };
  4051. a.points = { { 0, 0.2f, 0.0f }, { 8 * lynx::ppq, 0.9f, 0.0f } };
  4052. s.automations.push_back (a);
  4053. s.playlist.clear();
  4054. for (int bar = 0; bar < 2; ++bar)
  4055. s.playlist.push_back ({ 0, 0, bar * 4 * lynx::ppq, 4 * lynx::ppq, 0 });
  4056. lynx::Clip automationClip;
  4057. automationClip.kind = lynx::ClipKind::automation;
  4058. automationClip.automation = 0;
  4059. automationClip.length = 8 * lynx::ppq;
  4060. automationClip.track = 1;
  4061. s.playlist.push_back (automationClip);
  4062. s.mode = lynx::PlayMode::song;
  4063. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-stems190gj-" + juce::String (juce::Time::currentTimeMillis()));
  4064. juce::String problems;
  4065. auto run = [&] (lynx::exportopts::Options o, const juce::String& name) {
  4066. o.stems = lynx::exportopts::Stems::mixerTracks;
  4067. o.maxTailSeconds = 3.0;
  4068. const auto alone = dir.getChildFile ("alone"), shared = dir.getChildFile ("shared");
  4069. alone.createDirectory();
  4070. shared.createDirectory();
  4071. const auto ext = juce::String (lynx::exportopts::extension (o.format));
  4072. const auto planAlone = lynx::planStemExport (s, o, alone.getChildFile (name + ext));
  4073. const auto planShared = lynx::planStemExport (s, o, shared.getChildFile (name + ext));
  4074. auto now = [] (std::function<void()> f) { f(); };
  4075. lynx::StemRunStats stats;
  4076. const auto a = lynx::runStemExport (planAlone, now, {}, {}, {}, {}, true);
  4077. const auto b = lynx::runStemExport (planShared, now, {}, {}, {}, {}, false, true, &stats);
  4078. if (a != (int) planAlone.items.size() || b != a)
  4079. problems << name << ": " << a << " / " << b << " files; ";
  4080. // (every insert from the one render, insert 5 with its side-chain too: it stays ducked as in the mix)
  4081. if (stats.passes != 1 || stats.inPass < 6)
  4082. problems << name << ": renders " << stats.passes << " shared, " << stats.inPass << " in it, " << stats.alone << " alone; ";
  4083. for (std::size_t k = 0; k < planShared.items.size() && k < planAlone.items.size(); ++k)
  4084. {
  4085. juce::MemoryBlock x, y;
  4086. planAlone.items[k].file.loadFileAsData (x);
  4087. planShared.items[k].file.loadFileAsData (y);
  4088. if (x.getSize() == 0 || x != y)
  4089. problems << name << ": " << planShared.items[k].file.getFileName() << " differs; ";
  4090. }
  4091. };
  4092. lynx::exportopts::Options streamed;
  4093. streamed.wavBits = 24;
  4094. streamed.stemsIncludeMaster = true;
  4095. run (streamed, "streamed");
  4096. lynx::exportopts::Options buffered;
  4097. buffered.wavBits = 32;
  4098. buffered.normalize = true;
  4099. run (buffered, "buffered");
  4100. dir.deleteRecursively();
  4101. return problems.isEmpty() ? juce::String ("OK") : "ERROR " + problems;
  4102. }
  4103. static juce::String faultReportSelfTest()
  4104. {
  4105. #if (JUCE_WINDOWS && (defined (_M_X64) || defined (__x86_64__))) \
  4106. || ((JUCE_LINUX || JUCE_MAC) && (defined (__x86_64__) || defined (__aarch64__)))
  4107. const auto exe = juce::File::getSpecialLocation (juce::File::currentExecutableFile);
  4108. const auto root = juce::File::getSpecialLocation (juce::File::tempDirectory)
  4109. .getChildFile ("lynx-faulttest-" + juce::String::toHexString (juce::Random::getSystemRandom().nextInt64()));
  4110. juce::StringArray problems;
  4111. #if JUCE_WINDOWS
  4112. const char* const kinds[] = { "plain", "unwalkable" };
  4113. #else
  4114. const char* const kinds[] = { "plain", "guarded", "guarded-libc", "thread", "thread-libc" };
  4115. #endif
  4116. for (const auto* kind : kinds)
  4117. {
  4118. const auto folder = root.getChildFile (kind);
  4119. folder.createDirectory();
  4120. juce::ChildProcess child;
  4121. const auto started = child.start (juce::StringArray { exe.getFullPathName(), "--faulttest", kind, folder.getFullPathName() }, 0);
  4122. if (! started || ! child.waitForProcessToFinish (60000))
  4123. {
  4124. child.kill();
  4125. problems.add (juce::String (kind) + ": " + (started ? "did not end" : "did not start"));
  4126. continue;
  4127. }
  4128. juce::String text;
  4129. for (const auto& file : folder.findChildFiles (juce::File::findFiles, false, "crash *.txt"))
  4130. text = file.loadFileAsString();
  4131. #if JUCE_WINDOWS
  4132. const auto found = text.contains ("0xc0000005");
  4133. #else
  4134. const auto found = text.contains ("segmentation fault") || text.contains ("bus error");
  4135. #endif
  4136. if (folder.getChildFile ("swallowed.txt").existsAsFile())
  4137. problems.add (juce::String (kind) + ": LYNX's own fault was caught as a plugin's ("
  4138. + folder.getChildFile ("swallowed.txt").loadFileAsString() + ")");
  4139. else if (! found)
  4140. problems.add (juce::String (kind) + ": " + (text.isEmpty() ? "no crash file" : "a crash file without the fault")
  4141. + " (exit code 0x" + juce::String::toHexString ((juce::int64) child.getExitCode()) + ")");
  4142. }
  4143. root.deleteRecursively();
  4144. return problems.isEmpty() ? juce::String ("OK") : "ERROR " + problems.joinIntoString ("; ");
  4145. #else
  4146. return "SKIPPED (Windows x64, Linux / macOS x86-64 / ARM64 only)";
  4147. #endif
  4148. }
  4149. void runSelfTest (const juce::String& reportPath, const juce::String& demoProjectPath)
  4150. {
  4151. lynx::AudioEngine offline (false);
  4152. const auto peak = offline.renderOffline (2.0, 48000.0);
  4153. const auto audioOk = peak > 0.01f && peak < 10.0f;
  4154. // project format round trip, with accents in the name
  4155. auto original = lynx::Song::makeDefault();
  4156. original.channels[0].name = "Bumbo ação";
  4157. original.playlist.push_back ({ 0, 2, 3840, 1920, 960 });
  4158. original.mode = lynx::PlayMode::song;
  4159. original.mixer[3].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::delay));
  4160. original.mixer[3].effects[0].params[1] = 0.25f;
  4161. lynx::Automation automation;
  4162. automation.name = "Pan";
  4163. automation.target = { lynx::AutomationTargetKind::effectParam, 3, 0, 1 };
  4164. automation.points = { { 0, 0.25f, 0.5f }, { 3840, 1.0f, 0.0f } };
  4165. original.automations.push_back (automation);
  4166. lynx::Clip automationClip;
  4167. automationClip.kind = lynx::ClipKind::automation;
  4168. automationClip.automation = 0;
  4169. automationClip.track = 4;
  4170. automationClip.length = 3840;
  4171. original.playlist.push_back (automationClip);
  4172. original.loopStart = 960;
  4173. original.loopEnd = 7680;
  4174. original.playlistTracks.resize (3);
  4175. original.playlistTracks[2].colour = 0xFF2A6FDB; // a track colour (round 90)
  4176. { // the clip grid (round 181a)
  4177. lynx::launcher::setClip (original, 1, 2, { 0, 0, 0, 1920, 0 });
  4178. auto& slot = *lynx::launcher::settingsAt (*original.clipGrid, 1, 2);
  4179. slot.name = "Clip ação";
  4180. slot.mode = lynx::LaunchMode::toggle;
  4181. slot.quant = lynx::LaunchQuant::eighthTriplet;
  4182. slot.legato = true;
  4183. slot.loop = false;
  4184. original.clipGrid->scenes[0].name = "Intro";
  4185. original.clipGrid->globalQuant = lynx::LaunchQuant::bars2;
  4186. }
  4187. std::uint32_t savedGroove = 0;
  4188. { // round 190bv: the groove pool, a groove on the slot's clip, and that clip copied and the copy moved
  4189. lynx::Groove g;
  4190. g.name = "Balanço";
  4191. g.base = lynx::GrooveBase::eighth;
  4192. g.quantize = 0.25f;
  4193. g.timing = 0.8f;
  4194. g.random = 0.1f;
  4195. g.velocity = -0.5f;
  4196. g.length = 1920;
  4197. g.points = { { 0, 1.0f }, { 560, 0.5f } };
  4198. savedGroove = lynx::groove::add (original.grooves, g);
  4199. original.grooves.amount = 1.2f;
  4200. lynx::groove::setClipGroove (original, 1, 2, savedGroove);
  4201. lynx::session::moveClip (original, 1, 2, 0, 1, true);
  4202. lynx::session::moveClip (original, 0, 1, 2, 0, false);
  4203. original.playlist[0].groove = savedGroove; // round 190fm: a Playlist pattern clip's groove
  4204. }
  4205. original.playlistTracks[2].grouped = true; // track groups and rack filter groups (round 104)
  4206. original.playlistTracks[1].collapsed = true;
  4207. original.channelGroups = { "Drums", "Keys" };
  4208. original.channels[1].group = 1;
  4209. original.channels[1].cutOthersOnly = original.channels[1].cutAtNoteEnd = true; // FL Studio Mobile's cut rule (round 190fe)
  4210. juce::String error;
  4211. if (demoProjectPath.isNotEmpty()) // sample project for checking the UI with --snapshot
  4212. lynx::ProjectFile::save (original, juce::File (demoProjectPath), error);
  4213. const auto reloaded = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (original), error);
  4214. // round 190bw: FL's curve modes of automation points come back from a project, tension whole; a bent point
  4215. // without a mode (a project saved before the modes: [tick, value, tension]) keeps LYNX's older law
  4216. const auto curveModesOk = [&original] {
  4217. auto song = original;
  4218. auto& a = song.automations[0];
  4219. a.points = { { 0, 0.25f, 0.5f, (std::uint8_t) lynx::flcurve::stairs },
  4220. { 960, 1.0f, -0.123456f, (std::uint8_t) lynx::flcurve::smooth },
  4221. { 1920, 0.5f, 0.0f, (std::uint8_t) lynx::flcurve::hold },
  4222. { 2400, 0.75f, 0.7f, lynx::AutomationPoint::legacyCurve },
  4223. { 2880, 0.3f, 0.0f, 0 },
  4224. { 3840, 0.6f, 0.0f, 0 } };
  4225. a.lfo.on = true;
  4226. a.lfo.amp = { { 0, 1.0f, -0.25f, (std::uint8_t) lynx::flcurve::pulse }, { 960, 0.5f, 0.0f, 0 } };
  4227. juce::String e;
  4228. const auto text = lynx::ProjectFile::toJson (song);
  4229. const auto back = lynx::ProjectFile::fromJson (text, e);
  4230. return back && back->automations.size() == 1 && back->automations[0].points == a.points && back->automations[0].lfo.amp == a.lfo.amp
  4231. && back->automations[0].valueAt (700.0) == a.valueAt (700.0) && back->automations[0].valueAt (2600.0) == a.valueAt (2600.0);
  4232. }();
  4233. const auto projectOk = curveModesOk && reloaded && reloaded->channels.size() == original.channels.size()
  4234. && reloaded->channels[0].name == original.channels[0].name
  4235. && reloaded->patterns[0].notes.size() == original.patterns[0].notes.size()
  4236. && reloaded->patterns[0].notes[3].start == original.patterns[0].notes[3].start
  4237. && reloaded->mode == lynx::PlayMode::song && reloaded->playlist.size() == 2
  4238. && reloaded->clipGrid.has_value() && reloaded->clipGrid->globalQuant == lynx::LaunchQuant::bars2
  4239. && reloaded->clipGrid->scenes.size() == 3 && reloaded->clipGrid->scenes[0].name == "Intro"
  4240. && lynx::launcher::clipAt (*reloaded->clipGrid, 1, 2) != nullptr
  4241. && [&reloaded] {
  4242. auto grid = *reloaded->clipGrid;
  4243. const auto* slot = lynx::launcher::settingsAt (grid, 1, 2);
  4244. return slot != nullptr && slot->name == "Clip ação" && slot->mode == lynx::LaunchMode::toggle
  4245. && slot->quant == lynx::LaunchQuant::eighthTriplet && slot->legato && ! slot->loop;
  4246. }()
  4247. && [&reloaded, &original, savedGroove] { // round 190bv
  4248. auto grid = *reloaded->clipGrid;
  4249. const auto* kept = lynx::launcher::settingsAt (grid, 1, 2);
  4250. const auto* moved = lynx::launcher::settingsAt (grid, 2, 0);
  4251. const auto* clip = lynx::launcher::clipAt (grid, 2, 0);
  4252. return reloaded->grooves == original.grooves && reloaded->grooves.grooves.size() == 1
  4253. && reloaded->grooves.amount == 1.2f && reloaded->grooves.grooves[0].name == "Balanço"
  4254. && reloaded->grooves.grooves[0].points.size() == 2 && savedGroove != 0
  4255. && kept != nullptr && kept->groove == savedGroove
  4256. && lynx::launcher::clipAt (grid, 0, 1) == nullptr
  4257. && clip != nullptr && clip->pattern == 0 && clip->length == 1920
  4258. && moved != nullptr && moved->groove == savedGroove && moved->name == "Clip ação"
  4259. && moved->mode == lynx::LaunchMode::toggle && moved->legato && ! moved->loop
  4260. && reloaded->playlist[0].groove == savedGroove && reloaded->playlist[1].groove == 0; // (190fm)
  4261. }()
  4262. && reloaded->playlist[1].kind == lynx::ClipKind::automation && reloaded->playlist[1].automation == 0
  4263. && reloaded->automations.size() == 1 && reloaded->automations[0].target == automation.target
  4264. && reloaded->automations[0].points.size() == 2 && reloaded->automations[0].points[0].tension == 0.5f
  4265. && reloaded->automations[0].points[1].tick == 3840
  4266. && reloaded->loopStart == 960 && reloaded->loopEnd == 7680
  4267. && reloaded->playlistTracks.size() == 3 && reloaded->playlistTracks[2].colour == 0xFF2A6FDB
  4268. && reloaded->playlistTracks[1].colour == 0
  4269. && reloaded->playlistTracks[2].grouped && reloaded->playlistTracks[1].collapsed && ! reloaded->playlistTracks[1].grouped
  4270. && reloaded->channelGroups == original.channelGroups && reloaded->channels[1].group == 1 && reloaded->channels[0].group == -1
  4271. && reloaded->channels[1].cutOthersOnly && reloaded->channels[1].cutAtNoteEnd && ! reloaded->channels[0].cutOthersOnly
  4272. && ! reloaded->channels[0].cutAtNoteEnd
  4273. && reloaded->playlist[0].offset == 960 && reloaded->playlist[0].track == 2
  4274. && reloaded->mixer[3].effects.size() == 1
  4275. && reloaded->mixer[3].effects[0].kind == lynx::EffectKind::delay
  4276. && reloaded->mixer[3].effects[0].params[1] == 0.25f;
  4277. // round trip of the newer features: synth/sampler with modulation, EQs, utility, markers
  4278. auto rich = lynx::Song::makeDefault();
  4279. auto& synth = rich.channels[4].synth;
  4280. synth.osc[1] = { lynx::Waveform::square, -1, 7.0f, 0.4f, 5, -0.25f };
  4281. synth.filterType = 2;
  4282. synth.mono = true;
  4283. synth.portaBeats = 0.125f;
  4284. synth.am = true;
  4285. synth.filterEnv = { 3.0f, 0.01f, 0.02f, 0.3f, 0.25f, 0.4f };
  4286. synth.lfo[lynx::lfoPitch] = { 0.5f, 0.25f, true, 1, 0.1f, 0.2f };
  4287. auto& sampler = rich.channels[0].sampler;
  4288. sampler.cutoff = 1200.0f;
  4289. sampler.resonance = 0.3f;
  4290. sampler.filterType = 1;
  4291. sampler.pitchEnv = { -12.0f, 0.0f, 0.0f, 0.05f, 0.0f, 0.1f };
  4292. sampler.lfo[lynx::lfoVolume] = { 0.5f, 0.5f, false, 2, 0.0f, 0.0f };
  4293. rich.mixer[2].eq.gainDb = { 3.0f, -2.5f, 1.0f };
  4294. rich.mixer[2].eq.hz[1] = 2200.0f;
  4295. auto peqSlot = lynx::makeEffectSlot (lynx::EffectKind::parametricEq);
  4296. peqSlot.params[(std::size_t) lynx::peq::param (2, 2)] = lynx::peq::gainValue (6.0);
  4297. peqSlot.params[(std::size_t) (lynx::peq::slopeParam + 0)] = lynx::peq::slopeValue (3);
  4298. rich.mixer[2].effects.push_back (peqSlot);
  4299. auto utilitySlot = lynx::makeEffectSlot (lynx::EffectKind::utility);
  4300. utilitySlot.params[1] = 0.2f;
  4301. rich.mixer[2].effects.push_back (utilitySlot);
  4302. auto vocodexSlot = lynx::makeEffectSlot (lynx::EffectKind::vocodex); // FL's raw state travels as base64
  4303. for (int i = 0; i < 300; ++i)
  4304. vocodexSlot.state.push_back ((std::uint8_t) (i * 37));
  4305. vocodexSlot.sidechain = 1;
  4306. vocodexSlot.sidechain2 = 2;
  4307. rich.mixer[3].effects.push_back (vocodexSlot);
  4308. rich.addMarker ({ 3840, "Refrão", 0, 4 });
  4309. rich.addMarker ({ 7680, {}, 7, 8 });
  4310. const auto richBack = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (rich), error);
  4311. auto paramsClose = [] (const lynx::EffectParams& a, const lynx::EffectParams& b) {
  4312. for (std::size_t i = 0; i < a.size(); ++i)
  4313. if (std::abs (a[i] - b[i]) > 1.0e-3f)
  4314. return false;
  4315. return true;
  4316. };
  4317. // round 190bu: a one-knob effect, the chain's Blend and its preset name travel in the project; a project without
  4318. // them reads as before (no goal, Blend 100 %) and writes none of the new keys
  4319. bool fx190buOk = false;
  4320. {
  4321. auto song = lynx::Song::makeDefault();
  4322. const auto plainJson = lynx::ProjectFile::toJson (song);
  4323. const auto* preset = lynx::chains::find ("Whisper Air");
  4324. if (preset != nullptr && song.mixer.size() > 2)
  4325. {
  4326. lynx::chains::apply (song, 1, *preset);
  4327. song.mixer[2].effects.push_back (lynx::goals::make (lynx::goals::room, 0.62f));
  4328. song.mixer[2].effects.push_back (lynx::goals::make (lynx::goals::bass, 0.3f));
  4329. song.mixer[2].chainBlend = 0.4f;
  4330. const auto json = lynx::ProjectFile::toJson (song);
  4331. const auto back = lynx::ProjectFile::fromJson (json, error);
  4332. const auto plainBack = lynx::ProjectFile::fromJson (plainJson, error);
  4333. auto same = back && back->mixer.size() == song.mixer.size();
  4334. for (std::size_t t = 1; same && t <= 2; ++t)
  4335. {
  4336. const auto& a = song.mixer[t];
  4337. const auto& b = back->mixer[t];
  4338. same = a.effects.size() == b.effects.size() && std::abs (a.chainBlend - b.chainBlend) < 1.0e-6f && a.chainPreset == b.chainPreset;
  4339. for (std::size_t i = 0; same && i < a.effects.size(); ++i)
  4340. same = a.effects[i].kind == b.effects[i].kind && a.effects[i].goal == b.effects[i].goal
  4341. && std::abs (a.effects[i].goalAmount - b.effects[i].goalAmount) < 1.0e-6f && a.effects[i].row == b.effects[i].row
  4342. && lynx::goals::active (b.effects[i]) == lynx::goals::active (a.effects[i]);
  4343. }
  4344. fx190buOk = same && lynx::chains::unchanged (*back, 1) && back->mixer[2].chainPreset.empty()
  4345. && ! plainJson.contains ("\"goal\"") && ! plainJson.contains ("chainBlend") && ! plainJson.contains ("chainPreset")
  4346. && json.contains ("\"goalAmount\"") && plainBack && plainBack->mixer[1].chainBlend == 1.0f
  4347. && lynx::ProjectFile::toJson (*back) == json;
  4348. // a user's chain preset file: the slots, Blend and name come back; the strip's level is not part of it
  4349. song.mixer[2].volume = 0.31f;
  4350. const auto file = lynx::ProjectFile::mixerTrackStateToJson (lynx::chains::stateOf (song.mixer[2], "Mine"));
  4351. const auto state = lynx::ProjectFile::mixerTrackStateFromJson (file, error);
  4352. fx190buOk = fx190buOk && state && state->effects.size() == 2 && state->effects[0].goal == lynx::goals::room
  4353. && lynx::goals::active (state->effects[1]) && std::abs (state->chainBlend - 0.4f) < 1.0e-6f && state->chainPreset == "Mine"
  4354. && state->volume == lynx::MixerTrack().volume;
  4355. }
  4356. }
  4357. const auto richOk = fx190buOk && richBack && richBack->channels[4].synth == synth && richBack->channels[0].sampler == sampler
  4358. && richBack->mixer[2].eq == rich.mixer[2].eq && richBack->mixer[2].effects.size() == 2
  4359. && richBack->mixer[2].effects[0].kind == lynx::EffectKind::parametricEq
  4360. && paramsClose (richBack->mixer[2].effects[0].params, peqSlot.params)
  4361. && richBack->mixer[2].effects[1].kind == lynx::EffectKind::utility
  4362. && paramsClose (richBack->mixer[2].effects[1].params, utilitySlot.params)
  4363. && richBack->mixer[3].effects.size() == 1 && richBack->mixer[3].effects[0].kind == lynx::EffectKind::vocodex
  4364. && richBack->mixer[3].effects[0].state == vocodexSlot.state && richBack->mixer[3].effects[0].sidechain2 == 2
  4365. && richBack->markers() == rich.markers();
  4366. // issue #96's per-plugin option: saved only when on; old projects (no field) read as off
  4367. bool hostKeysOk = false;
  4368. {
  4369. auto song = lynx::Song::makeDefault();
  4370. lynx::ChannelDef plugin;
  4371. plugin.instrument = lynx::InstrumentKind::plugin;
  4372. plugin.plugin.id = "x";
  4373. song.channels.push_back (plugin);
  4374. const auto channel = song.channels.size() - 1;
  4375. const auto off = lynx::ProjectFile::toJson (song);
  4376. song.channels[channel].plugin.allowHostKeys = true;
  4377. song.channels[channel].plugin.hostKeysFirst = true;
  4378. song.channels[channel].plugin.pinned = true; // (round 190ao: Pin on top)
  4379. song.channels[channel].plugin.velocityMode = lynx::prefs::pluginVelocityFixed; // (round 190ao: the plugin's own velocity)
  4380. song.channels[channel].plugin.fixedVelocity = 64;
  4381. const auto on = lynx::ProjectFile::toJson (song);
  4382. const auto offBack = lynx::ProjectFile::fromJson (off, error);
  4383. const auto onBack = lynx::ProjectFile::fromJson (on, error);
  4384. hostKeysOk = ! off.contains ("allowHostKeys") && on.contains ("allowHostKeys") && offBack && onBack
  4385. && ! offBack->channels[channel].plugin.allowHostKeys && onBack->channels[channel].plugin.allowHostKeys
  4386. && ! off.contains ("hostKeysFirst") && ! offBack->channels[channel].plugin.hostKeysFirst && onBack->channels[channel].plugin.hostKeysFirst
  4387. && ! off.contains ("pinnedOnTop") && ! offBack->channels[channel].plugin.pinned && onBack->channels[channel].plugin.pinned
  4388. && ! off.contains ("velocityMode") && ! off.contains ("fixedVelocity") && offBack->channels[channel].plugin.velocityMode == 0
  4389. && offBack->channels[channel].plugin.fixedVelocity == lynx::prefs::defaultFixedVelocity
  4390. && onBack->channels[channel].plugin.velocityMode == lynx::prefs::pluginVelocityFixed && onBack->channels[channel].plugin.fixedVelocity == 64;
  4391. }
  4392. // round 190ad: a new project has FL's plugin levels and keeps them through a save; a project saved before
  4393. // (no "pluginLevels") reads as LYNX's own law, and stays so when it opens
  4394. bool pluginLevelsOk = false;
  4395. {
  4396. const auto fresh = lynx::makeNewProject();
  4397. const auto saved = lynx::ProjectFile::toJson (fresh);
  4398. const auto back = lynx::ProjectFile::fromJson (saved, error);
  4399. auto old = lynx::Song::makeDefault(); // (what every earlier version made)
  4400. const auto oldSaved = lynx::ProjectFile::toJson (old);
  4401. const auto oldBack = lynx::ProjectFile::fromJson (oldSaved, error);
  4402. const auto stripped = lynx::ProjectFile::fromJson (saved.replace ("\"pluginLevels\"", "\"pluginLevelsGone\""), error);
  4403. pluginLevelsOk = fresh.flPluginLevels && saved.contains ("\"pluginLevels\"") && back && back->flPluginLevels
  4404. && ! old.flPluginLevels && ! oldSaved.contains ("pluginLevels") && oldBack && ! oldBack->flPluginLevels
  4405. && stripped && ! stripped->flPluginLevels;
  4406. }
  4407. // hardware output targets (REA round 156): saved only when set; old projects (no field) keep the defaults
  4408. bool hwOutOk = false;
  4409. {
  4410. auto song = lynx::Song::makeDefault();
  4411. const auto plain = lynx::ProjectFile::toJson (song);
  4412. song.mixer[0].outputChannel = lynx::outputNone;
  4413. song.mixer[1].outputChannel = 2;
  4414. song.mixer[1].outputMode = lynx::OutputMode::monoRight;
  4415. song.mixer[2].outputChannel = 6;
  4416. song.mixer[3].outputChannel = 4;
  4417. song.mixer[3].outputMode = lynx::OutputMode::monoSum;
  4418. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  4419. const auto plainBack = lynx::ProjectFile::fromJson (plain, error);
  4420. hwOutOk = back && back->mixer[0].outputChannel == lynx::outputNone && back->mixer[1].outputChannel == 2
  4421. && back->mixer[1].outputMode == lynx::OutputMode::monoRight && back->mixer[2].outputChannel == 6
  4422. && back->mixer[2].outputMode == lynx::OutputMode::stereo && back->mixer[3].outputMode == lynx::OutputMode::monoSum
  4423. && back->mixer[4].outputChannel == lynx::outputDefault && ! plain.contains ("\"output\"") && plainBack
  4424. && plainBack->mixer[0].outputChannel == lynx::outputDefault && plainBack->mixer[1].outputChannel == lynx::outputDefault;
  4425. }
  4426. // round 168j: FL's icons (channel / mixer track / playlist track), PDC Automatic / Compensate automations, Time
  4427. // settings, scale highlighting and data folder — saved only when set, old projects load with FL's defaults
  4428. bool flp168jOk = false;
  4429. {
  4430. auto song = lynx::Song::makeDefault();
  4431. const auto plain = lynx::ProjectFile::toJson (song);
  4432. song.channels[0].icon = 75;
  4433. song.mixer[2].icon = 71;
  4434. song.playlistTracks.resize (3);
  4435. song.playlistTracks[2].icon = 30;
  4436. song.autoPdc = false;
  4437. song.compensateAutomations = false;
  4438. song.timeSignatureMode = true;
  4439. song.scaleHighlight = { 10, 5 };
  4440. song.dataFolder = "D:\\Projects\\data";
  4441. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  4442. const auto plainBack = lynx::ProjectFile::fromJson (plain, error);
  4443. flp168jOk = back && back->channels[0].icon == 75 && back->mixer[2].icon == 71 && back->playlistTracks.size() >= 3
  4444. && back->playlistTracks[2].icon == 30 && ! back->autoPdc && ! back->compensateAutomations && back->timeSignatureMode
  4445. && back->scaleHighlight == song.scaleHighlight && back->dataFolder == song.dataFolder && plainBack && plainBack->autoPdc
  4446. && plainBack->compensateAutomations && ! plainBack->timeSignatureMode && plainBack->scaleHighlight == lynx::Song::ScaleHighlight {}
  4447. && plainBack->dataFolder.empty() && plainBack->channels[0].icon == 0 && ! plain.contains ("\"icon\"")
  4448. && ! plain.contains ("autoPdc") && ! plain.contains ("scaleHighlight");
  4449. }
  4450. // round 180d: clip fades take FL's S curve; a project saved before that keeps its straight fades, also after another
  4451. // save, and a clip made in it takes the S curve. FL's fade tensions and stretch mode and PITCH survive a save.
  4452. // issue #122: playlist tracks linked to inserts (audio) and channels (instrument) survive save, load and save
  4453. // again byte for byte (they were read before the mixer and fell back to Unassigned)
  4454. bool trackModes122Ok = false;
  4455. {
  4456. auto song = lynx::Song::makeDefault();
  4457. song.playlistTracks.resize (6);
  4458. song.playlistTracks[1].mode = lynx::PlaylistTrackMode::audio;
  4459. song.playlistTracks[1].mixerTrack = 3;
  4460. song.playlistTracks[4].mode = lynx::PlaylistTrackMode::audio;
  4461. song.playlistTracks[4].mixerTrack = (int) song.mixer.size() - 1;
  4462. song.playlistTracks[5].mode = lynx::PlaylistTrackMode::instrument;
  4463. song.playlistTracks[5].channel = 1;
  4464. song.playlistTracks[5].mixerTrack = 2;
  4465. const auto json = lynx::ProjectFile::toJson (song, false);
  4466. const auto loaded = lynx::ProjectFile::fromJson (json, error);
  4467. const auto again = loaded ? lynx::ProjectFile::toJson (*loaded, false) : juce::String();
  4468. trackModes122Ok = loaded && json.contains ("playlistTrackModes") && again == json && loaded->playlistTracks.size() >= 6
  4469. && loaded->playlistTracks[1].mode == lynx::PlaylistTrackMode::audio && loaded->playlistTracks[1].mixerTrack == 3
  4470. && loaded->playlistTracks[4].mode == lynx::PlaylistTrackMode::audio
  4471. && loaded->playlistTracks[4].mixerTrack == (int) song.mixer.size() - 1
  4472. && loaded->playlistTracks[5].mode == lynx::PlaylistTrackMode::instrument && loaded->playlistTracks[5].channel == 1;
  4473. }
  4474. bool clipFades180dOk = false;
  4475. {
  4476. auto song = lynx::Song::makeDefault();
  4477. lynx::Clip faded;
  4478. faded.kind = lynx::ClipKind::audio;
  4479. faded.channel = 0;
  4480. faded.length = lynx::ppq * 8;
  4481. faded.fadeIn = lynx::ppq;
  4482. faded.fadeOutTension = -812.933f;
  4483. faded.fadeOut = lynx::ppq * 2;
  4484. lynx::Clip plainClip = faded;
  4485. plainClip.fadeIn = plainClip.fadeOut = 0;
  4486. plainClip.fadeOutTension = 0.0f;
  4487. plainClip.start = lynx::ppq * 16;
  4488. song.playlist = { faded, plainClip };
  4489. song.channels[0].sampler.flStretchMode = 5;
  4490. song.channels[0].sampler.flStretchPitch = 247;
  4491. const auto json = lynx::ProjectFile::toJson (song);
  4492. const auto current = lynx::ProjectFile::fromJson (json, error);
  4493. const auto oldJson = json.replace ("\"clipFadesPerClip\"", "\"clipFadesOther\"");
  4494. auto old = lynx::ProjectFile::fromJson (oldJson, error);
  4495. auto resaved = old;
  4496. if (resaved)
  4497. {
  4498. auto added = faded;
  4499. added.start = lynx::ppq * 32;
  4500. added.linearFades = 0;
  4501. resaved->playlist.push_back (added);
  4502. resaved = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (*resaved), error);
  4503. }
  4504. clipFades180dOk = current && old && resaved && json.contains ("clipFadesPerClip") && ! oldJson.contains ("clipFadesPerClip")
  4505. && current->playlist.size() == 2 && ! current->playlist[0].linearFades
  4506. && current->playlist[0].fadeOutTension == -812.933f && ! current->playlist[1].linearFades
  4507. && current->channels[0].sampler.flStretchMode == 5 && current->channels[0].sampler.flStretchPitch == 247
  4508. && old->playlist.size() == 2 && old->playlist[0].linearFades && ! old->playlist[1].linearFades
  4509. && resaved->playlist.size() == 3 && resaved->playlist[0].linearFades && ! resaved->playlist[1].linearFades
  4510. && ! resaved->playlist[2].linearFades && resaved->playlist[0].fadeOutTension == -812.933f;
  4511. }
  4512. // FL's legacy Pattern Blocks (round 170f): the option and every arrangement's blocks are saved; a project without
  4513. // them has neither in its file and loads with the option off
  4514. bool blocksOk = false;
  4515. {
  4516. auto song = lynx::Song::makeDefault();
  4517. const auto plain = lynx::ProjectFile::toJson (song);
  4518. song.patternBlocksOn = true;
  4519. lynx::patternblocks::place (song, 0, 0);
  4520. lynx::patternblocks::place (song, 0, 4 * 4 * lynx::ppq);
  4521. lynx::patternblocks::setMuted (song, 1, true); // (round 190ht, issue #127: a muted block keeps its mute)
  4522. song.addArrangement ("Second");
  4523. lynx::patternblocks::place (song, 0, 2 * 4 * lynx::ppq);
  4524. song.selectArrangement (0);
  4525. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  4526. const auto plainBack = lynx::ProjectFile::fromJson (plain, error);
  4527. blocksOk = back && back->patternBlocksOn && back->blocks == song.blocks && song.blocks.size() == 2 && back->blocks[1].muted
  4528. && back->arrangements.size() == 2 && back->arrangements[1].blocks == song.arrangements[1].blocks
  4529. && song.arrangements[1].blocks.size() == 1 && back->songLength() == song.songLength() && plainBack
  4530. && ! plainBack->patternBlocksOn && plainBack->blocks.empty() && ! plain.contains ("blocks")
  4531. && ! plain.contains ("patternBlocks");
  4532. }
  4533. // FL's pattern clip takeover (issue #158): saved when on; a project saved before it (no key) loads with it off and
  4534. // keeps playing every overlapping clip of a pattern in full; new projects have it on
  4535. bool takeoverOk = false;
  4536. {
  4537. auto song = lynx::Song::makeDefault();
  4538. const auto plain = lynx::ProjectFile::toJson (song);
  4539. song.patternClipTakeover = true;
  4540. const auto json = lynx::ProjectFile::toJson (song);
  4541. const auto back = lynx::ProjectFile::fromJson (json, error);
  4542. const auto plainBack = lynx::ProjectFile::fromJson (plain, error);
  4543. takeoverOk = back && back->patternClipTakeover && json.contains ("patternClipTakeover") && plainBack
  4544. && ! plainBack->patternClipTakeover && ! plain.contains ("patternClipTakeover")
  4545. && lynx::makeNewProject().patternClipTakeover;
  4546. }
  4547. // comping (round 177c): a comp's equal-power crossfades (Clip::fadeCurve) and the crossfade length are saved; a
  4548. // project without them has neither in its file
  4549. bool compOk = false;
  4550. {
  4551. auto song = lynx::Song::makeDefault();
  4552. const auto plain = lynx::ProjectFile::toJson (song);
  4553. lynx::ChannelDef take;
  4554. take.instrument = lynx::InstrumentKind::audioClip;
  4555. take.samplePath = "take.wav";
  4556. song.channels.push_back (take);
  4557. lynx::Clip a;
  4558. a.kind = lynx::ClipKind::audio;
  4559. a.channel = (int) song.channels.size() - 1;
  4560. a.length = lynx::ppq;
  4561. a.fadeOut = 20;
  4562. a.fadeCurve = 2;
  4563. auto b = a;
  4564. b.start = lynx::ppq - 20;
  4565. b.fadeOut = 0;
  4566. b.fadeIn = 20;
  4567. b.fadeCurve = 1;
  4568. // round 180d's FL fade fields (indices 17..20) and the comp curve (index 21) on one clip, all kept
  4569. auto c = a;
  4570. c.start = 4 * lynx::ppq;
  4571. c.fadeIn = 30;
  4572. c.fadeInTension = -0.75f;
  4573. c.fadeOutTension = 0.5f;
  4574. c.linearFades = 2;
  4575. c.flFadeFlags = 0x1234u;
  4576. c.fadeCurve = 3;
  4577. song.playlist = { a, b, c };
  4578. song.compCrossfadeMs = 12.5f;
  4579. song.playlistTracks.resize (2);
  4580. song.playlistTracks[0].compTrack = true;
  4581. song.playlistTracks[1].grouped = true;
  4582. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  4583. const auto plainBack = lynx::ProjectFile::fromJson (plain, error);
  4584. const auto* both = back && back->playlist.size() == 3 ? &back->playlist[2] : nullptr;
  4585. compOk = back && back->playlist.size() == 3 && back->playlist[0].fadeCurve == 2 && back->playlist[1].fadeCurve == 1
  4586. && both != nullptr && both->fadeCurve == 3 && both->fadeInTension == -0.75f && both->fadeOutTension == 0.5f
  4587. && both->linearFades == 2 && both->flFadeFlags == 0x1234u && both->fadeIn == 30
  4588. && back->playlist[1].fadeIn == 20 && back->compCrossfadeMs == 12.5f && back->playlistTracks[0].compTrack && ! back->playlistTracks[1].compTrack && plainBack
  4589. && plainBack->compCrossfadeMs == lynx::Song::defaultCompCrossfadeMs && ! plain.contains ("compCrossfadeMs") && ! plain.contains ("playlistCompTracks");
  4590. }
  4591. // Misc › Mono / Porta / Slide on every generator (round 168l): kept in the file; a project saved before (an
  4592. // imported engine's flags in its synth settings) gets them back, a Max polyphony of 1 is not Mono
  4593. bool polyOk = false;
  4594. {
  4595. auto song = lynx::Song::makeDefault();
  4596. lynx::ChannelDef osc;
  4597. osc.instrument = lynx::InstrumentKind::threeosc;
  4598. osc.misc.mono = osc.misc.porta = true;
  4599. osc.misc.portaBeats = 0.25f;
  4600. song.channels.push_back (osc);
  4601. auto old = osc;
  4602. old.misc = {};
  4603. old.synth.mono = old.synth.porta = true;
  4604. old.synth.portaBeats = 0.5f;
  4605. song.channels.push_back (old);
  4606. old.maxPolyphony = 1;
  4607. song.channels.push_back (old);
  4608. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  4609. const auto n = song.channels.size();
  4610. polyOk = back && back->channels.size() == n && back->channels[n - 3].misc.mono && back->channels[n - 3].misc.porta
  4611. && std::abs (back->channels[n - 3].misc.portaBeats - 0.25f) < 1e-6f && back->channels[n - 2].misc.mono
  4612. && back->channels[n - 2].misc.porta && std::abs (back->channels[n - 2].misc.portaBeats - 0.5f) < 1e-6f
  4613. && ! back->channels[n - 1].misc.mono && back->channels[n - 1].maxPolyphony == 1
  4614. && ! back->channels[4].misc.mono; // (the LYNX Synth keeps its own flags)
  4615. }
  4616. // FL's track latency (REA round 165f-mixer): manual ms, bypass mode and master compensation saved only when set
  4617. bool latencyOk = false;
  4618. {
  4619. auto song = lynx::Song::makeDefault();
  4620. const auto plain = lynx::ProjectFile::toJson (song);
  4621. song.mixer[1].latencyMs = -20.0f;
  4622. song.mixer[2].latencyMs = 12.5f;
  4623. song.mixer[2].latencyBypass = lynx::LatencyBypass::always;
  4624. song.mixer[3].latencyBypass = lynx::LatencyBypass::whenRecordingOrStopped;
  4625. song.mixer[3].compensateMasterLatency = false;
  4626. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  4627. latencyOk = back && back->mixer[1].latencyMs == -20.0f && back->mixer[2].latencyMs == 12.5f
  4628. && back->mixer[2].latencyBypass == lynx::LatencyBypass::always
  4629. && back->mixer[3].latencyBypass == lynx::LatencyBypass::whenRecordingOrStopped && ! back->mixer[3].compensateMasterLatency
  4630. && back->mixer[4].latencyMs == 0.0f && back->mixer[4].compensateMasterLatency
  4631. && ! plain.contains ("latencyMs") && ! plain.contains ("latencyBypass") && ! plain.contains ("compensateMaster");
  4632. }
  4633. // LYNX's pre-fader sends (round 190aq): saved only when one is used, in a list of its own ("preSends") that a
  4634. // version from before ignores (its sends then play post-fader, as FL's)
  4635. bool preSendOk = false;
  4636. {
  4637. auto song = lynx::Song::makeDefault();
  4638. song.setRoute (1, 3, true, 0.5f);
  4639. song.setRoute (1, 4, true);
  4640. song.setRoute (2, 3, true);
  4641. const auto plain = lynx::ProjectFile::toJson (song);
  4642. song.setSendPre (1, 3, true);
  4643. const auto json = lynx::ProjectFile::toJson (song);
  4644. const auto back = lynx::ProjectFile::fromJson (json, error);
  4645. preSendOk = back && back->sendPre (1, 3) && ! back->sendPre (1, 4) && ! back->sendPre (2, 3)
  4646. && std::abs (back->routeLevel (1, 3) - 0.5f) < 1.0e-4f && back->mixer[1].sends == song.mixer[1].sends
  4647. && ! plain.contains ("preSends") && json.contains ("preSends")
  4648. && json.replace ("\"preSends\"", "\"preSendsOld\"") != json;
  4649. // the same file without the list (what an older version reads): the sends are there, post-fader
  4650. if (const auto old = lynx::ProjectFile::fromJson (json.replace ("\"preSends\"", "\"unknownToOldVersions\""), error))
  4651. preSendOk = preSendOk && old->routes (1, 3) && ! old->sendPre (1, 3) && old->mixer[1].sends.size() == 2;
  4652. else
  4653. preSendOk = false;
  4654. }
  4655. // LYNX's "Low latency while recording" (round 190aq): a latency-adding effect on a monitored insert's path is
  4656. // bypassed in the engine only — PDC drops, the slot is marked, the song and the saved project stay as they are —
  4657. // and it is back when the option goes off
  4658. bool lowLatencyOk = false;
  4659. {
  4660. lynx::AudioEngine live (false);
  4661. live.editSong ([] (lynx::Song& s) {
  4662. s.mixer[1].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::limiter)); // 1.5 ms look-ahead
  4663. s.mixer[1].inputChannel = 0;
  4664. s.mixer[1].monitor = lynx::InputMonitor::on;
  4665. });
  4666. const auto before = live.getLatencySamples();
  4667. const auto saved = lynx::ProjectFile::toJson (live.getSong());
  4668. const auto idle = live.lowLatencyBypassedCount() == 0; // the option is off: nothing is bypassed
  4669. auto o = live.getRecordOptions();
  4670. o.lowLatencyRecording = true;
  4671. live.setRecordOptions (o);
  4672. const auto during = live.getLatencySamples();
  4673. const auto marked = live.isSlotLowLatencyBypassed (1, 0) && live.lowLatencyBypassedLatency (1, 0) > 0 && live.lowLatencyBypassedCount() >= 1;
  4674. const auto untouched = live.getSong().mixer[1].effects[0].enabled && lynx::ProjectFile::toJson (live.getSong()) == saved;
  4675. // monitoring leaves "On" (nothing armed): the effect returns
  4676. live.editSong ([] (lynx::Song& s) { s.mixer[1].monitor = lynx::InputMonitor::whenArmed; });
  4677. const auto released = live.getLatencySamples() == before && ! live.isSlotLowLatencyBypassed (1, 0);
  4678. live.editSong ([] (lynx::Song& s) { s.mixer[1].monitor = lynx::InputMonitor::on; });
  4679. const auto again = live.getLatencySamples() == during && live.isSlotLowLatencyBypassed (1, 0);
  4680. o.lowLatencyRecording = false;
  4681. live.setRecordOptions (o);
  4682. lowLatencyOk = before > 0 && idle && during < before && marked && untouched && released && again
  4683. && live.getLatencySamples() == before && live.lowLatencyBypassedCount() == 0;
  4684. }
  4685. // The Browser's "Preview in time" (round 190aq): a loop whose name gives its tempo is stretched to the project's
  4686. // and starts on the beat; a one-shot plays as it always did; off, nothing changes
  4687. bool previewInTimeOk = false;
  4688. double previewPrepareMs = 0.0;
  4689. {
  4690. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest-preview");
  4691. dir.deleteRecursively();
  4692. dir.createDirectory();
  4693. auto writeWav = [&dir] (const juce::String& name, int frames, bool loop) {
  4694. const auto wav = dir.getChildFile (name);
  4695. juce::WavAudioFormat format;
  4696. juce::AudioBuffer<float> audio (1, frames);
  4697. for (int i = 0; i < frames; ++i) // a click on every beat of 120 BPM over a tone, or a decaying hit
  4698. audio.setSample (0, i, loop ? (i % 24000 < 400 ? 0.8f : 0.0f) + 0.1f * std::sin (0.02f * (float) i)
  4699. : 0.6f * std::exp (-(float) i / 2000.0f) * std::sin (0.05f * (float) i));
  4700. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  4701. if (auto* w = format.createWriterFor (out.get(), 48000.0, 1, 16, {}, 0))
  4702. {
  4703. out.release();
  4704. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  4705. writer->writeFromAudioSampleBuffer (audio, 0, frames);
  4706. }
  4707. return wav;
  4708. };
  4709. const auto loop = writeWav ("selftest loop 120 bpm.wav", 96000, true); // 4 beats at 120 BPM
  4710. const auto hit = writeWav ("selftest hit.wav", 14400, false); // 0.3 s
  4711. lynx::AudioEngine player (false);
  4712. const auto projectBpm = player.getTransport().bpm.load();
  4713. // off (FL's preview): nothing is prepared, the file plays as it is
  4714. player.previewFile (loop);
  4715. const auto offOk = ! player.getPreviewTiming().pending && ! player.getPreviewTiming().inTime;
  4716. player.setPreviewInTime (true);
  4717. player.previewFile (hit); // a one-shot: as it always played, at once
  4718. const auto hitOk = ! player.getPreviewTiming().pending && ! player.getPreviewTiming().inTime;
  4719. player.previewFile (loop);
  4720. const auto queued = player.getPreviewTiming().pending || std::abs (projectBpm - 120.0) < 0.2;
  4721. player.finishPreviewJobs();
  4722. const auto timing = player.getPreviewTiming();
  4723. previewPrepareMs = player.getLastPreviewPrepareMs();
  4724. const auto wanted = lynx::previewtempo::stretchRatio (120.0, projectBpm);
  4725. const auto stretchedOk = timing.inTime && ! timing.pending && timing.source == lynx::previewtempo::Source::name
  4726. && std::abs (timing.fileBpm - 120.0) < 1.0e-9 && std::abs (timing.ratio - wanted) < 1.0e-12
  4727. && std::abs ((double) timing.frames - 96000.0 * wanted) < 96000.0 * 0.01;
  4728. // the second click on the same file has its stretch ready
  4729. player.previewFile (loop);
  4730. const auto cachedOk = ! player.getPreviewTiming().pending && player.getPreviewTiming().inTime && player.getPreviewTiming().frames == timing.frames;
  4731. player.previewFile ({});
  4732. const auto stoppedOk = ! player.getPreviewTiming().inTime && player.getPreviewInTimeProgress() < 0.0;
  4733. // the start: on the next heard beat while the transport plays (sample exact), at once when it is stopped
  4734. auto firstSample = [] (bool playing, double startTick, int latency) {
  4735. lynx::Transport transport;
  4736. transport.sampleRate.store (48000.0);
  4737. transport.bpm.store (120.0); // 0.04 ticks per sample
  4738. transport.playing.store (playing);
  4739. transport.positionTicks.store (startTick);
  4740. lynx::PreviewPlayer p;
  4741. p.prepareToPlay (48000.0, 512);
  4742. p.setTransport (&transport);
  4743. p.setSyncLatency (latency);
  4744. auto dc = std::make_shared<lynx::SampleData>();
  4745. dc->sampleRate = 48000.0;
  4746. dc->left.assign (48000, 0.5f);
  4747. p.playBrowser (dc, 1.0f, true);
  4748. juce::AudioBuffer<float> block (2, 512);
  4749. juce::MidiBuffer midi;
  4750. for (int done = 0; done < 48000; done += 512)
  4751. {
  4752. p.processBlock (block, midi);
  4753. for (int i = 0; i < 512; ++i)
  4754. if (block.getSample (0, i) != 0.0f)
  4755. return done + i;
  4756. if (playing)
  4757. transport.positionTicks.store (transport.positionTicks.load() + 512 * transport.ticksPerSample());
  4758. }
  4759. return -1;
  4760. };
  4761. const auto beatOk = firstSample (true, 480.0, 0) == 12000 // half a beat to go: 480 ticks / 0.04
  4762. && firstSample (true, 480.0, 100) == 12100 // the song is heard 100 samples late (PDC)
  4763. && firstSample (true, 960.0, 0) == 0 // on a beat: now
  4764. && firstSample (false, 480.0, 0) == 0; // stopped: a free start
  4765. previewInTimeOk = loop.existsAsFile() && hit.existsAsFile() && offOk && hitOk && queued && stretchedOk && cachedOk && stoppedOk && beatOk;
  4766. dir.deleteRecursively();
  4767. }
  4768. // LYNX substitutes (round 98): a missing plugin's slot plays a built-in equivalent and the project keeps the
  4769. // original reference byte for byte (.flp record and LYNX plugin state)
  4770. bool substituteOk = false;
  4771. {
  4772. auto song = lynx::Song::makeDefault();
  4773. lynx::ForeignPlugin vv; // an .flp VST3 record (ValhallaVintageVerb's class ID), opaque state
  4774. vv.format = lynx::ForeignPlugin::Format::vst3;
  4775. const std::uint8_t cid[] = { 0x76, 0x54, 0x53, 0x56, 0x65, 0x65, 0x76, 0x33, 0x61, 0x6c, 0x68, 0x61, 0x6c, 0x6c, 0x61, 0x76 };
  4776. std::copy (std::begin (cid), std::end (cid), vv.classId.begin());
  4777. vv.hasClassId = true;
  4778. vv.name = "ValhallaVintageVerb";
  4779. vv.path = "C:\\x\\ValhallaVintageVerb.vst3";
  4780. for (int i = 0; i < 777; ++i)
  4781. vv.state.push_back ((std::uint8_t) (i * 13 + 1));
  4782. lynx::EffectSlot fromFlp;
  4783. fromFlp.kind = lynx::EffectKind::plugin;
  4784. fromFlp.plugin.foreign = vv;
  4785. lynx::EffectSlot fromLynx; // a LYNX reference whose plugin isn't installed here
  4786. fromLynx.kind = lynx::EffectKind::plugin;
  4787. fromLynx.plugin.id = "VST3-FabFilter Pro-Q 3-1a2b3c4d-5e6f7a8b";
  4788. fromLynx.plugin.name = "FabFilter Pro-Q 3";
  4789. fromLynx.plugin.state = "AAECAwQFBgcICQ==";
  4790. const auto flpRef = fromFlp.plugin, lynxRef = fromLynx.plugin;
  4791. song.mixer[1].effects = { fromFlp, fromLynx };
  4792. const auto substitutesOn = lynx::pluginSubstitutesEnabled();
  4793. const auto changed = offline.getPluginHost().applySubstitutes (song);
  4794. auto& fx = song.mixer[1].effects;
  4795. // only the LYNX reference is substituted here (an .flp record is the import's job); do the .flp one directly
  4796. const auto flpSubstituted = lynx::substituteEffectSlot (fx[0], lynx::pluginIdentity (vv));
  4797. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  4798. substituteOk = flpSubstituted && fx[0].kind == lynx::EffectKind::epochVerb
  4799. && (! substitutesOn || (changed == 1 && fx[1].kind == lynx::EffectKind::facetEq && fx[1].substituteFor == lynxRef))
  4800. && back && back->mixer[1].effects.size() == 2 && back->mixer[1].effects[0].kind == lynx::EffectKind::epochVerb
  4801. && back->mixer[1].effects[0].substituteFor == flpRef && back->mixer[1].effects[0].substituteFor.foreign.state == vv.state
  4802. && back->mixer[1].effects[1].kind == fx[1].kind && back->mixer[1].effects[1].substituteFor == fx[1].substituteFor;
  4803. }
  4804. // undo/redo
  4805. offline.editSong ([] (lynx::Song& s) { s.bpm = 99.0; });
  4806. offline.editSong ([] (lynx::Song& s) { s.bpm = 101.0; });
  4807. offline.undo();
  4808. const auto afterUndo = offline.getSong().bpm;
  4809. offline.redo();
  4810. const auto undoOk = afterUndo == 99.0 && offline.getSong().bpm == 101.0 && offline.canUndo() && ! offline.canRedo()
  4811. && offline.isModified();
  4812. // Remote-owned steps still behave as ordinary native history when no RemoteControl instance is enabled.
  4813. // Only API undo/redo refuse device drift; remote reads, staging and publication never hold the audio-device callback lock.
  4814. const auto remoteHistoryResult = []() -> juce::String {
  4815. int checks = 0;
  4816. const auto require = [&] (bool condition, const char* message) {
  4817. ++checks;
  4818. if (! condition) throw std::runtime_error (message);
  4819. };
  4820. try
  4821. {
  4822. for (const auto session : { false, true })
  4823. {
  4824. lynx::AudioEngine history (false);
  4825. lynx::Song initial;
  4826. initial.channels.resize (1);
  4827. initial.channels[0].instrument = lynx::InstrumentKind::synth;
  4828. initial.mixer = lynx::Song::defaultMixer (1);
  4829. initial.bpm = 120.0;
  4830. history.setSong (std::move (initial));
  4831. history.setSessionHistory (session);
  4832. const auto editTempo = [&] (double bpm) {
  4833. require (history.editSongRemoteTransaction ([&] (lynx::Song& s) { s.bpm = bpm; }), "remote tempo edit was not committed");
  4834. };
  4835. const auto refused = [&] (const std::function<void()>& operation) {
  4836. const auto position = history.getHistoryPosition();
  4837. const auto before = lynx::ProjectFile::toJsonExact (history.getSong());
  4838. bool changed = false;
  4839. try { operation(); }
  4840. catch (const lynx::RemoteError& e) { changed = e.code == "changed" && ! e.uncertain; }
  4841. require (changed, "API history did not refuse untracked device changes");
  4842. require (history.getHistoryPosition() == position && lynx::ProjectFile::toJsonExact (history.getSong()) == before,
  4843. "refused API history changed the project or history position");
  4844. };
  4845. const auto withoutDeviceLock = [&] (const std::function<void()>& operation) {
  4846. juce::WaitableEvent locked, release;
  4847. bool timedOut = false;
  4848. std::thread callback ([&] {
  4849. const juce::ScopedLock lock (history.getDeviceManager().getAudioCallbackLock());
  4850. locked.signal();
  4851. timedOut = ! release.wait (3000);
  4852. });
  4853. const auto acquired = locked.wait (3000);
  4854. std::exception_ptr failure;
  4855. try { if (acquired) operation(); }
  4856. catch (...) { failure = std::current_exception(); }
  4857. release.signal();
  4858. callback.join();
  4859. // Check before rethrowing: an expected rejection must not conceal waiting for this lock.
  4860. require (acquired && ! timedOut, "remote read, edit or history publication waited for the audio-device callback lock");
  4861. if (failure) std::rethrow_exception (failure);
  4862. };
  4863. const auto baseline = lynx::ProjectFile::toJsonExact (history.getSong());
  4864. const auto baselineStamp = history.getSongStamp();
  4865. const auto baselinePosition = history.getHistoryPosition();
  4866. const auto unchanged = [&] {
  4867. return history.getSongStamp() == baselineStamp && history.getHistoryPosition() == baselinePosition
  4868. && lynx::ProjectFile::toJsonExact (history.getSong()) == baseline;
  4869. };
  4870. withoutDeviceLock ([&] {
  4871. require (lynx::ProjectFile::toJsonExact (history.snapshotForRemoteControl()) == baseline,
  4872. "remote snapshot changed the project");
  4873. require (history.remoteDeviceStateHash().isNotEmpty(), "remote snapshot did not hash device state");
  4874. });
  4875. require (unchanged(), "remote reads changed the project, revision or history");
  4876. bool staged = false;
  4877. withoutDeviceLock ([&] {
  4878. require (! history.editSongRemoteTransaction ([&] (lynx::Song&) { staged = true; }),
  4879. "remote no-op committed a history step");
  4880. });
  4881. require (staged && unchanged(), "remote no-op did not stage cleanly without changing history");
  4882. bool rejected = false;
  4883. try {
  4884. withoutDeviceLock ([&] {
  4885. history.editSongRemoteTransaction ([] (lynx::Song& next) {
  4886. next.bpm = 999.0;
  4887. throw lynx::RemoteError ("invalid", "selftest stage rejection");
  4888. });
  4889. });
  4890. }
  4891. catch (const lynx::RemoteError& e) { rejected = e.code == "invalid" && ! e.uncertain; }
  4892. require (rejected && unchanged(), "rejected staging changed the project, revision or history");
  4893. for (const auto cancelAfterStage : { false, true })
  4894. {
  4895. int calls = 0;
  4896. staged = false;
  4897. bool cancelledEdit = false;
  4898. try {
  4899. withoutDeviceLock ([&] {
  4900. history.editSongRemoteTransaction ([&] (lynx::Song& next) { staged = true; next.bpm = 999.0; },
  4901. [&] { return ++calls >= (cancelAfterStage ? 2 : 1); });
  4902. });
  4903. }
  4904. catch (const lynx::RemoteError& e) { cancelledEdit = e.code == "failed" && ! e.uncertain; }
  4905. require (cancelledEdit && staged == cancelAfterStage && unchanged(),
  4906. "cancelled edit changed the project, revision or history");
  4907. }
  4908. withoutDeviceLock ([&] { editTempo (130.0); });
  4909. require (history.getSong().bpm == 130.0 && history.getHistoryPosition() == baselinePosition + 1
  4910. && history.getSongStamp() > baselineStamp, "remote commit did not publish one history step");
  4911. history.editSong ([] (lynx::Song& s) { s.channels[0].volume = 0.23f; }, false);
  4912. refused ([&] { history.undoRemoteControl(); });
  4913. withoutDeviceLock ([&] { history.undo(); });
  4914. require (history.getHistoryPosition() == 0 && history.getSong().bpm == 120.0 && history.getRemoteHistoryError().isEmpty(),
  4915. "native undo refused device drift while remote control was disabled");
  4916. history.editSong ([] (lynx::Song& s) { s.channels[0].name = "Untracked change"; }, false);
  4917. refused ([&] { history.redoRemoteControl(); });
  4918. withoutDeviceLock ([&] { history.redo(); });
  4919. require (history.getHistoryPosition() == 1 && history.getSong().bpm == 130.0 && history.getRemoteHistoryError().isEmpty(),
  4920. "native redo refused device drift while remote control was disabled");
  4921. withoutDeviceLock ([&] { editTempo (140.0); });
  4922. history.editSong ([] (lynx::Song& s) { s.channels[0].volume = 0.42f; }, false);
  4923. withoutDeviceLock ([&] { history.jumpToHistory (0); });
  4924. require (history.getHistoryPosition() == 0 && history.getSong().bpm == 120.0, "native history jump stopped at a remote step");
  4925. withoutDeviceLock ([&] { history.jumpToHistory (2); });
  4926. require (history.getHistoryPosition() == 2 && history.getSong().bpm == 140.0, "native redo jump stopped at a remote step");
  4927. withoutDeviceLock ([&] { history.undoRemoteControl(); });
  4928. require (history.getHistoryPosition() == 1 && history.getSong().bpm == 130.0, "API undo failed with an unchanged device fence");
  4929. withoutDeviceLock ([&] { history.redoRemoteControl(); });
  4930. require (history.getHistoryPosition() == 2 && history.getSong().bpm == 140.0, "API redo failed with an unchanged device fence");
  4931. int cancelledChecks = 0;
  4932. bool cancelled = false;
  4933. try { history.undoRemoteControl ([&] { return ++cancelledChecks >= 2; }); }
  4934. catch (const lynx::RemoteError& e) { cancelled = e.code == "failed" && ! e.uncertain; }
  4935. require (cancelled && history.getHistoryPosition() == 2 && history.getSong().bpm == 140.0,
  4936. "cancelled API history moved a step");
  4937. withoutDeviceLock ([&] { history.undo(); });
  4938. require (history.getHistoryPosition() == 1 && history.getSong().bpm == 130.0 && history.getRemoteHistoryError().isEmpty(),
  4939. "API cancellation leaked into native history");
  4940. }
  4941. return "OK (" + juce::String (checks) + " checks)";
  4942. }
  4943. catch (const std::exception& e) { return "ERROR " + juce::String::fromUTF8 (e.what()); }
  4944. }();
  4945. // Hosted state access and processing share a per-instance lock, including fixed blocks and deferred resets.
  4946. const auto hostedStateLockResult = []() -> juce::String {
  4947. struct Probe final : juce::AudioPluginInstance
  4948. {
  4949. struct Parameter final : juce::HostedAudioProcessorParameter
  4950. {
  4951. explicit Parameter (Probe& p) : owner (p) {}
  4952. float getValue() const override { owner.access (owner.parameterReads); return value.load(); }
  4953. void setValue (float v) override { owner.access (owner.parameterWrites); value.store (v); }
  4954. float getDefaultValue() const override { return 0.0f; }
  4955. juce::String getName (int) const override { return "Value"; }
  4956. juce::String getLabel() const override { return {}; }
  4957. juce::String getParameterID() const override { return "value"; }
  4958. float getValueForText (const juce::String& text) const override { return text.getFloatValue(); }
  4959. Probe& owner;
  4960. std::atomic<float> value { 0.0f };
  4961. };
  4962. Probe() : AudioPluginInstance (BusesProperties().withInput ("Input", juce::AudioChannelSet::stereo(), true)
  4963. .withOutput ("Output", juce::AudioChannelSet::stereo(), true))
  4964. {
  4965. addHostedParameter (std::make_unique<Parameter> (*this));
  4966. }
  4967. const juce::String getName() const override { return "State lock probe"; }
  4968. void fillInPluginDescription (juce::PluginDescription& d) const override { d.name = getName(); }
  4969. void prepareToPlay (double, int) override {}
  4970. void releaseResources() override {}
  4971. void processBlock (juce::AudioBuffer<float>& audio, juce::MidiBuffer&) override { access (blocks); audio.clear(); }
  4972. void reset() override { access (resets, std::this_thread::get_id() == ui); } // (on the UI thread: the export reset)
  4973. double getTailLengthSeconds() const override { return 0.0; }
  4974. bool acceptsMidi() const override { return true; }
  4975. bool producesMidi() const override { return false; }
  4976. bool hasEditor() const override { return false; }
  4977. juce::AudioProcessorEditor* createEditor() override { return nullptr; }
  4978. int getNumPrograms() override { return 1; }
  4979. int getCurrentProgram() override { return 0; }
  4980. void setCurrentProgram (int) override {}
  4981. const juce::String getProgramName (int) override { return {}; }
  4982. void changeProgramName (int, const juce::String&) override {}
  4983. void getStateInformation (juce::MemoryBlock& state) override { access (captures); state.replaceAll ("state", 5); }
  4984. void setStateInformation (const void*, int) override { access (restores, true); }
  4985. // Round 190ha: only a restore and the export reset are exclusive with the audio side. A capture and the
  4986. // UI's parameter changes run beside processing, as on JUCE's own hosts (UI-thread calls never overlap
  4987. // each other here: they run in turn).
  4988. void access (std::atomic<int>& calls, bool exclusive = false)
  4989. {
  4990. ++calls;
  4991. if (exclusive)
  4992. {
  4993. ++exclusiveActive;
  4994. if (active.fetch_add (1) != 0) overlap = true;
  4995. }
  4996. else
  4997. {
  4998. ++active;
  4999. if (exclusiveActive.load() != 0) overlap = true;
  5000. }
  5001. juce::Thread::sleep (1); // widen the concurrent vendor-call window without using real plugins
  5002. --active;
  5003. if (exclusive) --exclusiveActive;
  5004. }
  5005. const std::thread::id ui = std::this_thread::get_id();
  5006. std::atomic<int> active { 0 }, exclusiveActive { 0 }, blocks { 0 }, resets { 0 }, captures { 0 }, restores { 0 };
  5007. std::atomic<int> parameterReads { 0 }, parameterWrites { 0 };
  5008. std::atomic<bool> overlap { false };
  5009. };
  5010. int checks = 0;
  5011. const auto require = [&] (bool condition, const char* message) {
  5012. ++checks;
  5013. if (! condition) throw std::runtime_error (message);
  5014. };
  5015. const auto exercise = [&] (auto& adapter, Probe& probe, const auto& render, const auto& reset) {
  5016. const auto saved = adapter.captureState();
  5017. require (saved.has_value(), "mock hosted state could not be captured");
  5018. juce::WaitableEvent start (true);
  5019. std::thread audio ([&] {
  5020. start.wait();
  5021. for (int i = 0; i < 32; ++i)
  5022. {
  5023. adapter.setParameter (0, i % 2 == 0 ? 0.25f : 0.75f);
  5024. (void) adapter.parameterValue (0);
  5025. reset();
  5026. render();
  5027. }
  5028. });
  5029. const juce::ScopeGuard joinAudio { [&] { if (audio.joinable()) audio.join(); } };
  5030. start.signal();
  5031. bool stateOk = true;
  5032. for (int i = 0; i < 32; ++i)
  5033. {
  5034. stateOk = adapter.captureState().has_value() && stateOk;
  5035. stateOk = adapter.restoreState (*saved) && stateOk;
  5036. adapter.setParameterFromUi (0, i % 2 == 0 ? 0.1f : 0.9f);
  5037. if (i % 8 == 0) adapter.resetForExport();
  5038. }
  5039. audio.join();
  5040. // Contended audio callbacks may all have bypassed while state was held.
  5041. // Exercise a successful callback after release before checking coverage.
  5042. adapter.setParameter (0, 0.5f);
  5043. (void) adapter.parameterValue (0);
  5044. reset();
  5045. render();
  5046. require (stateOk && probe.blocks > 0 && probe.resets > 0 && probe.captures > 0 && probe.restores > 0,
  5047. "mock did not exercise processing, resets and hosted state access");
  5048. require (probe.parameterReads > 0 && probe.parameterWrites > 0,
  5049. "mock did not exercise concurrent hosted parameter access");
  5050. require (! probe.overlap, "hosted processing/reset/parameters overlapped a state restore or the export reset");
  5051. require (! adapter.hasCrashed(), "mock hosted adapter crashed");
  5052. };
  5053. try
  5054. {
  5055. for (const auto fixed : { 0, 64 })
  5056. {
  5057. std::array<float, 128> left {}, right {};
  5058. auto instrument = std::make_unique<Probe>();
  5059. auto* instrumentProbe = instrument.get();
  5060. lynx::PluginInstrument voice (std::move (instrument), 128, fixed);
  5061. exercise (voice, *instrumentProbe, [&] { voice.render (left.data(), right.data(), 128, 1.0f, 1.0f); }, [&] { voice.panic(); });
  5062. auto effect = std::make_unique<Probe>();
  5063. auto* effectProbe = effect.get();
  5064. lynx::PluginEffect fx (std::move (effect), 128, fixed);
  5065. exercise (fx, *effectProbe, [&] { fx.process (left.data(), right.data(), 128, {}, 120.0); }, [&] { fx.transportReset(); });
  5066. }
  5067. return "OK (" + juce::String (checks) + " checks)";
  5068. }
  5069. catch (const std::exception& e) { return "ERROR " + juce::String::fromUTF8 (e.what()); }
  5070. }();
  5071. const auto hostedStateContentionResult = lynx::pluginStateContentionSelfTest();
  5072. // recording from the PC keyboard: a one-beat note lands in the pattern, in a single undo step
  5073. // (Blend on: this checks that the take joins the pattern's notes; a new install starts with Blend off)
  5074. const auto notesBefore = offline.getSong().patterns[0].notes.size();
  5075. {
  5076. auto o = offline.getRecordOptions();
  5077. o.mode = lynx::RecordMode::overdub;
  5078. offline.setRecordOptions (o);
  5079. }
  5080. offline.setRecording (true);
  5081. offline.play();
  5082. offline.getTransport().positionTicks.store (960.0);
  5083. offline.sendLiveNote (2, 72, 0.9f, true, true);
  5084. offline.getTransport().positionTicks.store (1920.0);
  5085. offline.sendLiveNote (2, 72, 0.0f, false, true);
  5086. offline.setRecording (false);
  5087. offline.stop();
  5088. const auto& recorded = offline.getSong().patterns[0].notes;
  5089. const auto recordOk = recorded.size() == notesBefore + 1
  5090. && std::any_of (recorded.begin(), recorded.end(), [] (const lynx::Note& n) {
  5091. return n.key == 72 && n.channel == 2 && n.length == 960 && n.start >= 960 && n.start < 3840;
  5092. });
  5093. offline.undo();
  5094. const auto recordUndoOk = offline.getSong().patterns[0].notes.size() == notesBefore;
  5095. // FL's Tools › Cancel recording (round 187a): the pass's notes go, an edit made before it stays, recording turns
  5096. // off and playback goes on; nothing to redo
  5097. bool cancelRecordOk = false;
  5098. {
  5099. offline.editSong ([] (lynx::Song& s) { s.bpm = 123.0; });
  5100. const auto notesThen = offline.getSong().patterns[0].notes.size();
  5101. offline.setRecording (true);
  5102. offline.play();
  5103. offline.getTransport().positionTicks.store (960.0);
  5104. offline.sendLiveNote (2, 74, 0.9f, true, true);
  5105. offline.getTransport().positionTicks.store (1920.0);
  5106. offline.sendLiveNote (2, 74, 0.0f, false, true);
  5107. offline.sendLiveNote (2, 76, 0.9f, true, true); // (still held when the pass is cancelled)
  5108. const auto cancelled = offline.cancelRecording();
  5109. cancelRecordOk = cancelled && ! offline.isRecording() && offline.getTransport().playing.load()
  5110. && offline.getSong().patterns[0].notes.size() == notesThen && offline.getSong().bpm == 123.0 && ! offline.canRedo()
  5111. && ! offline.cancelRecording(); // (not recording: nothing to cancel)
  5112. offline.sendLiveNote (2, 76, 0.0f, false, false);
  5113. offline.stop();
  5114. }
  5115. // MIDI: exporting the pattern and importing it back gives the same notes
  5116. bool midiOk = false;
  5117. {
  5118. auto source = lynx::Song::makeDefault();
  5119. source.patterns[0].notes.push_back ({ 1000, 480, 4, 67, 0.5f });
  5120. source.patterns[0].sortNotes();
  5121. const auto midiFile = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest.mid");
  5122. juce::String midiError;
  5123. const auto saved = lynx::MidiFileIo::savePattern (source, 0, midiFile, midiError);
  5124. const auto song = saved ? lynx::MidiFileIo::loadSong (midiFile, midiError) : std::nullopt;
  5125. midiFile.deleteFile();
  5126. if (song && song->patterns.size() == 1 && song->patterns[0].notes.size() == source.patterns[0].notes.size()
  5127. && std::abs (song->bpm - source.bpm) < 0.01)
  5128. {
  5129. midiOk = true;
  5130. const auto& a = source.patterns[0].notes;
  5131. const auto& b = song->patterns[0].notes;
  5132. for (std::size_t i = 0; i < a.size(); ++i)
  5133. midiOk = midiOk && a[i].start == b[i].start && a[i].key == b[i].key && a[i].length == b[i].length;
  5134. }
  5135. }
  5136. // project package (REA round 118): a project with a sample exported as .zip, extracted and opened again,
  5137. // finds its sample inside the extracted folder
  5138. bool packageOk = false;
  5139. {
  5140. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest-package");
  5141. dir.deleteRecursively();
  5142. dir.getChildFile ("src").createDirectory();
  5143. const auto wav = dir.getChildFile ("src/hit.wav");
  5144. {
  5145. juce::WavAudioFormat format;
  5146. juce::AudioBuffer<float> hit (1, 480);
  5147. for (int i = 0; i < 480; ++i)
  5148. hit.setSample (0, i, 0.5f * std::sin (0.1f * (float) i));
  5149. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  5150. if (auto* w = format.createWriterFor (out.get(), 48000.0, 1, 16, {}, 0))
  5151. {
  5152. out.release();
  5153. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  5154. writer->writeFromAudioSampleBuffer (hit, 0, 480);
  5155. }
  5156. }
  5157. auto source = lynx::Song::makeDefault();
  5158. lynx::ChannelDef c;
  5159. c.name = "Hit";
  5160. c.instrument = lynx::InstrumentKind::sampler;
  5161. c.samplePath = wav.getFullPathName().toStdString();
  5162. source.channels.push_back (c);
  5163. lynx::ProjectPackage::Result packed;
  5164. juce::String packageError;
  5165. const auto zip = dir.getChildFile ("Beat.zip");
  5166. if (wav.existsAsFile() && lynx::ProjectPackage::exportZip (source, "Beat", zip, packed, packageError) && packed.files == 1)
  5167. {
  5168. const auto project = lynx::ProjectPackage::extractZip (zip, dir.getChildFile ("out"), packageError);
  5169. const auto song = project.existsAsFile() ? lynx::ProjectFile::load (project, packageError) : std::nullopt;
  5170. if (song && ! song->channels.empty())
  5171. {
  5172. const juce::File back (juce::String::fromUTF8 (song->channels.back().samplePath.c_str()));
  5173. packageOk = back.existsAsFile() && back.isAChildOf (project.getParentDirectory()) && back.getSize() == wav.getSize();
  5174. }
  5175. }
  5176. dir.deleteRecursively();
  5177. }
  5178. // D#92, round 180a: a non-ASCII folder and a dotted name save and load back; an unwritable place says so, and a
  5179. // relative path resolves as the start-up argument does
  5180. bool projectSaveOk = false;
  5181. {
  5182. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest-save180a");
  5183. dir.deleteRecursively();
  5184. const auto folder = dir.getChildFile (juce::String::fromUTF8 ("M\xc3\xbasica nova"));
  5185. folder.createDirectory();
  5186. const auto named = lynx::ProjectFile::withProjectExtension (folder.getChildFile (juce::String::fromUTF8 ("Can\xc3\xa7\xc3\xa3o.v2")));
  5187. auto song = lynx::Song::makeDefault();
  5188. lynx::Note note;
  5189. note.length = 240;
  5190. note.key = 64;
  5191. song.patterns[0].notes.push_back (note);
  5192. juce::String error, blockedError;
  5193. const auto again = lynx::ProjectFile::save (song, named, error) ? lynx::ProjectFile::load (named, error) : std::nullopt;
  5194. const auto blocker = dir.getChildFile ("a file");
  5195. blocker.replaceWithText ("x");
  5196. const auto cwd = juce::File::getCurrentWorkingDirectory();
  5197. folder.setAsCurrentWorkingDirectory();
  5198. const auto relative = juce::File::getCurrentWorkingDirectory().getChildFile (named.getFileName());
  5199. cwd.setAsCurrentWorkingDirectory();
  5200. projectSaveOk = named.getFileName().endsWith (".v2.lynx") && again && again->patterns[0].notes.size() == song.patterns[0].notes.size()
  5201. && relative == named && ! lynx::ProjectFile::save (song, blocker.getChildFile ("x.lynx"), blockedError)
  5202. && blockedError.isNotEmpty() && lynx::ProjectFile::withProjectExtension (named) == named;
  5203. dir.deleteRecursively();
  5204. }
  5205. // Online Sessions (round 168a): a project sent as a .lynxpack (one sample used twice is stored once, the uids
  5206. // survive), a stand-in rendered through an ExportJob, the guest's part sent back and merged by the host
  5207. juce::String sessionResult = "ERROR";
  5208. {
  5209. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest-session");
  5210. dir.deleteRecursively();
  5211. dir.getChildFile ("src").createDirectory();
  5212. const auto wav = dir.getChildFile ("src/hit.wav");
  5213. {
  5214. juce::WavAudioFormat format;
  5215. juce::AudioBuffer<float> hit (1, 4800);
  5216. for (int i = 0; i < 4800; ++i)
  5217. hit.setSample (0, i, 0.5f * std::sin (0.05f * (float) i) * (1.0f - (float) i / 4800.0f));
  5218. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  5219. if (auto* w = format.createWriterFor (out.get(), 48000.0, 1, 16, {}, 0))
  5220. {
  5221. out.release();
  5222. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  5223. writer->writeFromAudioSampleBuffer (hit, 0, 4800);
  5224. }
  5225. }
  5226. auto host = lynx::Song::makeDefault();
  5227. host.mode = lynx::PlayMode::song;
  5228. const auto copyOfWav = dir.getChildFile ("src/hit copy.wav"); // the same bytes under another name: stored once
  5229. wav.copyFileTo (copyOfWav);
  5230. for (const auto& [name, file] : { std::pair<const char*, juce::File> { "Hit", wav }, { "Hit 2", copyOfWav } })
  5231. {
  5232. lynx::ChannelDef c;
  5233. c.name = name;
  5234. c.instrument = lynx::InstrumentKind::sampler;
  5235. c.samplePath = file.getFullPathName().toStdString();
  5236. host.channels.push_back (c);
  5237. }
  5238. const auto hitChannel = (int) host.channels.size() - 2;
  5239. lynx::Note hitNote;
  5240. hitNote.channel = hitChannel;
  5241. hitNote.length = 480;
  5242. host.patterns[0].notes.push_back (hitNote);
  5243. host.playlist.push_back ({ 0, 0, 0, host.patterns[0].effectiveLength (host.meter()), 0 });
  5244. lynx::uids::normalize (host);
  5245. const auto* guest = lynx::parts::invite (host, "Host", "Ana", 0xFF3D9BE9, false);
  5246. juce::String e;
  5247. std::vector<lynx::sessionpack::Rendered> rendered;
  5248. // (a sampler stands in for a plugin channel here: render() renders whatever it is given)
  5249. const std::vector<lynx::sessionpack::RenderItem> items { { false, hitChannel, false, "Hit", "Test" } };
  5250. const auto renderedOk = guest != nullptr && lynx::sessionpack::render (host, items, 44100.0, dir.getChildFile ("stems"), "Host", rendered, {}, e)
  5251. && rendered.size() == 1 && rendered[0].standIns.size() == 2
  5252. && juce::File (juce::String::fromUTF8 (rendered[0].standIns[0].path.c_str())).getSize() > 1000;
  5253. if (renderedOk)
  5254. lynx::sessionpack::apply (host, rendered);
  5255. lynx::sessionpack::Manifest m;
  5256. m.projectName = "Selftest";
  5257. m.from = *host.session.find (lynx::session::hostTag);
  5258. m.to = *host.session.find (2);
  5259. lynx::sessionpack::WriteResult written;
  5260. const auto pack = dir.getChildFile (juce::String ("Selftest") + lynx::sessionpack::extension);
  5261. const auto packOk = renderedOk && lynx::sessionpack::write (lynx::parts::guestCopy (host, 2), m, offline.getPluginHost(), pack, written, e)
  5262. && written.media == 3 && written.duplicates == 1; // the sample once (used twice), the stand-in pair
  5263. auto opened = packOk ? lynx::sessionpack::open (pack, dir.getChildFile ("received"), e) : std::nullopt;
  5264. bool openOk = false, mergeOk = false;
  5265. if (opened && opened->corrupt.isEmpty())
  5266. {
  5267. const auto& g = opened->song;
  5268. const juce::File sample (juce::String::fromUTF8 (g.channels[(std::size_t) hitChannel].samplePath.c_str()));
  5269. openOk = g.session.me == 2 && g.projectId == host.projectId && g.channels[(std::size_t) hitChannel].uid == host.channels[(std::size_t) hitChannel].uid
  5270. && sample.existsAsFile() && sample.isAChildOf (opened->folder) && g.channels[(std::size_t) hitChannel].standIns.size() == 2
  5271. && juce::File (juce::String::fromUTF8 (g.channels[(std::size_t) hitChannel].standIns[1].path.c_str())).existsAsFile();
  5272. // the guest adds a channel and a pattern of his own, sends his part back
  5273. auto copy = g;
  5274. lynx::ChannelDef mine;
  5275. mine.name = "Ana's hit";
  5276. mine.instrument = lynx::InstrumentKind::sampler;
  5277. mine.samplePath = sample.getFullPathName().toStdString();
  5278. copy.channels.push_back (mine);
  5279. lynx::Pattern p;
  5280. p.name = "Ana";
  5281. lynx::Note note;
  5282. note.channel = (int) copy.channels.size() - 1;
  5283. note.length = 240;
  5284. note.key = 64;
  5285. p.notes.push_back (note);
  5286. copy.patterns.push_back (p);
  5287. lynx::uids::normalize (copy);
  5288. // its uids survive a save and a load
  5289. const auto saved = dir.getChildFile ("guest.lynx");
  5290. auto reloaded = lynx::ProjectFile::save (copy, saved, e) ? lynx::ProjectFile::load (saved, e) : std::nullopt;
  5291. lynx::sessionpack::Manifest back;
  5292. back.part = true;
  5293. back.from = *copy.session.self();
  5294. const auto partFile = dir.getChildFile (juce::String ("Ana part") + lynx::sessionpack::extension);
  5295. lynx::sessionpack::WriteResult partWritten;
  5296. auto part = reloaded && reloaded->channels.back().uid == copy.channels.back().uid && lynx::uids::tagOf (reloaded->channels.back().uid) == 2
  5297. ? lynx::sessionpack::write (lynx::parts::extract (*reloaded, 2), back, offline.getPluginHost(), partFile, partWritten, e)
  5298. : false;
  5299. auto partOpened = part ? lynx::sessionpack::open (partFile, dir.getChildFile ("parts"), e) : std::nullopt;
  5300. if (partOpened && partOpened->manifest.part && lynx::sessionpack::adoptMedia (partOpened->song, dir.getChildFile ("Session media/Ana"), e))
  5301. {
  5302. const auto report = lynx::parts::merge (host, partOpened->song, 2);
  5303. const auto& added = host.channels.back();
  5304. mergeOk = report.ok && report.channels >= 1 && added.name == "Ana's hit" && lynx::uids::tagOf (added.uid) == 2
  5305. && juce::File (juce::String::fromUTF8 (added.samplePath.c_str())).isAChildOf (dir.getChildFile ("Session media/Ana"))
  5306. && host.channels[(std::size_t) hitChannel].name == "Hit";
  5307. }
  5308. }
  5309. // a crafted package whose project points at a file elsewhere on this computer: opening it must not
  5310. // reach that file, or merging would copy it into the project and the next package would send it on
  5311. if (mergeOk)
  5312. {
  5313. const auto secret = dir.getChildFile ("secret.wav");
  5314. wav.copyFileTo (secret);
  5315. auto evil = lynx::Song::makeDefault();
  5316. lynx::ChannelDef c;
  5317. c.instrument = lynx::InstrumentKind::sampler;
  5318. c.samplePath = secret.getFullPathName().toStdString();
  5319. evil.channels.push_back (c);
  5320. lynx::ChannelDef keys; // (FL Keys' zones are read by the engine but are not in the media list)
  5321. keys.instrument = lynx::InstrumentKind::flkeys;
  5322. keys.zones.push_back ({});
  5323. keys.zones.back().path = c.samplePath;
  5324. evil.channels.push_back (keys);
  5325. lynx::ChannelDef patch; // (a Patcher's nodes are not in the media list either)
  5326. patch.instrument = lynx::InstrumentKind::patcher;
  5327. patch.patcher.nodes.resize (2);
  5328. patch.patcher.nodes[0].generator = true;
  5329. patch.patcher.nodes[0].channel = c;
  5330. patch.patcher.nodes[1].effect.samplePath = c.samplePath;
  5331. evil.channels.push_back (patch);
  5332. evil.mixer[1].recordTo = dir.getChildFile ("overwritten.wav").getFullPathName().toStdString();
  5333. const auto evilProject = dir.getChildFile ("evil.lynx");
  5334. lynx::sessionpack::Manifest em;
  5335. em.part = true;
  5336. juce::ZipFile::Builder b;
  5337. const auto json = lynx::sessionpack::manifestToJson (em);
  5338. b.addEntry (new juce::MemoryInputStream (json.toRawUTF8(), json.getNumBytesAsUTF8(), true), 0, "manifest.json", {});
  5339. const auto evilPack = dir.getChildFile (juce::String ("Evil") + lynx::sessionpack::extension);
  5340. bool zipped = false;
  5341. if (lynx::ProjectFile::save (evil, evilProject, e))
  5342. {
  5343. b.addFile (evilProject, 0, "project.lynx");
  5344. juce::FileOutputStream out (evilPack);
  5345. zipped = out.openedOk() && b.writeToStream (out, nullptr);
  5346. }
  5347. auto evilOpened = zipped ? lynx::sessionpack::open (evilPack, dir.getChildFile ("evil"), e) : std::nullopt;
  5348. const auto media = dir.getChildFile ("Session media/Evil");
  5349. mergeOk = evilOpened && lynx::sessionpack::adoptMedia (evilOpened->song, media, e)
  5350. && std::none_of (evilOpened->song.channels.begin(), evilOpened->song.channels.end(), [&] (const lynx::ChannelDef& ch) {
  5351. return juce::File (juce::String::fromUTF8 (ch.samplePath.c_str())) == secret
  5352. || std::any_of (ch.zones.begin(), ch.zones.end(), [&] (const lynx::SampleZone& z) { return juce::File (juce::String::fromUTF8 (z.path.c_str())) == secret; });
  5353. })
  5354. && evilOpened->song.channels.back().patcher.nodes.size() == 2
  5355. && juce::File (juce::String::fromUTF8 (evilOpened->song.channels.back().patcher.nodes[0].channel.samplePath.c_str())) != secret
  5356. && juce::File (juce::String::fromUTF8 (evilOpened->song.channels.back().patcher.nodes[1].effect.samplePath.c_str())) != secret
  5357. && evilOpened->song.mixer[1].recordTo.empty()
  5358. && media.findChildFiles (juce::File::findFiles, true).isEmpty();
  5359. if (! mergeOk && e.isEmpty())
  5360. e = "a received package reached a file outside it";
  5361. }
  5362. // ... nor through its own folder: "..", Windows' dotted names (". ." climbs like ".." there), and a manifest
  5363. // media entry outside the package (it must not even be read: "/dev/zero" would never end)
  5364. if (mergeOk)
  5365. {
  5366. const auto secret = dir.getChildFile ("secret.wav");
  5367. const auto folder = dir.getChildFile ("evil2").getChildFile ("Evil2"); // (where open() will unpack it)
  5368. const auto climb = folder.getFullPathName() + "/media/../../../secret.wav";
  5369. const auto dotted = folder.getFullPathName() + "/. ./.. ./secret.wav";
  5370. auto evil = lynx::Song::makeDefault();
  5371. for (const auto& path : { climb, dotted })
  5372. {
  5373. lynx::ChannelDef c;
  5374. c.instrument = lynx::InstrumentKind::sampler;
  5375. c.samplePath = path.toStdString();
  5376. evil.channels.push_back (c);
  5377. }
  5378. juce::MemoryBlock secretBytes;
  5379. secret.loadFileAsData (secretBytes);
  5380. lynx::sessionpack::Manifest em;
  5381. em.part = true;
  5382. em.media.push_back ({ "sha256-" + juce::String (lynx::sha256Hex ((const std::uint8_t*) secretBytes.getData(), secretBytes.getSize())),
  5383. "secret.wav", (juce::int64) secretBytes.getSize(), "../../secret.wav" });
  5384. const auto evilProject = dir.getChildFile ("evil2.lynx");
  5385. juce::ZipFile::Builder b;
  5386. const auto json = lynx::sessionpack::manifestToJson (em);
  5387. b.addEntry (new juce::MemoryInputStream (json.toRawUTF8(), json.getNumBytesAsUTF8(), true), 0, "manifest.json", {});
  5388. const auto evilPack = dir.getChildFile (juce::String ("Evil2") + lynx::sessionpack::extension);
  5389. bool zipped = false;
  5390. if (lynx::ProjectFile::save (evil, evilProject, e))
  5391. {
  5392. b.addFile (evilProject, 0, "project.lynx");
  5393. juce::FileOutputStream out (evilPack);
  5394. zipped = out.openedOk() && b.writeToStream (out, nullptr);
  5395. }
  5396. auto evilOpened = zipped ? lynx::sessionpack::open (evilPack, dir.getChildFile ("evil2"), e) : std::nullopt;
  5397. const auto media = dir.getChildFile ("Session media/Evil2");
  5398. mergeOk = evilOpened && evilOpened->folder == folder && evilOpened->corrupt.contains ("secret.wav")
  5399. && lynx::sessionpack::adoptMedia (evilOpened->song, media, e) && evilOpened->song.channels.size() >= 2
  5400. && std::none_of (evilOpened->song.channels.begin(), evilOpened->song.channels.end(), [&] (const lynx::ChannelDef& ch) {
  5401. const auto p = juce::String::fromUTF8 (ch.samplePath.c_str());
  5402. return p == climb || p == dotted || (juce::File::isAbsolutePath (p) && juce::File (p) == secret);
  5403. })
  5404. && media.findChildFiles (juce::File::findFiles, true).isEmpty();
  5405. if (! mergeOk && e.isEmpty())
  5406. e = "a received package climbed out of its folder";
  5407. }
  5408. if (! packOk && e.isEmpty())
  5409. e = "media " + juce::String (written.media) + ", duplicates " + juce::String (written.duplicates) + ", missing "
  5410. + written.missing.joinIntoString (";");
  5411. sessionResult = mergeOk ? juce::String ("OK")
  5412. : "ERROR (" + juce::String (renderedOk ? packOk ? openOk ? "merge" : "open" : "pack" : "render") + (e.isEmpty() ? "" : ": " + e) + ")";
  5413. dir.deleteRecursively();
  5414. }
  5415. // WavPack: a .wv from the FL packs (if installed) opens through the sample loader
  5416. juce::String wavpack = "NO_FL";
  5417. {
  5418. const auto roots = lynx::findFlStudioRoots();
  5419. const auto packs = juce::File (juce::String::fromUTF8 (roots.data.c_str())).getChildFile ("Patches/Packs");
  5420. const auto found = packs.isDirectory() ? packs.findChildFiles (juce::File::findFiles, true, "*.wv") : juce::Array<juce::File> {};
  5421. if (! found.isEmpty())
  5422. {
  5423. lynx::SampleLibrary library;
  5424. const auto sample = library.load (found.getFirst().getFullPathName());
  5425. float peakWv = 0.0f;
  5426. if (sample != nullptr)
  5427. for (std::size_t i = 0; i < sample->frames(); ++i)
  5428. peakWv = std::max (peakWv, std::abs (sample->leftData()[i]));
  5429. wavpack = sample != nullptr && sample->frames() > 0 && peakWv > 1e-4f ? "OK" : "ERROR";
  5430. }
  5431. }
  5432. // every built-in effect's editor and engine with extreme settings (round 111): a crash or NaN output fails here
  5433. const auto effectsOk = runEffectFuzz (4, {}); // (no mouse drags: nothing may open on screen)
  5434. // FL's Patcher (round 141): a mixer slot and a generator channel with their graphs survive save / load, and the
  5435. // generator one plays through the rack
  5436. bool patcherOk = false;
  5437. {
  5438. auto song = lynx::Song::makeDefault();
  5439. song.mixer.resize (4);
  5440. auto slot = lynx::makeEffectSlot (lynx::EffectKind::patcher);
  5441. lynx::PatchNode reverb, gain;
  5442. reverb.effect = lynx::makeEffectSlot (lynx::EffectKind::utility); // (exact defaults: params are saved to 4 decimals)
  5443. reverb.label = "Room";
  5444. reverb.x = 120.5f;
  5445. reverb.y = 40.0f;
  5446. gain.effect = lynx::makeEffectSlot (lynx::EffectKind::utility);
  5447. gain.effect.enabled = false;
  5448. slot.patcher.nodes = { reverb, gain };
  5449. lynx::PatchWire a, b, c, control;
  5450. a.to = 0;
  5451. b.from = 0, b.to = 1, b.gain = 0.5f;
  5452. c.from = 1;
  5453. control.kind = lynx::PatchWire::Kind::control, control.from = 0, control.to = 1, control.toPort = 0, control.curve = { 0.0f, 0.25f, 1.0f };
  5454. slot.patcher.wires = { a, b, c, control };
  5455. slot.patcher.outputTracks = { 3 };
  5456. song.mixer[1].effects = { slot };
  5457. lynx::ChannelDef ch;
  5458. ch.name = "Patched";
  5459. ch.instrument = lynx::InstrumentKind::patcher;
  5460. lynx::PatchNode synth;
  5461. synth.generator = true;
  5462. synth.channel.instrument = lynx::InstrumentKind::synth;
  5463. synth.channel.name = "Synth";
  5464. ch.patcher.nodes = { synth };
  5465. lynx::PatchWire notes, out;
  5466. notes.kind = lynx::PatchWire::Kind::midi, notes.to = 0;
  5467. out.from = 0;
  5468. ch.patcher.wires = { notes, out };
  5469. // round 162: the I/O nodes' MIDI pins and a MIDI Out node between them
  5470. lynx::PatchNode midiOutNode;
  5471. midiOutNode.generator = true;
  5472. midiOutNode.channel.instrument = lynx::InstrumentKind::midiOut;
  5473. lynx::midictl::writeMidiOut (midiOutNode.channel.pluginState, { 4, 0, 0, -1, -1 });
  5474. ch.patcher.nodes.push_back (midiOutNode);
  5475. lynx::PatchWire portIn, portOut;
  5476. portIn.kind = portOut.kind = lynx::PatchWire::Kind::midi;
  5477. portIn.fromPort = lynx::patchMidiPortPin (7), portIn.to = 1;
  5478. portOut.from = 1, portOut.to = lynx::patchToHost, portOut.toPort = 9;
  5479. ch.patcher.wires.push_back (portIn);
  5480. ch.patcher.wires.push_back (portOut);
  5481. ch.patcher.fromMidiPorts = { 2, 7 };
  5482. ch.patcher.toMidiPorts = { 9, 11 };
  5483. ch.patcher.fromNotesHidden = true;
  5484. song.channels.push_back (ch);
  5485. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  5486. patcherOk = back && back->mixer.size() >= 2 && back->mixer[1].effects.size() == 1
  5487. && back->mixer[1].effects[0].kind == lynx::EffectKind::patcher && back->mixer[1].effects[0].patcher == slot.patcher
  5488. && back->channels.back().instrument == lynx::InstrumentKind::patcher && back->channels.back().patcher.nodes.size() == 2
  5489. && back->channels.back().patcher.fromMidiPorts == ch.patcher.fromMidiPorts
  5490. && back->channels.back().patcher.toMidiPorts == ch.patcher.toMidiPorts && back->channels.back().patcher.fromNotesHidden
  5491. && back->channels.back().patcher.nodes[1].channel.pluginState == midiOutNode.channel.pluginState
  5492. && back->channels.back().patcher.nodes[0].generator
  5493. && back->channels.back().patcher.nodes[0].channel.instrument == lynx::InstrumentKind::synth
  5494. && back->channels.back().patcher.wires == ch.patcher.wires;
  5495. }
  5496. // Round 183c, Racks: (1) a plain Patcher's stored JSON loads and saves back byte for byte and never holds a
  5497. // "rack" key (FL's Patcher is untouched); (2) an Audio Effect Rack slot and an Instrument Rack channel survive save /
  5498. // load with their chains, zones, macros, mappings, variations and compiled cables
  5499. juce::String rackResult = "OK";
  5500. {
  5501. lynx::MixerTrack plain;
  5502. plain.name = "Plain Patcher";
  5503. auto fx = lynx::makeEffectSlot (lynx::EffectKind::patcher);
  5504. lynx::PatchNode a, b;
  5505. a.effect = lynx::makeEffectSlot (lynx::EffectKind::utility);
  5506. a.label = "A";
  5507. a.x = 120.5f;
  5508. b.effect = lynx::makeEffectSlot (lynx::EffectKind::utility);
  5509. b.effect.enabled = false;
  5510. fx.patcher.nodes = { a, b };
  5511. lynx::PatchWire w1, w2, w3, wc;
  5512. w1.to = 0;
  5513. w2.from = 0, w2.to = 1, w2.gain = 0.5f;
  5514. w3.from = 1;
  5515. wc.kind = lynx::PatchWire::Kind::control, wc.from = 0, wc.to = 1, wc.toPort = 0, wc.curve = { 0.0f, 0.25f, 1.0f };
  5516. fx.patcher.wires = { w1, w2, w3, wc };
  5517. lynx::SurfaceControl knob;
  5518. knob.name = "Drive";
  5519. knob.value = 0.25f;
  5520. fx.patcher.surface = { knob };
  5521. lynx::PatchParam pp;
  5522. pp.node = 0, pp.param = 1, pp.name = "Balance";
  5523. fx.patcher.published = { pp };
  5524. plain.effects = { fx };
  5525. const auto first = juce::JSON::toString (lynx::ProjectFile::mixerTrackToVar (plain), true);
  5526. const auto again = juce::JSON::toString (lynx::ProjectFile::mixerTrackToVar (lynx::ProjectFile::mixerTrackFromVar (juce::JSON::parse (first))), true);
  5527. if (first != again || first.contains ("\"rack\"") || first.contains ("rackMixer"))
  5528. rackResult = "ERROR plain Patcher changed";
  5529. auto song = lynx::Song::makeDefault();
  5530. song.mixer.resize (3);
  5531. auto rackSlot = lynx::rack::makeRackSlot (lynx::RackDoc::Kind::audioEffect);
  5532. auto& doc = rackSlot.patcher;
  5533. lynx::PatchNode u;
  5534. u.effect = lynx::makeEffectSlot (lynx::EffectKind::utility);
  5535. const auto n0 = lynx::rack::addDevice (doc, 0, u);
  5536. lynx::rack::addChain (doc, "Wet");
  5537. lynx::rack::addDevice (doc, 1, u);
  5538. doc.rack[0].chains[1].select = { 10, 90, 30, 70 };
  5539. lynx::rack::setChainPan (doc, 1, -0.5f);
  5540. lynx::RackMapping m;
  5541. m.node = n0, m.param = 0, m.min = 0.2f, m.max = 0.9f;
  5542. lynx::rack::map (doc, 0, m);
  5543. lynx::RackMapping v;
  5544. v.target = lynx::RackMapping::Target::chainVolume, v.chain = 1, v.min = 0.0f, v.max = lynx::rack::unityVolume;
  5545. lynx::rack::map (doc, 1, v);
  5546. lynx::rack::setMacro (doc, 0, 64.0f);
  5547. lynx::rack::storeVariation (doc);
  5548. lynx::rack::setMacro (doc, 0, 100.0f);
  5549. lynx::rack::storeVariation (doc);
  5550. doc.rack[0].morphOn = true, doc.rack[0].morphA = 0, doc.rack[0].morphB = 1;
  5551. lynx::rack::setMorph (doc, 0.5f);
  5552. lynx::rack::compile (doc);
  5553. song.mixer[1].effects = { rackSlot };
  5554. lynx::ChannelDef inst;
  5555. inst.name = "Instrument Rack";
  5556. inst.instrument = lynx::InstrumentKind::patcher;
  5557. inst.patcher = lynx::rack::makeRack (lynx::RackDoc::Kind::instrument);
  5558. lynx::PatchNode synth;
  5559. synth.generator = true;
  5560. synth.channel.instrument = lynx::InstrumentKind::synth;
  5561. synth.channel.name = "Synth";
  5562. lynx::rack::addDevice (inst.patcher, 0, synth);
  5563. inst.patcher.rack[0].chains[0].velocity = { 1, 127, 64, 127 };
  5564. lynx::rack::compile (inst.patcher);
  5565. song.channels.push_back (inst);
  5566. const auto json = lynx::ProjectFile::toJson (song);
  5567. const auto back = lynx::ProjectFile::fromJson (json, error);
  5568. // (the devices' parameters are stored to 4 decimals: the documents are compared as stored, the rack exactly)
  5569. const auto loaded = back && back->mixer.size() >= 2 && back->mixer[1].effects.size() == 1;
  5570. const auto& got = loaded ? back->mixer[1].effects[0].patcher : doc;
  5571. if (! loaded)
  5572. rackResult = "ERROR rack slot not loaded";
  5573. else if (got.rack != doc.rack)
  5574. rackResult = "ERROR rack model";
  5575. else if (got.wires != doc.wires)
  5576. rackResult = "ERROR rack cables";
  5577. else if (got.nodes.size() != doc.nodes.size())
  5578. rackResult = "ERROR rack devices";
  5579. else if (back->channels.back().patcher.rack != inst.patcher.rack || back->channels.back().patcher.wires != inst.patcher.wires
  5580. || back->channels.back().patcher.zones != inst.patcher.zones || back->channels.back().patcher.nodes.size() != inst.patcher.nodes.size())
  5581. rackResult = "ERROR instrument rack";
  5582. // the slot's insert as stored, once more: the same text (the stored form is stable)
  5583. else if (const auto once = juce::JSON::toString (lynx::ProjectFile::mixerTrackToVar (back->mixer[1]), true);
  5584. once != juce::JSON::toString (lynx::ProjectFile::mixerTrackToVar (lynx::ProjectFile::mixerTrackFromVar (juce::JSON::parse (once))), true))
  5585. rackResult = "ERROR rack stored form not stable";
  5586. }
  5587. // Round 190ec, Drum Rack: pads (Receive / Play / Choke / Audio To / sends), return chains and the views survive save /
  5588. // load with their compiled zones and cables
  5589. if (rackResult == "OK")
  5590. {
  5591. lynx::Song song;
  5592. song.mixer.resize (2);
  5593. lynx::ChannelDef ch;
  5594. ch.name = "Drums";
  5595. ch.instrument = lynx::InstrumentKind::patcher;
  5596. ch.patcher = lynx::rack::makeDrumRack();
  5597. lynx::PatchNode synth;
  5598. synth.generator = true;
  5599. synth.channel.instrument = lynx::InstrumentKind::synth;
  5600. const auto kick = lynx::rack::addPad (ch.patcher, 36, "Kick", synth);
  5601. const auto hat = lynx::rack::addPad (ch.patcher, 42, "Hat", synth);
  5602. lynx::rack::addPad (ch.patcher, -1, "Every note");
  5603. lynx::rack::addReturn (ch.patcher, "A Verb");
  5604. lynx::rack::setPlay (ch.patcher, kick, 64);
  5605. lynx::rack::setChoke (ch.patcher, hat, 2);
  5606. lynx::rack::setSend (ch.patcher, hat, 0, 0.25f, false);
  5607. lynx::rack::setAudioTo (ch.patcher, kick, 0);
  5608. lynx::rack::rackOf (ch.patcher)->showIO = true;
  5609. lynx::rack::rackOf (ch.patcher)->padScroll = 17;
  5610. song.channels.push_back (ch);
  5611. juce::String error;
  5612. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  5613. const auto& got = back && ! back->channels.empty() ? back->channels.back().patcher : lynx::PatcherDoc {};
  5614. if (! back || ! lynx::rack::isDrumRack (got))
  5615. rackResult = "ERROR drum rack not loaded";
  5616. else if (got.rack != ch.patcher.rack)
  5617. rackResult = "ERROR drum rack model";
  5618. else if (got.zones != ch.patcher.zones || got.wires != ch.patcher.wires)
  5619. rackResult = "ERROR drum rack cables";
  5620. }
  5621. // FL engines in a native project (round 142, issue #5): every engine this PC can make survives save / load and
  5622. // the instruments play through the rack
  5623. juce::String nativesResult = "OK";
  5624. int nativesMade = 0, nativesSilent = 0;
  5625. {
  5626. auto song = lynx::Song::makeDefault();
  5627. song.channels.clear();
  5628. song.patterns[0].notes.clear();
  5629. song.mixer.resize (3);
  5630. const auto& fl = lynx::flStudioAccess();
  5631. for (const auto& e : lynx::natives::instrumentEngines())
  5632. if (lynx::natives::available (e, fl))
  5633. if (auto c = lynx::natives::makeChannel (e.kind, fl))
  5634. {
  5635. c->mixerTrack = 1;
  5636. song.channels.push_back (*c);
  5637. }
  5638. for (const auto& e : lynx::natives::effectEngines())
  5639. if (auto fx = lynx::natives::makeSlot (e.kind, fl))
  5640. song.mixer[2].effects.push_back (*fx);
  5641. nativesMade = (int) (song.channels.size() + song.mixer[2].effects.size());
  5642. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  5643. auto same = back && back->channels.size() == song.channels.size() && back->mixer.size() >= 3
  5644. && back->mixer[2].effects.size() == song.mixer[2].effects.size();
  5645. for (std::size_t i = 0; same && i < song.channels.size(); ++i)
  5646. {
  5647. const auto& a = song.channels[i];
  5648. const auto& b = back->channels[i];
  5649. same = a.instrument == b.instrument && a.pluginState == b.pluginState && a.samplePath == b.samplePath && a.zones.size() == b.zones.size()
  5650. && a.modelParams.size() == b.modelParams.size();
  5651. if (! same)
  5652. nativesResult = "ERROR channel " + juce::String::fromUTF8 (a.name.c_str());
  5653. }
  5654. for (std::size_t i = 0; same && i < song.mixer[2].effects.size(); ++i)
  5655. {
  5656. const auto& a = song.mixer[2].effects[i];
  5657. const auto& b = back->mixer[2].effects[i];
  5658. same = a.kind == b.kind && a.state == b.state;
  5659. for (std::size_t p = 0; same && p < a.params.size(); ++p)
  5660. same = std::abs (a.params[p] - b.params[p]) < 1.0e-3f;
  5661. if (! same)
  5662. nativesResult = juce::String ("ERROR effect ") + lynx::effectInfo (a.kind).name;
  5663. }
  5664. if (! back)
  5665. nativesResult = "ERROR " + error;
  5666. // each instrument plays a note alone. The Granulizer and Wave Traveller play the channel's sample, and a new
  5667. // one has none (a PC without FL Studio, macOS / Linux: FL's presets are not there either), so they get a
  5668. // generated one: a second of a 220 Hz tone (round 167m, PR #19: Wave Traveller was "SILENT 1" on macOS)
  5669. const auto toneWav = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest-natives.wav");
  5670. {
  5671. juce::WavAudioFormat format;
  5672. juce::AudioBuffer<float> tone (1, 48000);
  5673. for (int i = 0; i < 48000; ++i)
  5674. tone.setSample (0, i, 0.5f * std::sin (juce::MathConstants<float>::twoPi * 220.0f * (float) i / 48000.0f));
  5675. toneWav.deleteFile();
  5676. std::unique_ptr<juce::OutputStream> out (toneWav.createOutputStream().release());
  5677. if (auto* w = format.createWriterFor (out.get(), 48000.0, 1, 16, {}, 0))
  5678. {
  5679. out.release();
  5680. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  5681. writer->writeFromAudioSampleBuffer (tone, 0, 48000);
  5682. }
  5683. }
  5684. juce::StringArray silentNames;
  5685. for (std::size_t i = 0; same && i < song.channels.size(); ++i)
  5686. {
  5687. auto one = song;
  5688. one.channels = { song.channels[i] };
  5689. one.channels[0].mixerTrack = 1;
  5690. const auto kind = song.channels[i].instrument;
  5691. // A new Fruity Slicer has no sample and no slices, and FL's is silent then too (round 180c), so it is
  5692. // not one of the engines that must sound here (Linux / macOS CI: "SILENT 1 [Fruity Slicer]", 0.1.25)
  5693. if (kind == lynx::InstrumentKind::fruityslicer && one.channels[0].samplePath.empty())
  5694. continue;
  5695. if (kind == lynx::InstrumentKind::slicex && one.channels[0].samplePath.empty()) // (the same: no sample on its decks yet)
  5696. continue;
  5697. if (kind == lynx::InstrumentKind::directwave && one.channels[0].zones.empty()) // (FL's new DirectWave: no zones yet, round 190hz)
  5698. continue;
  5699. if ((kind == lynx::InstrumentKind::granulizer || kind == lynx::InstrumentKind::wavetraveller) && one.channels[0].samplePath.empty())
  5700. one.channels[0].samplePath = toneWav.getFullPathName().toStdString();
  5701. one.mixer[2].effects.clear();
  5702. // Drumaxx plays pad 1's key: FL's default kit has a pad at 48, LYNX's own bank kits (a PC without FL,
  5703. // macOS / Linux; round 168p) start at 36 (round 169d: "SILENT 1 [Drumaxx]" on the Linux / macOS CI)
  5704. auto key = 60;
  5705. if (kind == lynx::InstrumentKind::drumaxx)
  5706. {
  5707. const auto padKey = lynx::drumaxxParam (one.channels[0].pluginState, 4);
  5708. key = std::isfinite (padKey) && padKey >= 0.0f && padKey <= 127.0f ? (int) padKey : 48;
  5709. }
  5710. // FPC plays its pads' keys; a kit without a sample (FL's "Empty" kit: no FL Studio on this PC) is silent
  5711. // in FL too (round 190q)
  5712. if (kind == lynx::InstrumentKind::fpc)
  5713. {
  5714. const auto pads = lynx::fpcChannelPads (one.channels[0]);
  5715. if (pads.empty())
  5716. continue;
  5717. key = pads.front().key;
  5718. }
  5719. one.patterns[0].notes = { { 0, 1920, 0, key, 0.8f } };
  5720. lynx::AudioEngine player (false);
  5721. player.setSong (std::move (one));
  5722. player.dispatchPendingMessages();
  5723. if (! (player.renderOffline (1.0, 48000.0) > 1.0e-4f))
  5724. {
  5725. ++nativesSilent;
  5726. silentNames.add (juce::String::fromUTF8 (song.channels[i].name.c_str()));
  5727. }
  5728. }
  5729. toneWav.deleteFile();
  5730. if (nativesSilent > 0 && nativesResult == "OK")
  5731. nativesResult = "SILENT " + juce::String (nativesSilent) + " [" + silentNames.joinIntoString (", ") + "]";
  5732. }
  5733. const auto nativesOk = nativesResult == "OK";
  5734. // The metronome as FL 2026 plays it (round 165z-a2): FL's five sounds from its install, the downbeat at
  5735. // 0.9404 × the Tick two semitones up, into the Master ("---") by default; insert 2 as its track plays it through
  5736. // insert 2 (muted: silent); never in an export
  5737. juce::String metronomeResult = "OK";
  5738. int metronomeFlSounds = 0;
  5739. float metronomeMaster = 0.0f;
  5740. {
  5741. const auto& flData = lynx::flStudioAccess().roots.data;
  5742. const auto sounds = lynx::Metronome::loadSounds (flData.empty() ? juce::File() : lynx::platform::localFile (flData));
  5743. for (const auto& s : sounds)
  5744. metronomeFlSounds += s.fromFl ? 1 : 0;
  5745. auto renderClick = [] (int track, bool muteInsert, bool include) {
  5746. auto song = lynx::Song::makeDefault();
  5747. song.channels.clear();
  5748. song.playlist.clear();
  5749. for (auto& p : song.patterns)
  5750. p.notes.clear();
  5751. song.mixer[0].effects.clear(); // (the default Master limiter)
  5752. song.mixer[2].muted = muteInsert;
  5753. lynx::AudioEngine player (false);
  5754. player.setSong (std::move (song));
  5755. player.dispatchPendingMessages();
  5756. auto& t = player.getTransport();
  5757. t.metronome = true;
  5758. t.metronomeSound = 1; // Tick
  5759. t.metronomeTrack = track;
  5760. lynx::AudioEngine::RenderOptions o;
  5761. o.seconds = 0.25;
  5762. o.sampleRate = 44100.0;
  5763. o.pluginWarmUp = false;
  5764. o.includeMetronome = include;
  5765. return player.renderOffline (o);
  5766. };
  5767. metronomeMaster = renderClick (0, false, true);
  5768. const auto insert = renderClick (2, false, true);
  5769. const auto muted = renderClick (2, true, true);
  5770. const auto exported = renderClick (0, false, false);
  5771. // FL's Tick peaks at 1.0: its downbeat at most 0.9404 (the interpolation may land between peaks)
  5772. const auto expectHigh = metronomeFlSounds == lynx::metronome::soundCount ? lynx::metronome::downbeatGain + 1.0e-3f : 1.0f;
  5773. if (! (metronomeMaster > 0.5f && metronomeMaster < expectHigh))
  5774. metronomeResult = "ERROR master " + juce::String (metronomeMaster, 4);
  5775. else if (std::abs (insert - metronomeMaster) > 2.0e-3f)
  5776. metronomeResult = "ERROR insert " + juce::String (insert, 4);
  5777. else if (muted > 1.0e-4f)
  5778. metronomeResult = "ERROR muted insert " + juce::String (muted, 4);
  5779. else if (exported > 1.0e-4f)
  5780. metronomeResult = "ERROR in export " + juce::String (exported, 4);
  5781. }
  5782. const auto metronomeOk = metronomeResult == "OK";
  5783. // Settings › Audio "Driver settings…" with a fake driver panel (issue #13's crash, the panel's buffer kept)
  5784. const auto driverPanel = lynx::AudioEngine::driverPanelSelfTest();
  5785. // issue #134 (round 190c): the output device, its rate and its buffer changed under a playing project, on
  5786. // stand-in devices (a short run; --devicechangetest plays every instrument and effect)
  5787. const auto deviceChange = lynx::AudioEngine::deviceChangeSelfTest (10, false);
  5788. // round 190gh: export parity (B7) and MIDI device hot-plug (B8)
  5789. const auto exportParity = lynx::AudioEngine::exportParitySelfTest();
  5790. // round 190jb: exports with the live plugin instances (Surge XT when it is installed here; otherwise only noted)
  5791. juce::StringArray livePlugins;
  5792. #if JUCE_WINDOWS
  5793. livePlugins.add ("C:\\Program Files\\Common Files\\VST3\\Surge Synth Team\\Surge XT.vst3");
  5794. #elif JUCE_MAC
  5795. livePlugins.add ("/Library/Audio/Plug-Ins/VST3/Surge XT.vst3");
  5796. #else
  5797. livePlugins.add (juce::File::getSpecialLocation (juce::File::userHomeDirectory).getChildFile (".vst3/Surge XT.vst3").getFullPathName());
  5798. #endif
  5799. const auto exportLive = lynx::AudioEngine::exportLiveSelfTest ({}, livePlugins);
  5800. const auto midiHotplug = lynx::AudioEngine::midiHotplugSelfTest();
  5801. const auto midiOutPorts = lynx::AudioEngine::midiOutPortSelfTest(); // round 190jl
  5802. // Online Sessions P2 (round 169b): live sessions without a network (the JSON round trip of every entity, replicas
  5803. // through it, the invite code's keys)
  5804. const auto liveResult = lynx::livetest::selfTest (&rich);
  5805. // issue #67: every built-in effect's parameters, named and hidden (the Parametric EQ's FL law, processing, band
  5806. // mask...), at odd values, through a project save and reload: the same floats back
  5807. juce::String effectParamsResult = "OK";
  5808. {
  5809. auto song = lynx::Song::makeDefault();
  5810. song.mixer.resize (1);
  5811. for (int k = 0; k <= (int) lynx::lastEffectKind; ++k)
  5812. {
  5813. const auto kind = (lynx::EffectKind) k;
  5814. if (kind == lynx::EffectKind::plugin || kind == lynx::EffectKind::parallel)
  5815. continue;
  5816. auto fx = lynx::makeEffectSlot (kind);
  5817. for (std::size_t i = 0; i < fx.params.size(); ++i)
  5818. {
  5819. auto v = (float) ((double) ((i * 7919 + (std::size_t) k * 104729) % 65521) / 65521.0);
  5820. fx.params[i] = v == fx.params[i] ? 1.0f - v : v;
  5821. }
  5822. if (kind == lynx::EffectKind::fruitySend) // ("Send to" is written over the insert span)
  5823. fx.params[3] = 0.0f;
  5824. song.mixer.emplace_back();
  5825. song.mixer.back().name = "Insert " + std::to_string (song.mixer.size() - 1);
  5826. song.mixer.back().effects.push_back (fx);
  5827. }
  5828. // round 171b's Patcher round trip (coordinator): the Frequency Splitter, Fruity Delay 3 and Peak Controller
  5829. // nodes came back different (their FL defaults, e.g. the LFO speed 32750 / 65336, lost to 4 decimals)
  5830. {
  5831. auto patch = lynx::makeEffectSlot (lynx::EffectKind::patcher);
  5832. for (const auto kind : { lynx::EffectKind::frequencySplitter, lynx::EffectKind::fruityDelay3, lynx::EffectKind::peakController,
  5833. lynx::EffectKind::reverb, lynx::EffectKind::hardwareInsert })
  5834. {
  5835. lynx::PatchNode node;
  5836. node.effect = lynx::natives::newEffect (kind, lynx::flStudioAccess()).value_or (lynx::makeEffectSlot (kind));
  5837. if (kind == lynx::EffectKind::peakController)
  5838. node.effect.params[7] = 32750.0f / 65336.0f;
  5839. node.x = 200.0f, node.y = 60.0f * (float) patch.patcher.nodes.size();
  5840. patch.patcher.nodes.push_back (node);
  5841. }
  5842. song.mixer.emplace_back();
  5843. song.mixer.back().name = "Patcher";
  5844. song.mixer.back().effects.push_back (patch);
  5845. }
  5846. juce::String why;
  5847. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
  5848. if (back && back->mixer.size() == song.mixer.size())
  5849. {
  5850. const auto& a = song.mixer.back().effects[0].patcher.nodes;
  5851. const auto& b = back->mixer.back().effects[0].patcher.nodes;
  5852. for (std::size_t n = 0; n < a.size(); ++n)
  5853. if (n >= b.size() || ! (a[n].effect == b[n].effect))
  5854. effectParamsResult = juce::String ("ERROR Patcher node ") + lynx::effectInfo (a[n].effect.kind).name;
  5855. }
  5856. if (! back || back->mixer.size() != song.mixer.size())
  5857. effectParamsResult = "ERROR load " + why;
  5858. else
  5859. for (std::size_t t = 1; t + 1 < song.mixer.size() && effectParamsResult == "OK"; ++t)
  5860. if (back->mixer[t].effects.size() != 1 || back->mixer[t].effects[0].params != song.mixer[t].effects[0].params)
  5861. {
  5862. effectParamsResult = juce::String ("ERROR ") + lynx::effectInfo (song.mixer[t].effects[0].kind).name;
  5863. break;
  5864. }
  5865. }
  5866. // round 170j: the Themed plugin style (its resolution with and without art; every art draws)
  5867. const auto artResult = lynx::skin::artSelfTest();
  5868. // round 177b: a plugin's sidechain bus gets the slot's sidechain (one-click sidechain)
  5869. const auto sidechainResult = lynx::pluginSidechainSelfTest();
  5870. // round 190ap: the Versions panel's list of files, and its labels on disk beside them
  5871. const auto versionsResult = lynx::versionsSelfTest();
  5872. // round 190ap: a project opened with its plugins off creates none of them and saves their settings unchanged
  5873. const auto pluginsOffResult = lynx::pluginsOffSelfTest();
  5874. const auto missingFilesResult = lynx::missingFilesSelfTest(); // issue #165
  5875. // round 190cj: a dancer's own native window stays where the stage put it (it drifted off the screen: JUCE
  5876. // moved a transparent child window by the main window's client offset on every repaint)
  5877. juce::String danceWindowDetail;
  5878. const auto danceWindowResult = lynx::danceWindowSelfTest (&danceWindowDetail);
  5879. // issue #161: a click in a panel (a native child window that takes no focus on a click) of an inactive main
  5880. // window activates it (back from another app, Space played nothing until the Browser was clicked)
  5881. const auto clickActivationResult = lynx::nativechild::clickActivationSelfTest();
  5882. // round 190jy (queue item 44): the holes the native panels get under a docked editor drawn by the main window
  5883. const auto editorHolesResult = lynx::nativechild::editorHolesSelfTest();
  5884. // round 177b: automation lanes come back from a project (track, automation, height, folded)
  5885. juce::String lanesResult = "OK";
  5886. {
  5887. auto song = lynx::Song::makeDefault();
  5888. const auto lane = lynx::autolanes::addLane (song, 3, { lynx::AutomationTargetKind::mixerVolume, 1, 0, 0 }, "Vol", 0.4f);
  5889. song.playlistTracks[3].lanes[0].height = 72;
  5890. song.playlistTracks[3].lanesFolded = true;
  5891. // (the same round's clip LFO and modulators ride along)
  5892. auto& lfo = song.automations[(std::size_t) lane].lfo;
  5893. lfo.on = true;
  5894. lfo.level = -40;
  5895. lfo.speed = 30000;
  5896. lfo.flags = 1 | 4;
  5897. lfo.phase = 123456789u;
  5898. lfo.amp = { { 0, 0.5f, 0.0f }, { 960, 1.0f, 0.0f } };
  5899. lynx::Modulator mod;
  5900. mod.name = "LFO 1";
  5901. mod.shape = lynx::ModShape::square;
  5902. mod.sync = false;
  5903. mod.hz = 2.5;
  5904. mod.routes = { { { lynx::AutomationTargetKind::mixerPan, 1, 0, 0 }, -0.5f } };
  5905. song.modulators.push_back (mod);
  5906. juce::String why;
  5907. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
  5908. if (! back || back->playlistTracks.size() < 4 || ! (back->playlistTracks[3].lanes == song.playlistTracks[3].lanes)
  5909. || ! back->playlistTracks[3].lanesFolded || back->automations.size() != song.automations.size()
  5910. || ! (back->automations[(std::size_t) lane].points == song.automations[(std::size_t) lane].points)
  5911. || ! (back->automations[(std::size_t) lane].lfo == lfo) || ! (back->modulators == song.modulators))
  5912. lanesResult = "ERROR " + why;
  5913. }
  5914. // round 190cg: the loop switch, folded tracks and the tempo lane's range come back from a project; a project
  5915. // without them loads as before (loop on, nothing folded, the whole range)
  5916. juce::String arrange190cgResult = "OK";
  5917. {
  5918. auto song = lynx::Song::makeDefault();
  5919. juce::String why;
  5920. const auto plain = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
  5921. song.loopStart = 960;
  5922. song.loopEnd = 4800;
  5923. song.loopOff = true;
  5924. song.tempoViewLow = 80.0;
  5925. song.tempoViewHigh = 160.0;
  5926. song.playlistTracks.resize (std::max<std::size_t> (song.playlistTracks.size(), 6));
  5927. song.playlistTracks[2].folded = song.playlistTracks[5].folded = true;
  5928. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
  5929. if (! plain || plain->loopOff || plain->tempoViewLow != 0.0 || plain->tempoViewHigh != 0.0
  5930. || std::any_of (plain->playlistTracks.begin(), plain->playlistTracks.end(), [] (const lynx::PlaylistTrack& t) { return t.folded; }))
  5931. arrange190cgResult = "ERROR defaults " + why;
  5932. else if (! back || ! back->loopOff || back->loopStart != 960 || back->loopEnd != 4800 || back->loopPlays() || back->tempoViewLow != 80.0
  5933. || back->tempoViewHigh != 160.0 || back->playlistTracks.size() < 6 || ! back->playlistTracks[2].folded
  5934. || ! back->playlistTracks[5].folded || back->playlistTracks[3].folded)
  5935. arrange190cgResult = "ERROR round trip " + why;
  5936. }
  5937. // round 190gz (issue #170): "Link Playlist tracks to mixer tracks" comes back from a project with its links; a
  5938. // project without it loads with it off (FL's tracks)
  5939. juce::String trackauto190gzResult = "OK";
  5940. {
  5941. auto song = lynx::Song::makeDefault();
  5942. juce::String why;
  5943. const auto plain = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
  5944. lynx::Clip clip;
  5945. clip.kind = lynx::ClipKind::pattern;
  5946. clip.pattern = 0; // (the default pattern: Kick, Clap and Hat; a second one plays Kick alone)
  5947. song.playlist.push_back (clip);
  5948. auto& kick = song.patterns.emplace_back();
  5949. kick.name = "Kick";
  5950. kick.toggleStep (0, 0);
  5951. clip.pattern = (int) song.patterns.size() - 1;
  5952. clip.track = 1;
  5953. song.playlist.push_back (clip);
  5954. lynx::autolink::setOn (song, true);
  5955. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
  5956. if (! plain || plain->linkTracksToMixer)
  5957. trackauto190gzResult = "ERROR defaults " + why;
  5958. // (round 190ib: Track 1 holds Kick, Clap and Hat, so they all go through insert 1 and Track 1 is its audio
  5959. // track; Track 2 only repeats Kick and stays unassigned)
  5960. // (a .lynx keeps the tracks up to the last one that differs from a plain track: Track 2 may not be written)
  5961. else if (! back || ! back->linkTracksToMixer || back->playlistTracks.empty() || back->playlistTracks[0].mode != lynx::PlaylistTrackMode::audio
  5962. || back->playlistTracks[0].mixerTrack != 1
  5963. || (back->playlistTracks.size() > 1 && back->playlistTracks[1].mode != lynx::PlaylistTrackMode::unassigned)
  5964. || back->channels[1].mixerTrack != 1 || back->channels[2].mixerTrack != 1)
  5965. {
  5966. trackauto190gzResult = "ERROR round trip " + why;
  5967. if (back && ! back->playlistTracks.empty() && back->channels.size() >= 3)
  5968. trackauto190gzResult << " tracks " << (int) back->playlistTracks.size() << " mode " << (int) back->playlistTracks[0].mode << " insert "
  5969. << back->playlistTracks[0].mixerTrack << " routes " << back->channels[0].mixerTrack << " "
  5970. << back->channels[1].mixerTrack << " " << back->channels[2].mixerTrack;
  5971. }
  5972. }
  5973. // round 190fm: the MIDI Tools generators' settings come back from a project; a project without them loads with
  5974. // Live's defaults (and saves none)
  5975. juce::String midigen190fmResult = "OK";
  5976. {
  5977. auto song = lynx::Song::makeDefault();
  5978. juce::String why;
  5979. const auto plainJson = lynx::ProjectFile::toJson (song);
  5980. const auto plain = lynx::ProjectFile::fromJson (plainJson, why);
  5981. song.midiGenerate.tool = lynx::midigen::Settings::stacks;
  5982. song.midiGenerate.rhythmOptions.pattern = 3;
  5983. song.midiGenerate.seedOptions.voices = 2;
  5984. song.midiGenerate.shapeOptions.levels[4] = 0.25f;
  5985. song.midiGenerate.shapeOptions.preset = lynx::midigen::ShapeOptions::custom;
  5986. song.midiGenerate.stacksOptions.sequence.push_back ({ 4, 3, 67, 1, 1, 0.5f, 2.0f });
  5987. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
  5988. if (! plain || ! plain->midiGenerate.isDefault() || plainJson.contains ("midiGenerate"))
  5989. midigen190fmResult = "ERROR defaults " + why;
  5990. else if (! back || ! (back->midiGenerate == song.midiGenerate))
  5991. midigen190fmResult = "ERROR round trip " + why;
  5992. }
  5993. // round 190gi: audio clip envelopes come back from a project (an entry two clips share stays shared, an unused one
  5994. // is not written, the lane shown, FL's curve modes); a project without them writes neither "clipEnvelopes" nor a
  5995. // clip field 25 (older projects save byte-identical)
  5996. juce::String clipenv190giResult = "OK";
  5997. {
  5998. auto song = lynx::Song::makeDefault();
  5999. lynx::ChannelDef channel;
  6000. channel.instrument = lynx::InstrumentKind::audioClip;
  6001. channel.samplePath = "clipenv190gi.wav";
  6002. song.channels.push_back (channel);
  6003. lynx::Clip clip;
  6004. clip.kind = lynx::ClipKind::audio;
  6005. clip.channel = (int) song.channels.size() - 1;
  6006. clip.length = lynx::ppq * 4;
  6007. song.playlist.push_back (clip);
  6008. juce::String why;
  6009. const auto plainJson = lynx::ProjectFile::toJson (song);
  6010. lynx::ClipEnvelope e;
  6011. e.volume = { { 0, 1.0f, 0.0f, 0 }, { lynx::ppq * 4, 0.25f, 0.3f, 1 } };
  6012. e.pan = { { 0, 0.5f, 0.0f, 0 }, { lynx::ppq * 2, 0.0f, 0.0f, 0 } };
  6013. e.shown = lynx::clipenv::panLane;
  6014. song.clipEnvelopes.emplace_back(); // (no clip uses it: not written)
  6015. song.clipEnvelopes.push_back (e);
  6016. song.playlist.back().envelope = 1;
  6017. auto twin = song.playlist.back();
  6018. twin.start = lynx::ppq * 8;
  6019. song.playlist.push_back (twin);
  6020. const auto json = lynx::ProjectFile::toJson (song);
  6021. const auto back = lynx::ProjectFile::fromJson (json, why);
  6022. if (plainJson.contains ("clipEnvelopes") || ! json.contains ("clipEnvelopes"))
  6023. clipenv190giResult = "ERROR written " + why;
  6024. else if (! back || back->clipEnvelopes.size() != 1 || ! (back->clipEnvelopes[0] == e))
  6025. clipenv190giResult = "ERROR table " + why;
  6026. else
  6027. {
  6028. int withEnvelope = 0;
  6029. for (const auto& c : back->playlist)
  6030. withEnvelope += c.kind == lynx::ClipKind::audio && c.envelope == 0 ? 1 : 0;
  6031. if (withEnvelope != 2)
  6032. clipenv190giResult = "ERROR clips " + why;
  6033. }
  6034. }
  6035. // round 190gx: Beats' law in the .lynx — a new project's channels are Measured; a project saved before the law
  6036. // (no "beatsLaw190gx" mark, or a nine-number warpModes list) loads Classic; a Classic channel stays Classic
  6037. juce::String beatslaw190gxResult = "OK";
  6038. {
  6039. auto song = lynx::Song::makeDefault();
  6040. lynx::ChannelDef channel;
  6041. channel.instrument = lynx::InstrumentKind::audioClip;
  6042. channel.samplePath = "beatslaw190gx.wav";
  6043. channel.sampler.keepPitch = true;
  6044. channel.sampler.stretchMethod = lynx::StretchMethod::beats;
  6045. song.channels.push_back (channel);
  6046. const auto index = song.channels.size() - 1;
  6047. juce::String why;
  6048. const auto json = lynx::ProjectFile::toJson (song);
  6049. const auto lawOf = [&] (const juce::String& text) {
  6050. const auto back = lynx::ProjectFile::fromJson (text, why);
  6051. return back && back->channels.size() > index ? (int) back->channels[index].sampler.warpModes.beatsLaw : -1;
  6052. };
  6053. auto oldVar = juce::JSON::parse (json); // (the mark removed: a project saved before 190gx)
  6054. if (auto* o = oldVar.getDynamicObject())
  6055. o->removeProperty ("beatsLaw190gx");
  6056. const auto old = juce::JSON::toString (oldVar);
  6057. auto classic = song;
  6058. classic.channels[index].sampler.warpModes.beatsLaw = lynx::WarpModeSettings::beatsLawClassic;
  6059. auto nine = song;
  6060. nine.channels[index].sampler.warpModes.beatsLoop = 0; // (a 190fm project with a changed setting: nine numbers)
  6061. // (the list with its tenth number, the law, removed: what a 190fm build wrote)
  6062. auto nineVar = juce::JSON::parse (lynx::ProjectFile::toJson (nine));
  6063. bool trimmed = false;
  6064. if (auto* channels = nineVar.getProperty ("channels", {}).getArray(); channels != nullptr && (int) index < channels->size())
  6065. if (auto* modes = (*channels)[(int) index].getProperty ("samplerSettings", {}).getProperty ("warpModes", {}).getArray(); modes != nullptr && modes->size() == 11)
  6066. {
  6067. modes->removeLast (2); // (round 190ik's eleventh number too)
  6068. trimmed = true;
  6069. }
  6070. const auto nineJson = juce::JSON::toString (nineVar);
  6071. if (! json.contains ("beatsLaw190gx") || old.contains ("beatsLaw190gx"))
  6072. beatslaw190gxResult = "ERROR mark";
  6073. else if (lawOf (json) != lynx::WarpModeSettings::beatsLawPitchAware) // (round 190ik: the new default)
  6074. beatslaw190gxResult = "ERROR new " + why;
  6075. else if (lawOf (old) != lynx::WarpModeSettings::beatsLawClassic)
  6076. beatslaw190gxResult = "ERROR old " + why;
  6077. else if (lawOf (lynx::ProjectFile::toJson (classic)) != lynx::WarpModeSettings::beatsLawClassic)
  6078. beatslaw190gxResult = "ERROR classic kept " + why;
  6079. else if (! trimmed || lawOf (nineJson) != lynx::WarpModeSettings::beatsLawClassic)
  6080. beatslaw190gxResult = "ERROR nine-number list";
  6081. }
  6082. // round 190ik: the pitch-aware Beats law and the Texture / Complex Pro engines in the .lynx — a new project's channels
  6083. // use them; a project saved before 190ik (no "warpLaw190ik" mark, or a ten-number warpModes list) keeps Beats Measured
  6084. // and the Classic engines; a channel kept on an older law stays on it when saved again
  6085. juce::String warplaw190ikResult = "OK";
  6086. {
  6087. auto song = lynx::Song::makeDefault();
  6088. lynx::ChannelDef channel;
  6089. channel.instrument = lynx::InstrumentKind::audioClip;
  6090. channel.samplePath = "warplaw190ik.wav";
  6091. channel.sampler.keepPitch = true;
  6092. channel.sampler.stretchMethod = lynx::StretchMethod::texture;
  6093. song.channels.push_back (channel);
  6094. const auto index = song.channels.size() - 1;
  6095. juce::String why;
  6096. const auto lawsOf = [&] (const juce::String& text) {
  6097. const auto back = lynx::ProjectFile::fromJson (text, why);
  6098. if (! back || back->channels.size() <= index)
  6099. return std::pair<int, int> { -1, -1 };
  6100. const auto& w = back->channels[index].sampler.warpModes;
  6101. return std::pair<int, int> { (int) w.beatsLaw, (int) w.warpLaw };
  6102. };
  6103. const auto json = lynx::ProjectFile::toJson (song);
  6104. auto oldVar = juce::JSON::parse (json); // (the mark removed: a project saved by 0.1.28 / 0.1.29)
  6105. if (auto* o = oldVar.getDynamicObject())
  6106. o->removeProperty ("warpLaw190ik");
  6107. const auto old = juce::JSON::toString (oldVar);
  6108. auto kept = song; // a channel left on the older laws
  6109. kept.channels[index].sampler.warpModes.beatsLaw = lynx::WarpModeSettings::beatsLawMeasured;
  6110. kept.channels[index].sampler.warpModes.warpLaw = lynx::WarpModeSettings::warpLawClassic;
  6111. auto ten = song; // a changed setting saved by 0.1.28: a ten-number list
  6112. ten.channels[index].sampler.warpModes.textureFlux = 60.0f;
  6113. auto tenVar = juce::JSON::parse (lynx::ProjectFile::toJson (ten));
  6114. bool trimmed = false;
  6115. if (auto* channels = tenVar.getProperty ("channels", {}).getArray(); channels != nullptr && (int) index < channels->size())
  6116. if (auto* modes = (*channels)[(int) index].getProperty ("samplerSettings", {}).getProperty ("warpModes", {}).getArray(); modes != nullptr && modes->size() == 11)
  6117. {
  6118. modes->removeLast();
  6119. modes->set (9, 1); // (0.1.28 wrote Measured)
  6120. trimmed = true;
  6121. }
  6122. const auto tenJson = juce::JSON::toString (tenVar);
  6123. const std::pair<int, int> newest { lynx::WarpModeSettings::beatsLawPitchAware, lynx::WarpModeSettings::warpLawMeasured };
  6124. const std::pair<int, int> older { lynx::WarpModeSettings::beatsLawMeasured, lynx::WarpModeSettings::warpLawClassic };
  6125. if (! json.contains ("warpLaw190ik") || old.contains ("warpLaw190ik"))
  6126. warplaw190ikResult = "ERROR mark";
  6127. else if (lawsOf (json) != newest)
  6128. warplaw190ikResult = "ERROR new " + why;
  6129. else if (lawsOf (old) != older)
  6130. warplaw190ikResult = "ERROR old " + why;
  6131. else if (lawsOf (lynx::ProjectFile::toJson (kept)) != older)
  6132. warplaw190ikResult = "ERROR older laws kept " + why;
  6133. else if (! trimmed || lawsOf (tenJson) != std::pair<int, int> { lynx::WarpModeSettings::beatsLawMeasured, lynx::WarpModeSettings::warpLawClassic })
  6134. warplaw190ikResult = "ERROR ten-number list";
  6135. }
  6136. // round 190he (issue #152): a channel window's Scaling is saved with the channel; the default (125 %) writes
  6137. // nothing, so older projects and untouched channels read as before
  6138. juce::String editorScale190heResult = "OK";
  6139. {
  6140. auto song = lynx::Song::makeDefault();
  6141. song.channels[0].editorScale = 100;
  6142. song.channels[1].editorScale = 0;
  6143. juce::String why;
  6144. const auto json = lynx::ProjectFile::toJson (song);
  6145. const auto back = lynx::ProjectFile::fromJson (json, why);
  6146. auto outOfRange = juce::JSON::parse (json);
  6147. if (auto* chans = outOfRange.getProperty ("channels", {}).getArray(); chans != nullptr && ! chans->isEmpty())
  6148. if (auto* o = (*chans)[0].getDynamicObject())
  6149. o->setProperty ("editorScale", 9000);
  6150. const auto clamped = lynx::ProjectFile::fromJson (juce::JSON::toString (outOfRange), why);
  6151. if (! back || back->channels[0].editorScale != 100 || back->channels[1].editorScale != 0)
  6152. editorScale190heResult = "ERROR round trip " + why;
  6153. else if (json.indexOf ("editorScale") != json.lastIndexOf ("editorScale"))
  6154. editorScale190heResult = "ERROR written for a default channel";
  6155. else if (! clamped || clamped->channels[0].editorScale != lynx::editorscale::maxPercent)
  6156. editorScale190heResult = "ERROR not clamped";
  6157. }
  6158. // round 190he (coordinator's gate): a project saved before 190he (no "sfModBase190he") keeps the old 0.5 centre of
  6159. // a Modulation route on a Soundfont knob; a new song, saved and opened again, centres on the knob
  6160. juce::String sfModBase190heResult = "OK";
  6161. {
  6162. auto song = lynx::Song::makeDefault();
  6163. juce::String why;
  6164. const auto json = lynx::ProjectFile::toJson (song);
  6165. auto oldVar = juce::JSON::parse (json);
  6166. if (auto* o = oldVar.getDynamicObject())
  6167. o->removeProperty ("sfModBase190he");
  6168. const auto back = lynx::ProjectFile::fromJson (json, why);
  6169. const auto old = lynx::ProjectFile::fromJson (juce::JSON::toString (oldVar), why);
  6170. auto resaved = old ? lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (*old), why) : std::optional<lynx::Song> {};
  6171. if (! json.contains ("sfModBase190he") || ! back || ! back->soundfontModBaseReal)
  6172. sfModBase190heResult = "ERROR new song " + why;
  6173. else if (! old || old->soundfontModBaseReal)
  6174. sfModBase190heResult = "ERROR old project " + why;
  6175. else if (! resaved || resaved->soundfontModBaseReal)
  6176. sfModBase190heResult = "ERROR old project saved again";
  6177. }
  6178. // round 190hq: tempo markers (B11) and the fader / route PDC switch (B13) in the .lynx, and the copy for an older
  6179. // LYNX (B20): an effect 0.1.27 does not know keeps its slot (as a switched-off Utility) and loses its automation,
  6180. // the later slots and their automation stay; the copy for 0.1.28 turns the markers into a plain tempo clip
  6181. juce::String community190hqResult = "OK";
  6182. {
  6183. auto song = lynx::Song::makeDefault();
  6184. song.mode = lynx::PlayMode::song;
  6185. lynx::tempomarkers::add (song, 4 * lynx::ppq, 90.0);
  6186. lynx::tempomarkers::add (song, 8 * lynx::ppq, 140.0, true);
  6187. song.mixer[1].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::anvilBus));
  6188. song.mixer[1].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::delay));
  6189. for (const auto slot : { 0, 1 })
  6190. {
  6191. lynx::Automation a;
  6192. a.name = slot == 0 ? "Anvil" : "Delay";
  6193. a.target = { lynx::AutomationTargetKind::effectParam, 1, slot, 1 };
  6194. a.points = { { 0, 0.2f }, { 1920, 0.8f } };
  6195. song.automations.push_back (a);
  6196. }
  6197. juce::String why;
  6198. const auto json = lynx::ProjectFile::toJson (song);
  6199. const auto back = lynx::ProjectFile::fromJson (json, why);
  6200. auto unmarked = juce::JSON::parse (json);
  6201. if (auto* o = unmarked.getDynamicObject())
  6202. o->removeProperty ("mixerLevelPdc190hq");
  6203. const auto old = lynx::ProjectFile::fromJson (juce::JSON::toString (unmarked), why);
  6204. const auto marks = back ? lynx::tempomarkers::list (*back) : std::vector<lynx::tempomarkers::Mark> {};
  6205. const auto for127 = lynx::olderlynx::forRelease (song, "0.1.27");
  6206. const auto for128 = lynx::olderlynx::forRelease (song, "0.1.28");
  6207. const auto copy127 = for127.ok ? lynx::ProjectFile::fromJson (for127.json, why) : std::optional<lynx::Song> {};
  6208. const auto copy128 = for128.ok ? lynx::ProjectFile::fromJson (for128.json, why) : std::optional<lynx::Song> {};
  6209. const auto anvilLost = std::any_of (for127.lost.begin(), for127.lost.end(), [] (const lynx::olderlynx::Loss& l) {
  6210. return juce::String (l.text).startsWith ("Anvil Bus");
  6211. });
  6212. auto targetOf = [] (const std::optional<lynx::Song>& s, const char* name) {
  6213. if (s)
  6214. for (const auto& a : s->automations)
  6215. if (a.name == name)
  6216. return a.target;
  6217. return lynx::AutomationTarget {};
  6218. };
  6219. if (! back || ! back->compensateMixerLevels || ! old || old->compensateMixerLevels)
  6220. community190hqResult = "ERROR mixer level PDC mark " + why;
  6221. 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
  6222. || std::abs (back->tempoAt (5.0 * lynx::ppq) - 102.5) > 0.5) // (90 at bar 2, ramping into the gliding 140 at bar 3)
  6223. community190hqResult = "ERROR tempo markers round trip";
  6224. else if (! copy127 || for127.json.contains ("anvilBus") || copy127->mixer[1].effects.size() != 2
  6225. || copy127->mixer[1].effects[0].kind != lynx::EffectKind::utility || copy127->mixer[1].effects[0].enabled
  6226. || copy127->mixer[1].effects[1].kind != lynx::EffectKind::delay || ! anvilLost)
  6227. community190hqResult = "ERROR copy for 0.1.27: slots " + why;
  6228. else if (targetOf (copy127, "Anvil").kind != lynx::AutomationTargetKind::none
  6229. || ! (targetOf (copy127, "Delay") == lynx::AutomationTarget { lynx::AutomationTargetKind::effectParam, 1, 1, 1 }))
  6230. community190hqResult = "ERROR copy for 0.1.27: automation";
  6231. else if (! juce::JSON::parse (for127.json)["savedBy"].toString().equalsIgnoreCase ("0.1.27") || for127.json.contains ("tempoMarkers")
  6232. || for127.json.contains ("mixerLevelPdc190hq") || for127.json.contains ("beatsLaw190gx"))
  6233. community190hqResult = "ERROR copy for 0.1.27: fields";
  6234. else if (! copy128 || for128.json.contains ("tempoMarkers") || ! for128.json.contains ("anvilBus") || lynx::tempomarkers::automationIndex (*copy128) >= 0
  6235. || std::abs (copy128->tempoAt (5.0 * lynx::ppq) - 102.5) > 0.5 || std::abs (copy128->tempoAt (12.0 * lynx::ppq) - 140.0) > 0.01)
  6236. community190hqResult = "ERROR copy for 0.1.28";
  6237. else if (lynx::olderlynx::forRelease (song, "0.1.9").ok)
  6238. community190hqResult = "ERROR unknown release accepted";
  6239. }
  6240. // 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
  6241. // an empty Sampler, MPE note curves, muted Pattern Blocks, clips transposed past ±12, clip slots' Start markers and
  6242. // 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
  6243. // out; a DirectWave state's 36-byte sample format record is completed (0.1.28 skipped it, and the loop with it)
  6244. juce::String rollup030Result = "OK";
  6245. {
  6246. auto song = lynx::Song::makeDefault();
  6247. lynx::ChannelDef tetra;
  6248. tetra.name = "FM";
  6249. tetra.instrument = lynx::InstrumentKind::tetra;
  6250. tetra.modelParams = { 0.5f, 0.25f };
  6251. song.channels.push_back (tetra);
  6252. lynx::ChannelDef wave;
  6253. wave.name = "Piano";
  6254. wave.instrument = lynx::InstrumentKind::directwave;
  6255. {
  6256. auto doc = lynx::dw::freshDoc();
  6257. lynx::dw::Node zone;
  6258. zone.id = 3;
  6259. zone.container = true;
  6260. lynx::dw::Node format;
  6261. format.id = 0x1F7;
  6262. format.body.assign (36, 0);
  6263. format.body[20] = 2; // loop mode
  6264. format.body[24] = 44; // loop A
  6265. format.body[28] = 200; // loop B
  6266. zone.kids.push_back (format);
  6267. for (auto& n : doc.top)
  6268. if (n.id == 1 && n.container)
  6269. {
  6270. n.kids.push_back (zone);
  6271. break;
  6272. }
  6273. wave.pluginState = lynx::dw::writeDoc (doc);
  6274. }
  6275. song.channels.push_back (wave);
  6276. lynx::Note curved;
  6277. curved.key = 60;
  6278. curved.length = lynx::ppq;
  6279. lynx::NoteCurves curves;
  6280. curves.lane (lynx::NoteCurveLane::pitch) = { { 0.0f, 0.0f }, { 96.0f, 200.0f } };
  6281. curved.curves = curves;
  6282. song.patterns[0].notes.push_back (curved);
  6283. song.patternBlocksOn = true;
  6284. lynx::patternblocks::place (song, 0, 0);
  6285. lynx::patternblocks::place (song, 0, 4 * lynx::ppq);
  6286. lynx::patternblocks::setMuted (song, 1, true);
  6287. lynx::Clip up;
  6288. up.track = 1;
  6289. up.length = 4 * lynx::ppq;
  6290. up.pitch = 24.0f;
  6291. song.playlist.push_back (up);
  6292. lynx::Clip slotClip;
  6293. slotClip.length = 4 * lynx::ppq;
  6294. if (const auto id = lynx::launcher::setClip (song, 0, 0, slotClip); id >= 0)
  6295. {
  6296. song.clipGrid->slots[(std::size_t) id].startMarker = lynx::ppq;
  6297. song.clipGrid->slots[(std::size_t) id].ownScale = true;
  6298. }
  6299. song.mixer[1].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::voiceShift)); // (a new one: revision 1)
  6300. auto ridgeSlot = lynx::makeEffectSlot (lynx::EffectKind::ridgeStrip);
  6301. ridgeSlot.params[(std::size_t) lynx::mixsuite::ridge::k4Pink] = 1.0f;
  6302. song.mixer[2].effects.push_back (ridgeSlot);
  6303. auto hushSlot = lynx::makeEffectSlot (lynx::EffectKind::hushDeEsser); // (a new one: the measured timing, round 190iq)
  6304. hushSlot.params[(std::size_t) lynx::mixsuite::hush::allround] = 1.0f;
  6305. song.mixer[3].effects.push_back (hushSlot);
  6306. lynx::Automation coloured;
  6307. coloured.name = "Cutoff";
  6308. coloured.colour = 0xFFC03030u;
  6309. coloured.points = { { 0, 0.2f }, { 1920, 0.8f } };
  6310. song.automations.push_back (coloured);
  6311. lynx::mixsnap::take (song);
  6312. // rollup step 3 (round 190jk): Helix (190ja), the effects' hidden revisions (190is / 190it), a warped Texture
  6313. // channel with its offline transposition and tempo automation (190ik), a deactivated clip slot (190im)
  6314. lynx::ChannelDef helix;
  6315. helix.name = "WT";
  6316. helix.instrument = lynx::InstrumentKind::helix;
  6317. helix.modelParams = { 0.5f };
  6318. song.channels.push_back (helix);
  6319. lynx::ChannelDef loop;
  6320. loop.name = "Loop";
  6321. loop.instrument = lynx::InstrumentKind::sampler;
  6322. loop.sampler.stretchBeats = 8.0f;
  6323. loop.sampler.keepPitch = true;
  6324. loop.sampler.stretchMethod = lynx::StretchMethod::texture;
  6325. loop.sampler.stretchPitch = 5.0f;
  6326. song.channels.push_back (loop);
  6327. lynx::Automation tempoClip;
  6328. tempoClip.name = "Tempo";
  6329. tempoClip.target.kind = lynx::AutomationTargetKind::tempo;
  6330. tempoClip.points = { { 0, 0.4f }, { 1920, 0.6f } };
  6331. song.automations.push_back (tempoClip);
  6332. if (song.clipGrid)
  6333. for (auto& slot : song.clipGrid->slots)
  6334. slot.active = false;
  6335. auto echoSlot = lynx::makeEffectSlot (lynx::EffectKind::echoform); // (new: voicings revision 1)
  6336. echoSlot.params[(std::size_t) lynx::echosuite::echoform::voicing] = 1.0f;
  6337. song.mixer[4].effects.push_back (echoSlot);
  6338. auto haloSlot = lynx::makeEffectSlot (lynx::EffectKind::halo); // (new: revision 1 of the Measured law)
  6339. haloSlot.params[(std::size_t) lynx::verbs::halo::engineLaw] = 1.0f;
  6340. song.mixer[5].effects.push_back (haloSlot);
  6341. song.mixer[6].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::latticeMod));
  6342. auto luxeSlot = lynx::makeEffectSlot (lynx::EffectKind::luxeVerb);
  6343. luxeSlot.params[(std::size_t) lynx::luxeVerbSpaceDucking] = 0.5f;
  6344. song.mixer[7].effects.push_back (luxeSlot);
  6345. // rollup step 4 (round 190jt): Facet's automatic threshold (190jh), a MIDI Out channel (190jl), a hosted VST3's
  6346. // automated parameter (190jg), a nested Playlist folder (190jf), the Limiter's CURVE view (190jd)
  6347. auto facetSlot = lynx::makeEffectSlot (lynx::EffectKind::facetEq);
  6348. facetSlot.params[(std::size_t) lynx::facet::autoThresholdParam0 + 2] = 1.0f;
  6349. song.mixer[8].effects.push_back (facetSlot);
  6350. auto limiterSlot = lynx::makeEffectSlot (lynx::EffectKind::fruityLimiter);
  6351. limiterSlot.displayView = 1;
  6352. song.mixer[9].effects.push_back (limiterSlot);
  6353. lynx::ChannelDef midiOut;
  6354. midiOut.name = "Hardware";
  6355. midiOut.instrument = lynx::InstrumentKind::midiOut;
  6356. song.channels.push_back (midiOut);
  6357. lynx::ChannelDef hosted;
  6358. hosted.name = "Hosted";
  6359. hosted.instrument = lynx::InstrumentKind::plugin;
  6360. hosted.plugin.id = "VST3-Test Synth-1a2b3c4d-5e6f7a8b";
  6361. hosted.plugin.name = "Test Synth";
  6362. song.channels.push_back (hosted);
  6363. lynx::Automation pluginKnob;
  6364. pluginKnob.name = "Test Synth - Cutoff";
  6365. pluginKnob.target.kind = lynx::AutomationTargetKind::channelParam;
  6366. pluginKnob.target.index = (int) song.channels.size() - 1;
  6367. pluginKnob.target.param = 3;
  6368. pluginKnob.points = { { 0, 0.1f }, { 1920, 0.9f } };
  6369. song.automations.push_back (pluginKnob);
  6370. if (song.playlistTracks.size() < 4)
  6371. song.playlistTracks.resize (4);
  6372. song.playlistTracks[1].grouped = true;
  6373. song.playlistTracks[2].grouped = true;
  6374. song.playlistTracks[2].nest = 1;
  6375. // rollup step 5 (round 190kh): Hush's Single Vocal revision (190js), a slide note on an FL native generator (190jv)
  6376. song.mixer[10].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::hushDeEsser)); // (new: Single Vocal, revision 1)
  6377. lynx::ChannelDef slider;
  6378. slider.name = "Slides";
  6379. slider.instrument = lynx::InstrumentKind::sampler;
  6380. song.channels.push_back (slider);
  6381. if (song.patterns.empty())
  6382. song.patterns.emplace_back();
  6383. {
  6384. lynx::Note slide;
  6385. slide.start = 0;
  6386. slide.length = lynx::ppq;
  6387. slide.channel = (int) song.channels.size() - 1;
  6388. slide.key = 64;
  6389. slide.slide = true;
  6390. song.patterns[0].notes.push_back (slide);
  6391. }
  6392. // rollup step 6 (round 190km): Live's Crossfade Assign and a return track (190kc), the Simple Controls tab's own
  6393. // mapping (190ke), a Newtone slot whose state is version 3 (natives190kj: + the key and the notes' velocity)
  6394. song.mixer[11].crossfade = lynx::CrossfadeAssign::a;
  6395. song.crossfader = -0.5f;
  6396. song.mixer[12].liveReturn = true;
  6397. song.mixer[12].returnPre = true;
  6398. song.mixer[13].smartControls = "custom";
  6399. {
  6400. auto newtoneSlot = lynx::makeEffectSlot (lynx::EffectKind::newtone);
  6401. lynx::newtonefx::Track nt;
  6402. nt.frames = 48000;
  6403. nt.key = 9;
  6404. lynx::newtonefx::Note n;
  6405. n.origEnd = n.curEnd = 24000;
  6406. n.origPitch = 69.0;
  6407. n.velocity = 0.8;
  6408. n.validEnd = 20000;
  6409. nt.pitches = { n };
  6410. nt.notes = 1;
  6411. newtoneSlot.state = lynx::newtonefx::writeNative (nt);
  6412. song.mixer[14].effects.push_back (newtoneSlot);
  6413. }
  6414. const auto copy = lynx::olderlynx::forRelease (song, "0.1.28");
  6415. juce::String why;
  6416. const auto back = copy.ok ? lynx::ProjectFile::fromJson (copy.json, why) : std::optional<lynx::Song> {};
  6417. const auto said = [&copy] (const char* start) {
  6418. return std::any_of (copy.lost.begin(), copy.lost.end(), [start] (const lynx::olderlynx::Loss& l) { return juce::String (l.text).startsWith (start); });
  6419. };
  6420. const auto parsed = juce::JSON::parse (copy.json);
  6421. const auto* channels = parsed["channels"].getArray();
  6422. bool fmEmpty = false, notesCut = true, waveDone = false, wtEmpty = false, loopKnob = false;
  6423. if (channels != nullptr)
  6424. for (const auto& c : *channels)
  6425. {
  6426. if (c["name"].toString() == "FM")
  6427. fmEmpty = c["instrument"].toString() == "sampler" && ! c.hasProperty ("modelParams");
  6428. if (c["name"].toString() == "WT")
  6429. wtEmpty = c["instrument"].toString() == "sampler" && ! c.hasProperty ("modelParams");
  6430. if (c["name"].toString() == "Loop")
  6431. loopKnob = std::abs ((double) c["samplerSettings"]["pitch"] - 5.0) < 1.0e-6 && ! c["samplerSettings"].hasProperty ("stretchPitch")
  6432. && (! c["samplerSettings"]["warpModes"].isArray() || c["samplerSettings"]["warpModes"].size() <= 10);
  6433. if (c["name"].toString() == "Piano")
  6434. {
  6435. juce::MemoryOutputStream bytes;
  6436. if (juce::Base64::convertFromBase64 (bytes, c["pluginState"].toString()))
  6437. {
  6438. const auto* b = static_cast<const std::uint8_t*> (bytes.getData());
  6439. if (const auto st = lynx::dw::parseState (std::vector<std::uint8_t> (b, b + bytes.getDataSize())))
  6440. for (const auto& prog : st->programs)
  6441. for (const auto& z : prog.zones)
  6442. waveDone = waveDone || (z.loopMode == 2 && z.loopA == 44 && z.loopB == 200 && z.bits == 32);
  6443. if (const auto doc = lynx::dw::readDoc (std::vector<std::uint8_t> (b, b + bytes.getDataSize())))
  6444. for (const auto& n : doc->top)
  6445. for (const auto& z : n.kids)
  6446. for (const auto& r : z.kids)
  6447. if (r.id == 0x1F7)
  6448. waveDone = waveDone && r.body.size() == 40;
  6449. }
  6450. }
  6451. }
  6452. if (const auto* patterns = parsed["patterns"].getArray())
  6453. for (const auto& pt : *patterns)
  6454. if (const auto* notes = pt["notes"].getArray())
  6455. for (const auto& n : *notes)
  6456. notesCut = notesCut && n.size() <= 19;
  6457. if (! copy.ok || ! back)
  6458. rollup030Result = "ERROR copy " + why;
  6459. else if (! fmEmpty || ! said ("Tetra is not in this release"))
  6460. rollup030Result = "ERROR Tetra channel";
  6461. else if (! waveDone)
  6462. rollup030Result = "ERROR DirectWave short record";
  6463. else if (! notesCut || ! said ("{0} note(s) lose their MPE curves"))
  6464. rollup030Result = "ERROR note curves";
  6465. else if (back->blocks.size() != 1 || back->blocks[0].start != 0 || ! said ("{0} muted Pattern Block(s)"))
  6466. rollup030Result = "ERROR muted blocks";
  6467. else if (std::none_of (back->playlist.begin(), back->playlist.end(), [] (const lynx::Clip& c) { return c.pitch == 12.0f; })
  6468. || ! said ("{0} clip(s) transposed"))
  6469. rollup030Result = "ERROR clip pitch";
  6470. else if (copy.json.contains ("startMarker") || copy.json.contains ("clipScale") || ! said ("{0} clip slot(s) launch") || ! said ("Clip scales"))
  6471. rollup030Result = "ERROR clip slots";
  6472. else if (! said ("Voice Shift's Measured law") || ! said ("Ridge Strip's 4K Pink EQ") || ! said ("Hush De-esser's Allround mode")
  6473. || parsed["mixer"][1]["effects"][0]["params"].size() > lynx::voiceshift::revision
  6474. || parsed["mixer"][3]["effects"][0]["params"].size() > lynx::mixsuite::hush::timing)
  6475. rollup030Result = "ERROR effects";
  6476. else if (copy.json.contains ("mixSnapshots") || ! said ("Mix snapshots") || ! said ("Automation clip colours")
  6477. || std::any_of (back->automations.begin(), back->automations.end(), [] (const lynx::Automation& a) { return a.colour != 0; }))
  6478. rollup030Result = "ERROR view items";
  6479. else if (! wtEmpty || ! said ("Helix is not in this release"))
  6480. rollup030Result = "ERROR Helix channel";
  6481. else if (! said ("Echoform's echo voicings") || ! said ("Epoch Verb, Atrium, Foil Plate and Halo") || ! said ("Lattice Mod plays")
  6482. || ! said ("LuxeVerb's Space ducking")
  6483. || parsed["mixer"][4]["effects"][0]["params"].size() > lynx::echosuite::echoform::revision
  6484. || parsed["mixer"][5]["effects"][0]["params"].size() > lynx::verbs::halo::revision
  6485. || parsed["mixer"][6]["effects"][0]["params"].size() > lynx::echosuite::lattice::revision
  6486. || parsed["mixer"][7]["effects"][0]["params"].size() > lynx::luxeVerbSpaceDucking)
  6487. rollup030Result = "ERROR step-3 effects";
  6488. else if (! loopKnob || ! said ("Texture and Complex Pro play") || ! said ("Complex Pro and Texture transpositions") || ! said ("Warped samples do not follow"))
  6489. rollup030Result = juce::String ("ERROR warp engines ") + (loopKnob ? "" : "knob ") + (said ("Texture and Complex Pro play") ? "" : "engines ")
  6490. + (said ("Complex Pro and Texture transpositions") ? "" : "transpose ") + (said ("Warped samples do not follow") ? "" : "tempo");
  6491. else if (copy.json.contains ("\"inactive\"") || ! said ("{0} deactivated clip slot(s)"))
  6492. rollup030Result = "ERROR deactivated slots";
  6493. else if (! said ("Facet EQ's automatic dynamic thresholds") || parsed["mixer"][8]["effects"][0]["params"].size() > lynx::facet::autoThresholdParam0)
  6494. rollup030Result = "ERROR Facet automatic threshold";
  6495. else if (! said ("MIDI Out channels and plugins' MIDI output") || ! said ("Automation of hosted CLAP and VST3 plugins"))
  6496. rollup030Result = juce::String ("ERROR engine notes ") + (said ("MIDI Out channels") ? "" : "midi-out ") + (said ("Automation of hosted") ? "" : "timed");
  6497. else if (copy.json.contains ("playlistTrackNest") || copy.json.contains ("displayView") || ! said ("{0} track(s) in nested Playlist folders")
  6498. || ! said ("Fruity Limiter's CURVE view"))
  6499. rollup030Result = "ERROR step-4 view items";
  6500. else if (! said ("Hush De-esser's Single Vocal mode") || ! said ("Slide notes on FL's native generators"))
  6501. rollup030Result = juce::String ("ERROR step-5 engine notes ") + (said ("Hush De-esser's Single Vocal") ? "" : "hush ") + (said ("Slide notes") ? "" : "slides");
  6502. else if (! said ("The crossfader (Live's Crossfade Assign)") || ! said ("Live return tracks show") || ! said ("The Simple Controls tab's")
  6503. || copy.json.contains ("\"crossfade") || copy.json.contains ("liveReturn") || copy.json.contains ("returnPre")
  6504. || copy.json.contains ("smartControls") || copy.json.contains ("engineRev"))
  6505. rollup030Result = "ERROR step-6 mixer items";
  6506. else if (const auto nts = [&parsed] {
  6507. juce::MemoryOutputStream bytes;
  6508. std::vector<std::uint8_t> st;
  6509. if (juce::Base64::convertFromBase64 (bytes, parsed["mixer"][14]["effects"][0]["state"].toString()))
  6510. st.assign (static_cast<const std::uint8_t*> (bytes.getData()), static_cast<const std::uint8_t*> (bytes.getData()) + bytes.getDataSize());
  6511. return st;
  6512. }();
  6513. ! said ("Newtone's detected key") || lynx::newtonefx::nativeVersionOf (nts) != 2 || ! lynx::newtonefx::parseNative (nts)
  6514. || lynx::newtonefx::parseNative (nts)->pitches.size() != 1 || lynx::newtonefx::parseNative (nts)->pitches[0].curEnd != 24000)
  6515. rollup030Result = "ERROR step-6 Newtone state";
  6516. else if (const auto plain = lynx::olderlynx::forRelease (lynx::Song::makeDefault(), "0.1.28");
  6517. ! plain.ok || std::any_of (plain.lost.begin(), plain.lost.end(), [] (const lynx::olderlynx::Loss& l) {
  6518. const auto t = juce::String (l.text);
  6519. return t.startsWith ("Tetra") || t.contains ("MPE") || t.contains ("Pattern Block") || t.contains ("Voice Shift")
  6520. || t.contains ("Ridge") || t.contains ("Hush") || t.startsWith ("Automation clip colours") || t.startsWith ("Mix snapshots")
  6521. || t.startsWith ("Helix") || t.contains ("Echoform") || t.contains ("Halo") || t.contains ("Lattice") || t.contains ("LuxeVerb")
  6522. || t.contains ("Texture") || t.contains ("Beats'") || t.startsWith ("Warped") || t.contains ("deactivated")
  6523. || t.contains ("Facet") || t.contains ("MIDI Out") || t.contains ("hosted CLAP") || t.contains ("nested Playlist")
  6524. || t.contains ("CURVE") || t.startsWith ("Slide notes") || t.contains ("crossfader") || t.contains ("return tracks")
  6525. || t.contains ("Controls tab") || t.startsWith ("Harmor") || t.startsWith ("Newtone");
  6526. }))
  6527. rollup030Result = "ERROR a plain project reports a loss it does not have";
  6528. }
  6529. // round 190dr: the Session mixer's sections come back from a project (a project without them: Live's defaults);
  6530. // a device dragged to another track and a Warp switch are one undo step each in a real engine
  6531. juce::String livescr190drResult = "OK";
  6532. {
  6533. auto song = lynx::Song::makeDefault();
  6534. lynx::launcher::ensureGrid (song);
  6535. juce::String why;
  6536. const auto plain = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
  6537. song.clipGrid->mixerView.io = false;
  6538. song.clipGrid->mixerView.trackOptions = true;
  6539. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
  6540. if (! plain || ! plain->clipGrid || ! (plain->clipGrid->mixerView == lynx::SessionMixerView {}))
  6541. livescr190drResult = "ERROR view defaults " + why;
  6542. else if (! back || ! back->clipGrid || back->clipGrid->mixerView.io || ! back->clipGrid->mixerView.trackOptions || ! back->clipGrid->mixerView.shown)
  6543. livescr190drResult = "ERROR view round trip " + why;
  6544. lynx::AudioEngine e (false);
  6545. e.editSong ([] (lynx::Song& s) {
  6546. if (s.mixer.size() < 4)
  6547. s.mixer.resize (4);
  6548. s.mixer[2].effects.clear();
  6549. s.mixer[3].effects.clear();
  6550. for (auto kind : { lynx::EffectKind::eq, lynx::EffectKind::compressor })
  6551. {
  6552. lynx::EffectSlot fx;
  6553. fx.kind = kind;
  6554. s.mixer[2].effects.push_back (fx);
  6555. }
  6556. lynx::Automation a;
  6557. a.target = { lynx::AutomationTargetKind::effectMix, 2, 1, 0 };
  6558. s.automations.push_back (a);
  6559. }, false);
  6560. const auto id = e.getSong().mixer[2].effects[1].instance.id;
  6561. const auto automations = e.getSong().automations.size();
  6562. e.editSongStructural ([] (lynx::Song& s) { lynx::detailchain::moveEffectToInsert (s, 2, 1, 3, false); });
  6563. const auto& moved = e.getSong();
  6564. if (livescr190drResult == "OK"
  6565. && (moved.mixer[2].effects.size() != 1 || moved.mixer[3].effects.size() != 1 || moved.mixer[3].effects[0].instance.id != id
  6566. || moved.automations.size() != automations || moved.automations.back().target.index != 3 || moved.automations.back().target.slot != 0))
  6567. livescr190drResult = "ERROR device move";
  6568. e.undo();
  6569. const auto& undone = e.getSong();
  6570. if (livescr190drResult == "OK"
  6571. && (undone.mixer[2].effects.size() != 2 || undone.mixer[3].effects.size() != 0 || undone.mixer[2].effects[1].instance.id != id
  6572. || undone.automations.back().target.index != 2 || undone.automations.back().target.slot != 1))
  6573. livescr190drResult = "ERROR device move undo";
  6574. e.editSong ([] (lynx::Song& s) {
  6575. s.channels.resize (std::max<std::size_t> (s.channels.size(), 1));
  6576. s.channels[0].sampler.stretchBeats = 16.0f;
  6577. lynx::Clip c;
  6578. c.kind = lynx::ClipKind::audio;
  6579. c.channel = 0;
  6580. c.offset = 4 * lynx::ppq;
  6581. c.length = 8 * lynx::ppq;
  6582. lynx::launcher::setClip (s, 0, 0, c);
  6583. }, false);
  6584. e.editSong ([] (lynx::Song& s) { lynx::clipsample::setWarp (s, 0, false, 4.0); });
  6585. const auto* off = e.getSong().clipGrid ? lynx::launcher::clipAt (*e.getSong().clipGrid, 0, 0) : nullptr;
  6586. 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)))
  6587. livescr190drResult = "ERROR warp off";
  6588. e.undo();
  6589. const auto* on = e.getSong().clipGrid ? lynx::launcher::clipAt (*e.getSong().clipGrid, 0, 0) : nullptr;
  6590. if (livescr190drResult == "OK" && (e.getSong().channels[0].sampler.stretchBeats != 16.0f || on == nullptr || on->length != 8 * lynx::ppq))
  6591. livescr190drResult = "ERROR warp undo";
  6592. }
  6593. // round 190ef: the map modes' storage (.lynx round trip of key / MIDI mappings and a link's Min / Max; an older
  6594. // reader keeps the plain link), and in a real engine: a link's range, MIDI Map Mode catching the control instead
  6595. // of moving anything, a slot's MIDI mapping firing on its press and release
  6596. juce::String livewf190efResult = "OK";
  6597. {
  6598. using namespace lynx::remotemap;
  6599. auto song = lynx::Song::makeDefault();
  6600. lynx::launcher::ensureGrid (song);
  6601. const lynx::AutomationTarget vol { lynx::AutomationTargetKind::mixerVolume, 1, 0, 0 };
  6602. assignMidi (song, Target::parameter (vol), { 0, 20, -1 });
  6603. assignMidi (song, Target::slot (0, 0), { 0, lynx::linkNoteBase + 36, 2 });
  6604. assignKey (song, Target::sceneLaunch (0), 'S');
  6605. assignKey (song, Target::parameter ({ lynx::AutomationTargetKind::tempo, 0, 0, 0 }), 'T');
  6606. setRange (song, rows (song, Mode::midi)[0], 0.25f, 0.75f);
  6607. setRange (song, rows (song, Mode::key)[1], 0.9f, 0.1f);
  6608. juce::String why;
  6609. const auto json = lynx::ProjectFile::toJson (song);
  6610. const auto back = lynx::ProjectFile::fromJson (json, why);
  6611. if (! back || back->remoteMappings != song.remoteMappings || back->midiLinks != song.midiLinks)
  6612. livewf190efResult = "ERROR round trip " + why;
  6613. auto parsed = juce::JSON::parse (json);
  6614. if (auto* o = parsed.getDynamicObject())
  6615. {
  6616. o->removeProperty ("remoteMappings");
  6617. o->removeProperty ("midiLinkSettings");
  6618. }
  6619. const auto older = lynx::ProjectFile::fromJson (juce::JSON::toString (parsed), why);
  6620. if (livewf190efResult == "OK" && (! older || ! older->remoteMappings.empty() || older->midiLinks.size() != 1 || older->midiLinks[0].max != 1.0f))
  6621. livewf190efResult = "ERROR older reader";
  6622. const auto plain = lynx::ProjectFile::toJson (lynx::Song::makeDefault());
  6623. if (livewf190efResult == "OK" && plain.contains ("remoteMappings"))
  6624. livewf190efResult = "ERROR written without mappings";
  6625. lynx::AudioEngine e (false);
  6626. e.editSong ([vol] (lynx::Song& s) {
  6627. if (s.mixer.size() < 3)
  6628. s.mixer.resize (3);
  6629. lynx::MidiLink l { 20, 0, vol };
  6630. l.min = 0.25f;
  6631. l.max = 0.75f;
  6632. s.midiLinks = { l };
  6633. lynx::launcher::ensureGrid (s);
  6634. assignMidi (s, Target::slot (0, 0), { 0, 21, -1 });
  6635. });
  6636. e.injectControllerForTest (20, 0, 127);
  6637. const auto top = e.currentTargetValue (vol);
  6638. e.injectControllerForTest (20, 0, 0);
  6639. const auto bottom = e.currentTargetValue (vol);
  6640. if (livewf190efResult == "OK" && (std::abs (top - 0.75f) > 0.01f || std::abs (bottom - 0.25f) > 0.01f))
  6641. livewf190efResult = "ERROR range " + juce::String (bottom) + " " + juce::String (top);
  6642. std::vector<Fire> fired;
  6643. e.onRemoteFire = [&fired] (const Fire& f) { fired.push_back (f); };
  6644. e.injectControllerForTest (21, 0, 127);
  6645. e.injectControllerForTest (21, 0, 127); // (still down: no new press)
  6646. e.injectControllerForTest (21, 0, 0);
  6647. if (livewf190efResult == "OK"
  6648. && (fired.size() != 2 || fired[0].edge != Edge::press || fired[1].edge != Edge::release || ! (fired[0].target == Target::slot (0, 0))))
  6649. livewf190efResult = "ERROR slot fire " + juce::String ((int) fired.size());
  6650. e.setMapMode (Mode::midi);
  6651. fired.clear();
  6652. e.injectControllerForTest (20, 0, 127);
  6653. e.injectControllerForTest (21, 0, 127);
  6654. const auto caught = e.takeMapCapture();
  6655. if (livewf190efResult == "OK" && (std::abs (e.currentTargetValue (vol) - 0.25f) > 0.01f || ! fired.empty()))
  6656. livewf190efResult = "ERROR mappings acted in MIDI Map Mode";
  6657. else if (livewf190efResult == "OK" && (! caught || caught->number != 21 || caught->channel != 0 || e.takeMapCapture().has_value()))
  6658. livewf190efResult = "ERROR map capture";
  6659. e.setMapMode (Mode::off);
  6660. e.onRemoteFire = nullptr;
  6661. }
  6662. // round 190em: a scene's time signature denominator (.lynx round trip; an older file without it reads n/4; a
  6663. // 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
  6664. // armed track, the selected scene's slot, the tempo from a phrase played while stopped (8 notes at 148 BPM), the
  6665. // new clip launched and the transport started
  6666. juce::String livewf190emResult = "OK";
  6667. {
  6668. auto song = lynx::Song::makeDefault();
  6669. auto& grid = lynx::launcher::ensureGrid (song);
  6670. grid.scenes.resize (3);
  6671. lynx::session::setSceneSignature (song, 1, 6, 8);
  6672. lynx::session::setSceneTempo (song, 1, 100.0);
  6673. juce::String why;
  6674. const auto json = lynx::ProjectFile::toJson (song);
  6675. const auto back = lynx::ProjectFile::fromJson (json, why);
  6676. if (! back || ! back->clipGrid || back->clipGrid->scenes != song.clipGrid->scenes || back->clipGrid->scenes[1].beatUnit != 8)
  6677. livewf190emResult = "ERROR round trip " + why;
  6678. {
  6679. // a captured clip's blank label (ClipGridSlot::blankName) survives the round trip
  6680. auto withClip = song;
  6681. lynx::Clip c;
  6682. c.pattern = 0;
  6683. c.length = 4 * lynx::ppq;
  6684. if (withClip.patterns.empty())
  6685. withClip.patterns.emplace_back();
  6686. const auto slot = lynx::launcher::setClip (withClip, 0, 0, c);
  6687. if (slot >= 0)
  6688. withClip.clipGrid->slots[(std::size_t) slot].blankName = true;
  6689. const auto again = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (withClip), why);
  6690. const auto* keptClip = again && again->clipGrid ? lynx::launcher::clipAt (*again->clipGrid, 0, 0) : nullptr;
  6691. const auto* kept = keptClip != nullptr ? &again->clipGrid->slots[(std::size_t) keptClip->gridSlot] : nullptr;
  6692. if (livewf190emResult == "OK" && (slot < 0 || kept == nullptr || ! kept->blankName))
  6693. livewf190emResult = "ERROR blank clip name round trip";
  6694. }
  6695. auto parsed = juce::JSON::parse (json);
  6696. if (auto* scenes = parsed.getProperty ("clipGrid", {}).getProperty ("scenes", {}).getArray(); scenes != nullptr && scenes->size() > 1)
  6697. if (auto* o = (*scenes)[1].getDynamicObject())
  6698. o->removeProperty ("beatUnit");
  6699. const auto older = lynx::ProjectFile::fromJson (juce::JSON::toString (parsed), why);
  6700. if (livewf190emResult == "OK" && (! older || ! older->clipGrid || older->clipGrid->scenes.size() < 2 || older->clipGrid->scenes[1].beatUnit != 4
  6701. || older->clipGrid->scenes[1].beatsPerBar != 6))
  6702. livewf190emResult = "ERROR older reader";
  6703. if (livewf190emResult == "OK" && lynx::ProjectFile::toJson (lynx::Song::makeDefault()).contains ("beatUnit"))
  6704. livewf190emResult = "ERROR beatUnit written by default";
  6705. // round 190fg: the song meter's denominator round-trips through .lynx; a file without it reads n/4
  6706. {
  6707. auto six = lynx::Song::makeDefault();
  6708. six.beatsPerBar = 6;
  6709. six.beatUnit = 8;
  6710. const auto text = lynx::ProjectFile::toJson (six);
  6711. juce::String why2;
  6712. const auto back = lynx::ProjectFile::fromJson (text, why2);
  6713. auto json = juce::JSON::parse (text);
  6714. if (auto* o = json.getDynamicObject())
  6715. o->removeProperty ("beatUnit");
  6716. const auto old = lynx::ProjectFile::fromJson (juce::JSON::toString (json), why2);
  6717. if (livewf190emResult == "OK" && (! back || back->beatsPerBar != 6 || back->beatUnit != 8 || ! old || old->beatsPerBar != 6 || old->beatUnit != 4))
  6718. livewf190emResult = "ERROR song meter round trip";
  6719. }
  6720. lynx::AudioEngine e (false);
  6721. e.editSong ([] (lynx::Song& s) {
  6722. s.bpm = 120.0;
  6723. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 4));
  6724. auto& g = lynx::launcher::ensureGrid (s);
  6725. g.scenes.resize (3);
  6726. lynx::session::setSceneSignature (s, 2, 6, 8);
  6727. lynx::session::setSceneTempo (s, 2, 90.0);
  6728. }, false);
  6729. e.launcherCommand ({ lynx::launcher::Command::Type::launchScene, 0, 2 });
  6730. // (round 190fg: the song takes the scene's 6 / 8 as it is: six eighths a bar, 3 quarters long)
  6731. if (livewf190emResult == "OK" && (e.getSong().beatsPerBar != 6 || e.getSong().beatUnit != 8 || e.getSong().barTicks() != 3 * lynx::ppq
  6732. || e.getSong().bpm != 90.0))
  6733. livewf190emResult = "ERROR scene launch " + juce::String (e.getSong().beatsPerBar) + "/" + juce::String (e.getSong().beatUnit) + " "
  6734. + juce::String (e.getSong().bpm);
  6735. e.stop();
  6736. e.editSong ([] (lynx::Song& s) {
  6737. s.bpm = 120.0;
  6738. s.beatsPerBar = 4;
  6739. s.beatUnit = 4;
  6740. }, false);
  6741. e.setGridTrackArmed (2, true, true);
  6742. const auto now = juce::Time::getMillisecondCounterHiRes();
  6743. const auto beat = 60000.0 / 148.0;
  6744. for (int i = 0; i < 8; ++i)
  6745. {
  6746. const auto at = now - 9.0 * beat + i * beat;
  6747. e.logPlayedNoteForTest (at, 0, 60 + (i % 4) * 2, 0.8f, true);
  6748. e.logPlayedNoteForTest (at + beat * 0.5, 0, 60 + (i % 4) * 2, 0.8f, false);
  6749. }
  6750. int placed = -1;
  6751. bool into = true;
  6752. const auto r = e.captureMidiToSlot (2, 1, placed, into);
  6753. const auto& g = *e.getSong().clipGrid;
  6754. const auto* clip = lynx::launcher::clipAt (g, 2, 1);
  6755. if (livewf190emResult == "OK" && (r.notes != 8 || placed != 1 || into || clip == nullptr || clip->length != 8 * lynx::ppq))
  6756. livewf190emResult = "ERROR capture " + juce::String (r.notes) + " " + juce::String (placed) + (clip == nullptr ? " no clip" : " " + juce::String ((int) clip->length));
  6757. else if (livewf190emResult == "OK" && std::abs (e.getSong().bpm - 148.0) > 0.5)
  6758. livewf190emResult = "ERROR tempo " + juce::String (e.getSong().bpm, 2);
  6759. else if (livewf190emResult == "OK" && ! e.getTransport().playing.load())
  6760. livewf190emResult = "ERROR the capture did not start the transport";
  6761. e.stop();
  6762. }
  6763. const auto mixerBasics = lynx::mixerbasics::run();
  6764. // issue #142: every font has a typeface, and one without does not crash (fonts get theirs through the
  6765. // look and feel, as in the app)
  6766. auto& lookBefore = juce::LookAndFeel::getDefaultLookAndFeel();
  6767. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  6768. const auto fontsResult = lynx::theme::fontSelfTest();
  6769. const auto paintCachesResult = lynx::theme::paintCacheSelfTest(); // (round 190gr)
  6770. const auto motionOverlayResult = lynx::ui::MotionOverlay::selfTest(); // (round 190ip)
  6771. // round 190bm (0.1.25 showed the Mixer and the Playlist black): their cached pictures shown on native and
  6772. // software targets against straight paints (ui/PictureCheck.h; --picturetest runs more sizes and scales)
  6773. juce::String picturesResult = "OK";
  6774. {
  6775. lynx::AudioEngine pictureEngine (false);
  6776. auto pictureFailures = 0;
  6777. juce::String lines;
  6778. {
  6779. lynx::PlaylistComponent playlist (pictureEngine);
  6780. playlist.setBounds (0, 0, 1200, 700);
  6781. playlist.setVisible (true);
  6782. lines << lynx::ui::picturecheck::run (playlist, "Playlist 1200 x 700", { 1.0f, 1.5f }, pictureFailures, {});
  6783. }
  6784. {
  6785. lynx::MixerComponent mixer (pictureEngine);
  6786. mixer.setBounds (0, 0, 1200, 500);
  6787. mixer.setVisible (true);
  6788. lines << lynx::ui::picturecheck::run (mixer, "Mixer 1200 x 500", { 1.0f, 1.5f }, pictureFailures, {});
  6789. }
  6790. if (pictureFailures > 0 || ! lines.contains (": ok"))
  6791. picturesResult = "ERROR " + lines.trim().replace ("\n", "; ");
  6792. }
  6793. // round 190ci (the 0.1.26 release candidate ended when an FPC channel was added): every built-in generator and
  6794. // effect, its editor built as the Channel Rack / mixer opens it and painted once. The report file names the
  6795. // plugin being opened, so a run that dies there says which one.
  6796. const auto editorsResult = lynx::pluginthumbs::checkEditors ([&reportPath] (const juce::String& key) {
  6797. if (reportPath.isNotEmpty())
  6798. juce::File (reportPath).replaceWithText ("(opening the editor of " + key + ")\n");
  6799. });
  6800. // round 190ci: a fault leaves a crash file, also on a stack Windows cannot walk (that FPC fault left none)
  6801. const auto faultResult = faultReportSelfTest();
  6802. const auto stemsResult = stemsSinglePassSelfTest(); // round 190gj
  6803. const auto exportFormatsResult = lynx::shortexport::formatsCheck(); // AIFF and M4A (owner decision D5)
  6804. juce::LookAndFeel::setDefaultLookAndFeel (&lookBefore);
  6805. const auto ok = editorsResult.startsWith ("OK") && ! faultResult.startsWith ("ERROR") && stemsResult == "OK" && exportFormatsResult.startsWith ("OK")
  6806. && 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
  6807. && sessionResult == "OK" && liveResult.startsWith ("OK")
  6808. && wavpack != "ERROR" && effectsOk && driverPanel == "OK" && deviceChange.startsWith ("OK") && exportParity.startsWith ("OK") && exportLive.startsWith ("OK") && midiHotplug.startsWith ("OK") && midiOutPorts.startsWith ("OK") && metronomeOk && artResult == "OK" && effectParamsResult == "OK"
  6809. && sidechainResult == "OK" && lanesResult == "OK" && arrange190cgResult == "OK" && livescr190drResult == "OK" && livewf190efResult == "OK" && livewf190emResult == "OK" && versionsResult == "OK" && pluginsOffResult == "OK" && missingFilesResult == "OK"
  6810. && midigen190fmResult == "OK" && clipenv190giResult == "OK" && beatslaw190gxResult == "OK" && warplaw190ikResult == "OK" && editorScale190heResult == "OK" && sfModBase190heResult == "OK" && trackauto190gzResult == "OK" && community190hqResult == "OK" && rollup030Result == "OK"
  6811. && remoteHistoryResult.startsWith ("OK") && hostedStateLockResult.startsWith ("OK")
  6812. && hostedStateContentionResult.startsWith ("OK")
  6813. && danceWindowResult == "OK" && clickActivationResult == "OK" && motionOverlayResult.startsWith ("OK")
  6814. && editorHolesResult.startsWith ("OK");
  6815. juce::String report;
  6816. report << "connections=" << offline.getNumGraphConnections() << "\n"
  6817. << "peak=" << peak << "\n"
  6818. << "stems_single_pass=" << stemsResult << "\n"
  6819. << "export_formats=" << exportFormatsResult << "\n"
  6820. << "project=" << (projectOk ? "OK" : "ERROR " + error) << "\n"
  6821. << "playlist_track_modes_roundtrip=" << (trackModes122Ok ? "OK" : "ERROR") << "\n"
  6822. << "project_features=" << (richOk ? "OK" : "ERROR") << "\n"
  6823. << "hardware_outputs=" << (hwOutOk ? "OK" : "ERROR") << "\n"
  6824. << "plugin_host_keys_option=" << (hostKeysOk ? "OK" : "ERROR") << "\n"
  6825. << "plugin_levels_new_project=" << (pluginLevelsOk ? "OK" : "ERROR") << "\n"
  6826. << "flp168j_fields=" << (flp168jOk ? "OK" : "ERROR") << "\n"
  6827. << "clip_fades_180d=" << (clipFades180dOk ? "OK" : "ERROR") << "\n"
  6828. << "pattern_blocks=" << (blocksOk ? "OK" : "ERROR") << "\n"
  6829. << "pattern_clip_takeover=" << (takeoverOk ? "OK" : "ERROR") << "\n"
  6830. << "comp_crossfades=" << (compOk ? "OK" : "ERROR") << "\n"
  6831. << "channel_polyphony=" << (polyOk ? "OK" : "ERROR") << "\n"
  6832. << "track_latency=" << (latencyOk ? "OK" : "ERROR") << "\n"
  6833. << "pre_fader_sends=" << (preSendOk ? "OK" : "ERROR") << "\n"
  6834. << "low_latency_recording=" << (lowLatencyOk ? "OK" : "ERROR") << "\n"
  6835. << "preview_in_time=" << (previewInTimeOk ? "OK" : "ERROR") << " (2 s loop prepared in " << juce::String (previewPrepareMs, 1) << " ms)\n"
  6836. << "plugin_substitutes=" << (substituteOk ? "OK" : "ERROR") << "\n"
  6837. << "patcher=" << (patcherOk ? "OK" : "ERROR") << "\n"
  6838. << "racks=" << rackResult << "\n"
  6839. << "native_engines=" << nativesResult << " (" << nativesMade << " made)\n"
  6840. << "undo=" << (undoOk ? "OK" : "ERROR") << "\n"
  6841. << "mixer_basics=" << mixerBasics << "\n"
  6842. << "remote_history=" << remoteHistoryResult << "\n"
  6843. << "hosted_state_lock=" << hostedStateLockResult << "\n"
  6844. << "hosted_state_contention=" << hostedStateContentionResult << "\n"
  6845. << "fonts=" << fontsResult << "\n"
  6846. << "paint_caches=" << paintCachesResult << "\n"
  6847. << "motion_overlay=" << motionOverlayResult << "\n"
  6848. << "cached_pictures=" << picturesResult << "\n"
  6849. << "plugin_editors=" << editorsResult << "\n"
  6850. << "fault_report=" << faultResult << "\n"
  6851. << "recording=" << (recordOk && recordUndoOk ? "OK" : "ERROR") << "\n"
  6852. << "cancel_recording=" << (cancelRecordOk ? "OK" : "ERROR") << "\n"
  6853. << "midi=" << (midiOk ? "OK" : "ERROR") << "\n"
  6854. << "package=" << (packageOk ? "OK" : "ERROR") << "\n"
  6855. << "projectSave=" << (projectSaveOk ? "OK" : "ERROR") << "\n"
  6856. << "online_session=" << sessionResult << "\n"
  6857. << "live_session=" << liveResult << "\n"
  6858. << "wavpack=" << wavpack << "\n"
  6859. << "effects=" << (effectsOk ? "OK" : "NONFINITE") << "\n"
  6860. << "effect_params_saved=" << effectParamsResult << "\n"
  6861. << "driver_panel=" << driverPanel << "\n"
  6862. << "device_change=" << deviceChange << "\n"
  6863. << "export_parity=" << exportParity << "\n"
  6864. << "export_live=" << exportLive << "\n"
  6865. << "midi_hotplug=" << midiHotplug << "\n"
  6866. << "midi_out_ports=" << midiOutPorts.replace ("\n", " | ").trimCharactersAtEnd (" |") << "\n"
  6867. << "plugin_art=" << artResult << "\n"
  6868. << "plugin_sidechain=" << sidechainResult << "\n"
  6869. << "versions_panel=" << versionsResult << "\n"
  6870. << "plugins_off=" << pluginsOffResult << "\n"
  6871. << "missing_files_rows=" << missingFilesResult << "\n"
  6872. << "dance_window=" << danceWindowResult << "\n"
  6873. << "dance_window_detail=" << danceWindowDetail << "\n"
  6874. << "click_activation=" << clickActivationResult << "\n"
  6875. << "editor_holes=" << editorHolesResult << "\n"
  6876. << "lanes_saved=" << lanesResult << "\n"
  6877. << "arrange190cg_saved=" << arrange190cgResult << "\n"
  6878. << "livescr190dr=" << livescr190drResult << "\n"
  6879. << "livewf190ef=" << livewf190efResult << "\n"
  6880. << "livewf190em=" << livewf190emResult << "\n"
  6881. << "midigen190fm_saved=" << midigen190fmResult << "\n"
  6882. << "trackauto190gz_saved=" << trackauto190gzResult << "\n"
  6883. << "clipenv190gi_saved=" << clipenv190giResult << "\n"
  6884. << "beatslaw190gx_saved=" << beatslaw190gxResult << "\n"
  6885. << "warplaw190ik_saved=" << warplaw190ikResult << "\n"
  6886. << "editor_scale190he_saved=" << editorScale190heResult << "\n"
  6887. << "sf_mod_base190he=" << sfModBase190heResult << "\n"
  6888. << "community190hq_saved=" << community190hqResult << "\n"
  6889. << "rollup030_copy_for_0128=" << rollup030Result << "\n"
  6890. << "metronome=" << metronomeResult << " (FL sounds " << metronomeFlSounds << "/" << lynx::metronome::soundCount
  6891. << ", downbeat peak " << juce::String (metronomeMaster, 4) << ")\n";
  6892. // issue #138 (round 190c): a short note at the very start of the Playlist against the same note at bar 2, through
  6893. // the Export window's path (its own thread while the message loop runs: the report is finished from there)
  6894. if (reportPath.isNotEmpty())
  6895. juce::File (reportPath).replaceWithText (report + "(short_export running)\n");
  6896. lynx::shortexport::run (false, 1, {}, {}, [this, report, ok, reportPath] (juce::String shortExport) {
  6897. const auto all = ok && shortExport.startsWith ("OK");
  6898. const auto text = report + "short_export=" + shortExport + "\nresult=" + (all ? "OK" : "FAILED") + "\n";
  6899. if (reportPath.isNotEmpty())
  6900. juce::File (reportPath).replaceWithText (text);
  6901. setApplicationReturnValue (all ? 0 : 1);
  6902. quit();
  6903. });
  6904. }
  6905. // Every built-in effect in its native editor: random / extreme parameters, mouse drags over the editor, the editor
  6906. // painted, audio rendered at 44.1 / 48 / 96 kHz. Returns false when an effect output NaN / inf (muted by the
  6907. // renderer's guard). The report lists each effect. Used by --fxfuzz and (a short run) by --selftest.
  6908. bool runEffectFuzz (int rounds, const juce::String& reportPath, bool drags = false)
  6909. {
  6910. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  6911. lynx::setNativeEditorDemo (true);
  6912. juce::String report;
  6913. auto allFinite = true;
  6914. {
  6915. lynx::AudioEngine offline (false);
  6916. juce::Random random (111);
  6917. const auto value = [&] { const auto r = random.nextInt (6); return r == 0 ? 0.0f : r == 1 ? 1.0f : random.nextFloat(); };
  6918. for (int k = 0; k <= (int) lynx::lastEffectKind; ++k)
  6919. {
  6920. const auto kind = (lynx::EffectKind) k;
  6921. if (! lynx::NativeEffectWindows::canOpen (kind) || kind == lynx::EffectKind::patcher) // (the Patcher's editor is a graph window)
  6922. continue;
  6923. const auto before = lynx::RackRenderer::nonFiniteEffectBlocks();
  6924. const auto& info = lynx::effectInfo (kind);
  6925. // (FL engines: a fresh instance as the menus make it, from the user's FL installation; round 142)
  6926. auto fx = lynx::natives::newEffect (kind, lynx::flStudioAccess()).value_or (lynx::makeEffectSlot (kind));
  6927. int dragged = 0; // parameter changes made by the mouse drags
  6928. for (int round = 0; round < rounds; ++round)
  6929. {
  6930. if (round > 0)
  6931. for (std::size_t p = 0; p < info.params.size(); ++p)
  6932. fx.params[p] = round == 1 ? 0.0f : round == 2 ? 1.0f : value();
  6933. auto song = lynx::Song::makeDefault(); // its demo beat feeds the effect
  6934. song.mixer.resize (2);
  6935. song.mixer[0].name = "Master";
  6936. song.mixer[1].name = "Insert 1";
  6937. song.mixer[1].effects.assign (1, fx);
  6938. for (auto& channel : song.channels)
  6939. channel.mixerTrack = 1;
  6940. offline.setSong (std::move (song));
  6941. offline.dispatchPendingMessages();
  6942. const auto pages = juce::jmax (1, (int) lynx::plugui::layoutFor (kind).pages.size());
  6943. for (int page = 0; page < pages; ++page)
  6944. {
  6945. auto editor = kind == lynx::EffectKind::facetEq ? lynx::makeFacetEqEditor (offline, 1, 0, false)
  6946. : lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, page);
  6947. if (editor == nullptr || editor->getWidth() <= 0 || editor->getHeight() <= 0)
  6948. continue;
  6949. juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
  6950. const auto paint = [&] {
  6951. juce::Graphics g (image);
  6952. editor->paintEntireComponent (g, false);
  6953. };
  6954. paint();
  6955. // drags from a grid of points, as a user moving every control (plain left button)
  6956. if (round >= 3 && drags)
  6957. {
  6958. const auto source = juce::Desktop::getInstance().getMainMouseSource();
  6959. const auto step = juce::jmax (12, juce::jmin (editor->getWidth(), editor->getHeight()) / 8);
  6960. for (int y = step / 2; y < editor->getHeight(); y += step)
  6961. for (int x = step / 2; x < editor->getWidth(); x += step)
  6962. {
  6963. auto* target = editor->getComponentAt (x, y);
  6964. if (target == nullptr)
  6965. continue;
  6966. const auto at = target->getLocalPoint (editor.get(), juce::Point<float> ((float) x, (float) y));
  6967. const auto now = juce::Time::getCurrentTime();
  6968. const auto event = [&] (juce::Point<float> p, juce::ModifierKeys mods) {
  6969. return juce::MouseEvent (source, p, mods, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, target, target, now, at, now, 1, false);
  6970. };
  6971. const auto down = juce::ModifierKeys (juce::ModifierKeys::leftButtonModifier);
  6972. const juce::Component::SafePointer<juce::Component> alive (target);
  6973. target->mouseDown (event (at, down));
  6974. const auto dy = (float) (random.nextBool() ? 400 : -400), dx = (float) (random.nextInt (401) - 200);
  6975. if (alive != nullptr)
  6976. target->mouseDrag (event (at + juce::Point<float> (dx * 0.5f, dy * 0.5f), down));
  6977. if (alive != nullptr)
  6978. target->mouseDrag (event (at + juce::Point<float> (dx, dy), down));
  6979. if (alive != nullptr)
  6980. target->mouseUp (event (at + juce::Point<float> (dx, dy), juce::ModifierKeys()));
  6981. juce::PopupMenu::dismissAllActiveMenus();
  6982. offline.dispatchPendingMessages();
  6983. }
  6984. paint();
  6985. }
  6986. }
  6987. for (const auto rate : { 44100.0, 48000.0, 96000.0 })
  6988. offline.renderOffline (0.05, rate);
  6989. if (round == 0 || round >= 3) // keep what the drags set for the next round
  6990. if (offline.getSong().mixer.size() > 1 && ! offline.getSong().mixer[1].effects.empty())
  6991. {
  6992. const auto& now = offline.getSong().mixer[1].effects[0];
  6993. for (std::size_t p = 0; p < fx.params.size(); ++p)
  6994. dragged += now.params[p] != fx.params[p] ? 1 : 0;
  6995. dragged += now.state != fx.state ? 1 : 0;
  6996. fx = now;
  6997. }
  6998. }
  6999. const auto broken = lynx::RackRenderer::nonFiniteEffectBlocks() - before;
  7000. allFinite = allFinite && broken == 0;
  7001. report << info.name << ": " << (broken == 0 ? juce::String ("OK") : "non-finite output in " + juce::String ((juce::int64) broken) + " blocks")
  7002. << " (" << dragged << " changes by mouse)\n";
  7003. if (reportPath.isNotEmpty())
  7004. juce::File (reportPath).replaceWithText (report + "(running)\n"); // what was reached, if it crashes
  7005. }
  7006. }
  7007. lynx::setNativeEditorDemo (false);
  7008. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  7009. report << "result=" << (allFinite ? "OK" : "NONFINITE") << "\n";
  7010. if (reportPath.isNotEmpty())
  7011. juce::File (reportPath).replaceWithText (report);
  7012. return allFinite;
  7013. }
  7014. // --opentest (round 157a): see the command line. Runs on the message loop (the editors' timers, animations and
  7015. // native windows are real); one step per timer tick.
  7016. void runOpenTest (const juce::String& reportPath, bool visible, std::function<void (bool)> done)
  7017. {
  7018. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  7019. struct OpenTest final : juce::Timer
  7020. {
  7021. juce::String reportPath, report;
  7022. bool visible = false, ok = true;
  7023. std::function<void (bool)> done;
  7024. std::unique_ptr<lynx::AudioEngine> engine;
  7025. std::vector<std::pair<juce::String, std::function<void()>>> steps;
  7026. std::size_t next = 0;
  7027. std::atomic<std::int64_t> lastStep { 0 };
  7028. std::atomic<bool> finished { false };
  7029. std::thread watchdog;
  7030. juce::String current;
  7031. std::mutex currentLock;
  7032. int opened = 0, painted = 0;
  7033. // LYNX_OPENTEST_TIMEOUT (seconds): longer for sanitizer builds
  7034. const std::int64_t timeoutMs = 1000 * juce::jmax (5, juce::SystemStats::getEnvironmentVariable ("LYNX_OPENTEST_TIMEOUT", "20").getIntValue());
  7035. static std::int64_t now() { return (std::int64_t) juce::Time::getMillisecondCounter(); }
  7036. void write (const juce::String& tail = {}) { juce::File (reportPath).replaceWithText (report + tail); }
  7037. ~OpenTest() override
  7038. {
  7039. finished = true;
  7040. if (watchdog.joinable())
  7041. watchdog.join();
  7042. }
  7043. void start()
  7044. {
  7045. lastStep = now();
  7046. // the UI hang watch runs during the whole test (5 s): a slow step leaves its stack next to the report
  7047. const auto folder = juce::File (reportPath).getParentDirectory().getChildFile ("opentest-hang");
  7048. folder.deleteRecursively();
  7049. folder.createDirectory();
  7050. lynx::crashguard::startHangWatch (folder.getFullPathName().replaceCharacter ('\\', '/').toStdString(), 5000);
  7051. watchdog = std::thread ([this] {
  7052. while (! finished)
  7053. {
  7054. std::this_thread::sleep_for (std::chrono::milliseconds (200));
  7055. if (now() - lastStep.load() > timeoutMs)
  7056. {
  7057. juce::String at;
  7058. {
  7059. const std::lock_guard<std::mutex> l (currentLock);
  7060. at = current;
  7061. }
  7062. juce::File (reportPath).replaceWithText (report + "HANG at " + at + " (no progress for " + juce::String (timeoutMs / 1000) + " s; stack in opentest-hang)\nresult=HANG\n");
  7063. lynx::crashguard::exitNow (3);
  7064. }
  7065. }
  7066. });
  7067. startTimer (30);
  7068. }
  7069. // every LYNX window but none of the main one (there is none here): moved off-screen, painted once into an image
  7070. void touchWindows (bool resize, bool large)
  7071. {
  7072. auto& desktop = juce::Desktop::getInstance();
  7073. for (int i = desktop.getNumComponents(); --i >= 0;)
  7074. if (auto* c = desktop.getComponent (i); c != nullptr && c->isVisible())
  7075. {
  7076. if (! visible && c->getScreenX() > -3000)
  7077. c->setTopLeftPosition (-6000, -6000);
  7078. if (resize)
  7079. if (auto* w = dynamic_cast<juce::ResizableWindow*> (c))
  7080. {
  7081. const auto b = w->getBounds();
  7082. w->setSize (large ? b.getWidth() * 2 : juce::jmax (40, b.getWidth() / 3), large ? b.getHeight() * 2 : juce::jmax (40, b.getHeight() / 3));
  7083. }
  7084. if (c->getWidth() > 0 && c->getHeight() > 0 && c->getWidth() < 8000 && c->getHeight() < 8000)
  7085. {
  7086. juce::Image image (juce::Image::ARGB, c->getWidth(), c->getHeight(), true);
  7087. juce::Graphics g (image);
  7088. c->paintEntireComponent (g, false);
  7089. ++painted;
  7090. // LYNX_OPENTEST_SHOTS=folder: each window as first painted (before the resizes), for a look
  7091. if (const auto shots = juce::SystemStats::getEnvironmentVariable ("LYNX_OPENTEST_SHOTS", {}); shots.isNotEmpty() && ! resize)
  7092. {
  7093. juce::FileOutputStream out (juce::File (shots).getChildFile (juce::String (painted).paddedLeft ('0', 4) + ".png"));
  7094. if (out.openedOk())
  7095. {
  7096. out.setPosition (0), out.truncate();
  7097. juce::PNGImageFormat().writeImageToStream (c->createComponentSnapshot (c->getLocalBounds()), out);
  7098. }
  7099. }
  7100. }
  7101. }
  7102. }
  7103. void timerCallback() override
  7104. {
  7105. if (next >= steps.size())
  7106. {
  7107. stopTimer();
  7108. lynx::NativeEffectWindows::closeAll();
  7109. lynx::closeChannelSettings();
  7110. // the UI hang watch itself: the message thread spins past the stall time; the watcher must write the stack
  7111. {
  7112. const auto before = lynx::crashguard::lastHangFile();
  7113. for (const auto until = now() + 7000; now() < until;)
  7114. lastStep = now(); // (busy: no heartbeat; the test's own watchdog stays quiet)
  7115. for (const auto until = now() + 1500; now() < until && lynx::crashguard::lastHangFile() == before;)
  7116. std::this_thread::sleep_for (std::chrono::milliseconds (20));
  7117. lynx::crashguard::stopHangWatch();
  7118. const juce::File hang (juce::String::fromUTF8 (lynx::crashguard::lastHangFile().c_str()));
  7119. const auto text = hang.loadFileAsString();
  7120. const auto frames = juce::StringArray::fromLines (text).size() - 2;
  7121. #if JUCE_WINDOWS
  7122. const auto hangOk = lynx::crashguard::lastHangFile() != before && hang.existsAsFile() && text.contains ("LYNX.exe+0x") && frames >= 3;
  7123. #else
  7124. const auto hangOk = lynx::crashguard::lastHangFile() != before && hang.existsAsFile() && frames >= 3;
  7125. #endif
  7126. report << "hang watch: " << (hangOk ? "OK" : "FAIL") << " (" << hang.getFileName() << ", " << frames << " lines"
  7127. << (before.empty() ? juce::String() : "; a step stalled > 5 s earlier: " + juce::String::fromUTF8 (before.c_str())) << ")\n";
  7128. ok = ok && hangOk;
  7129. }
  7130. report << "windows opened: " << opened << ", paints: " << painted << "\nresult=" << (ok ? "OK" : "FAIL") << "\n";
  7131. write();
  7132. finished = true;
  7133. if (done)
  7134. done (ok);
  7135. return;
  7136. }
  7137. auto& [label, fn] = steps[next++];
  7138. {
  7139. const std::lock_guard<std::mutex> l (currentLock);
  7140. current = label;
  7141. }
  7142. fn();
  7143. lastStep = now();
  7144. lynx::crashguard::heartbeat();
  7145. }
  7146. };
  7147. auto* test = new OpenTest();
  7148. test->reportPath = reportPath;
  7149. test->visible = visible;
  7150. test->engine = std::make_unique<lynx::AudioEngine> (false);
  7151. test->done = [test, done] (bool ok) {
  7152. juce::MessageManager::callAsync ([test, done, ok] {
  7153. delete test;
  7154. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  7155. done (ok);
  7156. });
  7157. };
  7158. auto& engine = *test->engine;
  7159. lynx::setNativeEditorDemo (true); // live displays animate without an audio device
  7160. const auto songWith = [] (const lynx::EffectSlot& fx) {
  7161. auto song = lynx::Song::makeDefault();
  7162. song.mixer.resize (2);
  7163. song.mixer[0].name = "Master";
  7164. song.mixer[1].name = "Insert 1";
  7165. song.mixer[1].effects.assign (1, fx);
  7166. for (auto& channel : song.channels)
  7167. channel.mixerTrack = 1;
  7168. return song;
  7169. };
  7170. // an older project's slot: its parameter list cut to `count` and read back by the project reader (the
  7171. // parameters a newer LYNX added after them take their defaults)
  7172. const auto oldState = [songWith] (const lynx::EffectSlot& fx, std::size_t count) -> std::optional<lynx::Song> {
  7173. auto json = juce::JSON::parse (lynx::ProjectFile::toJson (songWith (fx)));
  7174. if (auto* mixer = json["mixer"].getArray(); mixer != nullptr && mixer->size() > 1)
  7175. if (auto* effects = (*mixer)[1]["effects"].getArray(); effects != nullptr && ! effects->isEmpty())
  7176. if (auto* params = (*effects)[0]["params"].getArray())
  7177. params->removeRange ((int) count, params->size());
  7178. juce::String error;
  7179. return lynx::ProjectFile::fromJson (juce::JSON::toString (json), error);
  7180. };
  7181. auto& steps = test->steps;
  7182. juce::Random random (157);
  7183. for (int k = 0; k <= (int) lynx::lastEffectKind; ++k)
  7184. {
  7185. const auto kind = (lynx::EffectKind) k;
  7186. if (! lynx::NativeEffectWindows::canOpen (kind) || kind == lynx::EffectKind::patcher)
  7187. continue;
  7188. const auto& info = lynx::effectInfo (kind);
  7189. const auto base = lynx::natives::newEffect (kind, lynx::flStudioAccess()).value_or (lynx::makeEffectSlot (kind));
  7190. const auto n = info.params.size();
  7191. std::vector<std::pair<juce::String, std::function<std::optional<lynx::Song>()>>> variants;
  7192. variants.push_back ({ "default", [=] { return std::optional<lynx::Song> (songWith (base)); } });
  7193. for (const auto value : { 0.0f, 1.0f })
  7194. variants.push_back ({ value == 0.0f ? "all 0" : "all 1", [=] {
  7195. auto fx = base;
  7196. for (std::size_t p = 0; p < n; ++p) fx.params[p] = value;
  7197. return std::optional<lynx::Song> (songWith (fx));
  7198. } });
  7199. const auto seed = random.nextInt64();
  7200. variants.push_back ({ "random", [=] {
  7201. juce::Random r (seed);
  7202. auto fx = base;
  7203. for (std::size_t p = 0; p < n; ++p) fx.params[p] = r.nextFloat();
  7204. return std::optional<lynx::Song> (songWith (fx));
  7205. } });
  7206. std::vector<std::size_t> cuts { n / 2 };
  7207. 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)
  7208. if (c < n) cuts.push_back (c);
  7209. for (const auto c : cuts)
  7210. variants.push_back ({ "old project (" + juce::String ((int) c) + " of " + juce::String ((int) n) + " params)", [=] { return oldState (base, c); } });
  7211. for (const auto& [variant, makeSong] : variants)
  7212. {
  7213. const auto label = juce::String::fromUTF8 (info.name) + " / " + variant;
  7214. steps.push_back ({ label + ": open", [test, &engine, label, makeSong = makeSong] {
  7215. auto song = makeSong();
  7216. if (! song)
  7217. {
  7218. test->report << "FAIL " << label << ": project reader refused the state\n";
  7219. test->ok = false;
  7220. return;
  7221. }
  7222. engine.setSong (std::move (*song));
  7223. engine.dispatchPendingMessages();
  7224. lynx::NativeEffectWindows::open (engine, 1, 0);
  7225. ++test->opened;
  7226. test->touchWindows (false, false);
  7227. } });
  7228. steps.push_back ({ label + ": run", [test, &engine] {
  7229. for (const auto rate : { 44100.0, 48000.0, 96000.0 })
  7230. engine.renderOffline (0.03, rate);
  7231. test->touchWindows (false, false);
  7232. } });
  7233. steps.push_back ({ label + ": small", [test] { test->touchWindows (true, false); } });
  7234. steps.push_back ({ label + ": large", [test] { test->touchWindows (true, true); } });
  7235. steps.push_back ({ label + ": close", [test, label] {
  7236. lynx::NativeEffectWindows::closeAll();
  7237. test->report << label << ": OK\n";
  7238. test->write ("(running)\n");
  7239. } });
  7240. }
  7241. }
  7242. // instruments: the channel window the Channel rack opens (Patcher: its graph window, not here)
  7243. for (int k = 0; k <= (int) lynx::InstrumentKind::soundfont; ++k)
  7244. {
  7245. const auto kind = (lynx::InstrumentKind) k;
  7246. if (kind == lynx::InstrumentKind::plugin || kind == lynx::InstrumentKind::patcher)
  7247. continue;
  7248. for (const auto* variant : { "default", "old project (saved and read back)", "odd settings" })
  7249. {
  7250. if (juce::String (variant) == "odd settings" && kind != lynx::InstrumentKind::soundfont)
  7251. continue;
  7252. const auto label = "instrument " + juce::String (k) + " / " + variant;
  7253. steps.push_back ({ label + ": open", [test, &engine, kind, label, variant = juce::String (variant), old = juce::String (variant) != "default"] {
  7254. auto song = lynx::Song::makeDefault();
  7255. auto channel = lynx::natives::makeChannel (kind, lynx::flStudioAccess());
  7256. lynx::ChannelDef def;
  7257. def.instrument = kind;
  7258. def.name = "Test";
  7259. song.channels.push_back (channel ? *channel : def);
  7260. if (kind == lynx::InstrumentKind::soundfont && variant != "default")
  7261. {
  7262. // a real font when FL's is there; NaN / huge / truncated settings
  7263. const auto& roots = lynx::flStudioAccess().roots;
  7264. if (! roots.data.empty())
  7265. song.channels.back().samplePath = (juce::File (juce::String::fromUTF8 (roots.data.c_str()))
  7266. .getChildFile ("Patches/Soundfonts/STR_Ensemble.sf2"))
  7267. .getFullPathName().toStdString();
  7268. if (variant == "odd settings")
  7269. song.channels.back().modelParams = { NAN, 1.0e9f, -1.0e9f, 0.5f, 7.0f };
  7270. }
  7271. if (old)
  7272. {
  7273. juce::String error;
  7274. if (auto again = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error))
  7275. song = std::move (*again);
  7276. }
  7277. const auto index = (int) song.channels.size() - 1;
  7278. engine.setSong (std::move (song));
  7279. engine.dispatchPendingMessages();
  7280. lynx::openChannelSettings (engine, index);
  7281. ++test->opened;
  7282. test->touchWindows (false, false);
  7283. } });
  7284. steps.push_back ({ label + ": run", [test, &engine] {
  7285. engine.renderOffline (0.03, 48000.0);
  7286. test->touchWindows (false, false);
  7287. } });
  7288. steps.push_back ({ label + ": small", [test] { test->touchWindows (true, false); } });
  7289. steps.push_back ({ label + ": large", [test] { test->touchWindows (true, true); } });
  7290. steps.push_back ({ label + ": close", [test, label] {
  7291. lynx::closeChannelSettings();
  7292. test->report << label << ": OK\n";
  7293. test->write ("(running)\n");
  7294. } });
  7295. }
  7296. }
  7297. test->start();
  7298. }
  7299. void runPluginOptionsTest (const juce::String& pluginPath, const juce::String& reportPath, const juce::String& shotsPath)
  7300. {
  7301. struct Test final : juce::Timer
  7302. {
  7303. juce::String reportPath, report;
  7304. juce::File shots;
  7305. std::unique_ptr<lynx::AudioEngine> engine;
  7306. std::unique_ptr<juce::DocumentWindow> mainWindow, other; // LYNX's main window stand-in; another secondary window
  7307. bool instrument = false, ok = true;
  7308. int channelIndex = -1, phase = 0;
  7309. juce::uint32 phaseStart = 0;
  7310. juce::AudioPluginInstance* instance = nullptr;
  7311. std::function<void (bool)> done;
  7312. void step (const juce::String& line)
  7313. {
  7314. report << line << "\n";
  7315. juce::File (reportPath).replaceWithText (report);
  7316. }
  7317. void expect (const juce::String& name, bool value)
  7318. {
  7319. step (name + "=" + juce::String ((int) value));
  7320. ok = ok && value;
  7321. }
  7322. void next (int to)
  7323. {
  7324. phase = to;
  7325. phaseStart = juce::Time::getMillisecondCounter();
  7326. }
  7327. int elapsed() const { return (int) (juce::Time::getMillisecondCounter() - phaseStart); }
  7328. lynx::PluginRef* ref (lynx::Song& song) const
  7329. {
  7330. if (instrument)
  7331. return channelIndex < 0 || channelIndex >= (int) song.channels.size() ? nullptr : &song.channels[(size_t) channelIndex].plugin;
  7332. return song.mixer.size() < 2 || song.mixer[1].effects.empty() ? nullptr : &song.mixer[1].effects[0].plugin;
  7333. }
  7334. const lynx::PluginRef& refNow() const { return *ref (const_cast<lynx::Song&> (engine->getSong())); }
  7335. juce::AudioPluginInstance* find()
  7336. {
  7337. if (instrument)
  7338. {
  7339. if (auto* p = dynamic_cast<lynx::PluginInstrument*> (engine->getChannelInstrument (channelIndex).get()))
  7340. return &p->getInstance();
  7341. }
  7342. else if (auto* p = dynamic_cast<lynx::PluginEffect*> (engine->getEffect (1, 0).get()))
  7343. return &p->getInstance();
  7344. return nullptr;
  7345. }
  7346. void openWindow()
  7347. {
  7348. std::shared_ptr<void> owner = instrument ? std::shared_ptr<void> (engine->getChannelInstrument (channelIndex))
  7349. : std::shared_ptr<void> (engine->getEffect (1, 0));
  7350. lynx::PluginWindows::open (owner, *instance, instance->getName(),
  7351. { engine.get(), [this] (lynx::Song& song) { return ref (song); }, instrument, instrument ? -1 : 1,
  7352. instrument ? -1 : 0, {}, {} });
  7353. }
  7354. void shot (const char* name, bool settingsPage = false)
  7355. {
  7356. if (shots != juce::File() && instance != nullptr)
  7357. step (juce::String ("shot_") + name + "=" + juce::String ((int) lynx::PluginWindows::saveWindowShot (*instance, shots.getChildFile (juce::String (name) + ".png"), settingsPage)));
  7358. }
  7359. // the plugin window is in front of the other secondary window
  7360. bool pluginInFront()
  7361. {
  7362. auto* plug = lynx::PluginWindows::hostWindowHandle (*instance);
  7363. #if JUCE_WINDOWS
  7364. return plug != nullptr && lynx::nativechild::isAbove (plug, other->getWindowHandle());
  7365. #else
  7366. auto& desktop = juce::Desktop::getInstance();
  7367. for (int i = 0; i < desktop.getNumComponents(); ++i)
  7368. if (auto* c = desktop.getComponent (i); c->getWindowHandle() == plug)
  7369. return c->isAlwaysOnTop() || desktop.getComponent (desktop.getNumComponents() - 1) == c;
  7370. return false;
  7371. #endif
  7372. }
  7373. void timerCallback() override
  7374. {
  7375. if (phase == 0) // waiting for the engine to host the plugin
  7376. {
  7377. instance = find();
  7378. if (instance == nullptr)
  7379. {
  7380. if (elapsed() > 20000)
  7381. finish ("not hosted");
  7382. return;
  7383. }
  7384. step ("hosted=" + instance->getName() + " format=" + instance->getPluginDescription().pluginFormatName);
  7385. openWindow();
  7386. next (1);
  7387. return;
  7388. }
  7389. if (phase == 1 && elapsed() >= 800) // Pin on top: off for a new plugin
  7390. {
  7391. expect ("pin_off_by_default", ! lynx::PluginWindows::isPinnedOnTop (*instance) && ! refNow().pinned);
  7392. shot ("pin-off");
  7393. const auto history = engine->getHistoryPosition();
  7394. lynx::PluginWindows::setPinnedOnTop (*instance, true);
  7395. expect ("pin_set", lynx::PluginWindows::isPinnedOnTop (*instance) && refNow().pinned);
  7396. expect ("pin_no_undo_step_project_modified", engine->getHistoryPosition() == history && engine->isModified());
  7397. // another secondary window brought in front of it
  7398. other = std::make_unique<juce::DocumentWindow> ("Another LYNX window", juce::Colours::darkslategrey, juce::DocumentWindow::closeButton);
  7399. other->setUsingNativeTitleBar (true);
  7400. other->setBounds (mainWindow->getX() + 60, mainWindow->getY() + 60, 420, 300);
  7401. other->setVisible (true);
  7402. lynx::keepAboveMainWindow (*other);
  7403. lynx::forceForegroundForTest (*other);
  7404. other->toFront (true);
  7405. next (2);
  7406. return;
  7407. }
  7408. if (phase == 2 && elapsed() >= 1200)
  7409. {
  7410. expect ("pinned_stays_in_front_of_a_clicked_window", pluginInFront());
  7411. shot ("pin-on");
  7412. // closed and opened again: the pin comes back from the project
  7413. lynx::PluginWindows::close (*instance);
  7414. openWindow();
  7415. next (3);
  7416. return;
  7417. }
  7418. if (phase == 3 && elapsed() >= 600)
  7419. {
  7420. expect ("pin_remembered_when_reopened", lynx::PluginWindows::isPinnedOnTop (*instance));
  7421. lynx::PluginWindows::setPinnedOnTop (*instance, false);
  7422. expect ("pin_cleared", ! lynx::PluginWindows::isPinnedOnTop (*instance) && ! refNow().pinned);
  7423. other->toFront (true);
  7424. next (4);
  7425. return;
  7426. }
  7427. if (phase == 4 && elapsed() >= 1000)
  7428. {
  7429. #if JUCE_WINDOWS
  7430. expect ("unpinned_goes_behind_a_clicked_window", ! pluginInFront());
  7431. #endif
  7432. other = nullptr;
  7433. // the wrapper settings page: LYNX's Velocity row in the MIDI group (instruments), default = follow
  7434. expect ("velocity_follows_midi_settings_by_default", refNow().velocityMode == lynx::prefs::pluginVelocityFollow
  7435. && refNow().fixedVelocity == lynx::prefs::defaultFixedVelocity);
  7436. shot ("wrapper-velocity-default", true);
  7437. engine->editSong ([this] (lynx::Song& song) {
  7438. if (auto* r = ref (song))
  7439. {
  7440. r->velocityMode = lynx::prefs::pluginVelocityFixed;
  7441. r->fixedVelocity = 96;
  7442. }
  7443. });
  7444. next (5);
  7445. return;
  7446. }
  7447. if (phase == 5 && elapsed() >= 400)
  7448. {
  7449. expect ("velocity_change_keeps_the_running_plugin", find() == instance);
  7450. shot ("wrapper-velocity-fixed", true);
  7451. engine->undo();
  7452. expect ("velocity_undo", refNow().velocityMode == lynx::prefs::pluginVelocityFollow && find() == instance);
  7453. // the preset menu's "Play a note when a preset loads": off by default, a user setting
  7454. expect ("audition_off_by_default", ! lynx::pluginpresetui::auditionOnLoad());
  7455. lynx::pluginpresetui::setAuditionOnLoad (true);
  7456. expect ("audition_menu_opened", lynx::PluginWindows::showPresetMenu (*instance));
  7457. next (6);
  7458. return;
  7459. }
  7460. if (phase == 6 && elapsed() >= 500) // the menu, as drawn
  7461. {
  7462. auto found = false;
  7463. auto& desktop = juce::Desktop::getInstance();
  7464. for (int c = desktop.getNumComponents(); --c >= 0 && ! found;)
  7465. if (auto* menu = desktop.getComponent (c); dynamic_cast<juce::TopLevelWindow*> (menu) == nullptr && menu->isVisible()
  7466. && menu->getHeight() > 60 && shots != juce::File())
  7467. {
  7468. const auto image = menu->createComponentSnapshot (menu->getLocalBounds(), true, 1.0f);
  7469. juce::FileOutputStream out (shots.getChildFile ("preset-menu-audition.png"));
  7470. found = out.openedOk() && juce::PNGImageFormat().writeImageToStream (image, out);
  7471. }
  7472. step ("shot_preset-menu-audition=" + juce::String ((int) found));
  7473. juce::PopupMenu::dismissAllActiveMenus();
  7474. // a preset loaded while the song is stopped: the note waits a moment, sounds, ends
  7475. const auto asked = engine->auditionPreset (*instance);
  7476. expect ("audition_only_for_channel_instruments", asked == instrument);
  7477. expect ("audition_waits_first", ! instrument || engine->auditionState() == 1);
  7478. next (7);
  7479. return;
  7480. }
  7481. if (phase == 7 && elapsed() >= 300)
  7482. {
  7483. expect ("audition_sounds", ! instrument || engine->auditionState() == 2);
  7484. next (8);
  7485. return;
  7486. }
  7487. if (phase == 8 && elapsed() >= 700)
  7488. {
  7489. expect ("audition_ends", engine->auditionState() == 0);
  7490. engine->getTransport().playing.store (true); // the song plays: no audition
  7491. expect ("no_audition_while_playing", ! engine->auditionPreset (*instance) && engine->auditionState() == 0);
  7492. engine->getTransport().playing.store (false);
  7493. lynx::pluginpresetui::setAuditionOnLoad (false);
  7494. expect ("audition_setting_off_again", ! lynx::pluginpresetui::auditionOnLoad());
  7495. finish ({});
  7496. }
  7497. }
  7498. void finish (const juce::String& failure)
  7499. {
  7500. stopTimer();
  7501. if (failure.isNotEmpty())
  7502. step ("failed=" + failure);
  7503. ok = ok && failure.isEmpty();
  7504. step (ok ? "result=OK" : "result=FAILED");
  7505. lynx::PluginWindows::closeAll();
  7506. done (ok);
  7507. }
  7508. };
  7509. auto* test = new Test();
  7510. test->reportPath = reportPath;
  7511. if (shotsPath.isNotEmpty())
  7512. {
  7513. test->shots = juce::File (shotsPath);
  7514. test->shots.createDirectory();
  7515. }
  7516. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  7517. test->done = [this, test] (bool ok) {
  7518. setApplicationReturnValue (ok ? 0 : 1);
  7519. juce::MessageManager::callAsync ([this, test] {
  7520. lynx::setMainWindowForOwnership (nullptr);
  7521. test->other = nullptr;
  7522. test->mainWindow = nullptr;
  7523. test->engine = nullptr;
  7524. delete test;
  7525. quit();
  7526. });
  7527. };
  7528. test->engine = std::make_unique<lynx::AudioEngine> (false);
  7529. test->mainWindow = std::make_unique<juce::DocumentWindow> ("LYNX test main window", juce::Colours::darkgrey, 0);
  7530. test->mainWindow->setBounds (20, 20, 300, 200);
  7531. test->mainWindow->setVisible (true);
  7532. lynx::setMainWindowForOwnership (test->mainWindow.get());
  7533. auto& host = test->engine->getPluginHost();
  7534. test->step ("plugins_in_file=" + juce::String (host.addPluginFile (juce::File (pluginPath))));
  7535. std::optional<juce::PluginDescription> chosen;
  7536. for (const auto& type : host.getKnownPlugins().getTypes())
  7537. if (juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginPath).getFileName() || type.fileOrIdentifier == pluginPath)
  7538. {
  7539. chosen = type;
  7540. break;
  7541. }
  7542. if (! chosen)
  7543. {
  7544. test->step ("result=FAILED (no plugin)");
  7545. test->done (false);
  7546. return;
  7547. }
  7548. test->instrument = chosen->isInstrument;
  7549. lynx::PluginRef ref;
  7550. ref.id = chosen->createIdentifierString().toStdString();
  7551. ref.name = chosen->name.toStdString();
  7552. test->engine->editSong ([&] (lynx::Song& song) {
  7553. if (test->instrument)
  7554. {
  7555. lynx::ChannelDef c;
  7556. c.name = ref.name;
  7557. c.instrument = lynx::InstrumentKind::plugin;
  7558. c.plugin = ref;
  7559. test->channelIndex = (int) song.channels.size();
  7560. song.channels.push_back (c);
  7561. }
  7562. else
  7563. {
  7564. while (song.mixer.size() < 2)
  7565. song.mixer.emplace_back();
  7566. lynx::EffectSlot slot;
  7567. slot.kind = lynx::EffectKind::plugin;
  7568. slot.plugin = ref;
  7569. song.mixer[1].effects.push_back (slot);
  7570. }
  7571. });
  7572. test->engine->markSaved();
  7573. test->step ("plugin=" + chosen->name + " instrument=" + juce::String ((int) test->instrument));
  7574. test->next (0);
  7575. test->startTimerHz (20);
  7576. }
  7577. void runReloadTest (const juce::String& pluginPath, const juce::String& reportPath, const juce::String& shotsPath, bool waitKill)
  7578. {
  7579. struct Test final : juce::Timer
  7580. {
  7581. juce::String reportPath, report;
  7582. juce::File shots;
  7583. std::unique_ptr<lynx::AudioEngine> engine;
  7584. std::unique_ptr<juce::DocumentWindow> mainWindow; // stands for LYNX's main window (window ownership)
  7585. bool instrument = false, waitKill = false, ok = true;
  7586. int channelIndex = -1, phase = 0, round = 0;
  7587. juce::uint32 phaseStart = 0;
  7588. int firstPid = 0, pid = 0, historyBefore = 0;
  7589. bool modifiedBefore = false;
  7590. float captured = -1.0f;
  7591. juce::AudioPluginInstance* instance = nullptr;
  7592. std::vector<lynx::ChannelDef> channelsBefore;
  7593. std::function<void (bool)> done;
  7594. lynx::AudioEngine::HostedSlot where() const { return instrument ? lynx::AudioEngine::HostedSlot { channelIndex, -1, -1 } : lynx::AudioEngine::HostedSlot { -1, 1, 0 }; }
  7595. void step (const juce::String& line)
  7596. {
  7597. report << line << "\n";
  7598. juce::File (reportPath).replaceWithText (report);
  7599. }
  7600. void expect (const juce::String& name, bool value)
  7601. {
  7602. step (name + "=" + juce::String ((int) value));
  7603. ok = ok && value;
  7604. }
  7605. void next (int to)
  7606. {
  7607. phase = to;
  7608. phaseStart = juce::Time::getMillisecondCounter();
  7609. }
  7610. int elapsed() const { return (int) (juce::Time::getMillisecondCounter() - phaseStart); }
  7611. juce::AudioPluginInstance* find()
  7612. {
  7613. if (instrument)
  7614. {
  7615. if (auto* p = dynamic_cast<lynx::PluginInstrument*> (engine->getChannelInstrument (channelIndex).get()))
  7616. return &p->getInstance();
  7617. }
  7618. else if (auto* p = dynamic_cast<lynx::PluginEffect*> (engine->getEffect (1, 0).get()))
  7619. return &p->getInstance();
  7620. return nullptr;
  7621. }
  7622. // a few blocks through the plugin (the offline engine has no audio thread): they carry parameter changes to
  7623. // the plugin's process and its values back
  7624. void pump (int blocks)
  7625. {
  7626. std::vector<float> l (512), r (512);
  7627. lynx::EffectParams none {};
  7628. for (int b = 0; b < blocks; ++b)
  7629. {
  7630. std::fill (l.begin(), l.end(), 0.0f);
  7631. std::fill (r.begin(), r.end(), 0.0f);
  7632. if (instrument)
  7633. {
  7634. if (auto in = engine->getChannelInstrument (channelIndex))
  7635. in->render (l.data(), r.data(), 512, 1.0f, 1.0f);
  7636. }
  7637. else if (auto fx = engine->getEffect (1, 0))
  7638. fx->process (l.data(), r.data(), 512, none, 120.0);
  7639. }
  7640. }
  7641. juce::AudioProcessorParameter* firstParam()
  7642. {
  7643. if (instance != nullptr)
  7644. for (auto* candidate : instance->getParameters())
  7645. if (candidate->isAutomatable() && ! candidate->isMetaParameter() && candidate != instance->getBypassParameter())
  7646. return candidate;
  7647. return nullptr;
  7648. }
  7649. void openWindow()
  7650. {
  7651. std::shared_ptr<void> owner = instrument ? std::shared_ptr<void> (engine->getChannelInstrument (channelIndex))
  7652. : std::shared_ptr<void> (engine->getEffect (1, 0));
  7653. lynx::PluginWindows::WrapperContext context { engine.get(), [this] (lynx::Song& song) -> lynx::PluginRef* {
  7654. if (instrument)
  7655. return channelIndex < 0 || channelIndex >= (int) song.channels.size()
  7656. ? nullptr : &song.channels[(size_t) channelIndex].plugin;
  7657. return song.mixer.size() < 2 || song.mixer[1].effects.empty() ? nullptr : &song.mixer[1].effects[0].plugin;
  7658. }, instrument, instrument ? -1 : 1, instrument ? -1 : 0, {}, {} };
  7659. context.reload = [] {}; // (the test reloads by itself; with it the window shows the notice)
  7660. lynx::PluginWindows::open (owner, *instance, instance->getName(), std::move (context));
  7661. }
  7662. void shot (const char* name, bool settingsPage = false)
  7663. {
  7664. if (shots != juce::File() && instance != nullptr)
  7665. step (juce::String ("shot_") + name + "=" + juce::String ((int) lynx::PluginWindows::saveWindowShot (*instance, shots.getChildFile (juce::String (name) + ".png"), settingsPage)));
  7666. }
  7667. void timerCallback() override
  7668. {
  7669. if (phase == 0) // waiting for the engine to host the plugin
  7670. {
  7671. instance = find();
  7672. if (instance == nullptr)
  7673. {
  7674. if (elapsed() > 20000)
  7675. finish ("not hosted");
  7676. return;
  7677. }
  7678. pid = firstPid = lynx::sandboxedPluginProcessId (*instance);
  7679. step ("hosted=" + instance->getName() + " format=" + instance->getPluginDescription().pluginFormatName + " pid=" + juce::String (pid));
  7680. expect ("separate_process", lynx::isSandboxedPlugin (*instance) && pid != 0);
  7681. expect ("running", ! engine->hostedPluginDown (where()) && engine->downHostedPlugins().empty());
  7682. // a setting that is captured (what a save or a backup does), then one that is not
  7683. if (auto* param = firstParam())
  7684. {
  7685. param->setValue (param->getValue() > 0.5f ? 0.13f : 0.87f);
  7686. pump (4);
  7687. engine->capturePluginStates();
  7688. captured = param->getValue();
  7689. param->setValue (captured > 0.5f ? 0.31f : 0.69f);
  7690. pump (4);
  7691. step ("param=" + param->getName (64) + " captured=" + juce::String (captured, 4) + " then=" + juce::String (param->getValue(), 4));
  7692. }
  7693. else
  7694. {
  7695. engine->capturePluginStates();
  7696. step ("param=none");
  7697. }
  7698. channelsBefore = engine->getSong().channels;
  7699. historyBefore = engine->getHistoryPosition();
  7700. modifiedBefore = engine->isModified();
  7701. if (shots != juce::File())
  7702. openWindow();
  7703. next (1);
  7704. return;
  7705. }
  7706. if (phase == 1 && elapsed() >= 600) // the plugin's process goes
  7707. {
  7708. shot (round == 0 ? "window-running" : "window-reloaded");
  7709. if (waitKill && round == 0)
  7710. {
  7711. juce::File (reportPath + ".pid").replaceWithText (juce::String (pid));
  7712. step ("waiting_for_kill pid=" + juce::String (pid));
  7713. }
  7714. else
  7715. lynx::crashSandboxedPluginForTest (*instance);
  7716. next (2);
  7717. return;
  7718. }
  7719. if (phase == 2) // LYNX notices
  7720. {
  7721. if (! engine->hostedPluginDown (where()))
  7722. {
  7723. pump (1); // (as the audio thread would: a block that gets no answer marks it too)
  7724. if (elapsed() > (waitKill && round == 0 ? 120000 : 10000))
  7725. finish ("the plugin never went down");
  7726. return;
  7727. }
  7728. step ("down_after_ms=" + juce::String (elapsed()));
  7729. const auto down = engine->downHostedPlugins();
  7730. expect ("listed_down", down.size() == 1 && down.front() == where());
  7731. expect ("listed_by_name", engine->downHostedPlugins (nameInSong()).size() == 1 && engine->downHostedPlugins ("no such plugin").empty());
  7732. next (3);
  7733. return;
  7734. }
  7735. if (phase == 3 && elapsed() >= 1500) // nothing reloads by itself
  7736. {
  7737. expect ("still_down_without_asking", engine->hostedPluginDown (where()) && find() == instance
  7738. && lynx::sandboxedPluginProcessId (*instance) == pid);
  7739. shot (round == 0 ? "reload-notice" : "reload-notice-again");
  7740. if (shots != juce::File() && round == 0)
  7741. {
  7742. lynx::PluginWindows::close (*instance);
  7743. lynx::PluginWindows::promptReload (*engine, where(), {});
  7744. next (4);
  7745. return;
  7746. }
  7747. next (5);
  7748. return;
  7749. }
  7750. if (phase == 4 && elapsed() >= 500) // the prompt a click on the channel / slot shows
  7751. {
  7752. auto found = false;
  7753. for (int c = juce::Desktop::getInstance().getNumComponents(); --c >= 0;)
  7754. if (auto* alert = dynamic_cast<juce::AlertWindow*> (juce::Desktop::getInstance().getComponent (c)))
  7755. {
  7756. const auto image = alert->createComponentSnapshot (alert->getLocalBounds(), true, 1.0f);
  7757. juce::FileOutputStream out (shots.getChildFile ("reload-prompt.png"));
  7758. found = out.openedOk() && juce::PNGImageFormat().writeImageToStream (image, out);
  7759. alert->exitModalState (0); // Close: nothing reloads
  7760. break;
  7761. }
  7762. step ("shot_reload-prompt=" + juce::String ((int) found));
  7763. next (45);
  7764. return;
  7765. }
  7766. if (phase == 45 && elapsed() >= 300)
  7767. {
  7768. expect ("still_down_after_close", engine->hostedPluginDown (where()));
  7769. next (5);
  7770. return;
  7771. }
  7772. if (phase == 5) // Reload, as the notice's button / the prompt / the menu item do
  7773. {
  7774. auto* old = instance;
  7775. const auto running = lynx::PluginWindows::reload (*engine, { where() });
  7776. instance = find();
  7777. const auto newPid = instance != nullptr ? lynx::sandboxedPluginProcessId (*instance) : 0;
  7778. expect ("reloaded", running == 1 && instance != nullptr && ! engine->hostedPluginDown (where()) && engine->downHostedPlugins().empty());
  7779. expect ("new_process", newPid != 0 && newPid != pid);
  7780. step ("pid=" + juce::String (newPid) + " same_object=" + juce::String ((int) (instance == old)));
  7781. expect ("old_window_closed", ! lynx::PluginWindows::isOpen (*old) || instance == old);
  7782. pid = newPid;
  7783. if (instance != nullptr)
  7784. {
  7785. pump (4);
  7786. if (auto* param = firstParam(); param != nullptr && captured >= 0.0f)
  7787. {
  7788. step ("param_after_reload=" + juce::String (param->getValue(), 4));
  7789. expect ("state_captured_last", std::abs (param->getValue() - captured) < 0.02f);
  7790. }
  7791. }
  7792. expect ("song_untouched", engine->getSong().channels == channelsBefore);
  7793. expect ("no_undo_step", engine->getHistoryPosition() == historyBefore && engine->isModified() == modifiedBefore);
  7794. if (instance == nullptr)
  7795. {
  7796. finish ("no instance after the reload");
  7797. return;
  7798. }
  7799. if (shots != juce::File())
  7800. openWindow();
  7801. if (round == 0) // once more: a plugin that crashes again waits for the user again
  7802. {
  7803. round = 1;
  7804. next (1);
  7805. return;
  7806. }
  7807. next (6);
  7808. return;
  7809. }
  7810. if (phase == 6 && elapsed() >= 400) // an edit and its undo keep the reloaded plugin
  7811. {
  7812. shot ("window-reloaded-twice");
  7813. auto* before = find();
  7814. engine->editSong ([] (lynx::Song& song) { song.bpm += 1.0f; });
  7815. engine->undo();
  7816. expect ("undo_keeps_the_reloaded_plugin", find() == before && ! engine->hostedPluginDown (where()));
  7817. lynx::PluginWindows::closeAll();
  7818. finish ({});
  7819. }
  7820. }
  7821. std::string nameInSong() const
  7822. {
  7823. const auto& song = engine->getSong();
  7824. return instrument ? song.channels[(size_t) channelIndex].plugin.name : song.mixer[1].effects[0].plugin.name;
  7825. }
  7826. void finish (const juce::String& failure)
  7827. {
  7828. stopTimer();
  7829. if (failure.isNotEmpty())
  7830. step ("failed=" + failure);
  7831. ok = ok && failure.isEmpty();
  7832. step (ok ? "result=OK" : "result=FAILED");
  7833. lynx::PluginWindows::closeAll();
  7834. done (ok);
  7835. }
  7836. };
  7837. lynx::setPluginSandboxAlerts (true); // (the deaths are recorded as in the app; no box: there is no main component)
  7838. auto* test = new Test();
  7839. test->reportPath = reportPath;
  7840. test->waitKill = waitKill;
  7841. if (shotsPath.isNotEmpty())
  7842. {
  7843. test->shots = juce::File (shotsPath);
  7844. test->shots.createDirectory();
  7845. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  7846. }
  7847. juce::File (reportPath + ".pid").deleteFile();
  7848. test->done = [this, test] (bool ok) {
  7849. setApplicationReturnValue (ok ? 0 : 1);
  7850. juce::MessageManager::callAsync ([this, test] {
  7851. lynx::setMainWindowForOwnership (nullptr);
  7852. test->mainWindow = nullptr;
  7853. test->engine = nullptr;
  7854. delete test;
  7855. quit();
  7856. });
  7857. };
  7858. test->engine = std::make_unique<lynx::AudioEngine> (false);
  7859. if (shotsPath.isNotEmpty())
  7860. {
  7861. test->mainWindow = std::make_unique<juce::DocumentWindow> ("LYNX test main window", juce::Colours::darkgrey, 0);
  7862. test->mainWindow->setBounds (20, 20, 300, 200);
  7863. test->mainWindow->setVisible (true);
  7864. lynx::setMainWindowForOwnership (test->mainWindow.get());
  7865. }
  7866. auto& host = test->engine->getPluginHost();
  7867. test->step ("plugins_in_file=" + juce::String (host.addPluginFile (juce::File (pluginPath))));
  7868. std::optional<juce::PluginDescription> chosen;
  7869. for (const auto& type : host.getKnownPlugins().getTypes())
  7870. if (juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginPath).getFileName() || type.fileOrIdentifier == pluginPath)
  7871. {
  7872. chosen = type;
  7873. break;
  7874. }
  7875. if (! chosen)
  7876. {
  7877. test->step ("result=FAILED (no plugin)");
  7878. test->done (false);
  7879. return;
  7880. }
  7881. test->instrument = chosen->isInstrument;
  7882. lynx::PluginRef ref;
  7883. ref.separateProcess = true;
  7884. ref.id = chosen->createIdentifierString().toStdString();
  7885. ref.name = chosen->name.toStdString();
  7886. test->engine->editSong ([&] (lynx::Song& song) {
  7887. if (test->instrument)
  7888. {
  7889. lynx::ChannelDef c;
  7890. c.name = ref.name;
  7891. c.instrument = lynx::InstrumentKind::plugin;
  7892. c.plugin = ref;
  7893. test->channelIndex = (int) song.channels.size();
  7894. song.channels.push_back (c);
  7895. }
  7896. else
  7897. {
  7898. while (song.mixer.size() < 2)
  7899. song.mixer.emplace_back();
  7900. lynx::EffectSlot slot;
  7901. slot.kind = lynx::EffectKind::plugin;
  7902. slot.plugin = ref;
  7903. song.mixer[1].effects.push_back (slot);
  7904. }
  7905. });
  7906. test->step ("plugin=" + chosen->name + " instrument=" + juce::String ((int) test->instrument));
  7907. test->next (0);
  7908. test->startTimerHz (20);
  7909. }
  7910. void runPlugWinTest (const juce::String& pluginPath, const juce::String& reportPath, const juce::String& only, int seconds)
  7911. {
  7912. struct Test final : juce::Timer
  7913. {
  7914. juce::String reportPath, report;
  7915. std::unique_ptr<lynx::AudioEngine> engine;
  7916. bool instrument = false;
  7917. int phase = 0, ticks = 0, seconds = 15, dockStep = 0;
  7918. juce::uint32 phaseStartMs = 0; // (phase 1 counts real time: the timer's ticks ran faster than 20 Hz here)
  7919. juce::AudioPluginInstance* instance = nullptr;
  7920. juce::AudioProcessorParameter* checked = nullptr;
  7921. std::unique_ptr<juce::DocumentWindow> mainWindow; // stands for LYNX's main window (window ownership)
  7922. lynx::Workspace* workspace = nullptr; // LYNX_PLUGWIN_DOCK=1: the real main window's desktop (issue #116)
  7923. int channelIndex = -1; // an instrument: its channel (added after the song's own channels)
  7924. int stepMs = 3000; // dock mode: each state held that long (screenshots)
  7925. bool keysDone = false;
  7926. bool dockOk = true;
  7927. std::function<void (bool)> done;
  7928. // LYNX_PLUGWIN_DROP=<sample> (issue #174): a Sample browser window beside the plugin window with that file
  7929. // selected. The report gives the row's and the editor's places on screen with what LYNX sees there (for a
  7930. // real drag by xdotool / SendInput in that time), and, before the plugin is removed, whether the plugin took
  7931. // the file (its saved state names it).
  7932. juce::File dropFile;
  7933. std::unique_ptr<juce::DocumentWindow> dropWindow;
  7934. lynx::BrowserComponent* dropBrowser = nullptr;
  7935. int dropStage = 0;
  7936. juce::uint32 dropReadyMs = 0; // (the Browser may take long to list a big library: the time counts from here)
  7937. void dropTick (int elapsedMs)
  7938. {
  7939. if (dropStage == 0 && elapsedMs >= 1000)
  7940. {
  7941. lynx::externaldrag::install();
  7942. auto content = lynx::BrowserComponent::makeSampleBrowserContent (*engine, [this] (lynx::BrowserComponent& b) { dropBrowser = &b; });
  7943. dropWindow = std::make_unique<juce::DocumentWindow> ("LYNX test sample browser", juce::Colours::darkgrey, 0);
  7944. dropWindow->setContentOwned (content.release(), false);
  7945. dropWindow->setBounds (20, 240, 340, 520);
  7946. dropWindow->setVisible (true);
  7947. if (dropBrowser != nullptr)
  7948. {
  7949. dropBrowser->showFilterForSnapshot (dropFile.getParentDirectory(), lynx::browserview::ContentFilter::all);
  7950. step ("drop_locate=" + juce::String ((int) dropBrowser->locateFile (dropFile)));
  7951. }
  7952. dropStage = 1;
  7953. }
  7954. else if (dropStage == 1 && elapsedMs >= 2500)
  7955. {
  7956. using namespace lynx::externaldrag;
  7957. const auto row = dropBrowser != nullptr ? dropBrowser->selectedRowScreenBounds() : juce::Rectangle<int>();
  7958. const auto from = row.getCentre();
  7959. // (physical pixels too: SendInput / xdotool work in those)
  7960. auto physical = [] (juce::Point<int> p) {
  7961. const auto q = juce::Desktop::getInstance().getDisplays().logicalToPhysical (p);
  7962. return " phys=" + juce::String (q.x) + "," + juce::String (q.y);
  7963. };
  7964. step ("drop_source=" + juce::String (from.x) + "," + juce::String (from.y) + " place=" + placeName (placeAt (from)) + physical (from));
  7965. if (const auto pid = lynx::sandboxedPluginProcessId (*instance); pid != 0)
  7966. step ("drop_target_pid=" + juce::String (pid)); // (its window is the other process's)
  7967. else if (auto* editor = instance->getActiveEditor())
  7968. {
  7969. const auto to = editor->getScreenBounds().getCentre();
  7970. step ("drop_target=" + juce::String (to.x) + "," + juce::String (to.y) + " place=" + placeName (placeAt (to)) + physical (to));
  7971. }
  7972. const auto files = filesOf (juce::String (lynx::BrowserComponent::dragDescription) + "|" + dropFile.getFullPathName(), nullptr);
  7973. step ("drop_files=" + files.joinIntoString (";"));
  7974. dropStage = 2;
  7975. dropReadyMs = juce::Time::getMillisecondCounter();
  7976. }
  7977. }
  7978. void dropResult()
  7979. {
  7980. juce::MemoryBlock state;
  7981. instance->getStateInformation (state);
  7982. const auto name = dropFile.getFileNameWithoutExtension().toStdString();
  7983. auto holds = [&name] (const juce::MemoryBlock& block) {
  7984. const auto* bytes = static_cast<const char*> (block.getData());
  7985. return ! name.empty() && std::search (bytes, bytes + block.getSize(), name.begin(), name.end()) != bytes + block.getSize();
  7986. };
  7987. auto received = holds (state);
  7988. // (JUCE's VST3 host keeps the plugin's own state base64-encoded inside an XML of its own)
  7989. auto xml = juce::AudioProcessor::getXmlFromBinary (state.getData(), (int) state.getSize());
  7990. if (xml == nullptr)
  7991. xml = juce::parseXML (state.toString());
  7992. if (! received && xml != nullptr)
  7993. for (auto* e : xml->getChildIterator())
  7994. {
  7995. juce::MemoryBlock inner;
  7996. if (inner.fromBase64Encoding (e->getAllSubText().trim()) && holds (inner))
  7997. received = true;
  7998. }
  7999. step ("drop_received=" + juce::String ((int) received));
  8000. }
  8001. // issue #116 (with LYNX_DOCKED_PLUGINS=1 and LYNX_PLUGWIN_DOCK=1), FL's f116 sequence for every floating
  8002. // panel: the docked plugin window goes behind a clicked panel and comes back in front when clicked; a
  8003. // panel called by its key comes in front too; Detached reopens it as a window of its own, which stays above
  8004. // every panel clicked (it is owned by the main window).
  8005. const std::array<lynx::workspace::Panel, 4> dockPanels { lynx::workspace::Panel::channelRack, lynx::workspace::Panel::playlist,
  8006. lynx::workspace::Panel::pianoRoll, lynx::workspace::Panel::mixer };
  8007. const int dockSteps = 2 * 4 + 18; // (the last one reports dock_result)
  8008. int danceChannel = -1; // issue #116 slice 4: a dance channel's dancer over the docked plugin
  8009. lynx::MainComponent* ui = nullptr; // dock mode: the real main window's contents
  8010. struct ScaleSpy final : juce::ComponentPeer::ScaleFactorListener
  8011. {
  8012. int calls = 0;
  8013. double last = 0.0;
  8014. void nativeScaleFactorChanged (double s) override { ++calls; last = s; }
  8015. } scaleSpy;
  8016. juce::ComponentPeer* spiedPeer = nullptr;
  8017. void* panelHandle (lynx::workspace::Panel p) const { return workspace->getFrame (p).getWindowHandle(); }
  8018. void dockCheck (int at)
  8019. {
  8020. using lynx::workspace::Panel;
  8021. auto* main = mainWindow->getWindowHandle();
  8022. auto* plug = lynx::PluginWindows::hostWindowHandle (*instance);
  8023. auto expect = [this] (const juce::String& name, bool value) {
  8024. step (name + "=" + juce::String ((int) value));
  8025. dockOk = dockOk && value;
  8026. };
  8027. auto id = [] (Panel p) { return juce::String (lynx::workspace::panelId (p)); };
  8028. if (at == 0)
  8029. {
  8030. expect ("docked", lynx::PluginWindows::isDocked (*instance));
  8031. expect ("plugin_native_child", plug != nullptr && lynx::nativechild::parentOf (plug) == main);
  8032. for (auto p : dockPanels)
  8033. {
  8034. auto* h = panelHandle (p);
  8035. expect (id (p) + "_visible", workspace->isPanelVisible (p));
  8036. expect (id (p) + "_native_child", h != nullptr && h != main && lynx::nativechild::parentOf (h) == main);
  8037. expect ("plugin_above_" + id (p) + "_when_opened", lynx::nativechild::isAbove (plug, h));
  8038. }
  8039. expect ("browser_plain", ! workspace->isNativePanel (Panel::browser));
  8040. }
  8041. if (at < 2 * 4)
  8042. {
  8043. const auto p = dockPanels[at / 2];
  8044. if (at % 2 == 0)
  8045. {
  8046. workspace->activate (p); // a click on the panel
  8047. expect (id (p) + "_above_plugin_after_its_click", lynx::nativechild::isAbove (panelHandle (p), plug));
  8048. // the plugin stays above the panels nobody clicked
  8049. for (auto other : dockPanels)
  8050. if (other != p)
  8051. expect ("plugin_above_" + id (other) + "_after_" + id (p) + "_click", lynx::nativechild::isAbove (plug, panelHandle (other)));
  8052. }
  8053. else
  8054. {
  8055. lynx::PluginWindows::open ({}, *instance, {}); // (open again = a click on the plugin)
  8056. expect ("plugin_above_" + id (p) + "_after_plugin_click", lynx::nativechild::isAbove (plug, panelHandle (p)));
  8057. }
  8058. return;
  8059. }
  8060. if (at == 8)
  8061. {
  8062. // a layout change elsewhere (a panel resized, the Browser shown) keeps the plugin in front; a panel
  8063. // called by its key comes in front of it
  8064. workspace->hide (Panel::browser);
  8065. workspace->show (Panel::browser);
  8066. for (auto p : dockPanels)
  8067. expect ("plugin_above_" + id (p) + "_after_layout_change", lynx::nativechild::isAbove (plug, panelHandle (p)));
  8068. workspace->show (Panel::mixer);
  8069. expect ("mixer_above_plugin_after_show", lynx::nativechild::isAbove (panelHandle (Panel::mixer), plug));
  8070. }
  8071. else if (at == 9)
  8072. {
  8073. // the setup wizard (Options › Setup wizard; first start) in front of the native panels and the plugin
  8074. ui->showSetupWizard();
  8075. }
  8076. else if (at == 10)
  8077. {
  8078. auto* overlay = ui->setupOverlayForTest();
  8079. auto* h = overlay != nullptr ? overlay->getWindowHandle() : nullptr;
  8080. expect ("setup_overlay_native_child", h != nullptr && h != main && lynx::nativechild::parentOf (h) == main);
  8081. expect ("setup_overlay_above_plugin", lynx::nativechild::isAbove (h, plug));
  8082. for (auto p : dockPanels)
  8083. expect ("setup_overlay_above_" + id (p), lynx::nativechild::isAbove (h, panelHandle (p)));
  8084. workspace->activate (Panel::playlist); // (a panel brought in front by code: the overlay stays in front)
  8085. lynx::PluginWindows::open ({}, *instance, {});
  8086. expect ("setup_overlay_stays_in_front", lynx::nativechild::isAbove (h, plug) && lynx::nativechild::isAbove (h, panelHandle (Panel::playlist)));
  8087. }
  8088. else if (at == 11)
  8089. {
  8090. ui->closeSetupWizardForSnapshot();
  8091. expect ("setup_overlay_closed", ui->setupOverlayForTest() == nullptr);
  8092. // drops: JUCE's list of windows in the native stacking order once a drag starts
  8093. workspace->activate (Panel::mixer);
  8094. workspace->hide (Panel::browser);
  8095. workspace->show (Panel::browser);
  8096. lynx::matchWindowOrderToScreen();
  8097. auto children = lynx::nativechild::attachedChildren (main);
  8098. auto& desktop = juce::Desktop::getInstance();
  8099. int last = -1;
  8100. bool ordered = children.size() >= 5;
  8101. for (auto* c : children)
  8102. if (c->isVisible())
  8103. {
  8104. int at2 = -1;
  8105. for (int k = 0; k < desktop.getNumComponents(); ++k)
  8106. if (desktop.getComponent (k) == c)
  8107. at2 = k;
  8108. ordered = ordered && at2 > last;
  8109. last = at2;
  8110. }
  8111. expect ("drop_order_matches_screen", ordered);
  8112. }
  8113. else if (at == 12)
  8114. {
  8115. // the main window's scale changes (a display with another scale): every native child placed again in
  8116. // physical pixels, the docked editor's window told (JUCE tells child windows nothing by itself)
  8117. for (int i = 0; i < juce::ComponentPeer::getNumPeers(); ++i)
  8118. if (auto* peer = juce::ComponentPeer::getPeer (i); peer != nullptr && peer->getNativeHandle() == plug)
  8119. spiedPeer = peer;
  8120. if (spiedPeer != nullptr)
  8121. spiedPeer->addScaleFactorListener (&scaleSpy);
  8122. lynx::nativechild::notifyScaleListenersForTest (*mainWindow);
  8123. juce::Desktop::getInstance().setGlobalScaleFactor (1.25f); // and LYNX's own UI zoom
  8124. }
  8125. else if (at == 13)
  8126. {
  8127. bool placed = true;
  8128. for (auto* c : lynx::nativechild::attachedChildren (main))
  8129. placed = placed && (! c->isVisible() || lynx::nativechild::placedPhysically (*c));
  8130. expect ("native_children_placed_at_125", placed);
  8131. expect ("docked_editor_told_the_scale", scaleSpy.calls > 0 && spiedPeer != nullptr
  8132. && std::abs (scaleSpy.last - spiedPeer->getPlatformScaleFactor()) < 0.001);
  8133. if (spiedPeer != nullptr && juce::ComponentPeer::isValidPeer (spiedPeer))
  8134. spiedPeer->removeScaleFactorListener (&scaleSpy);
  8135. juce::Desktop::getInstance().setGlobalScaleFactor (1.0f);
  8136. lynx::PluginWindows::setDetached (*instance, true);
  8137. }
  8138. else if (at == 14)
  8139. {
  8140. expect ("detached_reopened", lynx::PluginWindows::isOpen (*instance) && ! lynx::PluginWindows::isDocked (*instance));
  8141. expect ("detached_owned_by_main", plug != nullptr && lynx::nativechild::ownerOf (plug) == main);
  8142. expect ("detached_saved", find() == instance && engineRef() != nullptr && engineRef()->detached);
  8143. for (auto p : dockPanels)
  8144. workspace->activate (p);
  8145. }
  8146. else if (at == 15)
  8147. {
  8148. // (an owned top-level window: above the main window and so above all its child windows)
  8149. expect ("detached_stays_above_clicked_panels", plug != nullptr && lynx::nativechild::ownerOf (plug) == main
  8150. && lynx::nativechild::parentOf (plug) != main && lynx::PluginWindows::isOpen (*instance));
  8151. lynx::PluginWindows::setDetached (*instance, false);
  8152. }
  8153. else if (at == 16)
  8154. {
  8155. // issue #116 slice 4: a Fruity Dance dancer standing on the docked plugin window, in front of it
  8156. auto* stage = dynamic_cast<lynx::DanceStage*> (ui->danceStageForTest());
  8157. juce::Rectangle<int> over;
  8158. for (auto* c : lynx::nativechild::attachedChildren (main))
  8159. if (c->getWindowHandle() == plug)
  8160. over = ui->getLocalArea (nullptr, c->getScreenBounds());
  8161. expect ("dance_stage", stage != nullptr && ! over.isEmpty());
  8162. lynx::dance::Settings s;
  8163. s.move = lynx::dance::held; // (a still pose: the pixels tested below stay where they are)
  8164. s.x = over.getCentreX();
  8165. s.y = over.getCentreY() + 70;
  8166. const auto state = lynx::dance::toState (s);
  8167. engine->editSongStructural ([this, state] (lynx::Song& song) {
  8168. lynx::ChannelDef c;
  8169. c.name = "Fruity Dance";
  8170. c.instrument = lynx::InstrumentKind::fruitydance;
  8171. c.pluginState = state;
  8172. danceChannel = (int) song.channels.size();
  8173. song.channels.push_back (c);
  8174. });
  8175. engine->dispatchPendingMessages();
  8176. if (stage != nullptr)
  8177. stage->update();
  8178. }
  8179. else if (at == 17)
  8180. {
  8181. auto* stage = dynamic_cast<lynx::DanceStage*> (ui->danceStageForTest());
  8182. auto* w = stage != nullptr ? stage->windowOf (danceChannel) : nullptr;
  8183. auto* h = w != nullptr ? w->getWindowHandle() : nullptr;
  8184. expect ("dancer_window_native_child", h != nullptr && h != main && lynx::nativechild::parentOf (h) == main);
  8185. expect ("dancer_window_layered", lynx::nativechild::isLayered (h));
  8186. expect ("dancer_above_plugin", lynx::nativechild::isAbove (h, plug));
  8187. for (auto p : dockPanels)
  8188. expect ("dancer_above_" + id (p), lynx::nativechild::isAbove (h, panelHandle (p)));
  8189. // panels and the plugin brought in front (clicks, keys): the dancer stays in front of them
  8190. workspace->activate (Panel::mixer);
  8191. workspace->show (Panel::pianoRoll);
  8192. lynx::PluginWindows::open ({}, *instance, {});
  8193. expect ("dancer_stays_in_front", lynx::nativechild::isAbove (h, plug) && lynx::nativechild::isAbove (h, panelHandle (Panel::mixer))
  8194. && lynx::nativechild::isAbove (h, panelHandle (Panel::pianoRoll)));
  8195. // the mouse: the dancer's body takes it, its window's transparent pixels let it through
  8196. if (w != nullptr)
  8197. {
  8198. const auto picture = w->createComponentSnapshot (w->getLocalBounds(), true, 1.0f);
  8199. const auto body = stage->bodyOf (danceChannel) - (w->getScreenPosition() - stage->getScreenPosition());
  8200. juce::Point<int> solid { -1, -1 }, clear { -1, -1 };
  8201. for (int y = body.getCentreY() - 10; y < body.getBottom() && solid.x < 0; ++y)
  8202. for (int x = body.getX(); x < body.getRight() && solid.x < 0; ++x)
  8203. if (picture.getBounds().contains (x, y) && picture.getPixelAt (x, y).getAlpha() == 255)
  8204. solid = { x, y };
  8205. for (int y = 0; y < picture.getHeight() && clear.x < 0; y += 2)
  8206. for (int x = 0; x < picture.getWidth() && clear.x < 0; x += 2)
  8207. if (picture.getPixelAt (x, y).getAlpha() == 0 && ! body.expanded (8).contains (x, y))
  8208. clear = { x, y };
  8209. step ("dancer_window=" + w->getBounds().toString() + " solid=" + solid.toString() + " clear=" + clear.toString());
  8210. auto* atSolid = lynx::nativechild::windowAt (*w, solid);
  8211. auto* atClear = lynx::nativechild::windowAt (*w, clear);
  8212. expect ("dancer_takes_its_body_clicks", solid.x >= 0 && atSolid == h);
  8213. expect ("dancer_lets_clicks_through", clear.x >= 0 && atClear != nullptr && atClear != h);
  8214. expect ("stage_leaves_the_mouse", ! stage->hitTest (stage->bodyOf (danceChannel).getCentreX(), stage->bodyOf (danceChannel).getCentreY()));
  8215. }
  8216. }
  8217. else if (at == 18)
  8218. {
  8219. // no dance channel: no dancer window (nothing drawn, no cost)
  8220. auto* stage = dynamic_cast<lynx::DanceStage*> (ui->danceStageForTest());
  8221. engine->editSongStructural ([this] (lynx::Song& song) {
  8222. if (danceChannel >= 0 && danceChannel < (int) song.channels.size())
  8223. song.channels.erase (song.channels.begin() + danceChannel);
  8224. });
  8225. engine->dispatchPendingMessages();
  8226. if (stage != nullptr)
  8227. stage->update();
  8228. expect ("dancer_window_gone", stage != nullptr && stage->windowCount() == 0);
  8229. }
  8230. else if (at == 19 || at == 20)
  8231. {
  8232. // round 190ev (issue #152, "flickering windows"): on Windows a docked panel no longer fades by its
  8233. // window's alpha (each fade switched its drawing surface twice and the panel flashed); it shows and
  8234. // hides at once, as FL's docked windows. Elsewhere round 190i's fade stays.
  8235. auto& frame = workspace->getFrame (Panel::mixer);
  8236. if (at == 19)
  8237. {
  8238. workspace->show (Panel::mixer);
  8239. expect ("mixer_above_plugin_when_shown", lynx::nativechild::isAbove (panelHandle (Panel::mixer), plug));
  8240. workspace->hide (Panel::mixer);
  8241. expect ("mixer_hides_at_once", ! frame.isVisible() && workspace->nativeFadeDirection (Panel::mixer) == 0
  8242. && frame.getAlpha() == 1.0f && ! lynx::nativechild::isLayered (frame.getWindowHandle()));
  8243. }
  8244. else
  8245. {
  8246. workspace->show (Panel::mixer);
  8247. expect ("mixer_shows_at_once", frame.isVisible() && frame.getAlpha() == 1.0f && workspace->nativeFadeDirection (Panel::mixer) == 0
  8248. && ! lynx::nativechild::isLayered (frame.getWindowHandle())
  8249. && lynx::nativechild::isAbove (panelHandle (Panel::mixer), plug));
  8250. }
  8251. }
  8252. else if (at >= 21 && at <= 23)
  8253. {
  8254. // round 190ev (issue #152, "the Channel rack almost never comes to the front"): LYNX's own editor
  8255. // windows (here a channel's settings) are docked like FL's plugin windows, so a click on the rack
  8256. // brings the rack in front of them and a click on one brings it back; a click inside a docked
  8257. // plugin's own view (a native window JUCE never hears of) brings that plugin window in front.
  8258. auto docked = [] {
  8259. auto& desktop = juce::Desktop::getInstance();
  8260. for (int i = 0; i < desktop.getNumComponents(); ++i)
  8261. if (auto* c = desktop.getComponent (i); c != nullptr && c->isVisible() && (bool) c->getProperties()["lynxDockedWindow"])
  8262. return c;
  8263. return (juce::Component*) nullptr;
  8264. };
  8265. auto* rack = panelHandle (Panel::channelRack);
  8266. if (at == 21)
  8267. {
  8268. lynx::openChannelSettings (*engine, 0);
  8269. auto* ed = docked();
  8270. auto* h = ed != nullptr ? ed->getWindowHandle() : nullptr;
  8271. expect ("editor_docked", h != nullptr && lynx::nativechild::parentOf (h) == main && lynx::nativechild::ownerOf (h) == nullptr);
  8272. expect ("editor_above_rack_when_opened", h != nullptr && lynx::nativechild::isAbove (h, rack));
  8273. workspace->activate (Panel::channelRack); // a click on the rack
  8274. expect ("rack_above_editor_after_its_click", h != nullptr && lynx::nativechild::isAbove (rack, h));
  8275. // a real click (a message to the editor's own window) on its title bar, at a point where the editor
  8276. // can be seen. Round 190fc (0.1.27 RC M1): JUCE takes a button-down only where the system says its
  8277. // window is the one under the point (HWNDComponentPeer::contains asks WindowFromPoint), so the old
  8278. // fixed point (60, 8) was dropped whenever the rack, raised just above, covered it there: the
  8279. // check read 0 while real clicks (on what can be seen) raise the editor.
  8280. if (h != nullptr && ed != nullptr)
  8281. {
  8282. juce::Point<int> at (-1, -1);
  8283. for (int x = 30; x < ed->getWidth() - 40 && at.x < 0; x += 12)
  8284. if (lynx::nativechild::windowAt (*ed, { x, 8 }) == h)
  8285. at = { x, 8 };
  8286. step (juce::String ("editor_title_visible_at=") + juce::String (at.x));
  8287. if (at.x >= 0)
  8288. {
  8289. const auto scale = ed->getPeer() != nullptr ? ed->getPeer()->getPlatformScaleFactor() * (double) ed->getDesktopScaleFactor() : 1.0;
  8290. lynx::nativechild::postClickForTest (h, (at.toDouble() * scale).roundToInt());
  8291. }
  8292. }
  8293. }
  8294. else if (at == 22)
  8295. {
  8296. auto* ed = docked();
  8297. auto* h = ed != nullptr ? ed->getWindowHandle() : nullptr;
  8298. expect ("editor_above_rack_after_its_click", h != nullptr && lynx::nativechild::isAbove (h, rack));
  8299. workspace->activate (Panel::channelRack);
  8300. expect ("rack_above_plugin_after_its_click", lynx::nativechild::isAbove (rack, plug));
  8301. auto* view = lynx::nativechild::innermostChild (plug);
  8302. step (juce::String ("plugin_view_window=") + (view != nullptr ? "1" : "0"));
  8303. if (view != nullptr) // a click in the plugin's own view, near its top-left corner
  8304. lynx::nativechild::postClickForTest (view, { 2, 2 });
  8305. }
  8306. else
  8307. {
  8308. if (lynx::nativechild::innermostChild (plug) != nullptr)
  8309. expect ("plugin_above_rack_after_click_in_its_view", lynx::nativechild::isAbove (plug, rack));
  8310. lynx::closeChannelSettings();
  8311. // FL's Tools > Macros > Switch all plugin editors to > Detached (round 190i)
  8312. lynx::PluginWindows::setAllDetached (*engine, true);
  8313. }
  8314. }
  8315. else if (at == 24)
  8316. {
  8317. expect ("macro_detached_the_open_editor", lynx::PluginWindows::isOpen (*instance) && ! lynx::PluginWindows::isDocked (*instance)
  8318. && plug != nullptr && lynx::nativechild::ownerOf (plug) == main);
  8319. expect ("macro_detached_saved", find() == instance && engineRef() != nullptr && engineRef()->detached);
  8320. lynx::PluginWindows::setAllDetached (*engine, false); // ... > Attached
  8321. }
  8322. else
  8323. {
  8324. expect ("docked_again", lynx::PluginWindows::isDocked (*instance) && engineRef() != nullptr && ! engineRef()->detached);
  8325. step (juce::String ("dock_result=") + (dockOk ? "OK" : "FAILED"));
  8326. }
  8327. }
  8328. const lynx::PluginRef* engineRef() const
  8329. {
  8330. const auto& song = engine->getSong();
  8331. if (instrument)
  8332. return channelIndex < 0 || channelIndex >= (int) song.channels.size() ? nullptr : &song.channels[(size_t) channelIndex].plugin;
  8333. return song.mixer.size() < 2 || song.mixer[1].effects.empty() ? nullptr : &song.mixer[1].effects[0].plugin;
  8334. }
  8335. void step (const juce::String& line)
  8336. {
  8337. report << line << "\n";
  8338. juce::File (reportPath).replaceWithText (report);
  8339. }
  8340. juce::AudioPluginInstance* find()
  8341. {
  8342. if (instrument)
  8343. {
  8344. if (auto* p = dynamic_cast<lynx::PluginInstrument*> (engine->getChannelInstrument (channelIndex).get()))
  8345. return &p->getInstance();
  8346. }
  8347. else if (auto* p = dynamic_cast<lynx::PluginEffect*> (engine->getEffect (1, 0).get()))
  8348. return &p->getInstance();
  8349. return nullptr;
  8350. }
  8351. void timerCallback() override
  8352. {
  8353. ++ticks;
  8354. if (phase == 0) // waiting for the engine to host the plugin
  8355. {
  8356. instance = find();
  8357. if (instance == nullptr)
  8358. {
  8359. if (ticks > 200)
  8360. {
  8361. step ("result=FAILED (not hosted)");
  8362. stopTimer();
  8363. done (false);
  8364. }
  8365. return;
  8366. }
  8367. step ("hosted=" + instance->getName() + " format=" + instance->getPluginDescription().pluginFormatName);
  8368. step ("programs=" + juce::String (instance->getNumPrograms()));
  8369. for (int p = 0; p < juce::jmin (5, instance->getNumPrograms()); ++p)
  8370. step ("program" + juce::String (p) + "=" + instance->getProgramName (p));
  8371. step ("save_formats=" + lynx::pluginpresetui::saveWildcard (*instance));
  8372. // preset round trip: save, change the first parameter, load, compare
  8373. juce::AudioProcessorParameter* param = nullptr;
  8374. for (auto* candidate : instance->getParameters())
  8375. if (candidate->isAutomatable() && ! candidate->isMetaParameter() && candidate != instance->getBypassParameter())
  8376. {
  8377. param = candidate;
  8378. break;
  8379. }
  8380. if (param != nullptr)
  8381. {
  8382. step ("param=" + param->getName (64));
  8383. checked = param;
  8384. const auto file = lynx::pluginpresetui::folderFor (instance->getName()).getChildFile ("plugwintest.lynxpreset");
  8385. juce::String error;
  8386. const auto before = param->getValue();
  8387. const auto saved = lynx::pluginpresetui::save (*instance, file, "plugwintest", error);
  8388. param->setValueNotifyingHost (before > 0.5f ? 0.1f : 0.9f);
  8389. const auto changed = param->getValue();
  8390. const auto loaded = saved && lynx::pluginpresetui::load (*instance, file, error);
  8391. step ("preset_roundtrip saved=" + juce::String ((int) saved) + " loaded=" + juce::String ((int) loaded) + " param0 before="
  8392. + juce::String (before, 4) + " changed=" + juce::String (changed, 4) + " after=" + juce::String (param->getValue(), 4)
  8393. + (error.isNotEmpty() ? " error=" + error : juce::String()));
  8394. for (const auto* ext : { "fxp", "fxb", "vstpreset" })
  8395. {
  8396. juce::String e2;
  8397. const auto f2 = file.withFileExtension (ext);
  8398. const auto ok2 = lynx::pluginpresetui::save (*instance, f2, "plugwintest", e2) && lynx::pluginpresetui::load (*instance, f2, e2);
  8399. step (juce::String ("preset_") + ext + "=" + juce::String ((int) ok2) + (e2.isNotEmpty() ? " (" + e2 + ")" : juce::String()));
  8400. f2.deleteFile();
  8401. }
  8402. step ("browser_lists=" + juce::String (lynx::pluginpresetui::userPresets (instance->getName()).size()));
  8403. }
  8404. std::shared_ptr<void> owner = instrument ? std::shared_ptr<void> (engine->getChannelInstrument (channelIndex))
  8405. : std::shared_ptr<void> (engine->getEffect (1, 0));
  8406. lynx::PluginWindows::open (owner, *instance, instance->getName(),
  8407. { engine.get(), [this] (lynx::Song& song) -> lynx::PluginRef* {
  8408. if (instrument)
  8409. return channelIndex < 0 || channelIndex >= (int) song.channels.size()
  8410. ? nullptr : &song.channels[(size_t) channelIndex].plugin;
  8411. return song.mixer.size() < 2 || song.mixer[1].effects.empty() ? nullptr : &song.mixer[1].effects[0].plugin;
  8412. }, instrument });
  8413. owner.reset();
  8414. step ("window_open=" + juce::String ((int) lynx::PluginWindows::isOpen (*instance)));
  8415. phase = 1;
  8416. ticks = 0;
  8417. phaseStartMs = juce::Time::getMillisecondCounter();
  8418. return;
  8419. }
  8420. if (phase == 1 && ticks >= 30 && ! keysDone && juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGWIN_KEYS", {}).isNotEmpty() && instance->getActiveEditor() != nullptr)
  8421. keysDone = ! lynx::pluginKeysTestTick (*instance->getActiveEditor(),
  8422. [this] (bool on) {
  8423. engine->editSong ([this, on] (lynx::Song& song) {
  8424. (instrument ? song.channels[(size_t) channelIndex].plugin : song.mixer[1].effects[0].plugin).hostKeysFirst = on;
  8425. });
  8426. },
  8427. [this] (const juce::String& line) { step (line); });
  8428. const auto elapsedMs = (int) (juce::Time::getMillisecondCounter() - phaseStartMs);
  8429. if (phase == 1 && ticks == 20 && checked != nullptr)
  8430. step ("param_after_1s=" + juce::String (checked->getValue(), 4));
  8431. // round 190in: LYNX_PLUGWIN_MENU=<png>: FL's ▸ wrapper menu of the open window (two columns for a channel)
  8432. if (const auto menuShot = juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGWIN_MENU", {}); phase == 1 && ticks == 10 && menuShot.isNotEmpty())
  8433. if (const auto menu = lynx::PluginWindows::wrapperMenuForSnapshot (*instance))
  8434. {
  8435. juce::PopupMenu left, right;
  8436. auto* to = &left;
  8437. for (juce::PopupMenu::MenuItemIterator it (*menu); it.next();)
  8438. {
  8439. to->addItem (it.getItem());
  8440. if (it.getItem().shouldBreakAfter)
  8441. to = &right;
  8442. }
  8443. juce::StringArray names { "Plugin" };
  8444. std::vector<juce::PopupMenu> menus { left };
  8445. if (right.getNumItems() > 0)
  8446. {
  8447. names.add ("Channel");
  8448. menus.push_back (right);
  8449. }
  8450. LynxApplication::saveMenus (names, menus, menuShot);
  8451. step ("wrapper_menu_items=" + juce::String (left.getNumItems()) + "+" + juce::String (right.getNumItems()));
  8452. }
  8453. // (3 s apart: time for screenshots of each state)
  8454. if (phase == 1 && workspace != nullptr && dockStep < dockSteps && elapsedMs >= (dockStep + 1) * stepMs)
  8455. dockCheck (dockStep++);
  8456. if (phase == 1 && dropFile.existsAsFile())
  8457. dropTick (elapsedMs);
  8458. // (with LYNX_PLUGWIN_DROP: `seconds` after the drop places were reported, time for the drag)
  8459. const auto dropDone = ! dropFile.existsAsFile()
  8460. || (dropStage == 2 && (int) (juce::Time::getMillisecondCounter() - dropReadyMs) >= seconds * 1000);
  8461. if (phase == 1 && elapsedMs >= seconds * 1000 && dropDone && (workspace == nullptr || dockStep >= dockSteps)) // remove the plugin from the song
  8462. {
  8463. if (dropFile.existsAsFile())
  8464. dropResult();
  8465. engine->editSong ([this] (lynx::Song& song) {
  8466. if (instrument)
  8467. {
  8468. if (channelIndex >= 0 && channelIndex < (int) song.channels.size())
  8469. song.channels.erase (song.channels.begin() + channelIndex);
  8470. }
  8471. else
  8472. song.mixer[1].effects.clear();
  8473. });
  8474. step ("removed");
  8475. phase = 2;
  8476. ticks = 0;
  8477. return;
  8478. }
  8479. if (phase == 2 && ticks >= 40)
  8480. {
  8481. const auto open = lynx::PluginWindows::isOpen (*instance);
  8482. step ("window_open_after_remove=" + juce::String ((int) open));
  8483. step (open || ! dockOk ? "result=FAILED" : "result=OK");
  8484. stopTimer();
  8485. lynx::PluginWindows::closeAll();
  8486. done (! open && dockOk);
  8487. }
  8488. }
  8489. };
  8490. // round 190in: LYNX_PLUGWIN_ZOOM=<percent>: LYNX's interface zoom for the run (the wrapper's header at 150 %)
  8491. if (const auto zoom = juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGWIN_ZOOM", {}).getIntValue(); zoom >= 50 && zoom <= 300)
  8492. juce::Desktop::getInstance().setGlobalScaleFactor ((float) zoom / 100.0f);
  8493. auto* test = new Test();
  8494. test->reportPath = reportPath;
  8495. test->seconds = seconds;
  8496. if (const auto drop = juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGWIN_DROP", {}); drop.isNotEmpty())
  8497. test->dropFile = juce::File (drop);
  8498. test->done = [this, test] (bool ok) {
  8499. setApplicationReturnValue (ok ? 0 : 1);
  8500. juce::MessageManager::callAsync ([this, test] {
  8501. lynx::setMainWindowForOwnership (nullptr);
  8502. lynx::PluginWindows::setDockWorkspace (nullptr);
  8503. test->dropWindow = nullptr; // (its Browser before the engine)
  8504. test->workspace = nullptr;
  8505. test->mainWindow = nullptr; // (dock mode: the main component with it, before the engine)
  8506. test->engine = nullptr;
  8507. delete test;
  8508. quit();
  8509. });
  8510. };
  8511. test->engine = std::make_unique<lynx::AudioEngine> (false);
  8512. test->mainWindow = std::make_unique<juce::DocumentWindow> ("LYNX test main window", juce::Colours::darkgrey, 0);
  8513. test->mainWindow->setBounds (20, 20, 300, 200);
  8514. if (juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGWIN_DOCK", {}) == "1" && lynx::nativechild::dockingEnabled())
  8515. {
  8516. // the real main window's contents (it docks plugin windows in its own desktop), so the panels are real
  8517. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  8518. auto* ui = new lynx::MainComponent (*test->engine, false);
  8519. test->mainWindow->setUsingNativeTitleBar (true);
  8520. test->mainWindow->setContentOwned (ui, false);
  8521. test->mainWindow->setBounds (20, 20, 1500, 900);
  8522. test->workspace = &ui->workspaceForTest();
  8523. test->ui = ui;
  8524. if (const auto ms = juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGWIN_STEP_MS", {}).getIntValue(); ms > 0)
  8525. test->stepMs = ms;
  8526. }
  8527. test->mainWindow->setVisible (true);
  8528. lynx::setMainWindowForOwnership (test->mainWindow.get());
  8529. if (test->workspace != nullptr)
  8530. {
  8531. using lynx::workspace::Panel;
  8532. for (auto p : { Panel::playlist, Panel::mixer, Panel::pianoRoll, Panel::channelRack })
  8533. test->workspace->show (p);
  8534. test->step ("dock_test=2 rack_visible=" + juce::String ((int) test->workspace->isPanelVisible (Panel::channelRack)));
  8535. }
  8536. auto& host = test->engine->getPluginHost();
  8537. test->step ("plugins_in_file=" + juce::String (host.addPluginFile (juce::File (pluginPath))));
  8538. std::optional<juce::PluginDescription> chosen;
  8539. for (const auto& type : host.getKnownPlugins().getTypes())
  8540. if ((juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginPath).getFileName() || type.fileOrIdentifier == pluginPath)
  8541. && (only.isEmpty() || type.name == only))
  8542. {
  8543. chosen = type;
  8544. break;
  8545. }
  8546. if (! chosen)
  8547. {
  8548. test->step ("result=FAILED (no plugin)");
  8549. test->done (false);
  8550. return;
  8551. }
  8552. test->instrument = chosen->isInstrument;
  8553. lynx::PluginRef ref;
  8554. ref.separateProcess = juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGWIN_SEPARATE", {}) == "1"; // (issue #96's other-process check)
  8555. ref.id = chosen->createIdentifierString().toStdString();
  8556. ref.name = chosen->name.toStdString();
  8557. test->engine->editSong ([&] (lynx::Song& song) {
  8558. if (test->instrument)
  8559. {
  8560. lynx::ChannelDef c;
  8561. c.name = ref.name;
  8562. c.instrument = lynx::InstrumentKind::plugin;
  8563. c.plugin = ref;
  8564. test->channelIndex = (int) song.channels.size();
  8565. song.channels.push_back (c);
  8566. }
  8567. else
  8568. {
  8569. while (song.mixer.size() < 2)
  8570. song.mixer.emplace_back();
  8571. lynx::EffectSlot slot;
  8572. slot.kind = lynx::EffectKind::plugin;
  8573. slot.plugin = ref;
  8574. song.mixer[1].effects.push_back (slot);
  8575. }
  8576. });
  8577. test->step ("plugin=" + chosen->name + " instrument=" + juce::String ((int) test->instrument));
  8578. test->startTimerHz (20);
  8579. }
  8580. void runEditorCrashTest (const juce::String& pluginPath, const juce::String& reportPath)
  8581. {
  8582. struct CrashTest final : juce::Timer
  8583. {
  8584. juce::String reportPath, report;
  8585. std::unique_ptr<lynx::PluginHost> host;
  8586. juce::AudioPluginInstance* plugin = nullptr;
  8587. std::shared_ptr<juce::AudioPluginInstance> keep; // a window whose plugin nobody else holds is closed as orphaned
  8588. std::function<void (bool)> done;
  8589. int ticks = 0, crashesBefore = 0;
  8590. void step (const juce::String& line)
  8591. {
  8592. report << line << "\n";
  8593. juce::File (reportPath).replaceWithText (report); // at each step: a crash leaves the last one
  8594. }
  8595. void timerCallback() override
  8596. {
  8597. ++ticks;
  8598. const auto crashes = lynx::PluginWindows::editorCrashCount() - crashesBefore;
  8599. const auto open = lynx::PluginWindows::isOpen (*plugin);
  8600. if ((crashes > 0 && ! open) || ticks >= 50) // 100 ms ticks: up to 5 s
  8601. {
  8602. stopTimer();
  8603. step ("editor_crashes=" + juce::String (crashes) + " window_open=" + juce::String ((int) open) + " ticks=" + juce::String (ticks));
  8604. bool traced = false;
  8605. if (crashes > 0)
  8606. {
  8607. const auto last = lynx::PluginWindows::editorCrashes().back();
  8608. traced = last.traceFile.existsAsFile() && last.traceFile.loadFileAsString().contains ("LYNX Test Crash");
  8609. step ("plugin=" + last.plugin + " detail=" + last.detail + " trace=" + last.traceFile.getFileName() + " traced="
  8610. + juce::String ((int) traced));
  8611. last.traceFile.deleteFile();
  8612. }
  8613. // still alive: one more message through the loop after the fault
  8614. juce::MessageManager::callAsync ([this, ok = crashes == 1 && ! open && traced] {
  8615. step ("message_loop_after_fault=1");
  8616. step (juce::String ("result=") + (ok ? "OK" : "FAILED"));
  8617. done (ok);
  8618. });
  8619. }
  8620. }
  8621. };
  8622. auto* test = new CrashTest();
  8623. test->reportPath = reportPath;
  8624. test->done = [this, test] (bool ok)
  8625. {
  8626. setApplicationReturnValue (ok ? 0 : 1);
  8627. juce::MessageManager::callAsync ([this, test] { lynx::PluginWindows::closeAll(); delete test; quit(); });
  8628. };
  8629. #if ! JUCE_WINDOWS
  8630. test->step ("result=SKIPPED (Windows only: on macOS / Linux a plugin fault is a signal, see docs/analise/REA_rodada174a.md)");
  8631. test->done (true);
  8632. return;
  8633. #else
  8634. _putenv_s ("LYNX_TEST_CRASH", "editor");
  8635. test->host = std::make_unique<lynx::PluginHost> (false);
  8636. test->step ("plugins_in_file=" + juce::String (test->host->addPluginFile (juce::File (pluginPath))));
  8637. std::shared_ptr<juce::AudioPluginInstance> instance;
  8638. for (const auto& type : test->host->getKnownPlugins().getTypes())
  8639. {
  8640. if (juce::File (type.fileOrIdentifier).getFileName() != juce::File (pluginPath).getFileName())
  8641. continue;
  8642. juce::String error;
  8643. instance = std::shared_ptr<juce::AudioPluginInstance> (lynx::createRightInstance (test->host->getFormats(), type, 48000.0, 512, error).release());
  8644. test->step ("plugin=" + type.name + (instance == nullptr ? " error=" + error : juce::String()));
  8645. break;
  8646. }
  8647. if (instance == nullptr || ! instance->hasEditor())
  8648. {
  8649. test->step ("result=FAILED (no plugin with an editor)");
  8650. test->done (false);
  8651. return;
  8652. }
  8653. lynx::preparePlugin (*instance, 48000.0, 512);
  8654. test->plugin = instance.get();
  8655. test->keep = instance;
  8656. test->crashesBefore = lynx::PluginWindows::editorCrashCount();
  8657. lynx::PluginWindows::open (instance, *instance, instance->getName()); // (the window keeps the plugin alive)
  8658. test->step ("window_open=" + juce::String ((int) lynx::PluginWindows::isOpen (*instance)));
  8659. test->startTimer (100);
  8660. #endif
  8661. }
  8662. void runEditorTest (const juce::String& pluginPath, const juce::String& reportPath, const juce::String& only)
  8663. {
  8664. struct EditorTest final : juce::Timer
  8665. {
  8666. juce::String reportPath, report;
  8667. std::unique_ptr<lynx::PluginHost> host;
  8668. std::unique_ptr<juce::AudioPluginInstance> plugin;
  8669. std::unique_ptr<juce::DocumentWindow> window;
  8670. std::function<void (bool)> done;
  8671. void step (const juce::String& line)
  8672. {
  8673. report << line << "\n";
  8674. juce::File (reportPath).replaceWithText (report); // written at each step: a crash leaves the last one
  8675. }
  8676. void timerCallback() override
  8677. {
  8678. stopTimer();
  8679. window = nullptr;
  8680. step ("step=closed");
  8681. plugin = nullptr;
  8682. step ("result=OK");
  8683. done (true);
  8684. }
  8685. };
  8686. auto* test = new EditorTest();
  8687. test->reportPath = reportPath;
  8688. test->done = [this, test] (bool ok)
  8689. {
  8690. setApplicationReturnValue (ok ? 0 : 1);
  8691. juce::MessageManager::callAsync ([this, test] { delete test; quit(); });
  8692. };
  8693. test->host = std::make_unique<lynx::PluginHost> (false);
  8694. test->step ("plugins_in_file=" + juce::String (test->host->addPluginFile (juce::File (pluginPath))));
  8695. test->step ("exe=" + juce::File::getSpecialLocation (juce::File::currentExecutableFile).getFullPathName());
  8696. for (const auto& type : test->host->getKnownPlugins().getTypes())
  8697. {
  8698. if (juce::File (type.fileOrIdentifier).getFileName() != juce::File (pluginPath).getFileName()
  8699. || (only.isNotEmpty() && type.name != only))
  8700. continue;
  8701. juce::String error;
  8702. test->plugin = lynx::createRightInstance (test->host->getFormats(), type, 48000.0, 512, error);
  8703. test->step ("plugin=" + type.name + (test->plugin == nullptr ? " error=" + error : juce::String()));
  8704. break;
  8705. }
  8706. if (test->plugin == nullptr)
  8707. {
  8708. test->step ("result=FAILED");
  8709. test->done (false);
  8710. return;
  8711. }
  8712. lynx::preparePlugin (*test->plugin, 48000.0, 512);
  8713. test->step ("step=create_editor");
  8714. test->window = std::make_unique<juce::DocumentWindow> (test->plugin->getName(), juce::Colours::black, juce::DocumentWindow::closeButton);
  8715. test->window->setUsingNativeTitleBar (true);
  8716. if (auto* editor = test->plugin->createEditorIfNeeded())
  8717. test->window->setContentOwned (editor, true);
  8718. else
  8719. test->step ("no_editor");
  8720. test->step ("step=show");
  8721. test->window->centreWithSize (test->window->getWidth(), test->window->getHeight());
  8722. test->window->setVisible (true);
  8723. test->step ("step=shown");
  8724. test->startTimer (4000);
  8725. }
  8726. void runFitTest (const juce::String& reportPath, int percent)
  8727. {
  8728. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  8729. struct FitTest final : juce::Timer
  8730. {
  8731. juce::String path, report;
  8732. bool ok = true;
  8733. int step = 0, percent = 150;
  8734. std::unique_ptr<juce::DocumentWindow> tall, big;
  8735. std::function<void()> done;
  8736. // `whole`: the window must fit entirely (a resizable one); else its title bar and close button must be on the screen
  8737. void check (const juce::String& what, juce::Component& w, bool whole)
  8738. {
  8739. juce::BorderSize<int> frame;
  8740. if (auto* peer = w.getPeer())
  8741. if (const auto f = peer->getFrameSizeIfPresent())
  8742. frame = *f;
  8743. auto outer = frame.addedTo (w.getBounds());
  8744. const auto* display = juce::Desktop::getInstance().getDisplays().getDisplayForRect (outer);
  8745. const auto area = display != nullptr ? display->userArea : outer;
  8746. #if JUCE_LINUX
  8747. // round 164: a compositor that draws the frame itself (WSLg's Weston) reports its invisible shadow in
  8748. // the frame (59 px on top, 38 around at 100%): only what is visible is checked, give or take 4 px
  8749. const auto shadow = frame.getLeft() >= 16 ? frame.getLeft() : 0;
  8750. outer = outer.reduced (shadow);
  8751. const auto slack = shadow > 0 ? 4 : 0;
  8752. #else
  8753. const auto slack = 0;
  8754. #endif
  8755. const auto passed = outer.getY() >= area.getY() - slack && outer.getRight() <= area.getRight() + slack && outer.getX() >= area.getX() - slack
  8756. && (! whole || outer.getBottom() <= area.getBottom() + 1 + slack);
  8757. report << (passed ? "ok " : "FAIL ") << what << " window=" << outer.toString() << " (frame " << frame.getTop() << ","
  8758. << frame.getLeft() << ") screen=" << area.toString() << "\n";
  8759. ok = ok && passed;
  8760. }
  8761. void start()
  8762. {
  8763. report << "scale=" << percent << "%\n";
  8764. juce::Desktop::getInstance().setGlobalScaleFactor ((float) percent / 100.0f);
  8765. // a tool window taller than the screen, centred (its title bar would be above the screen)
  8766. tall = std::make_unique<juce::DocumentWindow> ("LYNX fit test - tall", lynx::theme::colour::bg2, juce::DocumentWindow::closeButton);
  8767. tall->setUsingNativeTitleBar (true);
  8768. auto* content = new juce::Component();
  8769. const auto area = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea;
  8770. content->setSize (500, area.getHeight() + 200);
  8771. tall->setContentOwned (content, true);
  8772. tall->setCentrePosition (area.getCentre());
  8773. tall->setVisible (true);
  8774. lynx::keepAboveMainWindow (*tall);
  8775. // LYNX_FITTEST_MS: how long each window stays (default 700 ms; longer to take screenshots of them)
  8776. startTimer (juce::jlimit (300, 60000, juce::SystemStats::getEnvironmentVariable ("LYNX_FITTEST_MS", "700").getIntValue()));
  8777. }
  8778. void timerCallback() override
  8779. {
  8780. ++step;
  8781. if (step == 1)
  8782. {
  8783. check ("tall tool window: title bar and close button on the screen", *tall, false);
  8784. tall.reset();
  8785. // round 164: a fixed-size LYNX tool window whose content is taller than the screen: it scrolls
  8786. auto content = std::make_unique<juce::Component>();
  8787. const auto screen = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea;
  8788. content->setSize (520, screen.getHeight() + 300);
  8789. lynx::openToolWindow (std::move (content), "LYNX fit test - fixed size", "fittest-fixed");
  8790. return;
  8791. }
  8792. if (step == 2)
  8793. {
  8794. if (auto* w = lynx::findToolWindow ("fittest-fixed"))
  8795. {
  8796. check ("fixed-size tool window taller than the screen: fits (its content scrolls)", *w, true);
  8797. const auto scrolls = w->getContentComponent() != nullptr && w->getContentComponent()->getNumChildComponents() > 0
  8798. && dynamic_cast<juce::Viewport*> (w->getContentComponent()->getChildComponent (0)) != nullptr;
  8799. report << (scrolls ? "ok " : "FAIL ") << "its content is in a scrolling viewport\n";
  8800. ok = ok && scrolls;
  8801. }
  8802. else
  8803. {
  8804. report << "FAIL fixed-size tool window not found\n";
  8805. ok = false;
  8806. }
  8807. lynx::closeAllToolWindows();
  8808. // a resizable window that fits at 100%, then the zoom goes up (the main window's case)
  8809. juce::Desktop::getInstance().setGlobalScaleFactor (1.0f);
  8810. big = std::make_unique<juce::DocumentWindow> ("LYNX fit test - zoom", lynx::theme::colour::bg2, juce::DocumentWindow::allButtons);
  8811. big->setUsingNativeTitleBar (true);
  8812. big->setResizable (true, false);
  8813. big->setResizeLimits (400, 300, 10000, 10000);
  8814. const auto area = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea;
  8815. big->setBounds (area.getX() + 40, area.getY() + 60, area.getWidth() * 9 / 10 - 40, area.getHeight() * 9 / 10 - 60);
  8816. big->setVisible (true);
  8817. return;
  8818. }
  8819. if (step == 3)
  8820. {
  8821. juce::Desktop::getInstance().setGlobalScaleFactor ((float) percent / 100.0f);
  8822. juce::Timer::callAfterDelay (200, [] { lynx::fitAllWindowsOnScreen(); });
  8823. return;
  8824. }
  8825. if (step == 4)
  8826. {
  8827. check ("resizable window after the zoom change: fits the screen", *big, true);
  8828. big.reset();
  8829. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  8830. juce::File (path).replaceWithText (report);
  8831. stopTimer();
  8832. if (done)
  8833. done();
  8834. }
  8835. }
  8836. };
  8837. static std::unique_ptr<FitTest> test;
  8838. test = std::make_unique<FitTest>();
  8839. test->path = reportPath;
  8840. test->percent = juce::jlimit (50, 300, percent);
  8841. test->done = [this] { juce::MessageManager::callAsync ([this] { test.reset(); quit(); }); };
  8842. test->start();
  8843. }
  8844. void runFocusTest (const juce::String& reportPath)
  8845. {
  8846. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  8847. struct FocusTest final : juce::Timer
  8848. {
  8849. juce::String reportPath, report;
  8850. bool ok = true;
  8851. int stepIndex = 0;
  8852. std::unique_ptr<lynx::AudioEngine> engine;
  8853. lynx::MainComponent* ui = nullptr;
  8854. std::unique_ptr<juce::DocumentWindow> main;
  8855. std::function<void()> done;
  8856. void line (const juce::String& text)
  8857. {
  8858. report << text << "\n";
  8859. juce::File (reportPath).replaceWithText (report);
  8860. }
  8861. void check (const juce::String& what, bool passed)
  8862. {
  8863. line ((passed ? "ok " : "FAIL ") + what);
  8864. ok = ok && passed;
  8865. }
  8866. juce::ComponentPeer* mainPeer() const { return main != nullptr ? main->getPeer() : nullptr; }
  8867. bool focusInMain() const
  8868. {
  8869. auto* f = juce::Component::getCurrentlyFocusedComponent();
  8870. return f != nullptr && main->isParentOf (f);
  8871. }
  8872. // a click (press and release) at the middle of the panel's content, through the native window it is in
  8873. static void click (juce::Component& frame, bool right)
  8874. {
  8875. auto* peer = frame.getPeer();
  8876. if (peer == nullptr)
  8877. return;
  8878. const auto at = peer->getComponent().getLocalPoint (&frame, frame.getLocalBounds().getCentre().toFloat());
  8879. const auto button = right ? juce::ModifierKeys::rightButtonModifier : juce::ModifierKeys::leftButtonModifier;
  8880. const auto now = juce::Time::currentTimeMillis();
  8881. peer->handleMouseEvent (juce::MouseInputSource::InputSourceType::mouse, at, juce::ModifierKeys (button), 1.0f, 0.0f, now);
  8882. peer->handleMouseEvent (juce::MouseInputSource::InputSourceType::mouse, at, juce::ModifierKeys(), 1.0f, 0.0f, now + 40);
  8883. }
  8884. bool space()
  8885. {
  8886. auto* peer = mainPeer(); // (the system sends the key to the window with the focus: the main one)
  8887. return peer != nullptr && peer->handleKeyPress (juce::KeyPress (juce::KeyPress::spaceKey, juce::ModifierKeys(), ' '));
  8888. }
  8889. juce::TextEditor* firstField (juce::Component& c)
  8890. {
  8891. if (auto* t = dynamic_cast<juce::TextEditor*> (&c); t != nullptr && t->isShowing() && t->getWantsKeyboardFocus())
  8892. return t;
  8893. for (auto* child : c.getChildren())
  8894. if (auto* t = firstField (*child))
  8895. return t;
  8896. return nullptr;
  8897. }
  8898. // the user tabs away and comes back with a click in `panel`
  8899. void backWithClickIn (lynx::workspace::Panel panel, bool right)
  8900. {
  8901. auto& frame = ui->workspaceForTest().getFrame (panel);
  8902. const auto name = juce::String (lynx::workspace::panelId (panel)) + (right ? " (right click)" : "");
  8903. auto* peer = mainPeer();
  8904. line (name + ": native child window=" + juce::String ((int) lynx::nativechild::isAttached (frame)));
  8905. check (name + ": the main window has the keys before", ui->hasKeyboardFocus (true));
  8906. peer->handleFocusLoss(); // (another app is in front: the main window lost the system focus)
  8907. check (name + ": nothing in LYNX has the keys while it is in the background", ! focusInMain());
  8908. // the cause: JUCE answers the system's "activate?" from the panel's own component, which takes no focus on a click
  8909. line (name + ": JUCE's answer alone would activate the window=" + juce::String ((int) frame.getMouseClickGrabsKeyboardFocus()));
  8910. const auto activates = lynx::nativechild::clickActivatesWindow (frame, false);
  8911. check (name + ": a click in it activates the inactive main window", activates);
  8912. #if JUCE_WINDOWS
  8913. if (lynx::nativechild::isAttached (frame))
  8914. check (name + ": its native window answers WM_MOUSEACTIVATE with MA_ACTIVATE",
  8915. lynx::nativechild::mouseActivateAnswerForTest (frame, true) == 1 /* MA_ACTIVATE */);
  8916. #endif
  8917. if (activates)
  8918. peer->handleFocusGain(); // (the system activates the main window and gives it the focus)
  8919. click (frame, right);
  8920. }
  8921. void spacePlays (lynx::workspace::Panel panel, bool right)
  8922. {
  8923. const auto name = juce::String (lynx::workspace::panelId (panel)) + (right ? " (right click)" : "");
  8924. check (name + ": the main window has the keys after the click", ui->hasKeyboardFocus (true));
  8925. auto& transport = engine->getTransport();
  8926. if (transport.playing.load())
  8927. engine->stop();
  8928. const auto used = space();
  8929. check (name + ": Space starts playback", used && transport.playing.load());
  8930. engine->stop();
  8931. }
  8932. void timerCallback() override
  8933. {
  8934. using lynx::workspace::Panel;
  8935. auto& ws = ui->workspaceForTest();
  8936. switch (stepIndex++)
  8937. {
  8938. case 0:
  8939. line ("docking=" + juce::String ((int) lynx::nativechild::dockingEnabled()));
  8940. ws.show (Panel::playlist);
  8941. ws.show (Panel::pianoRoll);
  8942. ui->grabKeyboardFocus();
  8943. break;
  8944. case 1: backWithClickIn (Panel::playlist, false); break;
  8945. case 2: spacePlays (Panel::playlist, false); ui->grabKeyboardFocus(); break;
  8946. case 3: backWithClickIn (Panel::pianoRoll, false); break;
  8947. case 4: spacePlays (Panel::pianoRoll, false); ui->grabKeyboardFocus(); break;
  8948. case 5: backWithClickIn (Panel::playlist, true); break;
  8949. case 6:
  8950. juce::PopupMenu::dismissAllActiveMenus(); // (the right click's menu)
  8951. spacePlays (Panel::playlist, true);
  8952. break;
  8953. case 7:
  8954. {
  8955. // a text field (the Browser's search box) keeps the keys through a switch to another app and back:
  8956. // nothing in LYNX takes them from it (no periodic grab); inside the active window the click's
  8957. // activation answer is unchanged, and a click in the Playlist ends the typing as before (issue #9,
  8958. // as FL ends typing in its search field)
  8959. auto* field = firstField (*ui);
  8960. line ("text field found=" + juce::String ((int) (field != nullptr)));
  8961. if (field != nullptr)
  8962. {
  8963. auto& frame = ws.getFrame (Panel::playlist);
  8964. field->grabKeyboardFocus();
  8965. check ("the text field has the keys", field->hasKeyboardFocus (false));
  8966. mainPeer()->handleFocusLoss();
  8967. mainPeer()->handleFocusGain(); // (back with Alt+Tab, or a click that activates the window)
  8968. check ("the text field gets the keys back with the window", field->hasKeyboardFocus (false));
  8969. check ("active window: a click in a panel does not activate it again", ! lynx::nativechild::clickActivatesWindow (frame, true));
  8970. click (frame, false);
  8971. check ("a click in the Playlist ends the typing: the main window has the keys", ui->hasKeyboardFocus (true) && ! field->hasKeyboardFocus (false));
  8972. }
  8973. line (ok ? "result=OK" : "result=FAILED");
  8974. stopTimer();
  8975. done();
  8976. break;
  8977. }
  8978. default:
  8979. break;
  8980. }
  8981. }
  8982. };
  8983. auto* test = new FocusTest();
  8984. test->reportPath = reportPath;
  8985. startFocusTestWindow (*test);
  8986. test->startTimer (600);
  8987. }
  8988. // --simplekeytest (round 190fc, 0.1.27 RC H2): in the Simple layout Space often did nothing after a click in the
  8989. // window (the dock, a track header, the grid, the Lyrics button) or after a demo opened from Welcome › Start from. The
  8990. // main window in the Simple layout; each step clicks as the system would (through the native window under the point)
  8991. // and presses Space where the system sends it (the native window of the component with the focus): playback must
  8992. // start, except while a text field the user clicked into has the keys (it types). Shows a window (Windows: GUI lock).
  8993. void runSimpleKeyTest (const juce::String& reportPath)
  8994. {
  8995. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  8996. struct KeyTest final : juce::Timer
  8997. {
  8998. juce::String reportPath, report;
  8999. bool ok = true;
  9000. int stepIndex = 0, instrumentTrack = 0;
  9001. std::unique_ptr<lynx::AudioEngine> engine;
  9002. lynx::MainComponent* ui = nullptr;
  9003. std::unique_ptr<juce::DocumentWindow> main;
  9004. std::function<void()> done;
  9005. void line (const juce::String& text)
  9006. {
  9007. report << text << "\n";
  9008. juce::File (reportPath).replaceWithText (report);
  9009. }
  9010. void check (const juce::String& what, bool passed)
  9011. {
  9012. line ((passed ? "ok " : "FAIL ") + what);
  9013. ok = ok && passed;
  9014. }
  9015. static juce::String describe (juce::Component* c)
  9016. {
  9017. if (c == nullptr)
  9018. return "nothing";
  9019. juce::String path;
  9020. for (auto* p = c; p != nullptr && path.length() < 160; p = p->getParentComponent())
  9021. {
  9022. auto name = p->getComponentID().isNotEmpty() ? p->getComponentID() : p->getName();
  9023. if (name.isEmpty())
  9024. name = juce::String (typeid (*p).name()).fromLastOccurrenceOf ("::", false, false).substring (0, 28);
  9025. path << (path.isEmpty() ? "" : " < ") << name;
  9026. }
  9027. return path;
  9028. }
  9029. // the first showing component with this ID in the main window or a native child window of it
  9030. juce::Component* find (const juce::String& id)
  9031. {
  9032. std::function<juce::Component* (juce::Component&)> in = [&] (juce::Component& root) -> juce::Component* {
  9033. if (root.getComponentID() == id && root.isShowing())
  9034. return &root;
  9035. for (auto* c : root.getChildren())
  9036. if (auto* f = in (*c))
  9037. return f;
  9038. return nullptr;
  9039. };
  9040. if (auto* f = in (*main))
  9041. return f;
  9042. if (auto* peer = main->getPeer())
  9043. for (auto* attached : lynx::nativechild::attachedChildren (peer->getNativeHandle()))
  9044. if (auto* f = in (*attached))
  9045. return f;
  9046. return nullptr;
  9047. }
  9048. // a click (press and release) at `local` in `c`, through the native window it is in
  9049. juce::String lastHit;
  9050. void click (juce::Component& c, juce::Point<int> local)
  9051. {
  9052. auto* peer = c.getPeer();
  9053. if (peer == nullptr)
  9054. return;
  9055. const auto at = peer->getComponent().getLocalPoint (&c, local.toFloat());
  9056. lastHit = describe (peer->getComponent().getComponentAt (at.roundToInt()));
  9057. line (" click at " + local.toString() + " in " + describe (&c).upToFirstOccurrenceOf (" < ", false, false) + " -> " + lastHit);
  9058. const auto now = juce::Time::currentTimeMillis();
  9059. peer->handleMouseEvent (juce::MouseInputSource::InputSourceType::mouse, at, juce::ModifierKeys (juce::ModifierKeys::leftButtonModifier), 1.0f, 0.0f, now);
  9060. peer->handleMouseEvent (juce::MouseInputSource::InputSourceType::mouse, at, juce::ModifierKeys(), 1.0f, 0.0f, now + 40);
  9061. }
  9062. void click (juce::Component& c) { click (c, c.getLocalBounds().getCentre()); }
  9063. // Space where the system sends it: the native window of the focused component (else the main one)
  9064. bool space()
  9065. {
  9066. // Windows: posted to the window with the system's focus, as a real key goes (the system's own routing)
  9067. if (lynx::nativechild::pressSpaceForTest (main->getWindowHandle()))
  9068. return true;
  9069. auto* focused = juce::Component::getCurrentlyFocusedComponent();
  9070. auto* peer = focused != nullptr && focused->getPeer() != nullptr ? focused->getPeer() : main->getPeer();
  9071. return peer != nullptr && peer->handleKeyPress (juce::KeyPress (juce::KeyPress::spaceKey, juce::ModifierKeys(), ' '));
  9072. }
  9073. void spacePlays (const juce::String& after)
  9074. {
  9075. line (" keys at: " + describe (juce::Component::getCurrentlyFocusedComponent()));
  9076. auto& transport = engine->getTransport();
  9077. if (transport.playing.load())
  9078. engine->stop();
  9079. space();
  9080. check ("Space plays after " + after, transport.playing.load());
  9081. engine->stop();
  9082. }
  9083. void timerCallback() override
  9084. {
  9085. auto* simple = ui->getSimpleWorkflowForSnapshot();
  9086. auto& playlist = ui->getPlaylistForSnapshot();
  9087. switch (stepIndex++)
  9088. {
  9089. case 0:
  9090. ui->setLayoutStyle (lynx::layoutstyle::Style::simple);
  9091. ui->grabKeyboardFocus();
  9092. break;
  9093. case 1:
  9094. check ("the Simple workflow is up", simple != nullptr);
  9095. if (simple == nullptr)
  9096. return finish();
  9097. spacePlays ("the layout came up");
  9098. simple->showWelcome();
  9099. break;
  9100. case 2:
  9101. if (auto* demo = find ("tour.welcome.demo"))
  9102. click (*demo); // Welcome › Open a demo song: the Start from list
  9103. else
  9104. check ("Welcome > Open a demo song found", false);
  9105. break;
  9106. case 3:
  9107. {
  9108. if (! simple->isStartFromShowing()) // (X11: a child window just mapped may miss the first click)
  9109. if (auto* demo = find ("tour.welcome.demo"))
  9110. {
  9111. line (" the first click was not taken: once more");
  9112. click (*demo);
  9113. }
  9114. check ("Start from is up", simple->isStartFromShowing());
  9115. if (auto* start = dynamic_cast<lynx::StartFromPanel*> (simple->startFromForSnapshot()))
  9116. check ("a demo song opens from it", start->openForSnapshot (1));
  9117. break;
  9118. }
  9119. case 4:
  9120. check ("Start from closed with the demo open", ! simple->isStartFromShowing() && ! engine->getSong().playlist.empty());
  9121. spacePlays ("a demo opened from Welcome > Start from");
  9122. instrumentTrack = [] (const lynx::Song& song) { // the first Instrument track (the dock's Keyboard and Editor tabs are for it)
  9123. for (int t = 0; t < (int) song.playlistTracks.size(); ++t)
  9124. if (lynx::simpletracks::kindOf (song, t) == lynx::simpletracks::Kind::instrument)
  9125. return t;
  9126. return 0;
  9127. } (engine->getSong());
  9128. line ("instrument track: " + juce::String (instrumentTrack));
  9129. playlist.selectTrack (instrumentTrack);
  9130. simple->trackSelected (instrumentTrack);
  9131. break;
  9132. case 5:
  9133. if (auto* dock = simple->dockForSnapshot(); dock != nullptr && dock->isShowing())
  9134. {
  9135. click (*dock, { dock->getWidth() - 6, dock->getHeight() - 6 }); // (its empty corner)
  9136. spacePlays ("a click in the dock");
  9137. }
  9138. else
  9139. check ("the dock shows", false);
  9140. break;
  9141. case 6:
  9142. if (auto* tab = find ("simple.dock.keyboard"))
  9143. {
  9144. click (*tab);
  9145. spacePlays ("a click on a dock tab (Keyboard)");
  9146. }
  9147. if (auto* tab = find ("simple.dock.editor"))
  9148. {
  9149. click (*tab);
  9150. spacePlays ("a click on a dock tab (Editor)");
  9151. }
  9152. break;
  9153. case 7:
  9154. if (auto* lyrics = find ("simple.lyrics"))
  9155. {
  9156. click (*lyrics);
  9157. spacePlays ("a click on the Lyrics button");
  9158. }
  9159. else
  9160. check ("the Lyrics button found", false);
  9161. break;
  9162. case 8:
  9163. {
  9164. const auto lane = playlist.trackRowForSnapshot (instrumentTrack).withTrimmedLeft (playlist.headerWidth);
  9165. click (playlist, { juce::jmax (4, playlist.headerWidth / 2), lane.getCentreY() });
  9166. spacePlays ("a click on a track header");
  9167. click (playlist, lane.getCentre() + juce::Point<int> (40, 0));
  9168. spacePlays ("a click in the Playlist grid");
  9169. break;
  9170. }
  9171. case 9:
  9172. {
  9173. // a text field the user clicks into keeps its typing keys; a click outside gives Space back
  9174. // a dock knob clicked keeps the arrow keys, and Space still plays from it
  9175. for (auto tab : { lynx::SimpleDock::Tab::effects, lynx::SimpleDock::Tab::instrument })
  9176. {
  9177. juce::Component* knob = nullptr;
  9178. std::function<void (juce::Component&)> seek = [&] (juce::Component& c) {
  9179. if (knob == nullptr && c.isShowing() && (bool) c.getProperties().getWithDefault ("lynxClickKeepsKeys", false))
  9180. knob = &c;
  9181. for (auto* child : c.getChildren())
  9182. seek (*child);
  9183. };
  9184. if (auto* dock = simple->dockForSnapshot())
  9185. {
  9186. dock->setTab (tab);
  9187. seek (*dock);
  9188. }
  9189. if (knob != nullptr)
  9190. {
  9191. click (*knob);
  9192. spacePlays ("a click on a dock knob");
  9193. break;
  9194. }
  9195. }
  9196. if (auto* dock = simple->dockForSnapshot())
  9197. dock->setTab (lynx::SimpleDock::Tab::instrument);
  9198. juce::TextEditor* field = nullptr;
  9199. std::function<void (juce::Component&)> look = [&] (juce::Component& c) {
  9200. if (auto* t = dynamic_cast<juce::TextEditor*> (&c); t != nullptr && t->isShowing() && field == nullptr)
  9201. field = t;
  9202. for (auto* child : c.getChildren())
  9203. look (*child);
  9204. };
  9205. if (auto* dock = simple->dockForSnapshot())
  9206. look (*dock);
  9207. line ("text field in the dock found=" + juce::String ((int) (field != nullptr)));
  9208. if (field != nullptr)
  9209. {
  9210. click (*field);
  9211. const auto before = field->getText();
  9212. space();
  9213. check ("Space types into the text field the user clicked", field->getText() != before && ! engine->getTransport().playing.load());
  9214. engine->stop();
  9215. field->clear();
  9216. const auto lane = playlist.trackRowForSnapshot (instrumentTrack).withTrimmedLeft (playlist.headerWidth);
  9217. click (playlist, lane.getCentre() + juce::Point<int> (60, 0));
  9218. spacePlays ("a click in the grid after typing");
  9219. }
  9220. // H1: the first-song tour's card in front of the native panels, taking no keys (started on the demo
  9221. // as it is: Help's question about a new project is a dialog)
  9222. if (auto* tour = simple->tourForSnapshot())
  9223. tour->start();
  9224. break;
  9225. }
  9226. case 10:
  9227. {
  9228. auto* tour = simple->tourForSnapshot();
  9229. auto* card = tour != nullptr ? tour->cardForSnapshot() : nullptr;
  9230. check ("the tour runs", tour != nullptr && tour->isRunning() && card != nullptr && card->isVisible());
  9231. if (card == nullptr)
  9232. return finish();
  9233. auto& frame = ui->workspaceForTest().getFrame (lynx::workspace::Panel::playlist);
  9234. const auto native = lynx::nativechild::dockingEnabled() && lynx::nativechild::isAttached (frame);
  9235. line ("playlist native child window=" + juce::String ((int) native) + ", tour card native child window="
  9236. + juce::String ((int) lynx::nativechild::isAttached (*card)));
  9237. if (native)
  9238. {
  9239. check ("the tour card is a native child window of the main window (not under the panels)", lynx::nativechild::isAttached (*card));
  9240. #if JUCE_WINDOWS
  9241. check ("the tour card is above the Playlist's native window", lynx::nativechild::isAbove (card->getWindowHandle(), frame.getWindowHandle()));
  9242. juce::Component* layer = nullptr;
  9243. for (auto* c : lynx::nativechild::attachedChildren (main->getPeer()->getNativeHandle()))
  9244. if (c != nullptr && c->getComponentID() == "tour.layer")
  9245. layer = c;
  9246. check ("the ring's layer is above the Playlist too", layer != nullptr && lynx::nativechild::isAbove (layer->getWindowHandle(), frame.getWindowHandle()));
  9247. check ("the ring's layer lets clicks through to the Playlist",
  9248. layer != nullptr && lynx::nativechild::windowAt (*layer, layer->getLocalBounds().getCentre()) != layer->getWindowHandle());
  9249. #endif
  9250. }
  9251. check ("the tour card took no keys", ! card->hasKeyboardFocus (true));
  9252. spacePlays ("the tour came up");
  9253. if (auto* next = card->findChildWithID ("tour.next"); next != nullptr && next->isShowing())
  9254. {
  9255. click (*next);
  9256. check ("a click on the card took no keys", ! card->hasKeyboardFocus (true));
  9257. spacePlays ("a click on the tour card");
  9258. }
  9259. finish();
  9260. break;
  9261. }
  9262. default:
  9263. break;
  9264. }
  9265. }
  9266. void finish()
  9267. {
  9268. line (ok ? "result=OK" : "result=FAILED");
  9269. stopTimer();
  9270. done();
  9271. }
  9272. };
  9273. auto* test = new KeyTest();
  9274. test->reportPath = reportPath;
  9275. startFocusTestWindow (*test);
  9276. // Windows: kept above other apps' windows for its few seconds (JUCE takes a button-down only where the system finds
  9277. // its window under the point, and the test clicks through LYNX's own peers, not the system's input)
  9278. #if JUCE_WINDOWS
  9279. test->main->setAlwaysOnTop (true); // (Linux: JUCE makes the X11 window again for it; the private X server has no other windows)
  9280. #endif
  9281. test->startTimer (700);
  9282. }
  9283. template <typename Test>
  9284. void startFocusTestWindow (Test& t)
  9285. {
  9286. auto* test = &t;
  9287. test->engine = std::make_unique<lynx::AudioEngine> (false);
  9288. test->main = std::make_unique<juce::DocumentWindow> ("LYNX focus test", lynx::theme::window, juce::DocumentWindow::allButtons);
  9289. test->main->setUsingNativeTitleBar (true);
  9290. test->ui = new lynx::MainComponent (*test->engine, false);
  9291. test->main->setContentOwned (test->ui, true);
  9292. test->main->setResizable (true, true);
  9293. test->main->centreWithSize (1280, 760);
  9294. test->main->setVisible (true);
  9295. lynx::setMainWindowForOwnership (test->main.get());
  9296. test->done = [this, test] {
  9297. setApplicationReturnValue (test->ok ? 0 : 1);
  9298. juce::MessageManager::callAsync ([this, test] {
  9299. lynx::setMainWindowForOwnership (nullptr);
  9300. test->main = nullptr;
  9301. delete test;
  9302. quit();
  9303. });
  9304. };
  9305. }
  9306. void runWindowTest (const juce::String& reportPath)
  9307. {
  9308. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  9309. struct WindowTest final : juce::Timer
  9310. {
  9311. juce::String reportPath, report;
  9312. bool ok = true;
  9313. int stepIndex = 0;
  9314. std::unique_ptr<lynx::AudioEngine> engine;
  9315. lynx::MainComponent* ui = nullptr;
  9316. std::unique_ptr<juce::DocumentWindow> main, pluginLike;
  9317. juce::TextEditor* pluginField = nullptr;
  9318. std::unique_ptr<juce::AlertWindow> nameDialog;
  9319. std::function<void()> done;
  9320. void line (const juce::String& text)
  9321. {
  9322. report << text << "\n";
  9323. juce::File (reportPath).replaceWithText (report);
  9324. }
  9325. void check (const juce::String& what, bool passed)
  9326. {
  9327. line ((passed ? "ok " : "FAIL ") + what);
  9328. ok = ok && passed;
  9329. }
  9330. bool isAbove (juce::Component* w) { return w != nullptr && lynx::isAboveMainWindow (*w); }
  9331. bool focusIn (juce::Component* w)
  9332. {
  9333. auto* f = juce::Component::getCurrentlyFocusedComponent();
  9334. return w != nullptr && f != nullptr && (f == w || w->isParentOf (f));
  9335. }
  9336. void timerCallback() override
  9337. {
  9338. switch (stepIndex++)
  9339. {
  9340. case 0:
  9341. line ("foreground=" + juce::String (juce::Process::isForegroundProcess() ? 1 : 0));
  9342. ui->openQuickAddForTest();
  9343. break;
  9344. case 1:
  9345. {
  9346. auto* w = lynx::findToolWindow ("quickadd");
  9347. check ("quick-add palette open", w != nullptr);
  9348. check ("quick-add palette active", w != nullptr && w->isActiveWindow());
  9349. check ("quick-add palette owned by the main window", w != nullptr && lynx::isOwnedByMainWindow (*w));
  9350. check ("quick-add palette above the main window", isAbove (w));
  9351. auto* f = juce::Component::getCurrentlyFocusedComponent();
  9352. check ("quick-add search box has the keyboard focus", focusIn (w) && dynamic_cast<juce::TextEditor*> (f) != nullptr && f->hasKeyboardFocus (false) && w->isActiveWindow());
  9353. lynx::closeAllToolWindows();
  9354. lynx::openAudioEditor (*engine);
  9355. break;
  9356. }
  9357. case 2:
  9358. {
  9359. auto* w = lynx::findToolWindow ("audioeditor");
  9360. check ("audio editor open", w != nullptr);
  9361. check ("audio editor active", w != nullptr && w->isActiveWindow());
  9362. check ("audio editor owned by the main window", w != nullptr && lynx::isOwnedByMainWindow (*w));
  9363. check ("audio editor above the main window", isAbove (w));
  9364. lynx::forceForegroundForTest (*main); // the user clicks the main window
  9365. break;
  9366. }
  9367. case 3:
  9368. {
  9369. auto* w = lynx::findToolWindow ("audioeditor");
  9370. check ("audio editor stays above the main window after clicking it", isAbove (w));
  9371. lynx::closeAllToolWindows();
  9372. // a plugin editor's window: its own controls keep the keyboard focus
  9373. pluginLike = std::make_unique<juce::DocumentWindow> ("Plugin", juce::Colours::black, juce::DocumentWindow::closeButton);
  9374. pluginLike->setUsingNativeTitleBar (true);
  9375. auto* field = new juce::TextEditor();
  9376. field->setSize (300, 120);
  9377. pluginLike->setContentOwned (field, true);
  9378. pluginLike->centreWithSize (300, 120);
  9379. pluginLike->setVisible (true);
  9380. lynx::keepAboveMainWindow (*pluginLike);
  9381. pluginLike->toFront (true);
  9382. field->grabKeyboardFocus();
  9383. pluginField = field;
  9384. break;
  9385. }
  9386. case 4:
  9387. check ("plugin window active", pluginLike->isActiveWindow());
  9388. check ("plugin window keeps the keyboard focus", pluginField->hasKeyboardFocus (false) && pluginLike->isActiveWindow());
  9389. check ("plugin window above the main window", isAbove (pluginLike.get()));
  9390. pluginLike = nullptr;
  9391. lynx::forceForegroundForTest (*main);
  9392. juce::Component::unfocusAllComponents();
  9393. break;
  9394. case 5:
  9395. check ("main window takes the keyboard focus back when it is active", ui->hasKeyboardFocus (true));
  9396. // round 165q: a name dialog (F4's next empty pattern, Rename and color...) opens ready to type
  9397. nameDialog = lynx::makeNameAndColourDialog ("Rename pattern", "Pattern 2", 0xff808080u);
  9398. nameDialog->enterModalState (true, nullptr, false);
  9399. lynx::keepAboveMainWindow (*nameDialog);
  9400. break;
  9401. case 6:
  9402. {
  9403. auto* f = juce::Component::getCurrentlyFocusedComponent();
  9404. auto* field = dynamic_cast<juce::TextEditor*> (f);
  9405. check ("name dialog: its text field has the keyboard focus", field != nullptr && focusIn (nameDialog.get()));
  9406. if (field != nullptr)
  9407. field->keyPressed (juce::KeyPress ('x', {}, 'x'));
  9408. check ("name dialog: typing replaces the name", nameDialog->getTextEditorContents ("name") == "x");
  9409. nameDialog->exitModalState (0);
  9410. nameDialog = nullptr;
  9411. line (ok ? "result=OK" : "result=FAILED");
  9412. stopTimer();
  9413. done();
  9414. break;
  9415. }
  9416. default:
  9417. break;
  9418. }
  9419. }
  9420. };
  9421. auto* test = new WindowTest();
  9422. test->reportPath = reportPath;
  9423. test->engine = std::make_unique<lynx::AudioEngine> (false);
  9424. test->main = std::make_unique<juce::DocumentWindow> ("LYNX window test", lynx::theme::window, juce::DocumentWindow::allButtons);
  9425. test->main->setUsingNativeTitleBar (true);
  9426. test->ui = new lynx::MainComponent (*test->engine, false);
  9427. test->main->setContentOwned (test->ui, true);
  9428. test->main->setResizable (true, true);
  9429. test->main->centreWithSize (1280, 760);
  9430. test->main->setVisible (true);
  9431. lynx::setMainWindowForOwnership (test->main.get());
  9432. lynx::forceForegroundForTest (*test->main);
  9433. test->main->toFront (true);
  9434. test->done = [this, test] {
  9435. setApplicationReturnValue (test->ok ? 0 : 1);
  9436. juce::MessageManager::callAsync ([this, test] {
  9437. lynx::closeAllToolWindows();
  9438. lynx::setMainWindowForOwnership (nullptr);
  9439. test->main = nullptr;
  9440. delete test;
  9441. quit();
  9442. });
  9443. };
  9444. test->startTimer (1500);
  9445. }
  9446. // --minimizeclicktest (issue #188): see the option. The main window holds a component that counts its mouse-downs.
  9447. void runMinimizeClickTest (const juce::String& reportPath)
  9448. {
  9449. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  9450. struct ClickPad final : juce::Component
  9451. {
  9452. int downs = 0;
  9453. void paint (juce::Graphics& g) override { g.fillAll (juce::Colours::darkslategrey); }
  9454. void mouseDown (const juce::MouseEvent&) override { ++downs; }
  9455. };
  9456. struct MinimizeTest final : juce::Timer
  9457. {
  9458. juce::String reportPath, report;
  9459. bool ok = true;
  9460. int stepIndex = 0, waits = 0;
  9461. std::unique_ptr<juce::DocumentWindow> main;
  9462. ClickPad* pad = nullptr;
  9463. juce::DocumentWindow* tool = nullptr;
  9464. juce::Point<int> inside, outside; // screen points: where the tool window is, and beside it
  9465. std::function<void()> done;
  9466. void line (const juce::String& text)
  9467. {
  9468. report << text << "\n";
  9469. juce::File (reportPath).replaceWithText (report);
  9470. }
  9471. void check (const juce::String& what, bool passed)
  9472. {
  9473. line ((passed ? "ok " : "FAIL ") + what);
  9474. ok = ok && passed;
  9475. }
  9476. // a left click at a screen point through the main window's peer: the path an X ButtonPress takes
  9477. bool clickReachesPad (juce::Point<int> screen)
  9478. {
  9479. auto* peer = main->getPeer();
  9480. if (peer == nullptr)
  9481. return false;
  9482. const auto before = pad->downs;
  9483. const auto local = peer->globalToLocal (screen.toFloat());
  9484. const auto now = juce::Time::currentTimeMillis();
  9485. peer->handleMouseEvent (juce::MouseInputSource::InputSourceType::mouse, local, juce::ModifierKeys (juce::ModifierKeys::leftButtonModifier),
  9486. juce::MouseInputSource::defaultPressure, juce::MouseInputSource::defaultOrientation, now);
  9487. peer->handleMouseEvent (juce::MouseInputSource::InputSourceType::mouse, local, juce::ModifierKeys(),
  9488. juce::MouseInputSource::defaultPressure, juce::MouseInputSource::defaultOrientation, now + 1);
  9489. return pad->downs == before + 1;
  9490. }
  9491. bool toolMinimised() const { return tool != nullptr && tool->getPeer() != nullptr && tool->getPeer()->isMinimised(); }
  9492. void timerCallback() override
  9493. {
  9494. switch (stepIndex)
  9495. {
  9496. case 0:
  9497. {
  9498. auto content = std::make_unique<juce::Component>();
  9499. content->setSize (420, 300);
  9500. tool = lynx::openToolWindow (std::move (content), "Tap tempo (test)", "minimizetest");
  9501. ++stepIndex;
  9502. return;
  9503. }
  9504. case 1:
  9505. {
  9506. check ("tool window open", tool != nullptr && tool->isShowing());
  9507. if (tool == nullptr)
  9508. break;
  9509. const auto r = tool->getScreenBounds();
  9510. inside = r.getCentre();
  9511. outside = { main->getScreenBounds().getX() + 40, main->getScreenBounds().getBottom() - 40 };
  9512. line ("main " + main->getScreenBounds().toString() + " tool " + r.toString());
  9513. lynx::matchWindowOrderToScreen();
  9514. check ("a click beside the tool window reaches the main window", clickReachesPad (outside));
  9515. check ("a click on the shown tool window does not reach the main window", ! clickReachesPad (inside));
  9516. tool->setMinimised (true);
  9517. ++stepIndex;
  9518. return;
  9519. }
  9520. case 2:
  9521. if (! toolMinimised() && ++waits < 20)
  9522. return;
  9523. check ("the window manager minimised the tool window", toolMinimised());
  9524. check ("the tool window stays visible for JUCE (as in the report)", tool->isVisible());
  9525. main->toFront (true); // a click on the main window: LYNX puts its secondary windows back above it in JUCE's list
  9526. lynx::matchWindowOrderToScreen();
  9527. ++stepIndex;
  9528. return;
  9529. case 3:
  9530. check ("a click where the minimised tool window was reaches the main window", clickReachesPad (inside));
  9531. check ("a click beside it still reaches the main window", clickReachesPad (outside));
  9532. tool->setMinimised (false);
  9533. waits = 0;
  9534. ++stepIndex;
  9535. return;
  9536. case 4:
  9537. if (toolMinimised() && ++waits < 20)
  9538. return;
  9539. tool->toFront (false);
  9540. lynx::matchWindowOrderToScreen();
  9541. ++stepIndex;
  9542. return;
  9543. case 5:
  9544. check ("the tool window is back", ! toolMinimised());
  9545. check ("a click on the restored tool window does not reach the main window", ! clickReachesPad (inside));
  9546. break;
  9547. default:
  9548. return;
  9549. }
  9550. line (ok ? "result=OK" : "result=FAILED");
  9551. stopTimer();
  9552. done();
  9553. }
  9554. };
  9555. auto* test = new MinimizeTest();
  9556. test->reportPath = reportPath;
  9557. test->main = std::make_unique<juce::DocumentWindow> ("LYNX minimise test", lynx::theme::window, juce::DocumentWindow::allButtons);
  9558. test->main->setUsingNativeTitleBar (true);
  9559. test->pad = new ClickPad();
  9560. test->pad->setSize (1200, 760);
  9561. test->main->setContentOwned (test->pad, true);
  9562. test->main->setTopLeftPosition (60, 60);
  9563. test->main->setVisible (true);
  9564. lynx::setMainWindowForOwnership (test->main.get());
  9565. test->main->toFront (true);
  9566. test->done = [this, test] {
  9567. setApplicationReturnValue (test->ok ? 0 : 1);
  9568. juce::MessageManager::callAsync ([this, test] {
  9569. lynx::closeAllToolWindows();
  9570. lynx::setMainWindowForOwnership (nullptr);
  9571. test->main = nullptr;
  9572. delete test;
  9573. quit();
  9574. });
  9575. };
  9576. test->startTimer (700);
  9577. }
  9578. // LYNX.exe --plugintest plugin.vst3 report.txt ["name"]: loads the plugin (or the one named in a shell), plays notes if it is an
  9579. // instrument (and runs audio through it if it is an effect) and measures the audio.
  9580. // Round 190fw: an instrument plugin file on channel 5 of an offline engine (Image-Line's "FL Studio VSTi", which
  9581. // runs FL Studio inside it). Without a project: four chords at 137 BPM, rendered (notes.wav), the plugin's state
  9582. // saved in <folder>/vstitest.lynx. With a project (one saved by LYNX with the plugin on a channel, e.g. after its
  9583. // window was used): that project. Then: the project loaded back from the file renders the same (reload.wav) and
  9584. // gives the same state back; the project's own notes removed, rendered at 100 and 150 BPM (tempo-100/150.wav), the
  9585. // onsets of what the plugin plays by itself must follow the host tempo; and the outputs the plugin offers.
  9586. void runVstiTest (const juce::String& pluginPath, const juce::String& folderPath, const juce::String& projectPath)
  9587. {
  9588. juce::String report;
  9589. auto ok = true;
  9590. const juce::File folder (folderPath);
  9591. folder.createDirectory();
  9592. const auto check = [&] (const juce::String& name, bool passed) {
  9593. report << name << "=" << (passed ? "OK" : "FAILED") << "\n";
  9594. ok = ok && passed;
  9595. };
  9596. struct Take
  9597. {
  9598. float peak = 0.0f;
  9599. std::vector<float> left;
  9600. };
  9601. // renders `song` with the plugin file known to the engine's host; `wav` (in the folder) gets the audio
  9602. const auto render = [&] (const lynx::Song& song, double seconds, const juce::String& wav, std::function<void (lynx::AudioEngine&)> after = {}) {
  9603. Take take;
  9604. lynx::AudioEngine engine (false);
  9605. engine.getPluginHost().addPluginFile (juce::File (pluginPath));
  9606. engine.setSong (song);
  9607. const auto file = folder.getChildFile (wav);
  9608. file.deleteFile();
  9609. std::unique_ptr<juce::AudioFormatWriter> writer;
  9610. if (auto stream = file.createOutputStream())
  9611. {
  9612. juce::WavAudioFormat format;
  9613. writer.reset (format.createWriterFor (stream.get(), 48000.0, 2, 24, {}, 0));
  9614. if (writer != nullptr)
  9615. stream.release();
  9616. }
  9617. lynx::AudioEngine::RenderOptions o;
  9618. o.seconds = seconds;
  9619. o.sampleRate = 48000.0;
  9620. o.output = writer.get();
  9621. o.capture = [&take] (const float* l, const float*, int n) { take.left.insert (take.left.end(), l, l + n); };
  9622. take.peak = engine.renderOffline (o);
  9623. writer.reset();
  9624. if (after)
  9625. after (engine);
  9626. return take;
  9627. };
  9628. // the channel that holds the plugin
  9629. const auto pluginChannel = [&] (const lynx::Song& song) {
  9630. for (std::size_t c = 0; c < song.channels.size(); ++c)
  9631. if (song.channels[c].instrument == lynx::InstrumentKind::plugin
  9632. && juce::String (song.channels[c].plugin.name).containsIgnoreCase (juce::File (pluginPath).getFileNameWithoutExtension().upToFirstOccurrenceOf (" (", false, false)))
  9633. return (int) c;
  9634. return -1;
  9635. };
  9636. lynx::Song song;
  9637. const auto saved = folder.getChildFile ("vstitest.lynx");
  9638. if (projectPath.isEmpty())
  9639. {
  9640. lynx::AudioEngine scanner (false);
  9641. report << "plugins_in_file=" << scanner.getPluginHost().addPluginFile (juce::File (pluginPath)) << "\n";
  9642. std::optional<juce::PluginDescription> type;
  9643. for (const auto& t : scanner.getPluginHost().getKnownPlugins().getTypes())
  9644. if (t.isInstrument && juce::File (t.fileOrIdentifier) == juce::File (pluginPath))
  9645. type = t;
  9646. check ("instrument_found", type.has_value());
  9647. if (! type)
  9648. {
  9649. juce::File (folder.getChildFile ("report.txt")).replaceWithText (report + "result=FAILED\n");
  9650. setApplicationReturnValue (1);
  9651. quit();
  9652. return;
  9653. }
  9654. report << "plugin=" << type->name << " (" << type->manufacturerName << ") outputs=" << type->numOutputChannels << "\n";
  9655. song = lynx::Song::makeDefault();
  9656. song.bpm = 137.0;
  9657. auto& c = song.channels[4];
  9658. c.instrument = lynx::InstrumentKind::plugin;
  9659. c.plugin = {};
  9660. c.plugin.id = type->createIdentifierString().toStdString();
  9661. c.plugin.name = type->name.toStdString();
  9662. c.name = type->name.toStdString();
  9663. c.volume = 1.0f;
  9664. for (std::size_t k = 0; k < song.channels.size(); ++k)
  9665. song.channels[k].muted = k != 4;
  9666. song.patterns[0].notes.clear();
  9667. for (int beat = 0; beat < 8; ++beat) // a chord per beat, two bars
  9668. for (int key : { 60, 64, 67 })
  9669. song.patterns[0].notes.push_back ({ (std::int64_t) beat * lynx::ppq, lynx::ppq / 2, 4, key + (beat / 4) * 5, 0.9f });
  9670. song.patterns[0].sortNotes();
  9671. const auto notes = render (song, 4.0, "notes.wav", [&song] (lynx::AudioEngine& engine) {
  9672. engine.capturePluginStates();
  9673. song = engine.getSong();
  9674. });
  9675. report << "notes_peak=" << notes.peak << "\n";
  9676. check ("notes_play", notes.peak > 0.001f && notes.peak < 10.0f);
  9677. juce::String error;
  9678. check ("project_saved", lynx::ProjectFile::save (song, saved, error));
  9679. }
  9680. else
  9681. {
  9682. juce::String error;
  9683. const auto loaded = lynx::ProjectFile::load (juce::File (projectPath), error);
  9684. check ("project_loaded", loaded.has_value());
  9685. if (loaded)
  9686. song = *loaded;
  9687. juce::File (projectPath).copyFileTo (saved);
  9688. }
  9689. const auto channel = pluginChannel (song);
  9690. check ("plugin_channel", channel >= 0);
  9691. if (channel >= 0)
  9692. {
  9693. const auto& plugin = song.channels[(std::size_t) channel].plugin;
  9694. juce::MemoryBlock state;
  9695. state.fromBase64Encoding (juce::String (plugin.state));
  9696. report << "channel=" << channel + 1 << " state_bytes=" << (int) state.getSize() << "\n";
  9697. check ("state_saved", state.getSize() > 0);
  9698. // the project read back from the file: the same sound, and the same state handed back
  9699. juce::String error;
  9700. const auto again = lynx::ProjectFile::load (saved, error);
  9701. check ("project_reloaded", again.has_value());
  9702. if (again)
  9703. {
  9704. std::string stateBack;
  9705. const auto first = render (*again, 4.0, "reload-a.wav");
  9706. const auto second = render (*again, 4.0, "reload-b.wav", [&] (lynx::AudioEngine& engine) {
  9707. engine.capturePluginStates();
  9708. stateBack = engine.getSong().channels[(std::size_t) channel].plugin.state;
  9709. });
  9710. // two loads of the same project: the same audio (sample for sample, or within -60 dB for a plugin
  9711. // with free-running modulation)
  9712. double energy = 0.0, difference = 0.0;
  9713. const auto n = std::min (first.left.size(), second.left.size());
  9714. for (std::size_t k = 0; k < n; ++k)
  9715. {
  9716. energy += (double) first.left[k] * first.left[k];
  9717. difference += ((double) first.left[k] - second.left[k]) * ((double) first.left[k] - second.left[k]);
  9718. }
  9719. const auto ratioDb = energy > 0.0 ? 10.0 * std::log10 (std::max (difference, 1e-30) / energy) : 0.0;
  9720. report << "reload_peak=" << first.peak << " reload_difference_db=" << juce::String (ratioDb, 1) << "\n";
  9721. check ("reload_plays", first.peak > 0.001f);
  9722. check ("reload_same_sound", energy > 0.0 && ratioDb < -60.0);
  9723. juce::MemoryBlock back;
  9724. back.fromBase64Encoding (juce::String (stateBack));
  9725. report << "state_back_bytes=" << (int) back.getSize() << " identical=" << (int) (back == state) << "\n";
  9726. check ("state_handed_back", back.getSize() > 0);
  9727. }
  9728. // the host tempo: what the plugin plays by itself (FL Studio's own patterns inside FL Studio VSTi) at two
  9729. // tempos, without the project's notes
  9730. auto self = song;
  9731. for (std::size_t k = 0; k < self.channels.size(); ++k)
  9732. self.channels[k].muted = (int) k != channel;
  9733. for (auto& pattern : self.patterns)
  9734. pattern.notes.erase (std::remove_if (pattern.notes.begin(), pattern.notes.end(), [channel] (const lynx::Note& n) { return n.channel == channel; }),
  9735. pattern.notes.end());
  9736. const auto onsets = [] (const std::vector<float>& x) {
  9737. // envelope rises over a threshold (10 ms hold-off of 60 ms): the times in seconds
  9738. std::vector<double> at;
  9739. float peak = 0.0f;
  9740. for (const auto v : x)
  9741. peak = std::max (peak, std::abs (v));
  9742. const auto threshold = peak * 0.3f;
  9743. auto quietFor = 1 << 30;
  9744. for (std::size_t k = 0; k < x.size(); ++k)
  9745. {
  9746. const auto loud = std::abs (x[k]) >= threshold;
  9747. if (loud && quietFor >= 48000 * 60 / 1000)
  9748. at.push_back ((double) k / 48000.0);
  9749. quietFor = loud ? 0 : quietFor + 1;
  9750. }
  9751. return at;
  9752. };
  9753. const auto medianGap = [] (const std::vector<double>& at) {
  9754. std::vector<double> gaps;
  9755. for (std::size_t k = 1; k < at.size(); ++k)
  9756. gaps.push_back (at[k] - at[k - 1]);
  9757. if (gaps.empty())
  9758. return 0.0;
  9759. std::sort (gaps.begin(), gaps.end());
  9760. return gaps[gaps.size() / 2];
  9761. };
  9762. self.bpm = 100.0;
  9763. const auto slow = render (self, 6.0, "tempo-100.wav");
  9764. self.bpm = 150.0;
  9765. const auto fast = render (self, 6.0, "tempo-150.wav");
  9766. const auto gapSlow = medianGap (onsets (slow.left)), gapFast = medianGap (onsets (fast.left));
  9767. report << "self_peak_100=" << slow.peak << " self_peak_150=" << fast.peak << " onsets_100=" << (int) onsets (slow.left).size()
  9768. << " onsets_150=" << (int) onsets (fast.left).size() << " gap_100=" << juce::String (gapSlow, 4) << " gap_150="
  9769. << juce::String (gapFast, 4) << "\n";
  9770. if (slow.peak > 0.001f && gapFast > 0.0)
  9771. {
  9772. report << "tempo_ratio=" << juce::String (gapSlow / gapFast, 3) << " (expected 1.5)\n";
  9773. check ("follows_host_tempo", std::abs (gapSlow / gapFast - 1.5) < 0.05);
  9774. }
  9775. else
  9776. report << "tempo: the plugin plays nothing by itself in this project\n";
  9777. // the outputs it offers (FL Studio VSTi (Multi): FL's mixer tracks as separate outputs)
  9778. lynx::AudioEngine engine (false);
  9779. engine.getPluginHost().addPluginFile (juce::File (pluginPath));
  9780. engine.setSong (song);
  9781. engine.renderOffline (0.2, 48000.0);
  9782. if (auto instrument = std::dynamic_pointer_cast<lynx::PluginInstrument> (engine.getChannelInstrument (channel)))
  9783. {
  9784. report << "outputs=" << (int) instrument->outputs().size() << ":";
  9785. for (const auto& o : instrument->outputs())
  9786. report << " [" << o.name << "]";
  9787. report << "\n";
  9788. check ("outputs_listed", ! instrument->outputs().empty());
  9789. }
  9790. else
  9791. check ("instrument_loaded", false);
  9792. }
  9793. report << "plugin_crashes=" << lynx::pluginCrashCount() << "\n";
  9794. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  9795. folder.getChildFile ("report.txt").replaceWithText (report);
  9796. setApplicationReturnValue (ok ? 0 : 1);
  9797. quit();
  9798. }
  9799. void runPluginTest (const juce::String& pluginPath, const juce::String& reportPath, const juce::String& only = {})
  9800. {
  9801. juce::String report;
  9802. bool ok = false;
  9803. {
  9804. lynx::AudioEngine offline (false);
  9805. auto& host = offline.getPluginHost();
  9806. const auto added = host.addPluginFile (juce::File (pluginPath));
  9807. report << "plugins_in_file=" << added << "\n";
  9808. juce::PluginDescription instrument, effect;
  9809. bool hasInstrument = false, hasEffect = false;
  9810. for (const auto& type : host.getKnownPlugins().getTypes())
  9811. {
  9812. if (juce::File (type.fileOrIdentifier).getFileName() != juce::File (pluginPath).getFileName()
  9813. || (only.isNotEmpty() && type.name != only))
  9814. continue;
  9815. report << " " << (type.isInstrument ? "instrument: " : "effect: ") << type.name << " (" << type.manufacturerName
  9816. << ") in " << type.fileOrIdentifier << "\n";
  9817. if (type.isInstrument && ! hasInstrument) { instrument = type; hasInstrument = true; }
  9818. if (! type.isInstrument && ! hasEffect) { effect = type; hasEffect = true; }
  9819. }
  9820. auto song = lynx::Song::makeDefault();
  9821. if (hasInstrument)
  9822. {
  9823. auto& c = song.channels[4]; // the "Synth" channel becomes the plugin
  9824. c.instrument = lynx::InstrumentKind::plugin;
  9825. c.plugin.id = instrument.createIdentifierString().toStdString();
  9826. c.plugin.name = instrument.name.toStdString();
  9827. c.volume = 1.0f;
  9828. for (int i = 0; i < 4; ++i) // one chord per beat
  9829. for (int key : { 60, 64, 67 })
  9830. song.patterns[0].notes.push_back ({ (std::int64_t) i * lynx::ppq, lynx::ppq / 2, 4, key, 0.9f });
  9831. song.patterns[0].sortNotes();
  9832. }
  9833. if (hasEffect)
  9834. {
  9835. lynx::EffectSlot slot;
  9836. slot.kind = lynx::EffectKind::plugin;
  9837. slot.plugin.id = effect.createIdentifierString().toStdString();
  9838. slot.plugin.name = effect.name.toStdString();
  9839. song.mixer[0].effects.push_back (slot);
  9840. }
  9841. const auto effectSlot = (int) song.mixer[0].effects.size() - 1; // (the default master may hold effects already)
  9842. offline.setSong (song);
  9843. // after a render: the rack (and its plugins) is built when the engine is prepared
  9844. const auto peak = offline.renderOffline (3.0, 48000.0);
  9845. const auto* loadedInstrument = dynamic_cast<lynx::PluginInstrument*> (offline.getChannelInstrument (4).get());
  9846. const auto* loadedEffect = dynamic_cast<lynx::PluginEffect*> (offline.getEffect (0, effectSlot).get());
  9847. report << "instrument_loaded=" << (loadedInstrument != nullptr ? "yes" : "no") << "\n"
  9848. << "effect_loaded=" << (loadedEffect != nullptr ? "yes" : "no") << "\n";
  9849. if (host.getLoadFailures().size() > 0) // why: the host's own message (license, missing file, load failure)
  9850. report << "load_failures=" << host.getLoadFailures().joinIntoString (" | ") << "\n";
  9851. report << "peak=" << peak << "\n";
  9852. // plugins that crashed inside a call, were caught and switched off (round 111)
  9853. report << "plugin_crashes=" << lynx::pluginCrashCount() << "\n";
  9854. for (const auto& c : lynx::pluginCrashes())
  9855. report << " crashed: " << c.plugin << " (" << lynx::crashguard::describe (c.code) << ")\n";
  9856. offline.capturePluginStates();
  9857. const auto stateSize = hasInstrument ? offline.getSong().channels[4].plugin.state.size() : (size_t) 0;
  9858. report << "state_bytes_base64=" << (int) stateSize << "\n";
  9859. ok = (hasInstrument || hasEffect) && (! hasInstrument || loadedInstrument != nullptr)
  9860. && (! hasEffect || loadedEffect != nullptr) && peak > 0.001f && peak < 10.0f;
  9861. }
  9862. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  9863. juce::File (reportPath).replaceWithText (report);
  9864. setApplicationReturnValue (ok ? 0 : 1);
  9865. quit();
  9866. }
  9867. // Round 190gg (B4): --crashguardtest plugin report.txt thread | ui. "thread": the plugin's own thread faults in its 40th
  9868. // block (Linux / macOS): that thread is parked, LYNX switches the plugin off (as the main window's timer does) and goes
  9869. // on; the other inserts play; Reload brings it back. "ui": the calls the UI makes into a plugin, under the guard: a
  9870. // preset load that crashes (the Plugin window's preset menu path) and making the editor (PluginWindows::open, the CLAP
  9871. // test plugin's "editor-create": a display is needed, e.g. Xvfb); each switches the plugin off, LYNX goes on.
  9872. void runCrashGuardThreadOrUiTest (const juce::String& pluginPath, const juce::String& reportPath, const juce::String& mode)
  9873. {
  9874. juce::String report;
  9875. bool ok = true;
  9876. const auto expect = [&] (const char* name, bool value) {
  9877. report << name << "=" << (value ? 1 : 0) << "\n";
  9878. ok = ok && value;
  9879. };
  9880. const auto setEnv = [] (const char* name, const char* value) {
  9881. #if JUCE_WINDOWS
  9882. _putenv_s (name, value);
  9883. #else
  9884. setenv (name, value, 1);
  9885. #endif
  9886. };
  9887. const auto render = [] (lynx::AudioEngine& engine, double seconds, float* peak) {
  9888. lynx::AudioEngine::RenderOptions o;
  9889. o.seconds = seconds;
  9890. o.sampleRate = 48000.0;
  9891. o.pluginWarmUp = false;
  9892. if (peak != nullptr)
  9893. o.capture = [peak] (const float* l, const float* r, int n) {
  9894. for (int k = 0; k < n; ++k)
  9895. *peak = std::max (*peak, std::max (std::abs (l[k]), std::abs (r[k])));
  9896. };
  9897. return engine.renderOffline (o);
  9898. };
  9899. report << "mode=" << mode << "\nthread_guard=" << (lynx::crashguard::pluginThreadFaultsCaught() ? "on" : "off") << "\n";
  9900. setEnv ("LYNX_TEST_CRASH", mode == "thread" ? "thread" : "");
  9901. setEnv ("LYNX_TEST_CRASH_AFTER", "40");
  9902. const auto tmp = juce::File::getSpecialLocation (juce::File::tempDirectory)
  9903. .getChildFile ("lynx-crashguardtest-" + juce::String::toHexString (juce::Random::getSystemRandom().nextInt64()));
  9904. tmp.createDirectory();
  9905. {
  9906. lynx::AudioEngine offline (false);
  9907. auto& host = offline.getPluginHost();
  9908. host.addPluginFile (juce::File (pluginPath));
  9909. juce::PluginDescription effect;
  9910. bool found = false;
  9911. for (const auto& type : host.getKnownPlugins().getTypes())
  9912. if (! found && ! type.isInstrument && juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginPath).getFileName())
  9913. {
  9914. effect = type;
  9915. found = true;
  9916. }
  9917. expect ("plugin_found", found);
  9918. auto song = lynx::Song::makeDefault();
  9919. lynx::EffectSlot slot;
  9920. slot.kind = lynx::EffectKind::plugin;
  9921. slot.plugin.id = effect.createIdentifierString().toStdString();
  9922. slot.plugin.name = effect.name.toStdString();
  9923. song.mixer[1].effects.push_back (slot);
  9924. offline.setSong (song);
  9925. const lynx::AudioEngine::HostedSlot where { -1, 1, 0 };
  9926. render (offline, 0.05, nullptr);
  9927. offline.editSong ([] (lynx::Song& s) { s.channels[0].volume = 0.85f; }, false);
  9928. render (offline, 0.05, nullptr);
  9929. auto* first = dynamic_cast<lynx::PluginEffect*> (offline.getEffect (1, 0).get());
  9930. expect ("plugin_loaded", first != nullptr);
  9931. const auto crashesBefore = lynx::pluginCrashCount();
  9932. if (mode == "thread")
  9933. {
  9934. const auto faultsBefore = lynx::crashguard::pluginThreadFaultCount();
  9935. float peak = 0.0f;
  9936. render (offline, 3.0, &peak); // (the plugin starts its faulting thread in its 40th block)
  9937. for (int i = 0; i < 200 && lynx::crashguard::pluginThreadFaultCount() == faultsBefore; ++i)
  9938. juce::Thread::sleep (10);
  9939. const auto faults = lynx::crashguard::pluginThreadFaults();
  9940. expect ("thread_fault_parked", lynx::crashguard::pluginThreadFaultCount() == faultsBefore + 1 && ! faults.empty());
  9941. if (! faults.empty())
  9942. report << "thread_fault=" << faults.back().where << " (" << lynx::crashguard::describe (faults.back().code) << ")\n";
  9943. expect ("not_yet_counted_as_a_call_crash", lynx::pluginCrashCount() == crashesBefore);
  9944. // what the main window's timer does
  9945. // (every instance of that module: the engine may hold more than the slot's, e.g. the offline render's)
  9946. if (first != nullptr)
  9947. report << "slot_file=" << first->getInstance().getPluginDescription().fileOrIdentifier << "\n";
  9948. const auto switched = lynx::switchOffPluginsOfThreadFaults();
  9949. report << "switched_off=" << switched << "\n";
  9950. expect ("plugin_switched_off", switched >= 1 && first != nullptr && first->hasCrashed() && lynx::pluginCrashCount() == crashesBefore + switched);
  9951. expect ("only_once", lynx::switchOffPluginsOfThreadFaults() == 0);
  9952. const auto down = offline.downHostedPlugins();
  9953. expect ("slot_down", down.size() == 1 && down[0] == where);
  9954. float after = 0.0f;
  9955. render (offline, 1.0, &after);
  9956. report << "peak_after=" << after << "\n";
  9957. expect ("audio_after_fault", after > 0.01f);
  9958. offline.editSong ([] (lynx::Song& s) { s.channels[0].volume = 0.0f; }, false);
  9959. float others = 0.0f;
  9960. render (offline, 1.0, &others);
  9961. expect ("other_inserts_play", others > 0.01f);
  9962. offline.editSong ([] (lynx::Song& s) { s.channels[0].volume = 0.85f; }, false);
  9963. const auto running = offline.reloadHostedPlugins (down);
  9964. auto* again = dynamic_cast<lynx::PluginEffect*> (offline.getEffect (1, 0).get());
  9965. float reloaded = 0.0f;
  9966. render (offline, 1.0, &reloaded);
  9967. expect ("reloaded_plays", running == 1 && again != nullptr && again != first && ! again->hasCrashed() && reloaded > 0.01f);
  9968. }
  9969. else
  9970. {
  9971. // a preset that crashes the plugin (the preset menu's load), saved first from the running plugin
  9972. auto& instance = first->getInstance();
  9973. const auto preset = tmp.getChildFile ("crash.lynxpreset");
  9974. juce::String error;
  9975. expect ("preset_saved", lynx::pluginpresetui::save (instance, preset, "crash", error) && preset.existsAsFile());
  9976. setEnv ("LYNX_TEST_CRASH", "state");
  9977. const auto loaded = lynx::pluginpresetui::load (instance, preset, error);
  9978. setEnv ("LYNX_TEST_CRASH", "");
  9979. report << "preset_error=" << error << "\n";
  9980. expect ("preset_crash_caught", ! loaded && lynx::pluginCrashCount() == crashesBefore + 1 && first->hasCrashed());
  9981. expect ("preset_plugin_down", offline.hostedPluginDown (where) && lynx::pluginInstanceDown (instance));
  9982. expect ("not_called_again", ! lynx::callPluginFromUi (instance, "test", [] {}) && lynx::pluginCrashCount() == crashesBefore + 1);
  9983. float after = 0.0f;
  9984. render (offline, 1.0, &after);
  9985. expect ("audio_after_preset_crash", after > 0.01f);
  9986. // Reload; then its editor crashes as it is made (PluginWindows::open): no window, the plugin is down
  9987. setEnv ("LYNX_TEST_CRASH", "editor-create");
  9988. const auto running = offline.reloadHostedPlugins (offline.downHostedPlugins());
  9989. auto held = offline.getEffect (1, 0);
  9990. auto* again = dynamic_cast<lynx::PluginEffect*> (held.get());
  9991. expect ("reloaded", running == 1 && again != nullptr && again != first && ! again->hasCrashed());
  9992. if (again != nullptr)
  9993. {
  9994. lynx::PluginWindows::open (held, again->getInstance(), "crash test", {});
  9995. expect ("editor_crash_caught", lynx::pluginCrashCount() == crashesBefore + 2 && again->hasCrashed());
  9996. expect ("no_window", ! lynx::PluginWindows::isOpen (again->getInstance()));
  9997. float editorAfter = 0.0f;
  9998. render (offline, 1.0, &editorAfter);
  9999. expect ("audio_after_editor_crash", editorAfter > 0.01f);
  10000. }
  10001. setEnv ("LYNX_TEST_CRASH", "");
  10002. }
  10003. }
  10004. setEnv ("LYNX_TEST_CRASH", "");
  10005. // LYNX's own faults (also on its own threads) stay crashes (child processes; the selftest runs the same)
  10006. const auto own = faultReportSelfTest();
  10007. report << "own_faults=" << own << "\n";
  10008. ok = ok && ! own.startsWith ("ERROR");
  10009. for (const auto& c : lynx::pluginCrashes())
  10010. report << " crashed: " << c.plugin << " (" << lynx::crashguard::describe (c.code) << ")\n";
  10011. tmp.deleteRecursively();
  10012. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  10013. juce::File (reportPath).replaceWithText (report);
  10014. setApplicationReturnValue (ok ? 0 : 1);
  10015. quit();
  10016. }
  10017. // LYNX --crashguardtest plugin report.txt [process|memcpy] (round 190dt): see the dispatch in initialise().
  10018. void runCrashGuardTest (const juce::String& pluginPath, const juce::String& reportPath, const juce::String& mode)
  10019. {
  10020. if (mode == "thread" || mode == "ui")
  10021. {
  10022. runCrashGuardThreadOrUiTest (pluginPath, reportPath, mode);
  10023. return;
  10024. }
  10025. juce::String report;
  10026. bool ok = true;
  10027. const auto expect = [&] (const char* name, bool value) {
  10028. report << name << "=" << (value ? 1 : 0) << "\n";
  10029. ok = ok && value;
  10030. };
  10031. const auto setEnv = [] (const char* name, const char* value) {
  10032. #if JUCE_WINDOWS
  10033. _putenv_s (name, value);
  10034. #else
  10035. setenv (name, value, 1);
  10036. #endif
  10037. };
  10038. // renders without the plugin warm-up (its silent blocks would count towards the crash)
  10039. const auto render = [] (lynx::AudioEngine& engine, double seconds, const std::function<void (const float*, const float*, int)>& capture) {
  10040. lynx::AudioEngine::RenderOptions o;
  10041. o.seconds = seconds;
  10042. o.sampleRate = 48000.0;
  10043. o.pluginWarmUp = false;
  10044. o.capture = capture;
  10045. return engine.renderOffline (o);
  10046. };
  10047. const auto peakOf = [] (float& peak) {
  10048. return [&peak] (const float* l, const float* r, int n) {
  10049. for (int k = 0; k < n; ++k)
  10050. peak = std::max (peak, std::max (std::abs (l[k]), std::abs (r[k])));
  10051. };
  10052. };
  10053. report << "guard=" << (lynx::crashguard::pluginFaultsCaught() ? "on" : "off") << "\nmode=" << mode << "\n";
  10054. setEnv ("LYNX_TEST_CRASH", mode == "memcpy" ? "memcpy" : "process");
  10055. setEnv ("LYNX_TEST_CRASH_AFTER", "40");
  10056. const auto tmp = juce::File::getSpecialLocation (juce::File::tempDirectory)
  10057. .getChildFile ("lynx-crashguardtest-" + juce::String::toHexString (juce::Random::getSystemRandom().nextInt64()));
  10058. tmp.createDirectory();
  10059. std::optional<lynx::Song> saved;
  10060. std::string savedState;
  10061. {
  10062. lynx::AudioEngine offline (false);
  10063. auto& host = offline.getPluginHost();
  10064. host.addPluginFile (juce::File (pluginPath));
  10065. juce::PluginDescription effect;
  10066. bool found = false;
  10067. for (const auto& type : host.getKnownPlugins().getTypes())
  10068. if (! found && ! type.isInstrument && juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginPath).getFileName())
  10069. {
  10070. effect = type;
  10071. found = true;
  10072. }
  10073. expect ("plugin_found", found);
  10074. // the plugin on insert 1 (the kick's); the clap and the hat play on inserts 2 and 3
  10075. auto song = lynx::Song::makeDefault();
  10076. lynx::EffectSlot slot;
  10077. slot.kind = lynx::EffectKind::plugin;
  10078. slot.plugin.id = effect.createIdentifierString().toStdString();
  10079. slot.plugin.name = effect.name.toStdString();
  10080. song.mixer[1].effects.push_back (slot);
  10081. offline.setSong (song);
  10082. const lynx::AudioEngine::HostedSlot where { -1, 1, 0 };
  10083. // the rack is published at the engine's rate and an offline render runs at its own (48 kHz) without publishing:
  10084. // one edit after a first render puts the rack (and the plugin) at the render's rate, so later edits keep it
  10085. render (offline, 0.05, {}); // (a few blocks, far from the 40th)
  10086. offline.editSong ([] (lynx::Song& s) { s.channels[0].volume = 0.85f; }, false);
  10087. render (offline, 0.05, {});
  10088. auto* first = dynamic_cast<lynx::PluginEffect*> (offline.getEffect (1, 0).get());
  10089. expect ("plugin_loaded", first != nullptr);
  10090. offline.capturePluginStates();
  10091. savedState = offline.getSong().mixer[1].effects[0].plugin.state;
  10092. expect ("state_captured", ! savedState.empty());
  10093. // the crash: 3 s, the plugin faults in its 40th block
  10094. const auto crashesBefore = lynx::pluginCrashCount();
  10095. juce::int64 position = 0, crashAt = -1;
  10096. float peakAfter = 0.0f;
  10097. const auto afterPeak = peakOf (peakAfter);
  10098. const auto peak = render (offline, 3.0, [&] (const float* l, const float* r, int n) {
  10099. if (crashAt < 0 && lynx::pluginCrashCount() != crashesBefore)
  10100. crashAt = position;
  10101. else if (crashAt >= 0)
  10102. afterPeak (l, r, n);
  10103. position += n;
  10104. });
  10105. report << "peak=" << peak << "\ncrash_at_sample=" << crashAt << "\npeak_after_crash=" << peakAfter << "\n";
  10106. const auto crashes = lynx::pluginCrashes();
  10107. expect ("crash_caught", lynx::pluginCrashCount() == crashesBefore + 1 && ! crashes.empty() && ! crashes.back().onLoad);
  10108. if (! crashes.empty())
  10109. report << "crash=" << crashes.back().plugin << " (" << lynx::crashguard::describe (crashes.back().code) << ")\n";
  10110. expect ("slot_marked_crashed", first != nullptr && offline.getEffect (1, 0).get() == first && first->hasCrashed());
  10111. const auto down = offline.downHostedPlugins();
  10112. expect ("slot_down", down.size() == 1 && down[0] == where);
  10113. expect ("audio_after_crash", crashAt >= 0 && peakAfter > 0.01f);
  10114. // the other inserts: with the kick (through the crashed slot) silent, the clap and the hat still play
  10115. offline.editSong ([] (lynx::Song& s) { s.channels[0].volume = 0.0f; }, false);
  10116. float othersPeak = 0.0f;
  10117. render (offline, 1.0, peakOf (othersPeak));
  10118. report << "other_inserts_peak=" << othersPeak << "\n";
  10119. expect ("other_inserts_play", othersPeak > 0.01f);
  10120. expect ("nothing_reloads_by_itself", offline.hostedPluginDown (where) && offline.getEffect (1, 0).get() == first);
  10121. offline.editSong ([] (lynx::Song& s) { s.channels[0].volume = 0.85f; }, false);
  10122. // the project saves with the settings the plugin had before it crashed, and opens again
  10123. offline.capturePluginStates();
  10124. expect ("state_kept", offline.getSong().mixer[1].effects[0].plugin.state == savedState);
  10125. const auto file = tmp.getChildFile ("crashed.lynx");
  10126. juce::String error;
  10127. expect ("project_saved", lynx::ProjectFile::save (offline.getSong(), file, error) && file.existsAsFile());
  10128. saved = lynx::ProjectFile::load (file, error);
  10129. expect ("project_reopens", saved.has_value() && saved->mixer.size() > 1 && saved->mixer[1].effects.size() == 1
  10130. && saved->mixer[1].effects[0].plugin.state == savedState);
  10131. // Reload (the prompt's button, round 190ao): a new instance; the module's block count is past 40 now
  10132. const auto running = offline.reloadHostedPlugins (down);
  10133. auto* again = dynamic_cast<lynx::PluginEffect*> (offline.getEffect (1, 0).get());
  10134. expect ("reloaded", running == 1 && again != nullptr && again != first && ! again->hasCrashed());
  10135. float reloadedPeak = 0.0f;
  10136. render (offline, 1.0, peakOf (reloadedPeak));
  10137. report << "reloaded_peak=" << reloadedPeak << "\n";
  10138. expect ("reloaded_plays", reloadedPeak > 0.01f && lynx::pluginCrashCount() == crashesBefore + 1 && again != nullptr && ! again->hasCrashed());
  10139. }
  10140. // the saved project opens again with the plugin crashing on its saved settings: left out, the rest plays, the
  10141. // settings stay in the project
  10142. setEnv ("LYNX_TEST_CRASH", "state");
  10143. if (saved.has_value())
  10144. {
  10145. lynx::AudioEngine reopened (false);
  10146. reopened.getPluginHost().addPluginFile (juce::File (pluginPath));
  10147. const auto before = lynx::pluginCrashCount();
  10148. reopened.setSong (*saved);
  10149. float reopenedPeak = 0.0f;
  10150. render (reopened, 1.0, peakOf (reopenedPeak));
  10151. const auto crashes = lynx::pluginCrashes();
  10152. report << "reopened_peak=" << reopenedPeak << "\n";
  10153. if (reopened.getPluginHost().getLoadFailures().size() > 0)
  10154. report << "load_failures=" << reopened.getPluginHost().getLoadFailures().joinIntoString (" | ") << "\n";
  10155. expect ("state_crash_caught", lynx::pluginCrashCount() == before + 1 && ! crashes.empty() && crashes.back().onLoad);
  10156. expect ("state_crash_left_out", dynamic_cast<lynx::PluginEffect*> (reopened.getEffect (1, 0).get()) == nullptr);
  10157. expect ("state_crash_project_plays", reopenedPeak > 0.01f);
  10158. reopened.capturePluginStates();
  10159. expect ("state_crash_settings_kept", reopened.getSong().mixer[1].effects.size() == 1
  10160. && reopened.getSong().mixer[1].effects[0].plugin.state == savedState);
  10161. }
  10162. setEnv ("LYNX_TEST_CRASH", "");
  10163. // LYNX's own faults inside a guarded call stay crashes (child processes; the selftest runs the same)
  10164. const auto own = faultReportSelfTest();
  10165. report << "own_faults=" << own << "\n";
  10166. ok = ok && ! own.startsWith ("ERROR");
  10167. report << "plugin_crashes=" << lynx::pluginCrashCount() << "\n";
  10168. for (const auto& c : lynx::pluginCrashes())
  10169. report << " crashed: " << c.plugin << " (" << lynx::crashguard::describe (c.code) << (c.onLoad ? ", loading its state" : "") << ")\n";
  10170. tmp.deleteRecursively();
  10171. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  10172. juce::File (reportPath).replaceWithText (report);
  10173. setApplicationReturnValue (ok ? 0 : 1);
  10174. quit();
  10175. }
  10176. // LYNX.exe --mpetest "LYNX Test MPE.clap" report.txt (tools/testplugin/lynx_test_mpe.c, issue #108): a hosted CLAP
  10177. // instrument with the wrapper's MPE switch on gets each note on its own member channel, its fine pitch / Mod X /
  10178. // Mod Y as tuning / brightness / pressure note expressions before the note on, and a sounding note's expression
  10179. // on that note's channel alone. The plugin writes down what it received; no window, no audio device.
  10180. // Round 190hy: see --mpeplaytest190hy. Note A (C4, 1 s): its pitch curve holds 0 for 0.5 s, rises an octave over
  10181. // 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
  10182. // rendered audio's zero crossings (a silent logging plugin: its log shows the expressions instead).
  10183. void runMpePlayTest190hy (const juce::String& pluginPath, const juce::String& reportPath)
  10184. {
  10185. const auto log = juce::File (reportPath).getSiblingFile (juce::File (reportPath).getFileNameWithoutExtension() + "-plugin.txt");
  10186. log.deleteFile();
  10187. #if JUCE_WINDOWS
  10188. _putenv_s ("LYNX_TEST_MPE_REPORT", log.getFullPathName().toRawUTF8());
  10189. #else
  10190. setenv ("LYNX_TEST_MPE_REPORT", log.getFullPathName().toRawUTF8(), 1);
  10191. #endif
  10192. juce::String report;
  10193. auto ok = false;
  10194. const auto wavFile = juce::File (reportPath).withFileExtension ("wav");
  10195. constexpr double rate = 44100.0;
  10196. {
  10197. lynx::AudioEngine offline (false);
  10198. auto& host = offline.getPluginHost();
  10199. report << "plugins_in_file=" << host.addPluginFile (juce::File (pluginPath)) << "\n";
  10200. const auto wanted = juce::File (pluginPath).hasFileExtension ("clap") ? "CLAP" : "VST3";
  10201. std::optional<juce::PluginDescription> type;
  10202. for (const auto& t : host.getKnownPlugins().getTypes())
  10203. if (t.pluginFormatName == wanted && t.isInstrument && ! type)
  10204. type = t;
  10205. report << "format=" << wanted << " found=" << (type ? type->name : juce::String ("none")) << "\n";
  10206. if (type)
  10207. {
  10208. lynx::Song s;
  10209. s.mixer = lynx::Song::defaultMixer (2);
  10210. s.bpm = 120.0;
  10211. lynx::ChannelDef c;
  10212. c.name = type->name.toStdString();
  10213. c.instrument = lynx::InstrumentKind::plugin;
  10214. c.plugin.id = type->createIdentifierString().toStdString();
  10215. c.plugin.name = type->name.toStdString();
  10216. c.plugin.mpe = true;
  10217. c.mixerTrack = 1;
  10218. s.channels.push_back (c);
  10219. s.patterns.emplace_back();
  10220. auto& p = s.patterns[0];
  10221. lynx::Note a;
  10222. a.channel = 0;
  10223. a.key = 60;
  10224. a.length = 2 * lynx::ppq;
  10225. a.velocity = 0.8f;
  10226. lynx::NoteCurves curves;
  10227. curves.lane (lynx::NoteCurveLane::pitch) = { { 0.0f, 0.0f }, { (float) lynx::ppq, 0.0f }, { 1.5f * (float) lynx::ppq, 1200.0f },
  10228. { 2.0f * (float) lynx::ppq, 1200.0f } };
  10229. a.curves = curves;
  10230. auto b = a;
  10231. b.key = 67;
  10232. b.start = 2 * lynx::ppq;
  10233. b.length = lynx::ppq;
  10234. b.curves.clear();
  10235. p.notes = { a, b };
  10236. p.lengthTicks = 16 * lynx::ppq; // (one pass: the notes play once in the 1.2 s rendered)
  10237. offline.setSong (std::move (s));
  10238. wavFile.deleteFile();
  10239. juce::WavAudioFormat wav;
  10240. std::unique_ptr<juce::AudioFormatWriter> writer (wav.createWriterFor (wavFile.createOutputStream().release(), rate, 2, 24, {}, 0));
  10241. const auto peak = writer != nullptr ? offline.renderOffline (1.6, rate, writer.get()) : 0.0f;
  10242. writer.reset();
  10243. report << "peak=" << peak << "\n";
  10244. ok = writer == nullptr && wavFile.existsAsFile();
  10245. }
  10246. } // (the plugin writes its log, if any, as it is destroyed)
  10247. // the frequency of [from, to) seconds of the left channel from its rising zero crossings
  10248. juce::AudioBuffer<float> audio;
  10249. {
  10250. juce::AudioFormatManager formats;
  10251. formats.registerBasicFormats();
  10252. if (std::unique_ptr<juce::AudioFormatReader> reader (formats.createReaderFor (wavFile)); reader != nullptr)
  10253. {
  10254. audio.setSize (1, (int) reader->lengthInSamples);
  10255. reader->read (&audio, 0, (int) reader->lengthInSamples, 0, true, false);
  10256. }
  10257. }
  10258. const auto frequency = [&audio] (double from, double to) {
  10259. const auto* x = audio.getReadPointer (0);
  10260. const auto n = audio.getNumSamples();
  10261. long first = -1, last = -1;
  10262. auto crossings = 0;
  10263. for (auto i = juce::jmax (1, (int) (from * rate)); i < juce::jmin (n, (int) (to * rate)); ++i)
  10264. if (x[i - 1] <= 0.0f && x[i] > 0.0f)
  10265. {
  10266. if (first < 0)
  10267. first = i;
  10268. else
  10269. ++crossings, last = i;
  10270. }
  10271. return crossings > 0 ? crossings * rate / (double) (last - first) : 0.0;
  10272. };
  10273. if (audio.getNumSamples() > 0 && audio.getMagnitude (0, 0, audio.getNumSamples()) > 0.001f)
  10274. {
  10275. 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);
  10276. report << "a_before_hz=" << before << " a_rising_hz=" << during << " a_after_hz=" << after << " b_hz=" << next << "\n";
  10277. report << "a_after_over_before=" << (before > 0.0 ? after / before : 0.0) << " (an octave: 2)\n";
  10278. report << "b_over_a_before=" << (before > 0.0 ? next / before : 0.0) << " (a fifth: 1.498)\n";
  10279. }
  10280. else
  10281. report << "audio=silent\n";
  10282. if (log.existsAsFile())
  10283. report << "--- plugin log ---\n" << log.loadFileAsString();
  10284. report << "result=" << (ok ? "RENDERED" : "FAILED") << "\n";
  10285. juce::File (reportPath).replaceWithText (report);
  10286. setApplicationReturnValue (ok ? 0 : 1);
  10287. quit();
  10288. }
  10289. void runMpeTest (const juce::String& pluginPath, const juce::String& reportPath)
  10290. {
  10291. const auto log = juce::File (reportPath).getSiblingFile (juce::File (reportPath).getFileNameWithoutExtension() + "-plugin.txt");
  10292. log.deleteFile();
  10293. #if JUCE_WINDOWS
  10294. _putenv_s ("LYNX_TEST_MPE_REPORT", log.getFullPathName().toRawUTF8());
  10295. #else
  10296. setenv ("LYNX_TEST_MPE_REPORT", log.getFullPathName().toRawUTF8(), 1);
  10297. #endif
  10298. juce::String report;
  10299. auto failures = 0;
  10300. {
  10301. lynx::AudioEngine engine (false);
  10302. auto& host = engine.getPluginHost();
  10303. report << "plugins_in_file=" << host.addPluginFile (juce::File (pluginPath)) << "\n";
  10304. std::optional<juce::PluginDescription> clap;
  10305. for (const auto& type : host.getKnownPlugins().getTypes())
  10306. if (type.pluginFormatName == "CLAP" && juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginPath).getFileName())
  10307. clap = type;
  10308. lynx::PluginRef ref;
  10309. if (clap)
  10310. {
  10311. ref.id = clap->createIdentifierString().toStdString();
  10312. ref.name = clap->name.toStdString();
  10313. }
  10314. ref.mpe = true;
  10315. juce::String error;
  10316. auto instrument = clap ? host.makeInstrument (ref, 48000.0, &error) : nullptr;
  10317. report << "instrument_loaded=" << (instrument != nullptr ? "yes" : "no") << (error.isNotEmpty() ? " (" + error + ")" : juce::String()) << "\n";
  10318. if (instrument != nullptr)
  10319. {
  10320. std::vector<float> l (256), r (256);
  10321. auto block = [&] { instrument->render (l.data(), r.data(), 256, 1.0f, 1.0f); };
  10322. block(); // (the zone's setup)
  10323. instrument->setNextNoteFinePitch (30.0f); // +30 cents
  10324. instrument->setNextNoteModulation (0.75f, 1.0f); // timbre 0.75, full pressure
  10325. instrument->noteOn (60, 0.8f);
  10326. instrument->noteOn (64, 0.5f); // a second note: its own channel, centre values
  10327. block();
  10328. instrument->noteExpression (60, (int) lynx::vfx::Prop::pitch, 200.0f, 0.0f);
  10329. instrument->noteExpression (64, (int) lynx::vfx::Prop::modX, 0.25f, 0.0f);
  10330. instrument->noteExpression (60, (int) lynx::vfx::Prop::modY, 0.75f, 0.0f);
  10331. block();
  10332. instrument->noteOff (60);
  10333. instrument->noteOff (64);
  10334. block();
  10335. }
  10336. else
  10337. ++failures;
  10338. } // (the plugin writes its log as it is destroyed)
  10339. struct Line
  10340. {
  10341. juce::String kind;
  10342. int a = 0, b = 0, c = 0, d = 0;
  10343. };
  10344. std::vector<Line> lines;
  10345. for (const auto& text : juce::StringArray::fromLines (log.loadFileAsString()))
  10346. {
  10347. const auto t = juce::StringArray::fromTokens (text, " ", "");
  10348. if (t.size() >= 3)
  10349. 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 });
  10350. }
  10351. report << "plugin_events=" << (int) lines.size() << "\n";
  10352. // the first line at or after `from` that matches (−1 = none); `value` within `tolerance` (thousandths)
  10353. auto find = [&lines] (const juce::String& kind, int a, int b, int value, int tolerance, int from = 0) {
  10354. for (auto i = (std::size_t) from; i < lines.size(); ++i)
  10355. {
  10356. const auto& x = lines[i];
  10357. const auto v = kind == "expr" ? x.d : x.c;
  10358. if (x.kind == kind && x.a == a && x.b == b && std::abs (v - value) <= tolerance)
  10359. return (int) i;
  10360. }
  10361. return -1;
  10362. };
  10363. auto check = [&] (const char* what, bool ok) {
  10364. report << what << "=" << (ok ? "ok" : "FAILED") << "\n";
  10365. failures += ok ? 0 : 1;
  10366. };
  10367. // (CLAP expression ids: 2 tuning in semitones, 5 brightness, 6 pressure; channels 0-based: the first member = 1)
  10368. const auto on60 = find ("on", 1, 60, 800, 5), on64 = find ("on", 2, 64, 500, 5);
  10369. check ("zone_setup_sent", find ("midi", 176, 6, 15, 0) >= 0 && find ("midi", 177, 6, 48, 0) >= 0);
  10370. check ("notes_on_their_own_channels", on60 >= 0 && on64 > on60);
  10371. const auto tune = find ("expr", 2, 1, 300, 3), bright = find ("expr", 5, 1, 756, 4), press = find ("expr", 6, 1, 1000, 1);
  10372. check ("expression_before_the_note_on", tune >= 0 && bright >= 0 && press >= 0 && tune < on60 && bright < on60 && press < on60);
  10373. 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);
  10374. const auto later = std::max (on60, on64) + 1;
  10375. check ("sounding_note_expression", later > 0 && find ("expr", 2, 1, 2000, 3, later) >= 0 && find ("expr", 5, 2, 252, 4, later) >= 0
  10376. && find ("expr", 6, 1, 504, 4, later) >= 0);
  10377. check ("other_note_untouched", later > 0 && find ("expr", 2, 2, 2000, 3, later) < 0 && find ("expr", 6, 2, 504, 4, later) < 0);
  10378. check ("notes_off_on_their_channels", find ("off", 1, 60, 0, 100000) >= 0 && find ("off", 2, 64, 0, 100000) >= 0);
  10379. auto expressionAsMidi = false; // (a CLAP-dialect plugin gets no raw bend / pressure / CC 74 on a member channel)
  10380. for (const auto& x : lines)
  10381. if (x.kind == "midi" && (x.a & 0x0f) != 0 && ((x.a & 0xf0) == 0xe0 || (x.a & 0xf0) == 0xd0 || ((x.a & 0xf0) == 0xb0 && x.b == 74)))
  10382. expressionAsMidi = true;
  10383. check ("no_duplicate_midi_expression", ! expressionAsMidi);
  10384. report << "--- plugin log ---\n" << log.loadFileAsString() << "result=" << (failures == 0 ? "OK" : "FAILED") << "\n";
  10385. juce::File (reportPath).replaceWithText (report);
  10386. setApplicationReturnValue (failures == 0 ? 0 : 1);
  10387. quit();
  10388. }
  10389. // LYNX.exe --claprestarttest "LYNX Test Restart.clap" report.txt (tools/testplugin/lynx_test_restart.c, PR #29): a
  10390. // CLAP effect on the Master that asks for a restart every 8 blocks while an export renders on a thread of its own
  10391. // (the message thread is free to run the restarts, as with the Export window). The plugin aborts the process when
  10392. // start / stop_processing run off the audio thread or activate / deactivate off the main thread (issue #46, as u-he
  10393. // Presswerk does; an export at 44.1 kHz and prepare calls from the export's thread check the latter) and counts deactivations that
  10394. // landed inside its process() call (must be none), the restarts must happen, and the delay compensation must end on
  10395. // the latency the plugin reports after its last restart.
  10396. void runClapRestartTest (const juce::String& pluginPath, const juce::String& reportPath)
  10397. {
  10398. struct Run
  10399. {
  10400. std::unique_ptr<lynx::AudioEngine> engine;
  10401. juce::String report;
  10402. int slot = -1;
  10403. std::thread render;
  10404. std::atomic<bool> done { false };
  10405. double renderSeconds = 0.0;
  10406. };
  10407. auto run = std::make_shared<Run>();
  10408. const auto counters = juce::File (reportPath).getSiblingFile (juce::File (reportPath).getFileNameWithoutExtension() + "-plugin.txt");
  10409. counters.deleteFile();
  10410. #if JUCE_WINDOWS
  10411. _putenv_s ("LYNX_TEST_RESTART_REPORT", counters.getFullPathName().toRawUTF8());
  10412. #else
  10413. setenv ("LYNX_TEST_RESTART_REPORT", counters.getFullPathName().toRawUTF8(), 1);
  10414. #endif
  10415. const auto fail = [this, reportPath] (juce::String report) {
  10416. report << "result=FAILED\n";
  10417. juce::File (reportPath).replaceWithText (report);
  10418. setApplicationReturnValue (1);
  10419. quit();
  10420. };
  10421. run->engine = std::make_unique<lynx::AudioEngine> (false);
  10422. auto& host = run->engine->getPluginHost();
  10423. run->report << "plugins_in_file=" << host.addPluginFile (juce::File (pluginPath)) << "\n";
  10424. std::optional<juce::PluginDescription> clap;
  10425. for (const auto& type : host.getKnownPlugins().getTypes())
  10426. if (type.pluginFormatName == "CLAP" && juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginPath).getFileName())
  10427. clap = type;
  10428. if (! clap)
  10429. {
  10430. fail (run->report + "no CLAP plugin in the file\n");
  10431. return;
  10432. }
  10433. auto song = lynx::Song::makeDefault();
  10434. lynx::EffectSlot slot;
  10435. slot.kind = lynx::EffectKind::plugin;
  10436. slot.plugin.id = clap->createIdentifierString().toStdString();
  10437. slot.plugin.name = clap->name.toStdString();
  10438. slot.smartDisable = false; // (processed every block, as with music playing: the export itself is silent)
  10439. song.mixer[0].effects = { slot }; // alone on the Master: the delay compensation is the plugin's latency
  10440. run->slot = (int) song.mixer[0].effects.size() - 1;
  10441. run->engine->setSong (song);
  10442. run->engine->renderOffline (0.1, 48000.0); // builds the rack (and the plugin) on the message thread
  10443. if (dynamic_cast<lynx::PluginEffect*> (run->engine->getEffect (0, run->slot).get()) == nullptr)
  10444. {
  10445. fail (run->report + "effect_loaded=no\n");
  10446. return;
  10447. }
  10448. auto effect = std::dynamic_pointer_cast<lynx::PluginEffect> (run->engine->getEffect (0, run->slot));
  10449. run->render = std::thread ([run, effect] () mutable {
  10450. const auto start = juce::Time::getMillisecondCounterHiRes();
  10451. run->engine->renderOffline (30.0, 48000.0);
  10452. run->renderSeconds = (juce::Time::getMillisecondCounterHiRes() - start) * 0.001;
  10453. // issue #46: an export at another rate / block size prepares the plugin from the export's thread; the
  10454. // plugin aborts unless activate / deactivate reach the main thread
  10455. auto& instance = effect->getInstance();
  10456. instance.prepareToPlay (44100.0, 1024);
  10457. instance.releaseResources();
  10458. instance.prepareToPlay (48000.0, 512);
  10459. run->engine->renderOffline (3.0, 44100.0); // (the engine rebuilds its rack at that rate)
  10460. // The engine has replaced this instance (made for 48 kHz) by then, so this is its last reference: it is
  10461. // deleted here, on the export's thread, and its deactivate / destroy go to the message thread, which this
  10462. // waits for. That has to happen before `done`: once the message thread sees it, it blocks in join() until
  10463. // this thread ends, and an instance deleted after that waited 10 s for it and then deactivated the plugin
  10464. // right here, off the main thread (the plugin aborts: about 1 run in 40 under load, round 190au).
  10465. effect.reset();
  10466. run->done = true;
  10467. });
  10468. // after the render: a second for the restarts still queued and the engine's timer (the new PDC plan)
  10469. auto finish = std::make_shared<std::function<void()>>();
  10470. *finish = [this, run, counters, reportPath, fail, finish] {
  10471. if (! run->done)
  10472. {
  10473. juce::Timer::callAfterDelay (50, *finish);
  10474. return;
  10475. }
  10476. run->render.join();
  10477. juce::Timer::callAfterDelay (1000, [this, run, counters, reportPath, fail] {
  10478. auto report = run->report;
  10479. int pluginLatency = -1;
  10480. if (const auto effect = run->engine->getEffect (0, run->slot)) // (not held past the engine's reset)
  10481. pluginLatency = effect->latencySamples();
  10482. const auto pdc = run->engine->getLatencySamples();
  10483. report << "render_seconds=" << juce::String (run->renderSeconds, 2) << "\n"
  10484. << "plugin_latency=" << pluginLatency << "\npdc_total=" << pdc << "\n"
  10485. << "plugin_crashes=" << lynx::pluginCrashCount() << "\n";
  10486. run->engine.reset(); // destroys the plugin: it writes its counters
  10487. // one line per plugin instance (the engine may have made more than one): none may have been
  10488. // deactivated inside process(), and the one that rendered must have restarted
  10489. int overlapped = 0, inactive = 0, requests = 0, activations = 0, lines = 0, wrongThread = 0, misordered = 0, unstopped = 0;
  10490. bool otherRate = false;
  10491. for (const auto& line : juce::StringArray::fromLines (counters.loadFileAsString()))
  10492. {
  10493. juce::StringPairArray values;
  10494. for (const auto& token : juce::StringArray::fromTokens (line, " ", ""))
  10495. if (token.contains ("="))
  10496. values.set (token.upToFirstOccurrenceOf ("=", false, false), token.fromFirstOccurrenceOf ("=", false, false));
  10497. if (values.size() == 0)
  10498. continue;
  10499. ++lines;
  10500. report << "instance: " << line << "\n";
  10501. overlapped += values["overlapped"].getIntValue();
  10502. inactive += values["inactive_blocks"].getIntValue();
  10503. // issue #46: activate / deactivate on the main thread, start / stop_processing on the audio thread
  10504. // (the plugin aborts the process otherwise, as u-he's do), in order, every start stopped
  10505. wrongThread += values["wrong_thread"].getIntValue();
  10506. misordered += values["misordered"].getIntValue();
  10507. unstopped += values["starts"].getIntValue() - values["stops"].getIntValue();
  10508. otherRate = otherRate || values["last_rate"].getIntValue() == 44100;
  10509. if (values["requests"].getIntValue() > requests)
  10510. {
  10511. requests = values["requests"].getIntValue();
  10512. activations = values["activations"].getIntValue();
  10513. }
  10514. }
  10515. report << "wrong_thread=" << wrongThread << "\nmisordered=" << misordered << "\nunstopped=" << unstopped
  10516. << "\nactivated_at_44100=" << (otherRate ? "yes" : "no") << "\n";
  10517. const auto ok = lines > 0 && requests > 0 && activations > requests / 2 && overlapped == 0 && inactive == 0
  10518. && wrongThread == 0 && misordered == 0 && unstopped == 0 && otherRate
  10519. && pluginLatency > 0 && pdc == pluginLatency && lynx::pluginCrashCount() == 0;
  10520. if (! ok)
  10521. {
  10522. fail (report);
  10523. return;
  10524. }
  10525. report << "result=OK\n";
  10526. juce::File (reportPath).replaceWithText (report);
  10527. setApplicationReturnValue (0);
  10528. quit();
  10529. });
  10530. };
  10531. juce::Timer::callAfterDelay (50, *finish);
  10532. }
  10533. // LYNX.exe --vst2test "LYNX Test Synth.dll" report.txt (tools/testplugin/lynx_test_vst2.c): LYNX's own VST2 host.
  10534. // Scans the DLL, imports it the way an .flp holds it (Fruity Wrapper VST2 state with a chunk, REA_rodada89 §2),
  10535. // renders with two saved gains (the level must follow the restored state) and checks the plugin saw the song tempo.
  10536. void runVst2Test (const juce::String& pluginPath, const juce::String& reportPath)
  10537. {
  10538. juce::String report;
  10539. bool ok = false;
  10540. {
  10541. lynx::AudioEngine offline (false);
  10542. auto& host = offline.getPluginHost();
  10543. report << "plugins_in_file=" << host.addPluginFile (juce::File (pluginPath)) << "\n";
  10544. std::optional<juce::PluginDescription> vst2;
  10545. for (const auto& type : host.getKnownPlugins().getTypes())
  10546. if (type.pluginFormatName == "VST")
  10547. vst2 = type;
  10548. auto render = [&] (float gain, float& tempoSeen, int& adopted) {
  10549. lynx::FlVst2State state;
  10550. state.flags = 8;
  10551. state.chunk = { 'L', 'X', 'V', '2', 0, 0, 0, 0 };
  10552. std::memcpy (state.chunk.data() + 4, &gain, 4);
  10553. auto song = lynx::Song::makeDefault();
  10554. song.bpm = 137.0;
  10555. auto& f = song.channels[4].plugin.foreign;
  10556. f.format = lynx::ForeignPlugin::Format::vst2;
  10557. f.vst2Id = (std::uint32_t) vst2->uniqueId;
  10558. f.name = "Some other name"; // found by the VST2 ID
  10559. f.state = lynx::writeFlVst2State (state);
  10560. song.channels[4].volume = 1.0f;
  10561. song.patterns[0].notes.clear();
  10562. song.patterns[0].notes.push_back ({ 0, 4 * lynx::ppq, 4, 69, 1.0f });
  10563. for (std::size_t c = 0; c < song.channels.size(); ++c)
  10564. if (c != 4)
  10565. song.channels[c].muted = true;
  10566. adopted = host.adoptFlPlugins (song);
  10567. offline.setSong (song);
  10568. const auto peak = offline.renderOffline (1.0, 48000.0);
  10569. offline.capturePluginStates();
  10570. juce::MemoryBlock saved;
  10571. saved.fromBase64Encoding (juce::String (offline.getSong().channels[4].plugin.state));
  10572. lynx::FlVst2State back;
  10573. tempoSeen = 0.0f;
  10574. if (lynx::parseFlVst2State (std::vector<std::uint8_t> ((const std::uint8_t*) saved.getData(), (const std::uint8_t*) saved.getData() + saved.getSize()), back)
  10575. && back.chunk.size() >= 12)
  10576. std::memcpy (&tempoSeen, back.chunk.data() + 8, 4);
  10577. return peak;
  10578. };
  10579. if (vst2)
  10580. {
  10581. report << "plugin=" << vst2->name << " id=" << vst2->uniqueId << " instrument=" << (int) vst2->isInstrument << "\n";
  10582. float tempoA = 0, tempoB = 0;
  10583. int adoptedA = 0, adoptedB = 0;
  10584. const auto quiet = render (0.1f, tempoA, adoptedA);
  10585. const auto loud = render (0.4f, tempoB, adoptedB);
  10586. report << "adopted=" << adoptedA << "," << adoptedB << " peak_gain_0.1=" << quiet << " peak_gain_0.4=" << loud
  10587. << " tempo_seen=" << tempoB * 1000.0f << "\n";
  10588. ok = adoptedA == 1 && adoptedB == 1 && quiet > 0.01f && std::abs (loud / quiet - 4.0f) < 0.2f
  10589. && std::abs (tempoB * 1000.0f - 137.0f) < 0.01f;
  10590. }
  10591. }
  10592. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  10593. juce::File (reportPath).replaceWithText (report);
  10594. setApplicationReturnValue (ok ? 0 : 1);
  10595. quit();
  10596. }
  10597. // LYNX --vst3noteidtest "LYNX Test Synth.vst3" report.txt (round 190fg, cmake/LynxPatchJuce.cmake fix 26): the VST3
  10598. // test synth (tools/testplugin/lynx_test_synth_vst3.cpp: voices kept by noteId, its log the ids it got) plays two
  10599. // 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).
  10600. // 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
  10601. // 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).
  10602. void runVst3NoteIdTest (const juce::String& pluginPath, const juce::String& reportPath)
  10603. {
  10604. juce::String report;
  10605. bool ok = false;
  10606. const auto logBase = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-noteid-" + juce::String (juce::Time::currentTimeMillis()));
  10607. // (read by each new instance)
  10608. #if JUCE_WINDOWS
  10609. _putenv_s ("LYNX_TEST_SYNTH_LOG", logBase.getFullPathName().toRawUTF8());
  10610. #else
  10611. setenv ("LYNX_TEST_SYNTH_LOG", logBase.getFullPathName().toRawUTF8(), 1);
  10612. #endif
  10613. struct E
  10614. {
  10615. bool on = false;
  10616. int key = 0, id = -1;
  10617. };
  10618. // (the lines each render added: a running instance keeps its log file open, so the files stay until the end)
  10619. std::map<juce::String, int> linesRead;
  10620. const auto readLog = [&logBase, &linesRead] {
  10621. std::vector<E> events;
  10622. for (const auto& f : logBase.getParentDirectory().findChildFiles (juce::File::findFiles, false, logBase.getFileName() + ".*"))
  10623. {
  10624. juce::StringArray lines;
  10625. f.readLines (lines);
  10626. auto& done = linesRead[f.getFullPathName()];
  10627. for (int i = done; i < lines.size(); ++i)
  10628. {
  10629. const auto p = juce::StringArray::fromTokens (lines[i], " ", {});
  10630. if (p.size() >= 5 && p[0].startsWith ("E"))
  10631. events.push_back ({ p[1] == "on", p[2].getIntValue(), p[4].getIntValue() });
  10632. }
  10633. done = lines.size() - (lines.isEmpty() || lines[lines.size() - 1].isNotEmpty() ? 0 : 1);
  10634. }
  10635. return events;
  10636. };
  10637. {
  10638. lynx::AudioEngine offline (false);
  10639. auto& host = offline.getPluginHost();
  10640. report << "plugins_in_file=" << host.addPluginFile (juce::File (pluginPath)) << "\n";
  10641. std::optional<juce::PluginDescription> vst3;
  10642. for (const auto& type : host.getKnownPlugins().getTypes())
  10643. if (type.pluginFormatName == "VST3" && type.isInstrument)
  10644. vst3 = type;
  10645. const auto render = [&] (bool tags) {
  10646. auto song = lynx::Song::makeDefault();
  10647. song.bpm = 120.0;
  10648. auto& c = song.channels[0];
  10649. c.instrument = lynx::InstrumentKind::plugin;
  10650. c.plugin.id = vst3->createIdentifierString().toStdString();
  10651. c.plugin.name = vst3->name.toStdString();
  10652. for (std::size_t k = 1; k < song.channels.size(); ++k)
  10653. song.channels[k].muted = true;
  10654. auto& notes = song.patterns[0].notes;
  10655. notes.clear();
  10656. const auto beat = (std::int64_t) lynx::ppq;
  10657. notes.push_back ({ 0, 4 * beat, 0, 60, 0.8f }); // A
  10658. notes.push_back ({ 2 * beat, 4 * beat, 0, 60, 0.8f }); // B
  10659. notes.push_back ({ 8 * beat, 6 * beat, 0, 64, 0.8f }); // C
  10660. notes.push_back ({ 10 * beat, 2 * beat, 0, 64, 0.8f }); // D (inside C)
  10661. song.patterns[0].sortNotes();
  10662. song.patterns[0].lengthTicks = 16 * beat;
  10663. offline.setSong (song);
  10664. offline.dispatchPendingMessages();
  10665. if (! tags)
  10666. juce::lynxNoteTagHook = nullptr; // (fix 14 alone: the oldest sounding id; the next instance sets it again)
  10667. offline.renderOffline (7.9, 48000.0); // (C ends at 7 s; the 8 s pattern does not loop yet)
  10668. return readLog();
  10669. };
  10670. const auto check = [&report] (const char* name, const std::vector<E>& events, bool expectOwn) {
  10671. // ons and offs of each key in the order the plugin got them
  10672. std::map<int, std::vector<int>> ons, offs;
  10673. for (const auto& e : events)
  10674. (e.on ? ons : offs)[e.key].push_back (e.id);
  10675. const auto& a = ons[60]; const auto& o60 = offs[60];
  10676. const auto& c = ons[64]; const auto& o64 = offs[64];
  10677. report << name << ": key 60 ons";
  10678. for (auto id : a) report << " " << id;
  10679. report << " offs";
  10680. for (auto id : o60) report << " " << id;
  10681. report << "; key 64 ons";
  10682. for (auto id : c) report << " " << id;
  10683. report << " offs";
  10684. for (auto id : o64) report << " " << id;
  10685. report << "\n";
  10686. if (a.size() != 2 || o60.size() != 2 || c.size() != 2 || o64.size() != 2 || a[0] < 0 || c[0] < 0)
  10687. return false;
  10688. const auto fifo = o60[0] == a[0] && o60[1] == a[1]; // A ends first: A's id either way
  10689. // LIFO: D (c[1]) ends first; its own id with the tags, C's (the oldest) without
  10690. const auto lifo = expectOwn ? (o64[0] == c[1] && o64[1] == c[0]) : (o64[0] == c[0] && o64[1] == c[1]);
  10691. return fifo && lifo;
  10692. };
  10693. if (vst3)
  10694. {
  10695. report << "plugin=" << vst3->name << "\n";
  10696. const auto withTags = render (true);
  10697. const auto okTags = check ("with_tags", withTags, true);
  10698. const auto withoutTags = render (false);
  10699. const auto okBefore = check ("fix14_only", withoutTags, false);
  10700. report << "own_ids=" << (okTags ? "yes" : "NO") << " fix14_only_oldest=" << (okBefore ? "yes" : "NO") << "\n";
  10701. ok = okTags && okBefore;
  10702. }
  10703. }
  10704. if (ok) // (a failure leaves the logs for a look: their path is in the report)
  10705. for (const auto& f : logBase.getParentDirectory().findChildFiles (juce::File::findFiles, false, logBase.getFileName() + ".*"))
  10706. f.deleteFile();
  10707. else
  10708. report << "synth_logs=" << logBase.getFullPathName() << ".*\n";
  10709. #if JUCE_WINDOWS
  10710. _putenv_s ("LYNX_TEST_SYNTH_LOG", "");
  10711. #else
  10712. unsetenv ("LYNX_TEST_SYNTH_LOG");
  10713. #endif
  10714. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  10715. juce::File (reportPath).replaceWithText (report);
  10716. setApplicationReturnValue (ok ? 0 : 1);
  10717. quit();
  10718. }
  10719. // Round 181c: a wrapper MIDI option changed on a running plugin must act like the same option on a new one. For each
  10720. // option: a control engine whose plugin is created with the option set (proves the test can see it), then an engine
  10721. // whose plugin is already running when the option changes through editSong, as the wrapper page does it. What the
  10722. // plugin received comes from the test plugin's own log. The running instance must also stay the same one.
  10723. void runWrapperMidiTest (const juce::String& pluginPath, const juce::String& reportPath)
  10724. {
  10725. juce::String report;
  10726. auto ok = true;
  10727. const juce::File logFile (juce::SystemStats::getEnvironmentVariable ("LYNX_TEST_VST2_MIDILOG", {}));
  10728. struct Event { juce::String instance; int status, data1, data2; };
  10729. auto take = [&] {
  10730. std::vector<Event> out;
  10731. juce::StringArray lines;
  10732. logFile.readLines (lines);
  10733. for (const auto& line : lines)
  10734. {
  10735. const auto p = juce::StringArray::fromTokens (line, " ", {});
  10736. if (p.size() == 4)
  10737. out.push_back ({ p[0], p[1].getIntValue(), p[2].getIntValue(), p[3].getIntValue() });
  10738. }
  10739. logFile.deleteFile();
  10740. return out;
  10741. };
  10742. auto count = [] (const std::vector<Event>& events, int status, int data1, int data2) {
  10743. int n = 0;
  10744. for (const auto& e : events)
  10745. n += (e.status & 0xF0) == status && (data1 < 0 || e.data1 == data1) && (data2 < 0 || e.data2 == data2) ? 1 : 0;
  10746. return n;
  10747. };
  10748. struct Option
  10749. {
  10750. const char* name;
  10751. std::function<void (lynx::PluginRef&)> before, change;
  10752. std::function<juce::String (const std::vector<Event>&)> seen;
  10753. };
  10754. const Option options[] = {
  10755. { "Send note release velocity off", {}, [] (lynx::PluginRef& r) { r.releaseVelocity = false; },
  10756. [&] (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)); } },
  10757. { "Send pitch bend range on", {}, [] (lynx::PluginRef& r) { r.sendBendRange = true; },
  10758. [&] (const std::vector<Event>& e) { return "rpn_range_12=" + juce::String (count (e, 0xB0, 6, 12)); } },
  10759. { "Pitch bend range 24", [] (lynx::PluginRef& r) { r.sendBendRange = true; }, [] (lynx::PluginRef& r) { r.bendRange = 24; },
  10760. [&] (const std::vector<Event>& e) { return "rpn_range_24=" + juce::String (count (e, 0xB0, 6, 24)); } },
  10761. { "Send MOD X as polyphonic aftertouch on", {}, [] (lynx::PluginRef& r) { r.modXAftertouch = true; },
  10762. [&] (const std::vector<Event>& e) { return "aftertouch=" + juce::String (count (e, 0xA0, 69, -1)); } },
  10763. { "Send All Notes Off when playback stops off", {}, [] (lynx::PluginRef& r) { r.allNotesOffOnStop = false; },
  10764. [&] (const std::vector<Event>& e) { return "cc123=" + juce::String (count (e, 0xB0, 123, -1)); } },
  10765. };
  10766. // each phase has its own engine: an engine keeps the running instance across setSong, so one engine would
  10767. // carry the control's plugin into the "before" phase
  10768. lynx::AudioEngine scanner (false);
  10769. auto& host = scanner.getPluginHost();
  10770. report << "plugins_in_file=" << host.addPluginFile (juce::File (pluginPath)) << "\n";
  10771. std::optional<juce::PluginDescription> vst2;
  10772. for (const auto& type : host.getKnownPlugins().getTypes())
  10773. if (type.pluginFormatName == "VST")
  10774. vst2 = type;
  10775. if (! vst2 || logFile.getFullPathName().isEmpty())
  10776. ok = false;
  10777. else
  10778. for (const auto& option : options)
  10779. {
  10780. auto makeSong = [&] (bool changed) {
  10781. auto song = lynx::Song::makeDefault();
  10782. auto& channel = song.channels[0];
  10783. channel.instrument = lynx::InstrumentKind::plugin;
  10784. channel.plugin = {};
  10785. channel.plugin.id = vst2->createIdentifierString().toStdString();
  10786. channel.plugin.name = vst2->name.toStdString();
  10787. if (option.before)
  10788. option.before (channel.plugin);
  10789. if (changed)
  10790. option.change (channel.plugin);
  10791. song.patterns[0].notes.clear();
  10792. lynx::Note note;
  10793. note.start = 0;
  10794. note.length = lynx::ppq;
  10795. note.channel = 0;
  10796. note.key = 69;
  10797. note.velocity = 1.0f;
  10798. note.release = 0.25f; // 32 of 127
  10799. note.modX = 0.75f;
  10800. song.patterns[0].notes.push_back (note);
  10801. for (std::size_t c = 1; c < song.channels.size(); ++c)
  10802. song.channels[c].muted = true;
  10803. return song;
  10804. };
  10805. // a block of the song, then a note held across "playback stopped", as the options act on either
  10806. auto play = [&] (lynx::AudioEngine& engine) {
  10807. logFile.deleteFile();
  10808. engine.renderOffline (1.0, 48000.0);
  10809. if (auto instrument = engine.getChannelInstrument (0))
  10810. {
  10811. instrument->noteOn (60, 1.0f);
  10812. instrument->transportStopped();
  10813. }
  10814. engine.renderOffline (0.1, 48000.0);
  10815. return take();
  10816. };
  10817. auto newEngine = [&] {
  10818. auto engine = std::make_unique<lynx::AudioEngine> (false);
  10819. engine->getPluginHost().addPluginFile (juce::File (pluginPath));
  10820. return engine;
  10821. };
  10822. std::vector<Event> control;
  10823. {
  10824. auto engine = newEngine();
  10825. engine->setSong (makeSong (true));
  10826. control = play (*engine);
  10827. }
  10828. auto engine = newEngine();
  10829. engine->setSong (makeSong (false));
  10830. const auto before = play (*engine);
  10831. const auto instrumentBefore = engine->getChannelInstrument (0).get();
  10832. engine->capturePluginStates(); // as the wrapper page does
  10833. engine->editSong ([&] (lynx::Song& song) { option.change (song.channels[0].plugin); });
  10834. const auto after = play (*engine);
  10835. const auto sameInstance = engine->getChannelInstrument (0).get() == instrumentBefore;
  10836. // the counts differ between phases (how many blocks the note spans, how many instances the phase made):
  10837. // what matters is whether each kind of event is there at all
  10838. auto shape = [] (const juce::String& seen) {
  10839. juce::String out;
  10840. for (const auto& token : juce::StringArray::fromTokens (seen, " ", {}))
  10841. out << token.upToFirstOccurrenceOf ("=", false, false) << (token.fromFirstOccurrenceOf ("=", false, false).getIntValue() > 0 ? "=yes " : "=no ");
  10842. return out;
  10843. };
  10844. auto instances = [] (const std::vector<Event>& events) {
  10845. std::set<juce::String> made;
  10846. for (const auto& e : events)
  10847. made.insert (e.instance);
  10848. return (int) made.size();
  10849. };
  10850. const auto a = option.seen (control) + " instances=" + juce::String (instances (control)),
  10851. b = option.seen (before) + " instances=" + juce::String (instances (before)),
  10852. c = option.seen (after) + " instances=" + juce::String (instances (after));
  10853. const auto visible = shape (option.seen (control)) != shape (option.seen (before));
  10854. const auto works = shape (option.seen (after)) == shape (option.seen (control));
  10855. report << option.name << ": control " << a << " | before " << b << " | after the change " << c << " | same_instance=" << (int) sameInstance
  10856. << " | test_sees_the_option=" << (int) visible << " | " << (! visible ? "NOT PROVEN" : works ? "acts on the plugin" : "DEAD until re-created") << "\n";
  10857. ok = ok && visible && works;
  10858. }
  10859. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  10860. juce::File (reportPath).replaceWithText (report);
  10861. setApplicationReturnValue (ok ? 0 : 1);
  10862. quit();
  10863. }
  10864. // LYNX.exe --wrappershot "LYNX Test Drums.dll" <folder> (round 188d): the wrapper's Processing tab drawn offscreen
  10865. // (no window, no focus) for the FL | LYNX review: wrap-default.png (a fresh plugin), wrap-automap.png (Auto map
  10866. // outputs, output 3 off: FL's shot b23), wrap-settings.png. Scale 1.5 (FL's shots are at 150 %).
  10867. void runWrapperShot (const juce::String& pluginPath, const juce::String& folderPath)
  10868. {
  10869. const juce::File folder (folderPath);
  10870. folder.createDirectory();
  10871. auto ok = false;
  10872. lynx::AudioEngine engine (false);
  10873. engine.getPluginHost().addPluginFile (juce::File (pluginPath));
  10874. std::optional<juce::PluginDescription> vst2;
  10875. for (const auto& type : engine.getPluginHost().getKnownPlugins().getTypes())
  10876. if (type.pluginFormatName == "VST" && juce::File (type.fileOrIdentifier) == juce::File (pluginPath))
  10877. vst2 = type; // (the profile may know other test plugins)
  10878. if (vst2 && ! vst2->isInstrument)
  10879. {
  10880. // an effect (round 188d): on insert 1, with insert 2 routed there as a sidechain (FL's k65 / k78 shots):
  10881. // wrap-fx-default.png, wrap-fx-automap.png (Auto map inputs and outputs)
  10882. auto song = lynx::Song::makeDefault();
  10883. if (song.mixer.size() < 4)
  10884. song.mixer.resize (4);
  10885. auto slot = lynx::makeEffectSlot (lynx::EffectKind::plugin);
  10886. slot.plugin.id = vst2->createIdentifierString().toStdString();
  10887. slot.plugin.name = vst2->name.toStdString();
  10888. song.mixer[1].effects = { slot };
  10889. lynx::mixerops::sidechainTo (song, 2, 1);
  10890. engine.setSong (song);
  10891. engine.renderOffline (0.05, 48000.0);
  10892. if (auto fx = std::dynamic_pointer_cast<lynx::PluginEffect> (engine.getEffect (1, 0)))
  10893. {
  10894. auto find = [] (lynx::Song& s) -> lynx::PluginRef* {
  10895. return s.mixer.size() < 2 || s.mixer[1].effects.empty() ? nullptr : &s.mixer[1].effects[0].plugin;
  10896. };
  10897. auto save = [&] (const char* name) {
  10898. const auto image = lynx::wrapperSettingsSnapshot (engine, find, fx->getInstance(), false, 1, 1.5f, 1, 0);
  10899. juce::FileOutputStream out (folder.getChildFile (name));
  10900. out.setPosition (0);
  10901. out.truncate();
  10902. return out.openedOk() && juce::PNGImageFormat().writeImageToStream (image, out);
  10903. };
  10904. ok = save ("wrap-fx-default.png");
  10905. engine.editSong ([] (lynx::Song& s) {
  10906. lynx::autoMapOutputs (s.mixer[1].effects[0].plugin.inputs, 2);
  10907. lynx::autoMapOutputs (s.mixer[1].effects[0].plugin.outputs, 2);
  10908. s.mixer[1].effects[0].sidechain = lynx::mixerops::sidechainIndexSource (s, 1, 1);
  10909. });
  10910. ok = ok && save ("wrap-fx-automap.png") && engine.getSong().mixer[1].effects[0].sidechain == 2;
  10911. }
  10912. }
  10913. else if (vst2)
  10914. {
  10915. auto song = lynx::Song::makeDefault();
  10916. auto& channel = song.channels[0];
  10917. channel.instrument = lynx::InstrumentKind::plugin;
  10918. channel.plugin = {};
  10919. channel.plugin.id = vst2->createIdentifierString().toStdString();
  10920. channel.plugin.name = vst2->name.toStdString();
  10921. channel.mixerTrack = 5;
  10922. engine.setSong (song);
  10923. engine.renderOffline (0.05, 48000.0); // (the plugin is hosted by then)
  10924. if (auto instrument = std::dynamic_pointer_cast<lynx::PluginInstrument> (engine.getChannelInstrument (0)))
  10925. {
  10926. auto find = [] (lynx::Song& s) -> lynx::PluginRef* { return s.channels.empty() ? nullptr : &s.channels[0].plugin; };
  10927. auto save = [&] (const char* name, int tab) {
  10928. const auto image = lynx::wrapperSettingsSnapshot (engine, find, instrument->getInstance(), true, tab, 1.5f);
  10929. juce::FileOutputStream out (folder.getChildFile (name));
  10930. out.setPosition (0);
  10931. out.truncate();
  10932. return out.openedOk() && juce::PNGImageFormat().writeImageToStream (image, out);
  10933. };
  10934. ok = save ("wrap-default.png", 1) && save ("wrap-settings.png", 0);
  10935. engine.editSong ([] (lynx::Song& s) {
  10936. lynx::autoMapOutputs (s.channels[0].plugin.outputs, 8);
  10937. s.channels[0].plugin.outputs.resize (8);
  10938. s.channels[0].plugin.outputs[2].active = 0;
  10939. s.channels[0].plugin.processInactive = false; // (as an LED click does, FL's b23)
  10940. });
  10941. ok = ok && save ("wrap-automap.png", 1);
  10942. }
  10943. }
  10944. setApplicationReturnValue (ok ? 0 : 1);
  10945. quit();
  10946. }
  10947. // LYNX.exe --multiouttest "LYNX Test Drums.dll" report.txt (round 188d, issue #114): a multi-output VST2
  10948. // (tools/testplugin/lynx_test_drums_vst2.c: key 36 = output 1 at 110 Hz, key 37 = output 2 at 220 Hz) on a
  10949. // channel routed to insert 1; the wrapper's Processing › Connections as FL plays them [EXEC fl188d]: every output
  10950. // on the channel's insert by default, an offset to another insert, an inactive output silent, the channel's
  10951. // volume on all of them. Measured on the master with insert 1 muted or not.
  10952. void runMultiOutTest (const juce::String& pluginPath, const juce::String& reportPath)
  10953. {
  10954. juce::String report;
  10955. auto ok = true;
  10956. lynx::AudioEngine scanner (false);
  10957. report << "plugins_in_file=" << scanner.getPluginHost().addPluginFile (juce::File (pluginPath)) << "\n";
  10958. std::optional<juce::PluginDescription> vst2;
  10959. for (const auto& type : scanner.getPluginHost().getKnownPlugins().getTypes())
  10960. if (type.pluginFormatName == "VST" && juce::File (type.fileOrIdentifier) == juce::File (pluginPath))
  10961. vst2 = type; // (the profile may know other test plugins)
  10962. struct Case
  10963. {
  10964. const char* name;
  10965. std::vector<lynx::PluginOutputRoute> routes;
  10966. bool muteInsert1;
  10967. float volume;
  10968. bool kick, snare; // expected on the master
  10969. };
  10970. const Case cases[] = {
  10971. { "defaults", {}, false, -1.0f, true, true },
  10972. { "defaults, insert 1 muted", {}, true, -1.0f, false, false },
  10973. { "auto map, insert 1 muted", { { 0, 1 }, { 1, 1 } }, true, -1.0f, false, true },
  10974. { "auto map", { { 0, 1 }, { 1, 1 } }, false, -1.0f, true, true },
  10975. { "output 2 inactive", { { 0, 1 }, { 1, 0 } }, false, -1.0f, true, false },
  10976. { "output 1 inactive", { { 0, 0 } }, false, -1.0f, false, true },
  10977. { "auto map, channel volume 0", { { 0, 1 }, { 1, 1 } }, false, 0.0f, false, false },
  10978. { "output 2 inactive, Process inactive inputs and outputs on", { { 0, 1 }, { 1, 0 } }, false, -1.0f, true, true },
  10979. };
  10980. auto tone = [] (const std::vector<float>& x, double hz) {
  10981. // Goertzel magnitude over the buffer (normalised to a sine's amplitude)
  10982. const auto w = 2.0 * juce::MathConstants<double>::pi * hz / 48000.0;
  10983. double s1 = 0.0, s2 = 0.0;
  10984. for (const auto v : x)
  10985. {
  10986. const auto s0 = v + 2.0 * std::cos (w) * s1 - s2;
  10987. s2 = s1;
  10988. s1 = s0;
  10989. }
  10990. 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());
  10991. };
  10992. if (! vst2)
  10993. ok = false;
  10994. else
  10995. for (const auto& c : cases)
  10996. {
  10997. lynx::AudioEngine engine (false);
  10998. engine.getPluginHost().addPluginFile (juce::File (pluginPath));
  10999. auto song = lynx::Song::makeDefault();
  11000. auto& channel = song.channels[0];
  11001. channel.instrument = lynx::InstrumentKind::plugin;
  11002. channel.plugin = {};
  11003. channel.plugin.id = vst2->createIdentifierString().toStdString();
  11004. channel.plugin.name = vst2->name.toStdString();
  11005. channel.plugin.outputs = c.routes;
  11006. // (FL's "Process inactive inputs and outputs" plays an inactive output: off but for the case named so)
  11007. channel.plugin.processInactive = juce::String (c.name).contains ("Process inactive");
  11008. channel.mixerTrack = 1;
  11009. if (c.volume >= 0.0f)
  11010. channel.volume = c.volume;
  11011. for (std::size_t k = 1; k < song.channels.size(); ++k)
  11012. song.channels[k].muted = true;
  11013. if (song.mixer.size() < 4)
  11014. song.mixer.resize (4);
  11015. song.mixer[1].muted = c.muteInsert1;
  11016. song.patterns[0].notes.clear();
  11017. for (const auto key : { 36, 37 })
  11018. {
  11019. lynx::Note note;
  11020. note.start = 0;
  11021. note.length = lynx::ppq;
  11022. note.channel = 0;
  11023. note.key = key;
  11024. note.velocity = 1.0f;
  11025. song.patterns[0].notes.push_back (note);
  11026. }
  11027. engine.setSong (song);
  11028. std::vector<float> master;
  11029. lynx::AudioEngine::RenderOptions options;
  11030. options.seconds = 0.25;
  11031. options.sampleRate = 48000.0;
  11032. options.capture = [&master] (const float* l, const float*, int n) { master.insert (master.end(), l, l + n); };
  11033. engine.renderOffline (options);
  11034. const auto kick = tone (master, 110.0), snare = tone (master, 220.0);
  11035. const auto pass = (kick > 0.01) == c.kick && (snare > 0.01) == c.snare;
  11036. report << c.name << ": kick_110Hz=" << juce::String (kick, 4) << " snare_220Hz=" << juce::String (snare, 4) << " expected kick="
  11037. << (int) c.kick << " snare=" << (int) c.snare << (pass ? " OK" : " FAILED") << "\n";
  11038. ok = ok && pass;
  11039. if (auto instrument = std::dynamic_pointer_cast<lynx::PluginInstrument> (engine.getChannelInstrument (0)))
  11040. if (&c == &cases[0])
  11041. {
  11042. report << "outputs=" << (int) instrument->outputs().size();
  11043. for (const auto& o : instrument->outputs())
  11044. report << " [" << o.name << " ch" << o.channel << "x" << o.channels << "]";
  11045. report << "\n";
  11046. ok = ok && instrument->outputs().size() == 8 && instrument->outputs()[1].name == "Snare";
  11047. }
  11048. }
  11049. // round 189j: "LYNX Test SC.dll" next to it (tools/testplugin/lynx_test_sc_vst2.c) as an effect on insert 1
  11050. const auto sc = juce::File (pluginPath).getSiblingFile ("LYNX Test SC.dll");
  11051. if (sc.existsAsFile())
  11052. ok = runEffectConnectionsTest (sc, report) && ok;
  11053. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  11054. juce::File (reportPath).replaceWithText (report);
  11055. setApplicationReturnValue (ok ? 0 : 1);
  11056. quit();
  11057. }
  11058. // Round 189j: a hosted effect's Processing › Connections against FL 2026's own renders of the same projects
  11059. // [EXEC fxconn189j: FL /R renders of LYNX's .flp exports, docs/analise/REA_rodada189j.md]. Insert 1: a 440 Hz
  11060. // sampler and "LYNX Test SC" (output 1 = input 1, output 2 = input 2); inserts 2 (1000 Hz) and 3 (1500 Hz) routed
  11061. // to insert 1 at level 0 only; insert 4 a 2500 Hz reference on the Master; insert 1 routed to the Master and at
  11062. // level 0 to inserts 5 (panned left) and 6 (right). Each tone's level per side, in dB from the reference's, must be
  11063. // FL's within 0.5 dB (absent: 50 dB under it).
  11064. bool runEffectConnectionsTest (const juce::File& scFile, juce::String& report)
  11065. {
  11066. lynx::AudioEngine scanner (false);
  11067. scanner.getPluginHost().addPluginFile (scFile);
  11068. std::optional<juce::PluginDescription> sc;
  11069. for (const auto& type : scanner.getPluginHost().getKnownPlugins().getTypes())
  11070. if (type.pluginFormatName == "VST" && juce::File (type.fileOrIdentifier) == scFile)
  11071. sc = type;
  11072. report << "effect_plugin=" << (sc ? sc->name : juce::String ("not found")) << "\n";
  11073. if (! sc)
  11074. return false;
  11075. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-fxconn189j");
  11076. dir.createDirectory();
  11077. const double tones[] = { 440.0, 1000.0, 1500.0, 2500.0 };
  11078. for (const auto hz : tones)
  11079. {
  11080. const auto wav = dir.getChildFile ("sine" + juce::String ((int) hz) + ".wav");
  11081. if (wav.existsAsFile())
  11082. continue;
  11083. juce::AudioBuffer<float> sine (1, 44100 * 3);
  11084. for (int i = 0; i < sine.getNumSamples(); ++i)
  11085. sine.setSample (0, i, 0.25f * (float) std::sin (2.0 * juce::MathConstants<double>::pi * hz * i / 44100.0));
  11086. juce::WavAudioFormat format;
  11087. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  11088. if (auto* w = format.createWriterFor (out.get(), 44100.0, 1, 16, {}, 0))
  11089. {
  11090. out.release();
  11091. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  11092. writer->writeFromAudioSampleBuffer (sine, 0, sine.getNumSamples());
  11093. }
  11094. }
  11095. using Route = lynx::PluginOutputRoute;
  11096. constexpr float none = -999.0f;
  11097. struct Case
  11098. {
  11099. const char* name;
  11100. std::vector<Route> inputs, outputs;
  11101. int tweak; // 1 no Master route, 2 insert 1 fader at 0.4, 3 Process inactive off, 4 Master route level 0, 5 route
  11102. // to 7 too, 6 insert 2 fader at 0.4, 7 insert 2 muted, 8 insert 2 panned left
  11103. float level[3][2]; // 440 / 1000 / 1500 Hz, left / right: dB from the reference, FL's
  11104. };
  11105. const Route d { 0, 1 };
  11106. const Case cases[] = {
  11107. { "e00 FL defaults", { d, d }, {}, 0, { { 6.1f, 6.1f }, { none, none }, { none, none } } },
  11108. { "e01 input 1 at 1", { { 1, 1 } }, {}, 0, { { 0, 0 }, { 0, 0 }, { none, none } } },
  11109. { "e02 input 1 at 2", { { 2, 1 } }, {}, 0, { { 0, 0 }, { none, none }, { 0, 0 } } },
  11110. { "e03 input 2 at 1", { d, { 1, 1 } }, {}, 0, { { 0, 0 }, { 0, 0 }, { none, none } } },
  11111. { "e04 output 2 at 1 (Master)", { d, { 1, 1 } }, { d, { 1, 1 } }, 0, { { 0, 0 }, { 0, 0 }, { none, none } } },
  11112. { "e05 output 2 at 2 (insert 5)", { d, { 1, 1 } }, { d, { 2, 1 } }, 0, { { 0, 0 }, { 3.0f, none }, { none, none } } },
  11113. { "e06 output 1 at 1", {}, { { 1, 1 } }, 0, { { 6.1f, 6.1f }, { none, none }, { none, none } } },
  11114. { "e07 output 2 at 5 (past the list)", { d, { 1, 1 } }, { d, { 5, 1 } }, 0, { { 0, 0 }, { none, 3.0f }, { none, none } } },
  11115. { "e08 inputs 1 and 2 at 1", { { 1, 1 }, { 1, 1 } }, {}, 0, { { none, none }, { 6.1f, 6.1f }, { none, none } } },
  11116. { "e09 output 2 inactive", { d, { 1, 1 } }, { d, { 0, 0 } }, 0, { { 0, 0 }, { 0, 0 }, { none, none } } },
  11117. { "e10 input 1 at 5 (past the list)", { { 5, 1 } }, {}, 0, { { 6.1f, 6.1f }, { none, none }, { none, none } } },
  11118. { "e11 output 2 at 3 (insert 6)", { d, { 1, 1 } }, { d, { 3, 1 } }, 0, { { 0, 0 }, { none, 3.0f }, { none, none } } },
  11119. { "e13 no Master route, output 2 at 1", { d, { 1, 1 } }, { d, { 1, 1 } }, 1, { { none, none }, { 3.0f, none }, { none, none } } },
  11120. { "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 } } },
  11121. { "e15 input 2 inactive", { d, { 1, 0 } }, { d, d }, 3, { { 0, 0 }, { none, none }, { none, none } } },
  11122. { "e16 output 2 inactive", { d, { 1, 1 } }, { d, { 0, 0 } }, 3, { { 0, 0 }, { none, none }, { none, none } } },
  11123. { "e18 route to 7 too, output 2 at 3", { d, { 1, 1 } }, { d, { 3, 1 } }, 5, { { 0, 0 }, { none, 3.0f }, { none, none } } },
  11124. { "e19 Master route at 0, output 2 at 1", { d, { 1, 1 } }, { d, { 1, 1 } }, 4, { { none, none }, { 0, 0 }, { none, none } } },
  11125. { "e22 input 1 at 1 inactive", { { 1, 0 } }, {}, 3, { { 0, 0 }, { none, none }, { none, none } } },
  11126. { "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 } } },
  11127. { "e24 input 1 at 1, insert 2 fader 0.4", { { 1, 1 } }, {}, 6, { { 0, 0 }, { -12.7f, -12.7f }, { none, none } } },
  11128. { "e25 input 1 at 1, insert 2 muted", { { 1, 1 } }, {}, 7, { { 0, 0 }, { none, none }, { none, none } } },
  11129. { "e26 input 1 at 1, insert 2 panned left", { { 1, 1 } }, {}, 8, { { 0, 0 }, { 3.0f, none }, { none, none } } },
  11130. };
  11131. auto goertzel = [] (const std::vector<float>& x, double hz) {
  11132. const auto w = 2.0 * juce::MathConstants<double>::pi * hz / 44100.0;
  11133. double s1 = 0.0, s2 = 0.0;
  11134. for (const auto v : x)
  11135. {
  11136. const auto s0 = v + 2.0 * std::cos (w) * s1 - s2;
  11137. s2 = s1;
  11138. s1 = s0;
  11139. }
  11140. 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());
  11141. return a > 1e-7 ? 20.0 * std::log10 (a) : -140.0;
  11142. };
  11143. auto ok = true;
  11144. for (const auto& c : cases)
  11145. {
  11146. lynx::AudioEngine engine (false);
  11147. engine.getPluginHost().addPluginFile (scFile);
  11148. auto song = lynx::Song::makeDefault();
  11149. song.bpm = 120.0;
  11150. song.channels.clear();
  11151. song.automations.clear();
  11152. for (auto& p : song.patterns)
  11153. p.notes.clear();
  11154. for (int k = 0; k < 4; ++k)
  11155. {
  11156. lynx::ChannelDef ch;
  11157. ch.name = "S" + std::to_string ((int) tones[k]);
  11158. ch.instrument = lynx::InstrumentKind::sampler;
  11159. ch.samplePath = dir.getChildFile ("sine" + juce::String ((int) tones[k]) + ".wav").getFullPathName().toStdString();
  11160. ch.mixerTrack = k + 1;
  11161. song.channels.push_back (ch);
  11162. lynx::Note note;
  11163. note.start = 0;
  11164. note.length = 8 * lynx::ppq;
  11165. note.channel = k;
  11166. note.key = 60;
  11167. note.velocity = 0.78f;
  11168. song.patterns[0].notes.push_back (note);
  11169. }
  11170. if (song.mixer.size() < 10)
  11171. song.mixer.resize (10);
  11172. for (auto& t : song.mixer)
  11173. {
  11174. t.effects.clear();
  11175. t.sends.clear();
  11176. t.toMaster = true;
  11177. }
  11178. lynx::EffectSlot fx;
  11179. fx.kind = lynx::EffectKind::plugin;
  11180. fx.plugin.id = sc->createIdentifierString().toStdString();
  11181. fx.plugin.name = sc->name.toStdString();
  11182. fx.plugin.inputs = c.inputs;
  11183. fx.plugin.outputs = c.outputs;
  11184. fx.plugin.processInactive = c.tweak != 3;
  11185. auto& one = song.mixer[1];
  11186. one.effects.push_back (fx);
  11187. one.sends = { { 5, 0.0f }, { 6, 0.0f } };
  11188. for (const int t : { 2, 3 })
  11189. {
  11190. song.mixer[(std::size_t) t].toMaster = false;
  11191. song.mixer[(std::size_t) t].sends = { { 1, 0.0f } };
  11192. }
  11193. song.mixer[5].pan = -1.0f;
  11194. song.mixer[6].pan = 1.0f;
  11195. one.toMaster = c.tweak != 1;
  11196. if (c.tweak == 2)
  11197. one.volume = 0.4f;
  11198. if (c.tweak == 4)
  11199. one.masterLevel = 0.0f;
  11200. if (c.tweak == 6)
  11201. song.mixer[2].volume = 0.4f;
  11202. song.mixer[2].muted = c.tweak == 7;
  11203. song.mixer[2].pan = c.tweak == 8 ? -1.0f : 0.0f;
  11204. if (c.tweak == 5)
  11205. {
  11206. one.sends = { { 7, 0.0f }, { 5, 0.0f }, { 6, 0.0f } };
  11207. song.mixer[7].pan = 0.5f;
  11208. }
  11209. // (input 2's index sets the slot's side input source, as the Connections page and the import do)
  11210. if (c.inputs.size() > 1 && c.inputs[1].offset > 0)
  11211. one.effects[0].sidechain = lynx::mixerops::sidechainIndexSource (song, 1, c.inputs[1].offset);
  11212. engine.setSong (song);
  11213. std::vector<float> left, right;
  11214. lynx::AudioEngine::RenderOptions options;
  11215. options.seconds = 1.2;
  11216. options.sampleRate = 44100.0;
  11217. options.capture = [&] (const float* l, const float* r, int n) {
  11218. left.insert (left.end(), l, l + n);
  11219. right.insert (right.end(), r, r + n);
  11220. };
  11221. engine.renderOffline (options);
  11222. const auto from = (std::size_t) 22050, to = (std::size_t) 44100;
  11223. if (right.size() < to)
  11224. {
  11225. report << c.name << ": rendered " << (int) right.size() << " samples FAILED\n";
  11226. ok = false;
  11227. continue;
  11228. }
  11229. const std::vector<float> l (left.begin() + (std::ptrdiff_t) from, left.begin() + (std::ptrdiff_t) to);
  11230. const std::vector<float> r (right.begin() + (std::ptrdiff_t) from, right.begin() + (std::ptrdiff_t) to);
  11231. const auto ref = 0.5 * (goertzel (l, 2500.0) + goertzel (r, 2500.0));
  11232. auto pass = ref > -60.0;
  11233. report << c.name << ": ref=" << juce::String (ref, 1);
  11234. for (int k = 0; k < 3; ++k)
  11235. for (int side = 0; side < 2; ++side)
  11236. {
  11237. const auto got = goertzel (side == 0 ? l : r, tones[k]) - ref;
  11238. const auto want = c.level[k][side];
  11239. const auto good = want == none ? got < -50.0 : std::abs (got - want) < 0.5;
  11240. pass = pass && good;
  11241. report << " " << (int) tones[k] << (side == 0 ? "L" : "R") << "=" << (got < -50.0 ? juce::String ("-") : juce::String (got, 1))
  11242. << (good ? "" : "(FL " + (want == none ? juce::String ("-") : juce::String (want, 1)) + ")");
  11243. }
  11244. report << (pass ? " OK" : " FAILED") << "\n";
  11245. ok = ok && pass;
  11246. }
  11247. return ok;
  11248. }
  11249. // LYNX.exe --wrappertest plugin.vst3 report.txt: builds a VST3 state the way FL's Fruity
  11250. // Wrapper stores it (REA_rodada5 §3.2), runs it through the import (adoptFlPlugins) and checks
  11251. // that the plugin comes back with the changed parameter.
  11252. void runWrapperTest (const juce::String& pluginPath, const juce::String& reportPath)
  11253. {
  11254. juce::String report;
  11255. bool ok = false;
  11256. {
  11257. lynx::AudioEngine offline (false);
  11258. auto& host = offline.getPluginHost();
  11259. host.addPluginFile (juce::File (pluginPath));
  11260. const juce::PluginDescription* vst3 = nullptr;
  11261. const auto types = host.getKnownPlugins().getTypes(); // copy: the pointer below points into it
  11262. for (const auto& type : types)
  11263. if (type.pluginFormatName == "VST3" && type.isInstrument)
  11264. vst3 = &type;
  11265. if (vst3 != nullptr)
  11266. {
  11267. juce::String error;
  11268. auto plugin = host.getFormats().createPluginInstance (*vst3, 48000.0, 512, error);
  11269. auto* parameter = plugin != nullptr && ! plugin->getParameters().isEmpty() ? plugin->getParameters()[0] : nullptr;
  11270. if (parameter != nullptr)
  11271. {
  11272. const auto target = parameter->getValue() > 0.5f ? 0.13f : 0.87f;
  11273. parameter->setValueNotifyingHost (target);
  11274. juce::MemoryBlock juceState;
  11275. plugin->getStateInformation (juceState);
  11276. report << "parameter=" << parameter->getName (64) << " target=" << target << "\n";
  11277. // JUCE state -> FL container: u32 1 + records 1 (flags), 3 (component), 2 (controller)
  11278. std::vector<std::uint8_t> flState;
  11279. auto put32 = [&] (std::uint32_t v) { for (int b = 0; b < 4; ++b) flState.push_back ((std::uint8_t) (v >> (8 * b))); };
  11280. auto record = [&] (std::uint32_t id, const juce::MemoryBlock& data) {
  11281. put32 (id);
  11282. put32 ((std::uint32_t) data.getSize());
  11283. put32 (0);
  11284. flState.insert (flState.end(), (const std::uint8_t*) data.getData(), (const std::uint8_t*) data.getData() + data.getSize());
  11285. };
  11286. put32 (1);
  11287. record (1, juce::MemoryBlock (64, true));
  11288. // record 4 (REA_rodada22 §2.3): slots 0/1 hold the ParamIDs of parameters 2 and 0, so FL's
  11289. // automations k = 0, 1, 2 mean positions 2, 0 and 1 (the first parameter without a slot)
  11290. juce::MemoryBlock slots;
  11291. const auto paramId = [&] (int i) {
  11292. const auto* hosted = dynamic_cast<const juce::HostedAudioProcessorParameter*> (plugin->getParameters()[i]);
  11293. return hosted != nullptr ? (std::uint32_t) hosted->getParameterID().getLargeIntValue() : 0u;
  11294. };
  11295. const bool reorder = plugin->getParameters().size() >= 3;
  11296. if (reorder)
  11297. {
  11298. for (auto v : { 2u, paramId (2), paramId (0) })
  11299. slots.append (&v, 4);
  11300. report << "slot_param_ids=" << (juce::int64) paramId (2) << "," << (juce::int64) paramId (0) << "\n";
  11301. }
  11302. if (auto xml = juce::AudioProcessor::getXmlFromBinary (juceState.getData(), (int) juceState.getSize()))
  11303. for (auto [tag, id] : { std::pair { "IComponent", 3u }, { "IEditController", 2u } })
  11304. if (auto* child = xml->getChildByName (tag))
  11305. {
  11306. juce::MemoryBlock data;
  11307. data.fromBase64Encoding (child->getAllSubText());
  11308. record (id, data);
  11309. report << tag << "_bytes=" << (int) data.getSize() << "\n";
  11310. }
  11311. if (reorder)
  11312. record (4, slots);
  11313. plugin.reset();
  11314. auto song = lynx::Song::makeDefault();
  11315. auto& f = song.channels[4].plugin.foreign;
  11316. f.format = lynx::ForeignPlugin::Format::vst3;
  11317. f.name = vst3->name.toStdString(); // no class ID: find it by name (fallback)
  11318. f.state = flState;
  11319. {
  11320. std::vector<std::uint8_t> comp, ctrl;
  11321. report << "split=" << (int) lynx::splitFlVst3State (flState, comp, ctrl) << " component=" << (int) comp.size()
  11322. << " saved_slots=" << (int) lynx::flVst3ParamSlots (flState).size() << "\n";
  11323. }
  11324. for (int k = 0; k < 3; ++k)
  11325. {
  11326. lynx::Automation a;
  11327. a.target = { lynx::AutomationTargetKind::channelParam, 4, 0, k };
  11328. song.automations.push_back (a);
  11329. }
  11330. const auto adopted = host.adoptFlPlugins (song);
  11331. report << "adopted=" << adopted << "\n";
  11332. juce::String mapped;
  11333. for (const auto& a : song.automations)
  11334. if (a.target.kind == lynx::AutomationTargetKind::channelParam && a.target.index == 4)
  11335. mapped << (mapped.isEmpty() ? "" : ",") << a.target.param;
  11336. report << "slot_positions=" << mapped << "\n";
  11337. const auto slotsOk = ! reorder || mapped == "2,0,1";
  11338. offline.setSong (song);
  11339. if (auto* loaded = dynamic_cast<lynx::PluginInstrument*> (offline.getChannelInstrument (4).get()))
  11340. {
  11341. const auto value = loaded->getInstance().getParameters()[0]->getValue();
  11342. report << "restored_value=" << value << "\n";
  11343. ok = adopted == 1 && std::abs (value - target) < 0.02f && slotsOk;
  11344. }
  11345. }
  11346. }
  11347. }
  11348. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  11349. juce::File (reportPath).replaceWithText (report);
  11350. setApplicationReturnValue (ok ? 0 : 1);
  11351. quit();
  11352. }
  11353. void runDemoSongs (const juce::String& folderPath)
  11354. {
  11355. const juce::File folder (folderPath);
  11356. folder.createDirectory();
  11357. bool ok = true;
  11358. for (int d = 1; d < lynx::demos::count; ++d)
  11359. {
  11360. juce::String error;
  11361. ok = lynx::ProjectFile::save (lynx::demos::make (d), folder.getChildFile (lynx::demos::fileName (d)), error) && ok;
  11362. }
  11363. setApplicationReturnValue (ok ? 0 : 1);
  11364. quit();
  11365. }
  11366. // --perfgen (round perfgate190id): each synthetic project of the performance gate written as <folder>/<name>.lynx, its
  11367. // audio as 16-bit WAVs in <folder>/<name>/ (written once: the same code makes the same audio). The report gives, per
  11368. // project, the .lynx size, the time to write it (ProjectFile::save, which reads it back) and to read it
  11369. // (ProjectFile::load), the medians of 5, and a hash of its text.
  11370. void runPerfGen (const juce::String& folderPath, const juce::String& reportPath, const juce::String& only)
  11371. {
  11372. const juce::File folder (folderPath);
  11373. folder.createDirectory();
  11374. const auto wanted = juce::StringArray::fromTokens (only, ",", "");
  11375. juce::String report;
  11376. bool ok = true;
  11377. auto median = [] (std::vector<double> v) {
  11378. std::sort (v.begin(), v.end());
  11379. return v[v.size() / 2];
  11380. };
  11381. for (const auto& name : lynx::perfprojects::names())
  11382. {
  11383. if (! wanted.isEmpty() && ! wanted.contains (juce::String (name)))
  11384. continue;
  11385. lynx::Song song;
  11386. lynx::perfprojects::Samples samples;
  11387. const auto audioFolder = folder.getChildFile (juce::String (name));
  11388. lynx::perfprojects::make (name, song, samples, audioFolder.getFullPathName().toStdString());
  11389. for (const auto& [path, data] : samples)
  11390. {
  11391. const juce::File wav { juce::String (path) };
  11392. if (wav.existsAsFile())
  11393. continue;
  11394. wav.getParentDirectory().createDirectory();
  11395. const auto frames = (int) data->frames();
  11396. juce::AudioBuffer<float> audio (2, frames);
  11397. audio.copyFrom (0, 0, data->leftData(), frames);
  11398. audio.copyFrom (1, 0, data->rightData(), frames);
  11399. juce::WavAudioFormat format;
  11400. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  11401. if (auto* w = out != nullptr ? format.createWriterFor (out.get(), data->sampleRate, 2, 16, {}, 0) : nullptr)
  11402. {
  11403. out.release();
  11404. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  11405. ok = writer->writeFromAudioSampleBuffer (audio, 0, frames) && ok;
  11406. }
  11407. else
  11408. ok = false;
  11409. }
  11410. const auto file = folder.getChildFile (juce::String (name) + ".lynx");
  11411. std::vector<double> saveMs, loadMs;
  11412. juce::String error;
  11413. bool loadedOk = true;
  11414. for (int rep = 0; rep < 5; ++rep)
  11415. {
  11416. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  11417. ok = lynx::ProjectFile::save (song, file, error) && ok;
  11418. const auto t1 = juce::Time::getMillisecondCounterHiRes();
  11419. const auto loaded = lynx::ProjectFile::load (file, error);
  11420. const auto t2 = juce::Time::getMillisecondCounterHiRes();
  11421. loadedOk = loadedOk && loaded.has_value() && loaded->channels.size() == song.channels.size()
  11422. && loaded->playlist.size() == song.playlist.size() && loaded->automations.size() == song.automations.size();
  11423. saveMs.push_back (t1 - t0);
  11424. loadMs.push_back (t2 - t1);
  11425. }
  11426. ok = ok && loadedOk;
  11427. const auto text = file.loadFileAsString();
  11428. std::uint64_t h = 1469598103934665603ull;
  11429. for (auto* c = text.toRawUTF8(); *c != 0; ++c)
  11430. h = (h ^ (std::uint8_t) *c) * 1099511628211ull;
  11431. report << name << ": channels=" << (int) song.channels.size() << " inserts=" << (int) song.mixer.size() - 1
  11432. << " clips=" << (int) song.playlist.size() << " automations=" << (int) song.automations.size()
  11433. << " wavs=" << (int) samples.size() << " lynx_kb=" << juce::String ((double) file.getSize() / 1024.0, 1)
  11434. << " save_ms=" << juce::String (median (saveMs), 2) << " load_ms=" << juce::String (median (loadMs), 2)
  11435. << " roundtrip=" << (loadedOk ? "OK" : "FAILED") << " text_hash=" << juce::String::toHexString ((juce::int64) h)
  11436. << (error.isNotEmpty() ? " error=" + error : juce::String()) << "\n";
  11437. }
  11438. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  11439. if (reportPath.isNotEmpty())
  11440. juce::File (reportPath).replaceWithText (report);
  11441. else
  11442. std::fputs (report.toRawUTF8(), stdout);
  11443. setApplicationReturnValue (ok ? 0 : 1);
  11444. quit();
  11445. }
  11446. void runShowcase (const juce::String& outputPath, int currentPattern)
  11447. {
  11448. const auto song = lynx::makeShowcaseSong (currentPattern);
  11449. juce::String error;
  11450. const auto ok = lynx::ProjectFile::save (song, juce::File (outputPath), error);
  11451. setApplicationReturnValue (ok ? 0 : 1);
  11452. quit();
  11453. }
  11454. // LYNX.exe --sandboxtest plugin.vst3 report.txt: opens the instrument in a separate process, plays a
  11455. // note, changes a parameter, checks the state (back in an in-process plugin) and makes the child hang
  11456. // to check that LYNX keeps going (silence, without waiting longer than the timeout).
  11457. // --sandboxtest: plays an instrument (a note) or an effect (a 440 Hz tone through it); render() adds into l / r
  11458. struct TestVoice
  11459. {
  11460. explicit TestVoice (std::unique_ptr<juce::AudioPluginInstance> p)
  11461. {
  11462. if (p->acceptsMidi() && p->getTotalNumInputChannels() == 0)
  11463. instrument = std::make_unique<lynx::PluginInstrument> (std::move (p), 512);
  11464. else
  11465. effect = std::move (p);
  11466. }
  11467. void noteOn()
  11468. {
  11469. if (instrument != nullptr)
  11470. instrument->noteOn (60, 0.9f);
  11471. }
  11472. void render (float* l, float* r, int n, float gainLeft, float gainRight)
  11473. {
  11474. if (instrument != nullptr)
  11475. {
  11476. instrument->render (l, r, n, gainLeft, gainRight);
  11477. return;
  11478. }
  11479. const auto channels = juce::jmax (2, effect->getTotalNumInputChannels(), effect->getTotalNumOutputChannels());
  11480. juce::AudioBuffer<float> block (channels, 512);
  11481. juce::MidiBuffer midi;
  11482. for (int done = 0; done < n; done += 512)
  11483. {
  11484. const auto k = juce::jmin (512, n - done);
  11485. block.setSize (channels, k, false, false, true);
  11486. for (int i = 0; i < k; ++i)
  11487. {
  11488. const auto v = 0.25f * (float) std::sin (phase);
  11489. phase += 2.0 * juce::MathConstants<double>::pi * 440.0 / 48000.0;
  11490. for (int c = 0; c < channels; ++c)
  11491. block.setSample (c, i, v);
  11492. }
  11493. effect->processBlock (block, midi);
  11494. for (int i = 0; i < k; ++i)
  11495. {
  11496. l[done + i] += gainLeft * block.getSample (0, i);
  11497. r[done + i] += gainRight * block.getSample (1, i);
  11498. }
  11499. }
  11500. }
  11501. void release()
  11502. {
  11503. instrument.reset();
  11504. effect.reset();
  11505. }
  11506. std::unique_ptr<lynx::PluginInstrument> instrument;
  11507. std::unique_ptr<juce::AudioPluginInstance> effect;
  11508. double phase = 0.0;
  11509. };
  11510. void runSandboxTest (const juce::String& pluginPath, const juce::String& reportPath)
  11511. {
  11512. juce::String report;
  11513. bool ok = false;
  11514. lynx::setPluginSandboxAlerts (false);
  11515. const juce::File log (reportPath + ".log");
  11516. auto step = [&] (const char* what) { log.appendText (juce::String (what) + "\n"); };
  11517. log.deleteFile();
  11518. {
  11519. lynx::PluginHost host (false);
  11520. host.addPluginFile (juce::File (pluginPath));
  11521. const auto types = host.getKnownPlugins().getTypes(); // getTypes() returns a copy
  11522. // the file's instrument, else its first effect (round 161: effects too, e.g. a Windows effect through yabridge)
  11523. const juce::PluginDescription* instrument = nullptr;
  11524. for (const auto& type : types)
  11525. if (type.isInstrument)
  11526. instrument = &type;
  11527. for (const auto& type : types)
  11528. if (instrument == nullptr && ! type.isInstrument)
  11529. instrument = &type;
  11530. step ("host");
  11531. juce::String error;
  11532. auto remote = instrument != nullptr ? lynx::createSandboxedPlugin (*instrument, 48000.0, 512, {}, error) : nullptr;
  11533. report << "opened=" << (remote != nullptr ? 1 : 0) << " error=" << error << "\n";
  11534. step ("created");
  11535. if (remote != nullptr)
  11536. {
  11537. auto& proxy = *remote;
  11538. TestVoice voice (std::move (remote));
  11539. std::vector<float> l (48000), r (48000);
  11540. auto peakOf = [&] {
  11541. float peak = 0.0f;
  11542. for (std::size_t k = 0; k < l.size(); ++k)
  11543. peak = std::max ({ peak, std::abs (l[k]), std::abs (r[k]) });
  11544. return peak;
  11545. };
  11546. const auto start = juce::Time::getMillisecondCounterHiRes();
  11547. voice.noteOn();
  11548. voice.render (l.data(), r.data(), 48000, 1.0f, 1.0f);
  11549. const auto renderMs = juce::Time::getMillisecondCounterHiRes() - start;
  11550. const auto peak = peakOf();
  11551. step ("played");
  11552. if (juce::JUCEApplication::getCommandLineParameters().contains ("--expect-crash"))
  11553. {
  11554. // a plugin that crashes while playing (round 161 test plugin): LYNX notices, mutes it and keeps running
  11555. const auto dead = lynx::isSandboxedPluginDead (proxy);
  11556. std::fill (l.begin(), l.end(), 0.0f);
  11557. std::fill (r.begin(), r.end(), 0.0f);
  11558. voice.render (l.data(), r.data(), 4096, 1.0f, 1.0f);
  11559. report << "peak=" << peak << " render_1s_ms=" << renderMs << " dead=" << (dead ? 1 : 0) << " peak_after=" << peakOf() << "\n";
  11560. ok = dead && peak > 1e-4f && renderMs < 2000.0 && peakOf() == 0.0f;
  11561. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  11562. juce::File (reportPath).replaceWithText (report);
  11563. setApplicationReturnValue (ok ? 0 : 1);
  11564. quit();
  11565. return;
  11566. }
  11567. report << "plugin=" << proxy.getName() << (instrument->isInstrument ? " (instrument)" : " (effect)") << " parameters="
  11568. << proxy.getParameters().size() << " peak=" << peak << " render_1s_ms=" << renderMs << "\n";
  11569. if (juce::JUCEApplication::getCommandLineParameters().contains ("--editor") && proxy.hasEditor())
  11570. {
  11571. // the plugin's own window, opened by the child process (4 s on screen); the child must stay responsive
  11572. std::unique_ptr<juce::AudioProcessorEditor> editor (proxy.createEditorIfNeeded());
  11573. juce::Thread::sleep (4000);
  11574. juce::MemoryBlock state;
  11575. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  11576. proxy.getStateInformation (state);
  11577. report << "editor_shown=1 state_with_editor_ms=" << (juce::Time::getMillisecondCounterHiRes() - t0) << " dead=" << (lynx::isSandboxedPluginDead (proxy) ? 1 : 0) << "\n";
  11578. editor.reset();
  11579. }
  11580. // parameter -> state -> in-process plugin
  11581. bool stateOk = false;
  11582. if (! proxy.getParameters().isEmpty())
  11583. {
  11584. auto* p = proxy.getParameters()[0];
  11585. const auto target = p->getValue() > 0.5f ? 0.13f : 0.87f;
  11586. p->setValue (target);
  11587. std::fill (l.begin(), l.end(), 0.0f);
  11588. voice.render (l.data(), r.data(), 512, 1.0f, 1.0f); // carries the change to the child
  11589. juce::MemoryBlock state;
  11590. proxy.getStateInformation (state);
  11591. if (auto local = host.getFormats().createPluginInstance (*instrument, 48000.0, 512, error))
  11592. {
  11593. local->setStateInformation (state.getData(), (int) state.getSize());
  11594. const auto back = local->getParameters()[0]->getValue();
  11595. // the same steps without the sandbox: some plugins quantise the value or keep it out of their state
  11596. auto control = target;
  11597. if (auto a = host.getFormats().createPluginInstance (*instrument, 48000.0, 512, error))
  11598. {
  11599. a->enableAllBuses();
  11600. a->prepareToPlay (48000.0, 512);
  11601. a->getParameters()[0]->setValue (target);
  11602. juce::AudioBuffer<float> block (juce::jmax (2, a->getTotalNumInputChannels(), a->getTotalNumOutputChannels()), 512);
  11603. block.clear();
  11604. juce::MidiBuffer none;
  11605. a->processBlock (block, none);
  11606. juce::MemoryBlock direct;
  11607. a->getStateInformation (direct);
  11608. if (auto b = host.getFormats().createPluginInstance (*instrument, 48000.0, 512, error))
  11609. {
  11610. b->setStateInformation (direct.getData(), (int) direct.getSize());
  11611. control = b->getParameters()[0]->getValue();
  11612. }
  11613. a->releaseResources();
  11614. }
  11615. report << "state_bytes=" << (int) state.getSize() << " target=" << target << " in_process=" << back << " in_process_control=" << control << "\n";
  11616. stateOk = std::abs (back - control) < 0.02f;
  11617. }
  11618. }
  11619. step ("state");
  11620. // hung child: the block returns in ~0.5 s, muted, and the plugin is marked dead
  11621. lynx::hangSandboxedPluginForTest (proxy);
  11622. juce::Thread::sleep (200);
  11623. std::fill (l.begin(), l.end(), 1.0f);
  11624. std::fill (r.begin(), r.end(), 1.0f);
  11625. const auto hangStart = juce::Time::getMillisecondCounterHiRes();
  11626. voice.render (l.data(), r.data(), 4096, 0.0f, 0.0f);
  11627. std::fill (l.begin(), l.end(), 0.0f);
  11628. std::fill (r.begin(), r.end(), 0.0f);
  11629. voice.render (l.data(), r.data(), 4096, 1.0f, 1.0f);
  11630. const auto hangMs = juce::Time::getMillisecondCounterHiRes() - hangStart;
  11631. const auto dead = lynx::isSandboxedPluginDead (proxy);
  11632. const auto hangPeak = peakOf();
  11633. report << "hung_ms=" << hangMs << " dead=" << (dead ? 1 : 0) << " peak_after=" << hangPeak << "\n";
  11634. // crashed child (round 161): a second instance aborts; LYNX notices, mutes it and keeps running
  11635. bool crashOk = false;
  11636. if (auto second = lynx::createSandboxedPlugin (*instrument, 48000.0, 512, {}, error))
  11637. {
  11638. auto& proxy2 = *second;
  11639. TestVoice voice2 (std::move (second));
  11640. voice2.noteOn();
  11641. voice2.render (l.data(), r.data(), 512, 1.0f, 1.0f);
  11642. lynx::crashSandboxedPluginForTest (proxy2);
  11643. const auto crashStart = juce::Time::getMillisecondCounterHiRes();
  11644. while (! lynx::isSandboxedPluginDead (proxy2) && juce::Time::getMillisecondCounterHiRes() - crashStart < 5000.0)
  11645. {
  11646. voice2.render (l.data(), r.data(), 512, 1.0f, 1.0f);
  11647. juce::Thread::sleep (5);
  11648. }
  11649. const auto crashMs = juce::Time::getMillisecondCounterHiRes() - crashStart;
  11650. std::fill (l.begin(), l.end(), 0.0f);
  11651. std::fill (r.begin(), r.end(), 0.0f);
  11652. voice2.render (l.data(), r.data(), 4096, 1.0f, 1.0f);
  11653. const auto crashDead = lynx::isSandboxedPluginDead (proxy2);
  11654. report << "crash_ms=" << crashMs << " crash_dead=" << (crashDead ? 1 : 0) << " crash_peak_after=" << peakOf() << "\n";
  11655. crashOk = crashDead && crashMs < 3000.0;
  11656. // issue #159: freeing the crashed plugin doesn't wait on its pipe (JUCE waited up to 10 s there for
  11657. // the gone child, on the message thread when the rack freed it); its teardown ends on its own
  11658. const auto freeStart = juce::Time::getMillisecondCounterHiRes();
  11659. voice2.release();
  11660. const auto freeMs = juce::Time::getMillisecondCounterHiRes() - freeStart;
  11661. const auto endedAll = lynx::finishSandboxTeardowns (15000);
  11662. report << "crashed_free_ms=" << freeMs << " teardown_done=" << (endedAll ? 1 : 0) << "\n";
  11663. crashOk = crashOk && freeMs < 250.0 && endedAll;
  11664. }
  11665. step ("crash");
  11666. ok = peak > 1e-4f && stateOk && dead && hangMs < 1500.0 && hangPeak == 0.0f && crashOk;
  11667. }
  11668. }
  11669. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  11670. juce::File (reportPath).replaceWithText (report);
  11671. setApplicationReturnValue (ok ? 0 : 1);
  11672. quit();
  11673. }
  11674. // --timertest (round 174f): a view's polling timer follows the view and its parents, and survives a minimised window
  11675. void runTimerTest (const juce::File& report)
  11676. {
  11677. struct Ticks final : juce::Timer
  11678. {
  11679. void timerCallback() override {}
  11680. } timer;
  11681. juce::Component top, parent, view;
  11682. parent.addChildComponent (view);
  11683. top.addChildComponent (parent);
  11684. top.setSize (320, 200);
  11685. lynx::ui::TimerWhileShowing watch (view, timer, 30);
  11686. juce::String text;
  11687. auto failures = 0;
  11688. auto expect = [&] (const char* step, bool running) {
  11689. const auto ok = timer.isTimerRunning() == running;
  11690. failures += ok ? 0 : 1;
  11691. text << step << ": timer " << (timer.isTimerRunning() ? "running" : "stopped") << (ok ? "" : " FAIL") << "\n";
  11692. };
  11693. expect ("never shown", false);
  11694. view.setVisible (true);
  11695. parent.setVisible (true);
  11696. expect ("view and parent visible, not on the desktop", false);
  11697. top.addToDesktop (juce::ComponentPeer::windowHasTitleBar);
  11698. top.setVisible (true);
  11699. expect ("window shown", true);
  11700. parent.setVisible (false);
  11701. expect ("parent hidden", false);
  11702. parent.setVisible (true);
  11703. expect ("parent shown", true);
  11704. view.setVisible (false);
  11705. expect ("view hidden", false);
  11706. top.getPeer()->setMinimised (true);
  11707. view.setVisible (true);
  11708. expect ("view shown while minimised", true);
  11709. top.getPeer()->setMinimised (false);
  11710. expect ("window restored", true);
  11711. top.setVisible (false);
  11712. expect ("window hidden", false);
  11713. top.setVisible (true);
  11714. expect ("window shown again", true);
  11715. top.removeFromDesktop();
  11716. text << "failures: " << failures << "\nresult=" << (failures == 0 ? "OK" : "FAIL") << "\n";
  11717. report.replaceWithText (text);
  11718. setApplicationReturnValue (failures == 0 ? 0 : 1);
  11719. quit();
  11720. }
  11721. // --cachetest (round 174f): PlaylistComponent::cacheSelfTest on the project, the Playlist off screen at 1466 x 930
  11722. void runCacheTest (const juce::File& project, const juce::File& report)
  11723. {
  11724. engine = std::make_unique<lynx::AudioEngine>();
  11725. juce::String error;
  11726. auto ok = false;
  11727. if (project.hasFileExtension ("flp"))
  11728. ok = engine->importFlpFile (project, error);
  11729. else if (auto song = lynx::ProjectFile::load (project, error))
  11730. {
  11731. engine->setSong (std::move (*song));
  11732. ok = true;
  11733. }
  11734. juce::String text = "project: " + project.getFullPathName() + "\n";
  11735. if (ok)
  11736. {
  11737. auto playlist = std::make_unique<lynx::PlaylistComponent> (*engine);
  11738. playlist->setBounds (0, 0, 1466, 930);
  11739. playlist->setVisible (true);
  11740. text << playlist->cacheSelfTest ([] { lynx::ui::WaveformCache::getInstance()->waitUntilIdle (60000); }, report.getParentDirectory());
  11741. }
  11742. else
  11743. text << "result=ERROR " << error << "\n";
  11744. report.replaceWithText (text);
  11745. setApplicationReturnValue (ok && text.contains ("result=OK") ? 0 : 1);
  11746. quit();
  11747. }
  11748. // --picturetest (round 190bm): ui/PictureCheck.h on the Playlist and the Mixer, at a window's usual size, at a 4K
  11749. // screen's, and wider than a GPU bitmap can be (16384 px)
  11750. void runPictureTest (const juce::File& report, const juce::File& project)
  11751. {
  11752. engine = std::make_unique<lynx::AudioEngine>();
  11753. juce::String error, text;
  11754. if (project != juce::File())
  11755. {
  11756. auto ok = false;
  11757. if (project.hasFileExtension ("flp"))
  11758. ok = engine->importFlpFile (project, error);
  11759. else if (auto song = lynx::ProjectFile::load (project, error))
  11760. {
  11761. engine->setSong (std::move (*song));
  11762. ok = true;
  11763. }
  11764. text << "project: " << project.getFullPathName() << (ok ? "" : " (not loaded: " + error + ")") << "\n";
  11765. }
  11766. #if JUCE_WINDOWS
  11767. text << "native image: " << juce::NativeImageType().create (juce::Image::RGB, 8, 8, true)->createType()->getTypeID()
  11768. << " (software = " << juce::SoftwareImageType().getTypeID() << ")\n";
  11769. #endif
  11770. auto failures = 0;
  11771. struct Size
  11772. {
  11773. int width, height;
  11774. std::vector<float> scales;
  11775. };
  11776. const auto folder = report.getParentDirectory();
  11777. 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 } } })
  11778. {
  11779. const auto label = [&size] (const char* name) { return juce::String (name) + " " + juce::String (size.width) + " x " + juce::String (size.height); };
  11780. {
  11781. auto playlist = std::make_unique<lynx::PlaylistComponent> (*engine);
  11782. playlist->setBounds (0, 0, size.width, size.height);
  11783. playlist->setVisible (true);
  11784. {
  11785. juce::Image warm (juce::Image::RGB, 64, 64, true); // (one paint asks for the waveforms, then they are waited for)
  11786. juce::Graphics g (warm);
  11787. playlist->paintEntireComponent (g, true);
  11788. }
  11789. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (60000);
  11790. text << lynx::ui::picturecheck::run (*playlist, label ("Playlist"), size.scales, failures, folder);
  11791. }
  11792. {
  11793. auto mixer = std::make_unique<lynx::MixerComponent> (*engine);
  11794. mixer->setBounds (0, 0, size.width, juce::jmin (size.height, 700));
  11795. mixer->setVisible (true);
  11796. text << lynx::ui::picturecheck::run (*mixer, label ("Mixer"), size.scales, failures, folder);
  11797. }
  11798. }
  11799. text << "failures: " << failures << "\nresult=" << (failures == 0 ? "OK" : "FAIL") << "\n";
  11800. report.replaceWithText (text);
  11801. setApplicationReturnValue (failures == 0 ? 0 : 1);
  11802. quit();
  11803. }
  11804. // --uiperf (round 161): opens the project in the normal window, plays it, and drives the heavy UI cases of round 151
  11805. // through the window's own event path — the default layout, the Mixer maximised (meters while playing, then
  11806. // scrolled), the Playlist maximised (scroll down, scroll sideways, zoom in and out) and the Channel rack scrolled.
  11807. // Every frame is painted right after its event (ComponentPeer::performAnyPendingRepaintsNow) and timed; the report
  11808. // has, per case, the time to show it and the frames' mean / p95 / max, how many took longer than 16 ms, and the
  11809. // process CPU. The same on every OS, so Linux (X11, XWayland) and Windows numbers can be put side by side.
  11810. void runUiPerf (const juce::File& project, const juce::File& report)
  11811. {
  11812. if (const auto profile = juce::SystemStats::getEnvironmentVariable ("LYNX_PROFILE_MAIN", {}); profile.isNotEmpty())
  11813. lynx::crashguard::startMainProfiler (profile.toStdString()); // (stopped in shutdown)
  11814. startupOptions = lynx::StartupOptions::load();
  11815. engine = std::make_unique<lynx::AudioEngine>();
  11816. lynx::videoview::install (*engine); // (Fruity Video Player channels: their sound tracks)
  11817. crashEngine = engine.get();
  11818. createMainWindow();
  11819. mainWindow->reveal();
  11820. // LYNX_UIPERF_SIZE=WxH, LYNX_UIPERF_SCALE=<percent> (round 179a): a large window, a HiDPI desktop's scale
  11821. if (const auto scale = juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_SCALE", {}).getIntValue(); scale > 0)
  11822. juce::Desktop::getInstance().setGlobalScaleFactor ((float) scale / 100.0f);
  11823. if (const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_SIZE", {}), "x", ""); size.size() == 2)
  11824. mainWindow->setBounds (0, 0, size[0].getIntValue(), size[1].getIntValue());
  11825. juce::String error;
  11826. auto ok = false;
  11827. const auto loadStart = juce::Time::getMillisecondCounterHiRes();
  11828. if (project.hasFileExtension ("flp;als;flm;band;blx")) // (round 190gr: a Live set, its Session clips in the grid)
  11829. ok = engine->importFlpFile (project, error);
  11830. else if (auto song = lynx::ProjectFile::load (project, error))
  11831. {
  11832. engine->setSong (std::move (*song));
  11833. ok = true;
  11834. }
  11835. const auto loadMs = juce::Time::getMillisecondCounterHiRes() - loadStart;
  11836. if (! ok)
  11837. {
  11838. report.replaceWithText ("project: " + project.getFullPathName() + "\nresult=ERROR " + error + "\n");
  11839. setApplicationReturnValue (1);
  11840. quit();
  11841. return;
  11842. }
  11843. // LYNX_UIPERF_MUTE=1: the Master fader down (the meters of the inserts still move): a run on a desktop someone uses
  11844. if (juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_MUTE", {}) == "1")
  11845. engine->editSong ([] (lynx::Song& s) { if (! s.mixer.empty()) s.mixer[0].volume = 0.0f; }, false);
  11846. struct Step
  11847. {
  11848. juce::String name;
  11849. std::function<void()> setup;
  11850. std::function<void (int)> action; // per frame; none: the step watches the window for `frames` ms
  11851. int frames;
  11852. std::function<juce::String()> finish = {}; // round 173f: after the step, its own lines for the report
  11853. };
  11854. struct UiPerf final : juce::Timer
  11855. {
  11856. LynxApplication& app;
  11857. juce::File report;
  11858. juce::String text;
  11859. std::vector<Step> steps;
  11860. std::size_t step = 0;
  11861. int frame = -1;
  11862. std::vector<double> times, rendered; // whole frames (event + paint + blit, when this timer paints) / the window's paints
  11863. std::vector<double> frames; // round 173f: the time of every frame the window painted (ui/FrameProbe.h)
  11864. double paintedPixels = 0.0; // round 190ge: the dirty area of those frames, summed (overdraw / repaint storms)
  11865. double setupMs = 0.0, wallStart = 0.0;
  11866. double cpuStart = 0.0; // process CPU seconds (std::clock is wall time on Windows)
  11867. bool threadsWanted = juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_THREADS", {}) == "1";
  11868. std::vector<lynx::ThreadCpu> threadsStart;
  11869. double messageCpuStart = 0.0; // the message thread's CPU seconds
  11870. // round 190jx: LYNX_UIPERF_PEER_PID=<pid> (Linux): another process's CPU over each step too (the X server, which
  11871. // draws the overlay's marks there)
  11872. int peerPid = juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_PEER_PID", "0").getIntValue();
  11873. double peerCpuStart = 0.0;
  11874. static double peerCpuSeconds (int pid)
  11875. {
  11876. if (pid <= 0)
  11877. return 0.0;
  11878. const auto stat = juce::File ("/proc/" + juce::String (pid) + "/stat").loadFileAsString();
  11879. const auto fields = juce::StringArray::fromTokens (stat.fromLastOccurrenceOf (")", false, false), " ", "");
  11880. // (after the name: state is field 0, utime 11, stime 12, in clock ticks)
  11881. return fields.size() > 12 ? (fields[11].getDoubleValue() + fields[12].getDoubleValue()) / 100.0 : 0.0;
  11882. }
  11883. int presentsStart = 0; // round 190jy: Direct2D presents of every LYNX window (Windows)
  11884. double audioLoadSum = 0.0; // the device's CPU use (AudioDeviceManager::getCpuUsage), summed per tick
  11885. int audioLoadTicks = 0;
  11886. // round 190kb: exact CPU cycles, the worker pool's waiting, the callbacks' deadlines, the Direct2D presents
  11887. std::uint64_t cyclesStart = 0;
  11888. lynx::WorkerPool::Stats poolStart;
  11889. lynx::RtStats::Snapshot rtStart; // (presentsStart: 190jy's, above)
  11890. UiPerf (LynxApplication& a, juce::File r) : app (a), report (std::move (r))
  11891. {
  11892. lynx::WorkerPool::nameCurrentThread ("LYNX message thread"); // (round 190kb: the threads' lines)
  11893. }
  11894. juce::ComponentPeer* peer() const { return app.mainWindow != nullptr ? app.mainWindow->getPeer() : nullptr; }
  11895. double paintNow() const
  11896. {
  11897. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  11898. if (auto* p = peer())
  11899. p->performAnyPendingRepaintsNow();
  11900. return juce::Time::getMillisecondCounterHiRes() - t0;
  11901. }
  11902. void timerCallback() override
  11903. {
  11904. if (step >= steps.size())
  11905. {
  11906. stopTimer();
  11907. finish();
  11908. return;
  11909. }
  11910. auto& s = steps[step];
  11911. if (frame < 0)
  11912. {
  11913. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  11914. if (s.setup)
  11915. s.setup();
  11916. paintNow();
  11917. setupMs = juce::Time::getMillisecondCounterHiRes() - t0;
  11918. times.clear();
  11919. rendered.clear();
  11920. frames.clear();
  11921. paintedPixels = 0.0;
  11922. wallStart = juce::Time::getMillisecondCounterHiRes();
  11923. cpuStart = lynx::processCpuSeconds();
  11924. messageCpuStart = lynx::threadCpuSeconds();
  11925. peerCpuStart = peerCpuSeconds (peerPid);
  11926. presentsStart = uiPerfPresents();
  11927. if (threadsWanted) // round 190ih: LYNX_UIPERF_THREADS=1, the CPU of every thread over the step
  11928. threadsStart = lynx::threadCpuList();
  11929. lynx::grossBeatPaintStats (true);
  11930. cyclesStart = lynx::processCpuCycles();
  11931. if (const auto* pool = app.engine->getWorkerPool())
  11932. poolStart = pool->stats();
  11933. rtStart = app.engine->getRtStats().snapshot();
  11934. audioLoadSum = 0.0;
  11935. audioLoadTicks = 0;
  11936. frame = 0;
  11937. return;
  11938. }
  11939. audioLoadSum += app.engine->getDeviceManager().getCpuUsage();
  11940. ++audioLoadTicks;
  11941. if (s.action)
  11942. s.action (frame);
  11943. if (const auto ms = paintNow(); ms > 0.25) // (nothing to paint: not a frame)
  11944. times.push_back (ms);
  11945. ++frame;
  11946. if (s.action ? frame < s.frames : juce::Time::getMillisecondCounterHiRes() - wallStart < (double) s.frames)
  11947. return;
  11948. const auto wall = juce::Time::getMillisecondCounterHiRes() - wallStart;
  11949. const auto cpu = 1000.0 * (lynx::processCpuSeconds() - cpuStart);
  11950. const auto messageCpu = 1000.0 * (lynx::threadCpuSeconds() - messageCpuStart);
  11951. text << s.name << ": show " << juce::String (setupMs, 1) << " ms\n"
  11952. << " painted frames: " << stats (rendered) << "\n"
  11953. << " timed here (event + paint + blit): " << stats (times)
  11954. << "\n window frames (probe): " << lynx::ui::FrameStats::of (frames, wall).describe()
  11955. << ", painted " << juce::String (wall > 0.0 ? paintedPixels / wall / 1000.0 : 0.0, 2) << " Mpx/s"
  11956. << "\n CPU " << juce::String (wall > 0.0 ? 100.0 * cpu / wall : 0.0, 0) << "% (process, " << juce::String (wall / 1000.0, 1) << " s), message thread "
  11957. << juce::String (wall > 0.0 ? 100.0 * messageCpu / wall : 0.0, 1) << "%, audio device "
  11958. << juce::String (audioLoadTicks > 0 ? 100.0 * audioLoadSum / audioLoadTicks : 0.0, 1) << "%\n";
  11959. if (peerPid > 0 && wall > 0.0)
  11960. text << " peer process " << peerPid << " CPU " << juce::String (100.0 * 1000.0 * (peerCpuSeconds (peerPid) - peerCpuStart) / wall, 1) << "%\n";
  11961. // round 190jy: every LYNX window's Direct2D presents (the main window's and each native child's) and how
  11962. // the docked LYNX editors were drawn
  11963. {
  11964. int native = 0, inMain = 0, hidden = 0;
  11965. for (auto* w : lynx::dockedEditorWindows())
  11966. if (w != nullptr)
  11967. (! w->isVisible() ? hidden : lynx::isEditorInMainWindow (*w) ? inMain : native) += 1;
  11968. text << " presents " << juce::String (wall > 0.0 ? 1000.0 * (uiPerfPresents() - presentsStart) / wall : 0.0, 1)
  11969. << "/s; docked editors: " << native << " own windows, " << inMain << " in the main window, " << hidden << " hidden\n";
  11970. }
  11971. const auto cycleRate = lynx::cpuCyclesPerSecond();
  11972. if (cycleRate > 0.0 && wall > 0.0)
  11973. text << " CPU cycles " << juce::String (100.0 * (double) (lynx::processCpuCycles() - cyclesStart) / cycleRate / (wall / 1000.0), 1)
  11974. << "% (process, exact); presents " << juce::String (1000.0 * (uiPerfPresents() - presentsStart) / wall, 1) << "/s\n";
  11975. if (const auto* pool = app.engine->getWorkerPool(); pool != nullptr && wall > 0.0)
  11976. {
  11977. // round 190kb: per second of the step (time in ms/s = tenths of a percent of one core)
  11978. const auto p = pool->stats();
  11979. const auto& a = poolStart;
  11980. const auto perS = [wall] (std::uint64_t v) { return juce::String (1000.0 * (double) v / wall, 0); };
  11981. const auto msS = [wall] (std::uint64_t ns) { return juce::String ((double) ns / 1.0e6 * 1000.0 / wall, 2); };
  11982. text << " pool: rounds " << perS (p.rounds - a.rounds) << "/s; workers work " << msS (p.workNs - a.workNs)
  11983. << " ms/s, spin " << msS (p.spinNs - a.spinNs) << " ms/s (" << perS (p.spins - a.spins) << "/s: found "
  11984. << perS (p.spinFound - a.spinFound) << ", parked " << perS (p.spinParked - a.spinParked) << ", timed out "
  11985. << perS (p.spinTimedOut - a.spinTimedOut) << "), sleeps " << perS (p.sleeps - a.sleeps) << "/s (early "
  11986. << perS (p.earlyWakes - a.earlyWakes) << "); waits " << msS (p.waitNs - a.waitNs) << " ms/s (" << perS (p.waits - a.waits)
  11987. << "/s, yields " << perS (p.waitYields - a.waitYields) << ", sleeps " << perS (p.waitSleeps - a.waitSleeps) << " = " << msS (p.waitSleepNs - a.waitSleepNs) << " ms/s"
  11988. << "); caller wait " << msS (p.callerWaitNs - a.callerWaitNs) << " ms/s (sleeps " << perS (p.callerSleeps - a.callerSleeps) << "/s)\n";
  11989. }
  11990. {
  11991. const auto r = app.engine->getRtStats().snapshot();
  11992. text << " callbacks " << juce::String ((juce::int64) (r.callbacks - rtStart.callbacks)) << ", over the deadline "
  11993. << juce::String ((juce::int64) (r.overBudget - rtStart.overBudget)) << ", 80-100 % " << juce::String ((juce::int64) (r.nearBudget - rtStart.nearBudget))
  11994. << ", late " << juce::String ((juce::int64) (r.lateCalls - rtStart.lateCalls)) << "\n";
  11995. }
  11996. if (threadsWanted && wall > 0.0)
  11997. {
  11998. // (round 190kb: and each thread's exact cycles in brackets, as % of one core; sorted by them where known)
  11999. std::vector<std::pair<double, juce::String>> rows;
  12000. for (const auto& t : lynx::threadCpuList())
  12001. {
  12002. auto before = 0.0;
  12003. std::uint64_t cyclesBefore = 0;
  12004. for (const auto& b : threadsStart)
  12005. if (b.id == t.id)
  12006. before = b.seconds, cyclesBefore = b.cycles;
  12007. const auto used = t.seconds - before;
  12008. const auto exact = cycleRate > 0.0 ? 100.0 * (double) (t.cycles - cyclesBefore) / cycleRate / (wall / 1000.0) : -1.0;
  12009. if (used > 0.0005 || exact > 0.05)
  12010. rows.push_back ({ exact >= 0.0 ? exact : 100.0 * 1000.0 * used / wall,
  12011. juce::String (t.id) + " " + (t.name.empty() ? juce::String ("(unnamed)") : juce::String (t.name)) + " "
  12012. + juce::String (100.0 * 1000.0 * used / wall, 1) + "%" + (exact >= 0.0 ? " [" + juce::String (exact, 1) + "%]" : juce::String()) });
  12013. }
  12014. std::sort (rows.begin(), rows.end(), [] (const auto& a, const auto& b) { return a.first > b.first; });
  12015. text << " threads:";
  12016. for (std::size_t k = 0; k < rows.size() && k < 16; ++k)
  12017. text << " " << rows[k].second << ";";
  12018. text << "\n";
  12019. }
  12020. if (const auto gb = lynx::grossBeatPaintStats (false); gb.isNotEmpty())
  12021. text << " " << gb << "\n";
  12022. if (s.finish)
  12023. text << s.finish();
  12024. juce::File (report).replaceWithText (text);
  12025. ++step;
  12026. frame = -1;
  12027. }
  12028. static juce::String stats (std::vector<double> sorted)
  12029. {
  12030. std::sort (sorted.begin(), sorted.end());
  12031. 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()))]; };
  12032. double sum = 0.0;
  12033. int over = 0;
  12034. for (auto t : sorted)
  12035. {
  12036. sum += t;
  12037. over += t > 16.0 ? 1 : 0;
  12038. }
  12039. return juce::String ((int) sorted.size()) + ", mean " + juce::String (sorted.empty() ? 0.0 : sum / (double) sorted.size(), 1)
  12040. + " ms, p95 " + juce::String (at (0.95), 1) + " ms, max " + juce::String (sorted.empty() ? 0.0 : sorted.back(), 1)
  12041. + " ms, >16 ms " + juce::String (over);
  12042. }
  12043. void finish()
  12044. {
  12045. // the cost of asking where the mouse is (X11: a round trip to the display server)
  12046. const auto q0 = juce::Time::getMillisecondCounterHiRes();
  12047. for (int i = 0; i < 100; ++i)
  12048. juce::ignoreUnused (juce::Desktop::getInstance().getMainMouseSource().getScreenPosition());
  12049. text << "mouse position query: " << juce::String ((juce::Time::getMillisecondCounterHiRes() - q0) / 100.0, 3) << " ms\n";
  12050. app.mainWindow->onFrame = nullptr;
  12051. app.mainWindow->watchFrames ({});
  12052. app.engine->stop();
  12053. text << "result=OK\n";
  12054. report.replaceWithText (text);
  12055. app.setApplicationReturnValue (0);
  12056. app.quit();
  12057. }
  12058. };
  12059. auto* ui = &mainWindow->getContent();
  12060. auto wheelAt = [this] (juce::Component& target, float dx, float dy, juce::ModifierKeys mods) {
  12061. auto* peer = mainWindow->getPeer();
  12062. if (peer == nullptr || ! target.isShowing())
  12063. return;
  12064. juce::ModifierKeys::currentModifiers = mods;
  12065. const auto local = peer->globalToLocal (target.localPointToGlobal (target.getLocalBounds().getCentre()).toFloat());
  12066. juce::MouseWheelDetails wheel { dx, dy, false, false, false };
  12067. peer->handleMouseWheel (juce::MouseInputSource::InputSourceType::mouse, local, juce::Time::currentTimeMillis(), wheel);
  12068. juce::ModifierKeys::currentModifiers = {};
  12069. };
  12070. auto run = std::make_unique<UiPerf> (*this, report);
  12071. mainWindow->onFrame = [r = run.get()] (double ms) { if (r->frame >= 0) r->rendered.push_back (ms); };
  12072. // round 173f: every frame the window paints; a fader drag's moves count as shown when a frame covers the fader
  12073. auto drag = std::make_shared<UiPerfDrag>();
  12074. mainWindow->watchFrames ([r = run.get(), drag] (double now, juce::Rectangle<int> area) {
  12075. if (r->frame >= 0)
  12076. {
  12077. r->frames.push_back (now);
  12078. r->paintedPixels += (double) area.getWidth() * (double) area.getHeight();
  12079. }
  12080. drag->framePainted (now, area);
  12081. });
  12082. run->text << "project: " << project.getFullPathName() << "\n"
  12083. << "LYNX " << getApplicationVersion() << ", " << juce::SystemStats::getOperatingSystemName() << ", "
  12084. << juce::SystemStats::getCpuModel() << ", window " << mainWindow->getWidth() << "x" << mainWindow->getHeight()
  12085. << ", scale " << juce::String (juce::Desktop::getInstance().getDisplays().getPrimaryDisplay() != nullptr
  12086. ? juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->scale : 1.0, 2)
  12087. << ", audio device " << (engine->getDeviceManager().getCurrentAudioDevice() != nullptr ? engine->getDeviceManager().getCurrentAudioDevice()->getName() : juce::String ("none")) << "\n"
  12088. << "load " << juce::String (loadMs / 1000.0, 2) << " s\n";
  12089. const auto none = juce::ModifierKeys();
  12090. // discussion #10 (round 173f): the reporter's screen — the Channel Rack and the Mixer open, the pattern playing —
  12091. // watched as it is, then insert 3's fader dragged up and down with the mouse (125 moves a second through the
  12092. // window's own mouse path, the frames painted as the window paints them)
  12093. const auto dragTrack = engine->getSong().mixer.size() > 3 ? 3 : 1;
  12094. run->steps.push_back ({ "rack + mixer, pattern playing", [this, ui] {
  12095. ui->showPanelsForSnapshot ({ lynx::workspace::Panel::channelRack, lynx::workspace::Panel::mixer });
  12096. engine->getTransport().songMode = false;
  12097. engine->rewind();
  12098. engine->play();
  12099. }, {}, 4000 });
  12100. run->steps.push_back ({ "fader drag by mouse, rack + mixer, pattern playing", [this, ui, drag, dragTrack] {
  12101. auto& strips = ui->getMixerForSnapshot().getStripsForSnapshot();
  12102. const auto rail = strips.faderRailForSnapshot (dragTrack);
  12103. drag->start (*mainWindow, strips, rail, engine.get(), dragTrack);
  12104. }, {}, 3000, [drag] { return drag->stop(); } });
  12105. run->steps.push_back ({ "song stopped during the drag", {}, {}, 500, [drag] { return drag->release(); } });
  12106. run->steps.push_back ({ "after the drag (released)", {}, {}, 600, [drag] { return drag->released(); } });
  12107. run->steps.push_back ({ "desktop, playing", [this, ui] { ui->showDesktopForSnapshot (false); engine->rewind(); engine->play(); }, {}, 3000 });
  12108. run->steps.push_back ({ "mixer maximised, playing", [ui] { ui->selectTabForSnapshot (3); }, {}, 3000 });
  12109. // round 177a: only the meters move, so the strips' picture must stay valid, also with a folded group's tab and VCA
  12110. // strips on screen (their levels are drawn over the picture, like the inserts' meters)
  12111. run->steps.push_back ({ "mixer meters over the picture, playing", [this, ui] {
  12112. ui->selectTabForSnapshot (3);
  12113. engine->getTransport().songMode = false;
  12114. engine->rewind();
  12115. engine->play();
  12116. ui->getMixerForSnapshot().getStripsForSnapshot().cacheCountersForPerf();
  12117. }, {}, 6000, [this, ui, report] {
  12118. const auto [spoiled, refills] = ui->getMixerForSnapshot().getStripsForSnapshot().cacheCountersForPerf();
  12119. if (juce::FileOutputStream out (report.withFileExtension ("png")); out.openedOk())
  12120. {
  12121. out.setPosition (0);
  12122. out.truncate();
  12123. juce::PNGImageFormat().writeImageToStream (mainWindow->createComponentSnapshot (mainWindow->getLocalBounds()), out);
  12124. }
  12125. return juce::String (" mixer picture: spoiled ") + juce::String (spoiled) + " times, drawn again " + juce::String (refills) + " times\n";
  12126. } });
  12127. // (round 190my: on a strip's blank body near the Mixer's centre — since FL's Current strip moved the strips, the
  12128. // centre itself is a control, which the wheel turns instead of scrolling)
  12129. run->steps.push_back ({ "mixer scroll", {}, [this, ui] (int f) {
  12130. auto& mixer = ui->getMixerForSnapshot();
  12131. auto& strips = mixer.getStripsForSnapshot();
  12132. auto* peer = mainWindow->getPeer();
  12133. if (peer == nullptr || ! strips.isShowing())
  12134. return;
  12135. const auto centre = strips.getLocalPoint (&mixer, mixer.getLocalBounds().getCentre());
  12136. const auto at = strips.wheelScrollPointForPerf (centre, strips.getParentComponent() != nullptr
  12137. ? strips.getLocalArea (strips.getParentComponent(), strips.getParentComponent()->getLocalBounds())
  12138. : strips.getLocalBounds());
  12139. const auto local = peer->globalToLocal (strips.localPointToGlobal (at).toFloat());
  12140. juce::ModifierKeys::currentModifiers = {};
  12141. juce::MouseWheelDetails wheel { 0.0f, f < 30 ? -0.25f : 0.25f, false, false, false };
  12142. peer->handleMouseWheel (juce::MouseInputSource::InputSourceType::mouse, local, juce::Time::currentTimeMillis(), wheel);
  12143. }, 60 });
  12144. // a fader dragged while the song plays (round 171c, discussion #10): 4 mouse moves per frame on insert 1's fader,
  12145. // through the old path (a whole snapshot per move) and through editLevels
  12146. auto faderMove = [this] (bool levels, int f) {
  12147. for (int k = 0; k < 4; ++k)
  12148. {
  12149. const auto v = 0.5f + 0.3f * std::sin ((float) (f * 4 + k) * 0.05f);
  12150. const auto edit = [v] (lynx::Song& s) { if (s.mixer.size() > 1) s.mixer[1].volume = v; };
  12151. if (levels)
  12152. engine->editLevels (edit, false); // (no undo step: in a real drag only the press saves one)
  12153. else
  12154. engine->editSong (edit, false);
  12155. }
  12156. };
  12157. run->steps.push_back ({ "mixer fader drag, playing, rebuild per move (before 171c)", {}, [faderMove] (int f) { faderMove (false, f); }, 60 });
  12158. run->steps.push_back ({ "mixer fader drag, playing, live levels (171c)", {}, [faderMove, this] (int f) { faderMove (true, f); if (f == 59) engine->flushLevels(); }, 60 });
  12159. // F8's Plugin picker (round 171c): opening it (the "show" time = building it + its first paint), its pictures
  12160. // loading while it stays open, pointing at the tiles, then closing it
  12161. run->steps.push_back ({ "plugin picker open (F8)", [ui] { ui->togglePluginPickerForSnapshot(); }, {}, 2500 });
  12162. run->steps.push_back ({ "plugin picker, pointing at tiles", {}, [ui] (int f) {
  12163. // (round 175b: the picker is its own window)
  12164. if (auto* picker = ui->pluginPickerForSnapshot(); picker != nullptr && picker->getPeer() != nullptr)
  12165. {
  12166. const auto p = picker->localPointToGlobal (juce::Point<int> (60 + (f * 37) % juce::jmax (1, picker->getWidth() - 120),
  12167. 90 + (f * 53) % juce::jmax (1, picker->getHeight() - 200)));
  12168. const auto local = picker->getPeer()->globalToLocal (p.toFloat());
  12169. picker->getPeer()->handleMouseEvent (juce::MouseInputSource::InputSourceType::mouse, local, {}, 0.0f, 0.0f,
  12170. juce::Time::currentTimeMillis());
  12171. }
  12172. }, 60 });
  12173. run->steps.push_back ({ "plugin picker close", [ui] { ui->togglePluginPickerForSnapshot(); }, {}, 300 });
  12174. run->steps.push_back ({ "playlist maximised, playing", [ui] { ui->selectTabForSnapshot (2); }, {}, 3000 });
  12175. run->steps.push_back ({ "playlist scroll down/up", [this] { engine->stop(); },
  12176. [wheelAt, ui, none] (int f) { wheelAt (ui->getPlaylistForSnapshot(), 0.0f, f < 40 ? -0.15f : 0.15f, none); }, 80 });
  12177. run->steps.push_back ({ "playlist scroll sideways", {},
  12178. [wheelAt, ui, none] (int f) { wheelAt (ui->getPlaylistForSnapshot(), f < 40 ? -0.15f : 0.15f, 0.0f, none); }, 80 });
  12179. // round 174f: Ctrl+wheel zoom, a notch every third frame (~20 a second), three in then three out, as dupmon drives it
  12180. run->steps.push_back ({ "playlist zoom (Ctrl+wheel)", {},
  12181. [wheelAt, ui] (int f) {
  12182. if (f % 3 == 0)
  12183. wheelAt (ui->getPlaylistForSnapshot(), 0.0f, (f / 9) % 2 == 0 ? 0.15f : -0.15f, juce::ModifierKeys (juce::ModifierKeys::ctrlModifier));
  12184. }, 120 });
  12185. run->steps.push_back ({ "playlist after the zoom (settles)", {}, {}, 500 });
  12186. run->steps.push_back ({ "whole window repainted", {}, [this] (int) { mainWindow->repaint(); }, 40 });
  12187. run->steps.push_back ({ "channel rack scroll", [ui] { ui->selectTabForSnapshot (0); },
  12188. [wheelAt, ui, none] (int f) { wheelAt (ui->getRackViewportForSnapshot(), 0.0f, f < 30 ? -0.25f : 0.25f, none); }, 60 });
  12189. // round 190ge: the other main views while the pattern plays, then every view with the transport stopped and
  12190. // nothing moving (an idle view should paint nothing: its frames and painted area are the repaint storms), then
  12191. // the Clip-launch grid playing
  12192. auto playPattern = [this] {
  12193. engine->getTransport().songMode = false;
  12194. engine->rewind();
  12195. engine->play();
  12196. };
  12197. run->steps.push_back ({ "piano roll maximised, pattern playing", [ui, playPattern] { ui->selectTabForSnapshot (1); playPattern(); }, {}, 3000 });
  12198. // round 190jx: the moving playheads alone, for the overlay's A/B (LYNX_UIPERF_ONLY="overlay A/B", LYNX_OVERLAY=0|1):
  12199. // the Playlist with the song playing and the Piano roll with the pattern playing, LYNX_UIPERF_PLAY_MS each (10 s)
  12200. {
  12201. const auto playMs = juce::jmax (1000, juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_PLAY_MS", "10000").getIntValue());
  12202. run->steps.push_back ({ "overlay A/B: playlist maximised, song playing", [this, ui] {
  12203. ui->selectTabForSnapshot (2);
  12204. engine->getTransport().songMode = true;
  12205. engine->rewind();
  12206. engine->play();
  12207. }, {}, playMs });
  12208. run->steps.push_back ({ "overlay A/B: piano roll maximised, pattern playing", [ui, playPattern] { ui->selectTabForSnapshot (1); playPattern(); }, {}, playMs,
  12209. [this] { engine->stop(); return juce::String(); } });
  12210. }
  12211. run->steps.push_back ({ "channel rack maximised, pattern playing", [ui, playPattern] { ui->selectTabForSnapshot (0); playPattern(); }, {}, 3000 });
  12212. const char* idleViews[] { "channel rack", "piano roll", "playlist", "mixer" };
  12213. for (int view = 0; view < 4; ++view)
  12214. run->steps.push_back ({ juce::String ("idle: ") + idleViews[view] + ", stopped", [this, ui, view] { engine->stop(); ui->selectTabForSnapshot (view); }, {}, 3000 });
  12215. run->steps.push_back ({ "idle: desktop, stopped", [this, ui] { engine->stop(); ui->showDesktopForSnapshot (false); }, {}, 3000 });
  12216. // round 190im (R1, DE-124): the automation editor window open over the Playlist, stopped and then playing (its
  12217. // timer only while it plays, its playhead columns only); closed after
  12218. {
  12219. int automation = -1;
  12220. for (const auto& c : engine->getSong().playlist)
  12221. if (c.kind == lynx::ClipKind::automation && c.automation >= 0 && automation < 0)
  12222. automation = c.automation;
  12223. if (automation >= 0)
  12224. {
  12225. run->steps.push_back ({ "automation editor open, stopped", [this, ui, automation] {
  12226. engine->stop();
  12227. ui->selectTabForSnapshot (2);
  12228. lynx::openAutomationEditor (*engine, automation);
  12229. }, {}, 3000 });
  12230. run->steps.push_back ({ "automation editor open, song playing", [this] {
  12231. engine->getTransport().songMode = true;
  12232. engine->rewind();
  12233. engine->play();
  12234. }, {}, 3000, [this] {
  12235. engine->stop();
  12236. auto& desktop = juce::Desktop::getInstance();
  12237. for (int i = desktop.getNumComponents(); --i >= 0;)
  12238. if (auto* w = dynamic_cast<juce::DocumentWindow*> (desktop.getComponent (i)); w != nullptr && w->getName().startsWith ("Automation - "))
  12239. w->closeButtonPressed();
  12240. return juce::String();
  12241. } });
  12242. }
  12243. }
  12244. run->steps.push_back ({ "clip grid, song playing", [this, ui] {
  12245. ui->selectTabForSnapshot (2);
  12246. ui->setClipLaunchWorkflow (true);
  12247. ui->setClipGridView (lynx::PlaylistArea::GridView::grid);
  12248. engine->getTransport().songMode = true;
  12249. engine->rewind();
  12250. engine->play();
  12251. }, {}, 3000 });
  12252. // round 190gr: the grid's clips launched (every scene that has clips, one after the other: the playing cells'
  12253. // progress bars move, the launches blink until their grid point)
  12254. run->steps.push_back ({ "clip grid, clips launched", [this] {
  12255. engine->getTransport().songMode = true;
  12256. if (const auto& grid = engine->getSong().clipGrid)
  12257. for (int scene = 0; scene < juce::jmin (8, (int) grid->scenes.size()); ++scene)
  12258. engine->launcherCommand ({ lynx::launcher::Command::Type::launchScene, 0, scene });
  12259. }, {}, 3000, [this] {
  12260. int playing = 0;
  12261. if (const auto* state = engine->launcherState())
  12262. for (const auto& t : state->tracks)
  12263. playing += t.playing.load() >= 0 ? 1 : 0;
  12264. engine->launcherCommand ({ lynx::launcher::Command::Type::stopAll });
  12265. return " tracks playing a clip: " + juce::String (playing) + "\n";
  12266. } });
  12267. run->steps.push_back ({ "idle: clip grid, stopped", [this] { engine->stop(); }, {}, 3000, [ui] { ui->setClipLaunchWorkflow (false); return juce::String(); } });
  12268. // round 190jn: the Clip-launch layout's Arrangement (Live's look: 19 px lanes, colour blocks, dark waveforms) playing,
  12269. // then idle
  12270. run->steps.push_back ({ "clip arrangement, song playing", [this, ui] {
  12271. ui->selectTabForSnapshot (2);
  12272. ui->setClipLaunchWorkflow (true);
  12273. ui->setClipGridView (lynx::PlaylistArea::GridView::song);
  12274. engine->getTransport().songMode = true;
  12275. engine->rewind();
  12276. engine->play();
  12277. }, {}, 3000 });
  12278. run->steps.push_back ({ "idle: clip arrangement, stopped", [this] { engine->stop(); }, {}, 3000, [ui] {
  12279. ui->setClipGridView (lynx::PlaylistArea::GridView::grid);
  12280. ui->setClipLaunchWorkflow (false);
  12281. return juce::String();
  12282. } });
  12283. // round 190ih: the plugin windows with live parts — Gross Beat (its locator), the Formula Controller (its monitor),
  12284. // the Envelope Controller (its meters and key line) — idle with the song stopped, then Gross Beat while it plays
  12285. // (CPU and frames; the windows are their own, so the main window's painted area stays the main window's)
  12286. run->steps.push_back ({ "idle: Gross Beat + Formula + Envelope controller windows, stopped", [this] {
  12287. engine->stop();
  12288. auto& song = engine->getSong();
  12289. int gbTrack = -1, gbSlot = -1;
  12290. for (int t = 0; t < (int) song.mixer.size() && gbTrack < 0; ++t)
  12291. for (int k = 0; k < (int) song.mixer[(std::size_t) t].effects.size(); ++k)
  12292. if (song.mixer[(std::size_t) t].effects[(std::size_t) k].kind == lynx::EffectKind::grossBeat)
  12293. {
  12294. gbTrack = t;
  12295. gbSlot = k;
  12296. break;
  12297. }
  12298. const auto last = (int) song.mixer.size() - 1;
  12299. const auto formulaSlot = last >= 1 ? (int) song.mixer[(std::size_t) last].effects.size() : -1;
  12300. engine->editSong ([last] (lynx::Song& s) {
  12301. if (last >= 1 && s.mixer[(std::size_t) last].effects.size() < (std::size_t) lynx::maxEffectSlots)
  12302. s.mixer[(std::size_t) last].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::formulaController));
  12303. lynx::ChannelDef env;
  12304. env.name = "Envelope Controller";
  12305. env.instrument = lynx::InstrumentKind::controller;
  12306. env.controllerState = lynx::writeEnvelopeController (lynx::defaultEnvelopeController());
  12307. s.channels.push_back (env);
  12308. }, false);
  12309. engine->dispatchPendingMessages();
  12310. // LYNX_UIPERF_WINDOWS: which of them (G Gross Beat, F Formula, E Envelope Controller; default all)
  12311. const auto which = juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_WINDOWS", "GFE");
  12312. if (gbTrack >= 0 && which.containsChar ('G'))
  12313. lynx::NativeEffectWindows::open (*engine, gbTrack, gbSlot);
  12314. if (formulaSlot >= 0 && which.containsChar ('F'))
  12315. lynx::FormulaControllerWindows::open (*engine, last, formulaSlot);
  12316. if (which.containsChar ('E'))
  12317. lynx::openChannelSettings (*engine, (int) engine->getSong().channels.size() - 1);
  12318. }, {}, 3000 });
  12319. // round 190ih: LYNX_UIPERF_GBAB=n — n cycles over Gross Beat's live-display variants, playing, 2.5 s each, in one
  12320. // process (other load hits every variant alike): the names carry the LYNX_GB_DIAG mask
  12321. if (const auto cycles = juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_GBAB", "0").getIntValue(); cycles > 0)
  12322. {
  12323. run->steps.push_back ({ "Gross Beat A/B start", [this] {
  12324. engine->getTransport().songMode = true;
  12325. engine->rewind();
  12326. engine->play();
  12327. }, {}, 1500 });
  12328. // (off, the default, 30 / s, off, 10 / s; LYNX_UIPERF_GBAB_MASKS="1,2,0" picks others, e.g. round 190iy's
  12329. // locator on the GPU overlay (0) against the repaint path (2))
  12330. std::vector<int> masks { 1, 0, 30 << 8, 1, 10 << 8 };
  12331. if (const auto list = juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_GBAB_MASKS", {}); list.isNotEmpty())
  12332. {
  12333. masks.clear();
  12334. for (const auto& m : juce::StringArray::fromTokens (list, ",", {}))
  12335. masks.push_back (m.trim().getIntValue());
  12336. }
  12337. for (int c = 0; c < cycles; ++c)
  12338. for (const int mask : masks)
  12339. run->steps.push_back ({ "Gross Beat A/B mask " + juce::String (mask) + " cycle " + juce::String (c + 1),
  12340. [this, mask] {
  12341. lynx::setGrossBeatDiagnostics (mask);
  12342. if (! engine->getTransport().playing.load()) // (the song ended: again)
  12343. {
  12344. engine->rewind();
  12345. engine->play();
  12346. }
  12347. }, {}, 2500 });
  12348. }
  12349. // round 190jy (queue item 44): LYNX_UIPERF_DOCKAB=n — the docked LYNX editors with live displays, playing, each set
  12350. // hidden / a native child window / drawn by the main window, n cycles of 2.5 s steps in one process.
  12351. // LYNX_UIPERF_DOCKAB_SETS (default "G,L,M,GLM"): G Gross Beat, L Fruity Limiter, M Maximus (both on the master).
  12352. if (const auto cycles = juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_DOCKAB", "0").getIntValue(); cycles > 0)
  12353. {
  12354. auto sets = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_DOCKAB_SETS", "G,L,M,GLM"), ",", {});
  12355. auto shown = std::make_shared<std::vector<juce::Component::SafePointer<juce::DocumentWindow>>>();
  12356. auto keepPlaying = [this] {
  12357. engine->getTransport().songMode = true;
  12358. if (! engine->getTransport().playing.load()) // (the song ended: again)
  12359. {
  12360. engine->rewind();
  12361. engine->play();
  12362. }
  12363. };
  12364. for (const auto& set : sets)
  12365. {
  12366. const auto name = set.trim();
  12367. run->steps.push_back ({ "dock A/B " + name + " open", [this, name, shown, keepPlaying] {
  12368. lynx::NativeEffectWindows::closeAll();
  12369. for (auto* w : lynx::dockedEditorWindows()) // (a channel's settings window of the set before)
  12370. if (w != nullptr)
  12371. w->closeButtonPressed();
  12372. shown->clear();
  12373. auto& song = engine->getSong();
  12374. auto openKind = [this] (lynx::EffectKind kind) {
  12375. auto& so = engine->getSong();
  12376. for (int t = 0; t < (int) so.mixer.size(); ++t)
  12377. for (int k = 0; k < (int) so.mixer[(std::size_t) t].effects.size(); ++k)
  12378. if (so.mixer[(std::size_t) t].effects[(std::size_t) k].kind == kind)
  12379. {
  12380. lynx::NativeEffectWindows::open (*engine, t, k);
  12381. return;
  12382. }
  12383. // (not in the project: on the master, after its effects)
  12384. if (so.mixer.empty() || so.mixer[0].effects.size() >= (std::size_t) lynx::maxEffectSlots)
  12385. return;
  12386. const auto slot = (int) so.mixer[0].effects.size();
  12387. engine->editSong ([kind] (lynx::Song& s2) { s2.mixer[0].effects.push_back (lynx::makeEffectSlot (kind)); }, false);
  12388. engine->dispatchPendingMessages();
  12389. lynx::NativeEffectWindows::open (*engine, 0, slot);
  12390. };
  12391. juce::ignoreUnused (song);
  12392. if (name.containsChar ('G'))
  12393. openKind (lynx::EffectKind::grossBeat);
  12394. if (name.containsChar ('L'))
  12395. openKind (lynx::EffectKind::fruityLimiter);
  12396. if (name.containsChar ('M'))
  12397. openKind (lynx::EffectKind::maximus);
  12398. // S: a Slicex channel (a 2 s tone in 4 regions) that plays the notes of the project's busiest
  12399. // channel, its settings window open (its deck's play line moves while it sounds)
  12400. if (name.containsChar ('S'))
  12401. {
  12402. const auto wav = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-uiperf-slicex.wav");
  12403. {
  12404. juce::AudioBuffer<float> tone (2, 96000);
  12405. for (int i = 0; i < tone.getNumSamples(); ++i)
  12406. tone.setSample (0, i, 0.3f * (float) std::sin (juce::MathConstants<double>::twoPi * (200.0 + 200.0 * (i / 24000)) * i / 48000.0));
  12407. tone.copyFrom (1, 0, tone, 0, 0, tone.getNumSamples());
  12408. wav.deleteFile();
  12409. if (auto out = std::unique_ptr<juce::OutputStream> (wav.createOutputStream()))
  12410. if (auto writer = std::unique_ptr<juce::AudioFormatWriter> (juce::WavAudioFormat().createWriterFor (out.get(), 48000.0, 2, 16, {}, 0)))
  12411. {
  12412. out.release();
  12413. writer->writeFromAudioSampleBuffer (tone, 0, tone.getNumSamples());
  12414. }
  12415. }
  12416. int busiest = -1;
  12417. {
  12418. std::map<int, int> count;
  12419. for (const auto& pat : engine->getSong().patterns)
  12420. for (const auto& n : pat.notes)
  12421. ++count[n.channel];
  12422. int best = 0;
  12423. for (const auto& [ch, n] : count)
  12424. if (n > best)
  12425. best = n, busiest = ch;
  12426. }
  12427. const auto index = (int) engine->getSong().channels.size();
  12428. engine->editSong ([&wav, busiest, index] (lynx::Song& s2) {
  12429. lynx::ChannelDef ch;
  12430. ch.name = "Slicex (uiperf)";
  12431. ch.instrument = lynx::InstrumentKind::slicex;
  12432. ch.samplePath = wav.getFullPathName().toStdString();
  12433. auto state = lynx::slicex::fresh();
  12434. lynx::slicex::setDeckFile (state, 0, ch.samplePath, 4);
  12435. lynx::slicex::setDeckBeats (state, 0, 0.0, 4.0);
  12436. ch.pluginState = lynx::slicex::write (state);
  12437. s2.channels.push_back (ch);
  12438. for (auto& pat : s2.patterns)
  12439. {
  12440. std::vector<lynx::Note> copies;
  12441. for (const auto& n : pat.notes)
  12442. if (n.channel == busiest)
  12443. {
  12444. auto c = n;
  12445. c.channel = index;
  12446. c.key = 60 + (int) (copies.size() % 4); // (the four slices in turn)
  12447. copies.push_back (c);
  12448. }
  12449. pat.notes.insert (pat.notes.end(), copies.begin(), copies.end());
  12450. pat.sortNotes();
  12451. }
  12452. }, false);
  12453. engine->dispatchPendingMessages();
  12454. lynx::openChannelSettings (*engine, index);
  12455. }
  12456. for (auto* w : lynx::dockedEditorWindows())
  12457. shown->emplace_back (w);
  12458. keepPlaying();
  12459. }, {}, 1500 });
  12460. static const char* variantNames[] = { "hidden", "own window", "main window" };
  12461. for (int c = 0; c < cycles; ++c)
  12462. for (int v = 0; v < 3; ++v)
  12463. run->steps.push_back ({ "dock A/B " + name + " " + variantNames[v] + " cycle " + juce::String (c + 1), [v, shown, keepPlaying] {
  12464. if (v > 0)
  12465. lynx::moveDockedEditors (v == 2);
  12466. for (auto& w : *shown)
  12467. if (w != nullptr && w->isVisible() != (v > 0))
  12468. w->setVisible (v > 0);
  12469. keepPlaying();
  12470. }, {}, 2500 });
  12471. }
  12472. run->steps.push_back ({ "dock A/B close", [this, shown] {
  12473. engine->stop();
  12474. shown->clear();
  12475. lynx::NativeEffectWindows::closeAll();
  12476. for (auto* w : lynx::dockedEditorWindows())
  12477. if (w != nullptr)
  12478. w->closeButtonPressed();
  12479. }, {}, 500 });
  12480. }
  12481. // round 190jy: LYNX_UIPERF_DOCKCHECK=1 — the checks of a docked editor drawn by the main window (ui/DockPaintCheck.h),
  12482. // on screen in this main window; LYNX_UIPERF_DOCKCHECK_SHOTS=<folder> keeps the two on-screen pictures compared
  12483. if (juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_DOCKCHECK", {}) == "1")
  12484. {
  12485. auto check = std::make_shared<std::unique_ptr<lynx::dockpaint::Check>>();
  12486. auto lines = std::make_shared<juce::String>();
  12487. for (int i = 0; i < lynx::dockpaint::Check::count(); ++i)
  12488. run->steps.push_back ({ "dock check " + juce::String (i), [this, ui, check, lines, i] {
  12489. if (*check == nullptr)
  12490. *check = std::make_unique<lynx::dockpaint::Check> (*engine, *ui, *mainWindow,
  12491. juce::File (juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_DOCKCHECK_SHOTS", {})));
  12492. *lines = (*check)->step (i);
  12493. }, {}, 700, [lines] { return *lines; } });
  12494. }
  12495. run->steps.push_back ({ "Gross Beat window, song playing", [this] {
  12496. engine->getTransport().songMode = true;
  12497. engine->rewind();
  12498. engine->play();
  12499. }, {}, 3000, [this] {
  12500. engine->stop();
  12501. lynx::NativeEffectWindows::closeAll();
  12502. lynx::FormulaControllerWindows::closeAll();
  12503. return juce::String();
  12504. } });
  12505. // round 190kb: LYNX_UIPERF_SPINAB=n — the worker pool's waiting policies (WorkerPool::Tuning) A/B inside one
  12506. // process while the song plays with live editor windows: per set (LYNX_UIPERF_SPINAB_SETS, default "G,GLM": G
  12507. // Gross Beat, L Fruity Limiter, M Maximus; on the master when the project has none), n cycles over every
  12508. // variant (LYNX_UIPERF_SPINAB_VARIANTS="name:spec;…", spec as LYNX_POOL) with the windows hidden and shown,
  12509. // 2.5 s steps, the order turning every cycle. Run with LYNX_UIPERF_THREADS=1 for the threads' lines.
  12510. if (const auto cycles = juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_SPINAB", "0").getIntValue(); cycles > 0)
  12511. {
  12512. auto sets = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_SPINAB_SETS", "G,GLM"), ",", {});
  12513. struct Variant
  12514. {
  12515. juce::String name, spec;
  12516. };
  12517. std::vector<Variant> variants;
  12518. for (const auto& v : juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable (
  12519. "LYNX_UIPERF_SPINAB_VARIANTS", "old:spin=60,adaptive=0,wait=0;new:spin=60,adaptive=1,dry=4,wait=1,waitspin=30"),
  12520. ";", {}))
  12521. if (v.containsChar (':'))
  12522. variants.push_back ({ v.upToFirstOccurrenceOf (":", false, false).trim(), v.fromFirstOccurrenceOf (":", false, false).trim() });
  12523. auto shown = std::make_shared<std::vector<juce::Component::SafePointer<juce::Component>>>();
  12524. // every step plays the same part of the song (LYNX_UIPERF_SPINAB_AT: a fraction of the song, default 0.4): the
  12525. // audio work differs from part to part far more than between the variants (a first run without this put the
  12526. // variants of one cycle in different parts and read the parts)
  12527. auto at = std::make_shared<double> (0.0);
  12528. const auto atFraction = juce::jlimit (0.0, 0.95, juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_SPINAB_AT", "0.4").getDoubleValue());
  12529. auto keepPlaying = [this, at] {
  12530. engine->getTransport().songMode = true;
  12531. engine->seek (*at);
  12532. if (! engine->getTransport().playing.load())
  12533. engine->play();
  12534. };
  12535. for (const auto& set : sets)
  12536. {
  12537. const auto name = set.trim();
  12538. run->steps.push_back ({ "spin A/B " + name + " open", [this, name, shown, keepPlaying, at, atFraction] {
  12539. *at = atFraction * engine->getTransport().songEnd.load();
  12540. lynx::NativeEffectWindows::closeAll();
  12541. shown->clear();
  12542. std::vector<juce::Component*> before;
  12543. auto& desktop = juce::Desktop::getInstance();
  12544. for (int i = 0; i < desktop.getNumComponents(); ++i)
  12545. before.push_back (desktop.getComponent (i));
  12546. auto openKind = [this] (lynx::EffectKind kind) {
  12547. auto& so = engine->getSong();
  12548. for (int t = 0; t < (int) so.mixer.size(); ++t)
  12549. for (int k = 0; k < (int) so.mixer[(std::size_t) t].effects.size(); ++k)
  12550. if (so.mixer[(std::size_t) t].effects[(std::size_t) k].kind == kind)
  12551. {
  12552. lynx::NativeEffectWindows::open (*engine, t, k);
  12553. return;
  12554. }
  12555. // (not in the project: on the master, after its effects)
  12556. if (so.mixer.empty() || so.mixer[0].effects.size() >= (std::size_t) lynx::maxEffectSlots)
  12557. return;
  12558. const auto slot = (int) so.mixer[0].effects.size();
  12559. engine->editSong ([kind] (lynx::Song& s2) { s2.mixer[0].effects.push_back (lynx::makeEffectSlot (kind)); }, false);
  12560. engine->dispatchPendingMessages();
  12561. lynx::NativeEffectWindows::open (*engine, 0, slot);
  12562. };
  12563. if (name.containsChar ('G'))
  12564. openKind (lynx::EffectKind::grossBeat);
  12565. if (name.containsChar ('L'))
  12566. openKind (lynx::EffectKind::fruityLimiter);
  12567. if (name.containsChar ('M'))
  12568. openKind (lynx::EffectKind::maximus);
  12569. for (int i = 0; i < desktop.getNumComponents(); ++i)
  12570. if (auto* c = desktop.getComponent (i); std::find (before.begin(), before.end(), c) == before.end())
  12571. shown->emplace_back (c);
  12572. keepPlaying();
  12573. }, {}, 1500, [shown, at] { return " windows of the set: " + juce::String ((int) shown->size()) + ", every step from tick " + juce::String (*at, 0) + "\n"; } });
  12574. for (int c = 0; c < cycles; ++c)
  12575. for (int k = 0; k < (int) variants.size() * 2; ++k)
  12576. {
  12577. // (the variants in turn, starting one further each cycle; hidden / shown swapped every cycle)
  12578. const auto& v = variants[(std::size_t) ((k / 2 + c) % (int) variants.size())];
  12579. const auto visible = ((k % 2) == 1) != ((c % 2) == 1);
  12580. run->steps.push_back ({ "spin A/B " + name + " " + v.name + (visible ? " shown" : " hidden") + " cycle " + juce::String (c + 1),
  12581. [spec = v.spec, visible, shown, keepPlaying] {
  12582. lynx::WorkerPool::tuning().apply (spec.toRawUTF8());
  12583. for (auto& w : *shown)
  12584. if (w != nullptr && w->isVisible() != visible)
  12585. w->setVisible (visible);
  12586. keepPlaying();
  12587. }, {}, 2500 });
  12588. }
  12589. }
  12590. run->steps.push_back ({ "spin A/B close", [this, shown] {
  12591. engine->stop();
  12592. shown->clear();
  12593. lynx::NativeEffectWindows::closeAll();
  12594. lynx::WorkerPool::tuning().apply (juce::SystemStats::getEnvironmentVariable ("LYNX_POOL", "").toRawUTF8());
  12595. }, {}, 500 });
  12596. }
  12597. // round 190iv: the Simple layout (its toolbar) idle and while the song plays
  12598. run->steps.push_back ({ "idle: simple layout, stopped", [this, ui] {
  12599. engine->stop();
  12600. ui->setLayoutStyle (lynx::layoutstyle::Style::simple, false);
  12601. }, {}, 3000 });
  12602. run->steps.push_back ({ "simple layout, song playing", [this] {
  12603. engine->getTransport().songMode = true;
  12604. engine->rewind();
  12605. engine->play();
  12606. }, {}, 3000, [this, ui] {
  12607. engine->stop();
  12608. ui->setLayoutStyle (lynx::layoutstyle::Style::pattern, false);
  12609. return juce::String();
  12610. } });
  12611. // LYNX_UIPERF_ONLY=text: only the steps whose name has that text
  12612. if (const auto only = juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_ONLY", {}); only.isNotEmpty())
  12613. 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());
  12614. // let the window draw the project first
  12615. perf = std::move (run);
  12616. juce::Timer::callAfterDelay (1500, [this] { if (perf != nullptr) perf->startTimer (16); });
  12617. }
  12618. // --rtstress: opens the project in the normal window with the saved audio device, plays it from the start for
  12619. // `seconds` and writes the real-time statistics (deadline misses, late device calls, load histogram, heaviest units)
  12620. // --rtstress --backuptest N (round 177d): while the project plays, a device's MIDI clock (10/s) and active sensing
  12621. // (3/s) arrive, and the project counts as changed. N > 0 also forces a backup every N seconds on top of the timed ones.
  12622. // The report tells how many backups were written, when, and what the MIDI counters did.
  12623. struct BackupTest final : juce::Timer
  12624. {
  12625. lynx::AudioEngine* engine = nullptr;
  12626. lynx::MainComponent* ui = nullptr;
  12627. double everyMs = 0.0, startMs = 0.0, lastForcedMs = 0.0, longestCallMs = 0.0;
  12628. int ticks = 0, forced = 0;
  12629. std::uint64_t seenOver = 0, seenNear = 0;
  12630. juce::String misses; // each callback over (or near) its deadline: how long after the last forced backup
  12631. void timerCallback() override
  12632. {
  12633. engine->injectMidiInput (juce::MidiMessage (0xf8));
  12634. if (++ticks % 3 == 0)
  12635. engine->injectMidiInput (juce::MidiMessage (0xfe));
  12636. const auto now = juce::Time::getMillisecondCounterHiRes();
  12637. const auto s = engine->getRtStats().snapshot();
  12638. if (s.overBudget != seenOver || s.nearBudget != seenNear)
  12639. {
  12640. misses << " +" << juce::String ((now - lastForcedMs) / 1000.0, 1) << " s after the last forced backup (or the start): over +"
  12641. << (juce::int64) (s.overBudget - seenOver) << ", near +" << (juce::int64) (s.nearBudget - seenNear) << "\n";
  12642. seenOver = s.overBudget;
  12643. seenNear = s.nearBudget;
  12644. }
  12645. if (everyMs > 0.0 && now - lastForcedMs >= everyMs)
  12646. {
  12647. lastForcedMs = now;
  12648. ++forced;
  12649. ui->backupNowForTest();
  12650. longestCallMs = juce::jmax (longestCallMs, juce::Time::getMillisecondCounterHiRes() - now);
  12651. }
  12652. }
  12653. };
  12654. std::unique_ptr<BackupTest> backupTest;
  12655. void startBackupTest()
  12656. {
  12657. const auto& cli = juce::JUCEApplication::getCommandLineParameterArray();
  12658. const auto at = cli.indexOf ("--backuptest");
  12659. auto* ui = mainWindow != nullptr ? dynamic_cast<lynx::MainComponent*> (mainWindow->getContentComponent()) : nullptr;
  12660. if (at < 0 || ui == nullptr)
  12661. return;
  12662. backupTest = std::make_unique<BackupTest>();
  12663. backupTest->engine = engine.get();
  12664. backupTest->ui = ui;
  12665. backupTest->everyMs = cli[at + 1].getDoubleValue() * 1000.0;
  12666. backupTest->startMs = backupTest->lastForcedMs = juce::Time::getMillisecondCounterHiRes();
  12667. // (the project counts as changed, so a backup has something to write; the Master's fader is down, so a long run
  12668. // makes no sound: everything else is processed as usual)
  12669. engine->editSong ([] (lynx::Song& s) {
  12670. if (! s.mixer.empty())
  12671. s.mixer[0].volume = 0.0f;
  12672. });
  12673. backupTest->startTimer (100);
  12674. }
  12675. juce::String finishBackupTest()
  12676. {
  12677. if (backupTest == nullptr)
  12678. return {};
  12679. backupTest->stopTimer();
  12680. juce::String text;
  12681. const auto played = engine->getMidiPlayed();
  12682. text << " backup test: MIDI light count " << (int) engine->getMidiActivity() << ", played count " << (int) played << " (clock and active sensing only)\n";
  12683. text << " backup test: " << backupTest->forced << " forced, longest forced call on the message thread "
  12684. << juce::String (backupTest->longestCallMs, 1) << " ms\n";
  12685. if (backupTest->misses.isNotEmpty())
  12686. text << " backup test: callbacks over or near the deadline (seen within 100 ms):\n" << backupTest->misses;
  12687. auto files = lynx::autosaveFolder().findChildFiles (juce::File::findFiles, false, "*.lynx");
  12688. text << " backup test: " << files.size() << " file(s) in the backup folder:\n";
  12689. for (const auto& f : files)
  12690. text << " " << juce::String ((f.getLastModificationTime().toMilliseconds() - juce::Time::getCurrentTime().toMilliseconds()) / 1000) << " s before the end: "
  12691. << f.getFileName() << " (" << f.getSize() << " bytes)\n";
  12692. engine->injectMidiInput (juce::MidiMessage::noteOn (1, 60, (juce::uint8) 1));
  12693. engine->injectMidiInput (juce::MidiMessage::noteOff (1, 60));
  12694. text << " backup test: after a played note, played count " << (int) engine->getMidiPlayed() << "\n";
  12695. backupTest.reset();
  12696. return text;
  12697. }
  12698. void runRealtimeStress (const juce::File& project, const juce::File& report, double seconds, int bufferSize,
  12699. const juce::String& deviceType, const juce::String& deviceName, const juce::String& recordTo = {})
  12700. {
  12701. startupOptions = lynx::StartupOptions::load();
  12702. engine = std::make_unique<lynx::AudioEngine>();
  12703. lynx::videoview::install (*engine); // (Fruity Video Player channels: their sound tracks)
  12704. crashEngine = engine.get();
  12705. // the user's saved device stays as it was: this run's choices are undone before quitting
  12706. savedDeviceState = engine->getDeviceManager().createStateXml();
  12707. auto& devices = engine->getDeviceManager();
  12708. const auto driverFile = addDriverFileDeviceType();
  12709. const auto type = deviceType.isEmpty() && driverFile ? juce::String (lynx::dllAsioTypeName) : deviceType;
  12710. if (type.isNotEmpty() && devices.getCurrentAudioDeviceType() != type)
  12711. devices.setCurrentAudioDeviceType (type, true);
  12712. if (bufferSize > 0 || deviceName.isNotEmpty())
  12713. {
  12714. auto setup = devices.getAudioDeviceSetup();
  12715. if (bufferSize > 0)
  12716. setup.bufferSize = bufferSize;
  12717. if (deviceName.isNotEmpty())
  12718. setup.outputDeviceName = deviceName;
  12719. const auto error = devices.setAudioDeviceSetup (setup, true);
  12720. if (error.isNotEmpty())
  12721. report.replaceWithText ("device error: " + error + "\n");
  12722. }
  12723. createMainWindow();
  12724. if (! juce::JUCEApplication::getCommandLineParameters().contains ("--no-window")) // --no-window: is it the UI?
  12725. mainWindow->reveal();
  12726. juce::String error;
  12727. auto ok = false;
  12728. const auto loadStart = juce::Time::getMillisecondCounterHiRes();
  12729. if (project.hasFileExtension ("flp"))
  12730. ok = engine->importFlpFile (project, error);
  12731. else if (auto song = lynx::ProjectFile::load (project, error))
  12732. {
  12733. engine->setSong (std::move (*song));
  12734. ok = true;
  12735. }
  12736. const auto loadMs = juce::Time::getMillisecondCounterHiRes() - loadStart;
  12737. if (! ok)
  12738. {
  12739. report.replaceWithText ("project: " + project.getFullPathName() + "\nresult=ERROR " + error + "\n");
  12740. restoreSavedDeviceState();
  12741. setApplicationReturnValue (1);
  12742. quit();
  12743. return;
  12744. }
  12745. if (recordTo.isNotEmpty())
  12746. engine->setAudioRecordingArmed (true); // opens the input of the driver
  12747. // let the window draw the project, then play from the start with fresh statistics
  12748. juce::Timer::callAfterDelay (1500, [this, project, report, seconds, loadMs, recordTo] {
  12749. if (engine == nullptr)
  12750. return;
  12751. engine->stop();
  12752. engine->rewind();
  12753. engine->getRtStats().reset();
  12754. engine->takeUiPulse();
  12755. if (recordTo.isNotEmpty())
  12756. engine->setRecording (true);
  12757. // --log folder: the audio logger records what the Master plays during the run (realtime vs export checks)
  12758. const auto& cli = juce::JUCEApplication::getCommandLineParameterArray();
  12759. if (const auto at = cli.indexOf ("--log"); at >= 0 && at + 1 < cli.size())
  12760. engine->getAudioLogger().start (juce::File (cli[at + 1].unquoted()), engine->getDeviceManager().getCurrentAudioDevice() != nullptr
  12761. ? engine->getDeviceManager().getCurrentAudioDevice()->getCurrentSampleRate() : 44100.0);
  12762. engine->play();
  12763. startBackupTest();
  12764. juce::Timer::callAfterDelay ((int) (seconds * 1000.0), [this, project, report, seconds, loadMs, recordTo] {
  12765. if (engine == nullptr)
  12766. return;
  12767. const auto backupReport = finishBackupTest();
  12768. engine->stop();
  12769. juce::String recording;
  12770. if (engine->getAudioLogger().isLogging())
  12771. {
  12772. recording << " logged: " << engine->getAudioLogger().currentFile().getFullPathName() << "\n";
  12773. engine->getAudioLogger().stop();
  12774. }
  12775. if (recordTo.isNotEmpty())
  12776. recording = finishStressTake (juce::File (recordTo), seconds);
  12777. const auto& cli = juce::JUCEApplication::getCommandLineParameterArray();
  12778. const auto s = engine->getRtStats().snapshot();
  12779. juce::String text;
  12780. text << "project: " << project.getFullPathName() << "\n"
  12781. << "LYNX " << getApplicationVersion() << ", " << juce::SystemStats::getOperatingSystemName() << ", "
  12782. << juce::SystemStats::getNumCpus() << " logical CPUs (" << juce::SystemStats::getNumPhysicalCpus() << " cores), "
  12783. << juce::SystemStats::getCpuModel() << "\n"
  12784. << "load " << juce::String (loadMs / 1000.0, 1) << " s, played " << juce::String (seconds, 0) << " s\n"
  12785. << engine->describeRealtime();
  12786. const auto pulse = engine->takeUiPulse();
  12787. text << " UI: the 30 Hz engine timer ran " << pulse.calls << " times (" << juce::String (pulse.calls / seconds, 1)
  12788. << "/s), longest gap " << juce::String (pulse.maxGapMs, 0) << " ms" << (mainWindow == nullptr || ! mainWindow->isVisible() ? " (window hidden)" : "") << "\n";
  12789. text << " load histogram (share of the deadline: callbacks):";
  12790. for (std::size_t b = 0; b < s.histogram.size(); ++b)
  12791. if (s.histogram[b] > 0)
  12792. text << " " << (int) (b * 10) << (b + 1 == s.histogram.size() ? juce::String ("+") : "-" + juce::String ((int) (b * 10 + 10))) << "%:" << (juce::int64) s.histogram[b];
  12793. text << "\n";
  12794. text << recording << backupReport;
  12795. // --settingsshot file.png (round 161): Options > Audio settings of this run's device, as a picture
  12796. if (const auto at = cli.indexOf ("--settingsshot"); at >= 0 && at + 1 < cli.size())
  12797. {
  12798. auto page = lynx::makeSettingsPanel (*engine, lynx::SettingsPage::audio);
  12799. juce::Image image (juce::Image::ARGB, page->getWidth(), page->getHeight(), true);
  12800. {
  12801. juce::Graphics g (image);
  12802. g.fillAll (lynx::theme::panel);
  12803. page->paintEntireComponent (g, false);
  12804. }
  12805. const juce::File shot (cli[at + 1].unquoted());
  12806. shot.deleteFile();
  12807. if (auto out = shot.createOutputStream())
  12808. juce::PNGImageFormat().writeImageToStream (image, *out);
  12809. }
  12810. text << "result=" << (s.callbacks == 0 ? "ERROR no audio callbacks" : s.overBudget == 0 && s.lateCalls == 0 ? "OK" : "GLITCHES") << "\n";
  12811. report.replaceWithText (text);
  12812. restoreSavedDeviceState();
  12813. setApplicationReturnValue (s.callbacks == 0 ? 1 : 0);
  12814. quit();
  12815. });
  12816. });
  12817. }
  12818. // --bendrectest (round 167a): see the command line above
  12819. void runBendRecordTest (const juce::File& report, bool songMode)
  12820. {
  12821. engine = std::make_unique<lynx::AudioEngine>();
  12822. auto text = std::make_shared<juce::String>();
  12823. auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
  12824. auto finish = [this] (int code) {
  12825. setApplicationReturnValue (code);
  12826. quit();
  12827. };
  12828. auto* device = engine->getDeviceManager().getCurrentAudioDevice();
  12829. if (device == nullptr)
  12830. {
  12831. step ("result=ERROR no audio device");
  12832. finish (1);
  12833. return;
  12834. }
  12835. step ("device=" + device->getTypeName() + " | " + device->getName() + " | mode " + (songMode ? "song" : "pattern"));
  12836. auto song = lynx::Song::makeDefault();
  12837. song.bpm = 120.0;
  12838. song.mode = songMode ? lynx::PlayMode::song : lynx::PlayMode::pattern;
  12839. engine->setSong (std::move (song));
  12840. auto o = engine->getRecordOptions();
  12841. o.mode = lynx::RecordMode::overdub;
  12842. o.recordNotes = true;
  12843. o.recordAutomation = true;
  12844. o.countInBars = 0;
  12845. o.waitForInput = false;
  12846. o.quantiseAutomation = false;
  12847. o.punchLoopRegion = false;
  12848. o.preRollBars = o.postRollBars = 0;
  12849. engine->setRecordOptions (o);
  12850. engine->stop();
  12851. engine->rewind();
  12852. engine->setRecording (true);
  12853. engine->startPlayback();
  12854. // 2 s of wheel at ~100 messages a second: 0 → +1 (0.5 s), +1 → −1 (1 s), −1 → 0 (0.5 s)
  12855. auto sent = std::make_shared<std::vector<std::pair<double, float>>>();
  12856. auto t0 = std::make_shared<double> (juce::Time::getMillisecondCounterHiRes());
  12857. engine->injectMidiInput (juce::MidiMessage::noteOn (1, 60, (juce::uint8) 100));
  12858. auto tick = std::make_shared<std::function<void()>>();
  12859. *tick = [this, sent, t0, tick, step, finish, songMode] {
  12860. if (engine == nullptr)
  12861. return;
  12862. const auto ms = juce::Time::getMillisecondCounterHiRes() - *t0;
  12863. if (ms < 2000.0)
  12864. {
  12865. const auto x = ms / 1000.0;
  12866. 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);
  12867. const auto wheel = juce::jlimit (0, 16383, 8192 + juce::roundToInt (v * 8191.0f));
  12868. engine->injectMidiInput (juce::MidiMessage::pitchWheel (1, wheel));
  12869. sent->push_back ({ ms, (float) (wheel - 8192) / 8192.0f });
  12870. juce::Timer::callAfterDelay (10, *tick);
  12871. return;
  12872. }
  12873. engine->injectMidiInput (juce::MidiMessage::pitchWheel (1, 8192));
  12874. engine->injectMidiInput (juce::MidiMessage::noteOff (1, 60));
  12875. juce::Timer::callAfterDelay (400, [this, sent, step, finish, songMode] {
  12876. if (engine == nullptr)
  12877. return;
  12878. engine->stop();
  12879. juce::Timer::callAfterDelay (600, [this, sent, step, finish, songMode] {
  12880. if (engine == nullptr)
  12881. return;
  12882. engine->setRecording (false);
  12883. const auto& s = engine->getSong();
  12884. // the channel's pitch bend (MIDI channel 1), recorded as a lane or a clip
  12885. std::vector<std::pair<std::int64_t, float>> got;
  12886. juce::String where = "nothing";
  12887. for (const auto& a : s.automations)
  12888. if (a.target.kind == lynx::AutomationTargetKind::channelParam && lynx::midictl::isPitchBend (a.target.param))
  12889. {
  12890. where = "automation clip \"" + juce::String (a.name) + "\"";
  12891. for (const auto& pt : a.points)
  12892. got.push_back ({ pt.tick, pt.value });
  12893. }
  12894. for (const auto& p : s.patterns)
  12895. for (const auto& lane : p.events)
  12896. if (lane.target.kind == lynx::AutomationTargetKind::channelParam && lynx::midictl::isPitchBend (lane.target.param))
  12897. {
  12898. where = "pattern \"" + juce::String (p.name) + "\" event lane";
  12899. for (const auto& e : lane.events)
  12900. got.push_back ({ e.tick, e.value });
  12901. }
  12902. int notes = 0;
  12903. for (const auto& p : s.patterns)
  12904. notes += (int) p.notes.size();
  12905. float lo = 1.0f, hi = 0.0f;
  12906. for (const auto& [t, v] : got)
  12907. lo = std::min (lo, v), hi = std::max (hi, v);
  12908. // ticks: in order, spread over the ~2 s sweep (8 beats of 96 ticks at 120 bpm ≈ 4 beats)
  12909. const auto span = got.empty() ? 0 : got.back().first - got.front().first;
  12910. const auto sorted = std::is_sorted (got.begin(), got.end(), [] (const auto& a, const auto& b) { return a.first < b.first; });
  12911. step ("sent=" + juce::String ((int) sent->size()) + " wheel messages over 2 s");
  12912. step ("recorded=" + juce::String ((int) got.size()) + " points in " + where + ", value " + juce::String (lo, 3) + " .. "
  12913. + juce::String (hi, 3) + " (0.5 = centre), ticks " + juce::String (span) + " apart, " + (sorted ? "in order" : "OUT OF ORDER")
  12914. + ", notes " + juce::String (notes));
  12915. if (! got.empty())
  12916. step ("last=" + juce::String (got.back().second, 3));
  12917. // song mode: a clip over the take, ending back at the centre. Pattern mode: the take loops the 1-bar pattern
  12918. // (4.6 beats of take), so the lane spans the bar and the last wheel message (the centre) lands inside it
  12919. const auto centred = std::any_of (got.begin(), got.end(), [] (const auto& p) { return std::abs (p.second - 0.5f) < 0.02f; });
  12920. const auto ok = got.size() >= 20 && hi > 0.97f && lo < 0.03f && sorted && notes >= 1
  12921. && (songMode ? span > lynx::ppq * 3 && span < lynx::ppq * 6 && std::abs (got.back().second - 0.5f) < 0.02f
  12922. : span > lynx::ppq * 2 && span <= lynx::ppq * 4 && centred);
  12923. step (ok ? "result=OK" : "result=FAILED");
  12924. finish (ok ? 0 : 1);
  12925. });
  12926. });
  12927. };
  12928. juce::Timer::callAfterDelay (300, *tick);
  12929. }
  12930. // --countinrectest (round 170d): see the command line above.
  12931. void runCountInRecordTest (const juce::File& report)
  12932. {
  12933. engine = std::make_unique<lynx::AudioEngine>();
  12934. engine->getDeviceManager().closeAudioDevice(); // the engine's callback is driven by hand below
  12935. struct StandIn final : juce::AudioIODevice
  12936. {
  12937. StandIn() : juce::AudioIODevice ("countin", "test") {}
  12938. juce::StringArray getOutputChannelNames() override { return { "L", "R" }; }
  12939. juce::StringArray getInputChannelNames() override { return {}; }
  12940. juce::Array<double> getAvailableSampleRates() override { return { 48000.0 }; }
  12941. juce::Array<int> getAvailableBufferSizes() override { return { 512 }; }
  12942. int getDefaultBufferSize() override { return 512; }
  12943. juce::String open (const juce::BigInteger&, const juce::BigInteger&, double, int) override { return {}; }
  12944. void close() override {}
  12945. bool isOpen() override { return true; }
  12946. void start (juce::AudioIODeviceCallback*) override {}
  12947. void stop() override {}
  12948. bool isPlaying() override { return true; }
  12949. juce::String getLastError() override { return {}; }
  12950. int getCurrentBufferSizeSamples() override { return 512; }
  12951. double getCurrentSampleRate() override { return 48000.0; }
  12952. int getCurrentBitDepth() override { return 32; }
  12953. juce::BigInteger getActiveOutputChannels() const override
  12954. {
  12955. juce::BigInteger b;
  12956. b.setRange (0, 2, true);
  12957. return b;
  12958. }
  12959. juce::BigInteger getActiveInputChannels() const override { return {}; }
  12960. int getOutputLatencyInSamples() override { return 256; }
  12961. int getInputLatencyInSamples() override { return 0; }
  12962. };
  12963. auto device = std::make_shared<StandIn>();
  12964. auto text = std::make_shared<juce::String>();
  12965. auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
  12966. auto finish = [this] (int code) {
  12967. setApplicationReturnValue (code);
  12968. quit();
  12969. };
  12970. constexpr std::int64_t bar = 4 * lynx::ppq; // 120 BPM, 4/4
  12971. lynx::Song song; // (as --cliplooptest: one synth channel on insert 1, an empty pattern)
  12972. song.bpm = 120.0;
  12973. song.mixer = lynx::Song::defaultMixer (2);
  12974. song.channels.resize (1);
  12975. song.channels[0].mixerTrack = 1;
  12976. song.patterns.emplace_back();
  12977. song.mode = lynx::PlayMode::song;
  12978. song.currentPattern = 0;
  12979. engine->setSong (song);
  12980. engine->getTransport().metronome.store (true);
  12981. auto o = engine->getRecordOptions();
  12982. o.mode = lynx::RecordMode::overdub;
  12983. o.countInBars = 1;
  12984. o.catchWindow = lynx::ppq / 4;
  12985. o.compensateOutput = true;
  12986. o.recordNotes = true;
  12987. o.recordAudio = false;
  12988. o.recordAutomation = false;
  12989. o.waitForInput = false;
  12990. o.quantise = 0;
  12991. o.placeSongClip = true;
  12992. o.recordingMarkers = false;
  12993. o.punchLoopRegion = false;
  12994. o.preRollBars = o.postRollBars = 0;
  12995. engine->setRecordOptions (o);
  12996. engine->deviceCallback().audioDeviceAboutToStart (device.get());
  12997. 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");
  12998. // an event heard at output sample `heard` (counted from the first block after Play), sent as MIDI input
  12999. struct Event
  13000. {
  13001. std::int64_t heard;
  13002. juce::MidiMessage message;
  13003. };
  13004. struct Pass
  13005. {
  13006. std::vector<float> out;
  13007. std::vector<Event> events;
  13008. std::int64_t playingAt = -1; // the first sample of the block the song started in
  13009. int block = 0, blocks = 0;
  13010. std::function<void()> done;
  13011. };
  13012. constexpr int n = 512;
  13013. constexpr double rate = 48000.0;
  13014. // one pass: the take recorded from bar 3, `blocks` blocks driven by hand, 8 at a time between the engine's timer
  13015. // ticks (the take is committed there); then stopped and its results left to the timer
  13016. auto runPass = std::make_shared<std::function<void (std::shared_ptr<Pass>)>>();
  13017. *runPass = [this] (std::shared_ptr<Pass> pass) {
  13018. auto& cb = engine->deviceCallback();
  13019. std::vector<float> l (n), r (n);
  13020. float* outs[] = { l.data(), r.data() };
  13021. juce::AudioIODeviceCallbackContext context;
  13022. if (pass->block == 0)
  13023. {
  13024. engine->stop();
  13025. engine->seek ((double) (2 * bar));
  13026. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, n, context); // (the seek, stopped)
  13027. engine->setRecording (true);
  13028. engine->startPlayback(); // the count-in starts
  13029. }
  13030. for (int k = 0; k < 8 && pass->block < pass->blocks; ++k, ++pass->block)
  13031. {
  13032. // the events heard in this block: stamped the way the engine's clock maps time to heard samples
  13033. const auto blockStart = (std::int64_t) pass->block * n;
  13034. const auto clock = engine->liveClock();
  13035. const auto compMs = 1000.0 * (n + 256) / rate;
  13036. for (auto& e : pass->events)
  13037. if (e.heard >= blockStart && e.heard < blockStart + n)
  13038. {
  13039. auto m = e.message;
  13040. m.setTimeStamp ((clock.timeMs + compMs + (double) (e.heard - blockStart) * 1000.0 / rate) * 0.001);
  13041. engine->injectMidiInput (m);
  13042. }
  13043. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, n, context);
  13044. pass->out.insert (pass->out.end(), l.begin(), l.end());
  13045. if (pass->playingAt < 0 && engine->getTransport().playing.load())
  13046. pass->playingAt = blockStart;
  13047. }
  13048. };
  13049. // (the recursion through the message loop; written out so each step lets the engine's timer run)
  13050. auto drive = std::make_shared<std::function<void (std::shared_ptr<Pass>)>>();
  13051. *drive = [this, runPass, drive, device] (std::shared_ptr<Pass> pass) { // (the stand-in lives while the passes run)
  13052. if (engine == nullptr)
  13053. return;
  13054. (*runPass) (pass);
  13055. if (pass->block < pass->blocks)
  13056. {
  13057. juce::Timer::callAfterDelay (40, [pass, drive] { (*drive) (pass); });
  13058. return;
  13059. }
  13060. engine->stop();
  13061. juce::Timer::callAfterDelay (300, [this, pass] {
  13062. if (engine == nullptr)
  13063. return;
  13064. engine->setRecording (false);
  13065. juce::Timer::callAfterDelay (200, [pass] { pass->done(); });
  13066. });
  13067. };
  13068. auto onsets = [] (const std::vector<float>& out) {
  13069. std::vector<std::int64_t> at;
  13070. std::int64_t last = -100000;
  13071. for (std::size_t i = 0; i < out.size(); ++i)
  13072. if (std::abs (out[i]) > 0.02f && (std::int64_t) i - last > 4000)
  13073. {
  13074. at.push_back ((std::int64_t) i);
  13075. last = (std::int64_t) i;
  13076. }
  13077. else if (std::abs (out[i]) > 0.02f)
  13078. last = (std::int64_t) i;
  13079. return at;
  13080. };
  13081. // the graph is (re)built on the message thread: start once it has settled
  13082. juce::Timer::callAfterDelay (1500, [this, step, finish, drive, onsets] {
  13083. if (engine == nullptr)
  13084. return;
  13085. auto first = std::make_shared<Pass>();
  13086. first->blocks = (int) (rate * 18.0 / n); // count-in + 8 bars
  13087. first->done = [this, first, step, finish, drive, onsets] {
  13088. const auto clicks = onsets (first->out);
  13089. juce::String list;
  13090. for (std::size_t i = 0; i < std::min<std::size_t> (clicks.size(), 8); ++i)
  13091. list << clicks[i] << " ";
  13092. step ("pass 1: clicks heard at samples " + list + "…, the song started in the block at " + juce::String (first->playingAt));
  13093. // the bar-3 downbeat: the click at the block the song started in
  13094. std::int64_t down = -1;
  13095. for (auto c : clicks)
  13096. if (std::abs (c - first->playingAt) < n)
  13097. down = c;
  13098. if (down < 0 || engine->getSong().patterns[0].notes.size() != 0)
  13099. {
  13100. step ("result=FAILED no downbeat click found (or notes recorded without input)");
  13101. finish (1);
  13102. return;
  13103. }
  13104. const auto ms = [down] (double t) { return down + (std::int64_t) std::llround (t * rate / 1000.0); };
  13105. auto second = std::make_shared<Pass>();
  13106. second->blocks = first->blocks;
  13107. auto add = [&second] (std::int64_t at, int key, bool on) {
  13108. second->events.push_back ({ at, on ? juce::MidiMessage::noteOn (1, key, (juce::uint8) 100) : juce::MidiMessage::noteOff (1, key) });
  13109. };
  13110. for (int key : { 60, 64, 67 }) // the chord, 15 ms early, held half a second
  13111. {
  13112. add (ms (-15.0), key, true);
  13113. add (ms (500.0), key, false);
  13114. }
  13115. add (ms (-1500.0), 62, true); // beat 2 of the count-in bar (bar 2)
  13116. add (ms (-1250.0), 62, false);
  13117. add (ms (503.0), 77, true); // 3 ms after beat 2
  13118. add (ms (603.0), 77, false);
  13119. for (int b = 1; b <= 6; ++b) // a note a bar ("it stopped after two bars")
  13120. {
  13121. add (ms (b * 2000.0), 70 + b, true);
  13122. add (ms (b * 2000.0 + 250.0), 70 + b, false);
  13123. }
  13124. second->done = [this, step, finish] {
  13125. const auto& s = engine->getSong();
  13126. const auto& p = s.patterns[0];
  13127. const lynx::Clip* clip = nullptr;
  13128. for (const auto& c : s.playlist)
  13129. if (c.kind == lynx::ClipKind::pattern && c.pattern == 0)
  13130. clip = &c;
  13131. const auto origin = clip != nullptr ? clip->start - clip->offset : -1;
  13132. step ("pass 2: " + juce::String ((int) p.notes.size()) + " notes recorded, clip at " + juce::String (clip != nullptr ? clip->start : -1));
  13133. auto ok = clip != nullptr && origin == bar && p.notes.size() == 11;
  13134. // where each one was heard (song ticks): 0.5 ms = ~1 tick
  13135. const std::vector<std::pair<int, double>> want = { { 60, 2.0 * bar }, { 64, 2.0 * bar }, { 67, 2.0 * bar },
  13136. { 62, 2.0 * bar - 3 * lynx::ppq }, { 77, 2.0 * bar + lynx::ppq + 3.0 * 1.92 },
  13137. { 71, 3.0 * bar }, { 72, 4.0 * bar }, { 73, 5.0 * bar },
  13138. { 74, 6.0 * bar }, { 75, 7.0 * bar }, { 76, 8.0 * bar } };
  13139. for (const auto& [key, tick] : want)
  13140. {
  13141. const lynx::Note* found = nullptr;
  13142. for (const auto& note : p.notes)
  13143. if (note.key == key)
  13144. found = &note;
  13145. const auto at = found != nullptr ? (double) (origin + found->start) : -1.0;
  13146. const auto good = found != nullptr && std::abs (at - tick) <= 2.0;
  13147. ok = ok && good;
  13148. step ("key " + juce::String (key) + ": heard at tick " + juce::String (tick, 2) + ", recorded at " + juce::String (at, 0)
  13149. + (good ? " ok" : " WRONG"));
  13150. }
  13151. const auto* chord = [&p] () -> const lynx::Note* {
  13152. for (const auto& note : p.notes)
  13153. if (note.key == 60)
  13154. return &note;
  13155. return nullptr;
  13156. }();
  13157. if (chord != nullptr)
  13158. step ("chord length " + juce::String (chord->length) + " ticks (caught 15 ms early, released 500 ms after bar 3: 960)");
  13159. step (ok ? "result=OK" : "result=FAILED");
  13160. finish (ok ? 0 : 1);
  13161. };
  13162. (*drive) (second);
  13163. };
  13164. (*drive) (first);
  13165. });
  13166. }
  13167. // --cliplooptest (round 167q): see the command line above.
  13168. // --slicexedittest (round 190aj): see the command line above
  13169. void runDirectWaveEditTest (const juce::String& project, const juce::File& script, const juce::File& report, const juce::String& prefix)
  13170. {
  13171. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  13172. juce::StringArray lines;
  13173. {
  13174. lynx::AudioEngine offline (false);
  13175. lynx::MainComponent ui (offline, false);
  13176. ui.setSize (1280, 720);
  13177. if (project == "new")
  13178. {
  13179. if (auto c = lynx::natives::makeChannel (lynx::InstrumentKind::directwave, {}))
  13180. offline.editSong ([c] (lynx::Song& s) { s.channels.push_back (*c); });
  13181. }
  13182. else
  13183. ui.openFile (juce::File (project));
  13184. offline.dispatchPendingMessages();
  13185. int channel = -1;
  13186. for (int c = 0; c < (int) offline.getSong().channels.size() && channel < 0; ++c)
  13187. if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::directwave)
  13188. channel = c;
  13189. if (channel < 0)
  13190. lines.add ("no DirectWave channel in " + project);
  13191. else
  13192. {
  13193. auto panel = lynx::makeChannelSettingsPanel (offline, channel);
  13194. juce::Component frame;
  13195. frame.setSize (panel->getWidth(), panel->getHeight());
  13196. frame.setOpaque (true);
  13197. frame.addAndMakeVisible (*panel);
  13198. panel->setTopLeftPosition (0, 0);
  13199. offline.dispatchPendingMessages();
  13200. juce::StringArray commands;
  13201. script.readLines (commands);
  13202. for (const auto& raw : commands)
  13203. {
  13204. const auto command = raw.trim();
  13205. if (command.isEmpty() || command.startsWith ("#"))
  13206. {
  13207. lines.add (command);
  13208. continue;
  13209. }
  13210. if (command.startsWith ("shot "))
  13211. {
  13212. frame.setSize (panel->getWidth(), panel->getHeight());
  13213. // (round 190jd: at the shot scale, --shot-scale / LYNX_SHOT_SCALE, with its suffix; scale 1 = the same pixels)
  13214. const auto image = lynx::shot::paint (frame, lynx::theme::panel);
  13215. const auto file = lynx::shot::file (juce::File (prefix + command.fromFirstOccurrenceOf (" ", false, false).trim() + ".png"));
  13216. file.deleteFile();
  13217. juce::PNGImageFormat png;
  13218. if (auto out = file.createOutputStream())
  13219. png.writeImageToStream (image, *out);
  13220. lines.add (command + " -> " + file.getFileName());
  13221. continue;
  13222. }
  13223. if (command.startsWith ("savestate "))
  13224. {
  13225. const auto& st = offline.getSong().channels[(std::size_t) channel].pluginState;
  13226. juce::File (command.fromFirstOccurrenceOf (" ", false, false).trim()).replaceWithData (st.data(), st.size());
  13227. lines.add (command + " -> " + juce::String ((int) st.size()) + " bytes");
  13228. continue;
  13229. }
  13230. const auto result = lynx::directWaveEditorTest (*panel, command);
  13231. offline.dispatchPendingMessages();
  13232. lines.add (command + " -> " + result);
  13233. }
  13234. }
  13235. }
  13236. report.replaceWithText (lines.joinIntoString ("\n") + "\nresult=DONE\n");
  13237. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  13238. quit();
  13239. }
  13240. void runSlicexEditTest (const juce::File& project, const juce::File& script, const juce::File& report, const juce::String& prefix)
  13241. {
  13242. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  13243. juce::StringArray lines;
  13244. {
  13245. lynx::AudioEngine offline (false);
  13246. lynx::MainComponent ui (offline, false);
  13247. ui.setSize (1280, 720);
  13248. ui.openFile (project);
  13249. offline.dispatchPendingMessages();
  13250. int channel = -1;
  13251. for (int c = 0; c < (int) offline.getSong().channels.size() && channel < 0; ++c)
  13252. if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::slicex)
  13253. channel = c;
  13254. if (channel < 0)
  13255. lines.add ("no Slicex channel in " + project.getFullPathName());
  13256. else
  13257. {
  13258. auto panel = lynx::makeChannelSettingsPanel (offline, channel);
  13259. juce::Component frame;
  13260. frame.setSize (panel->getWidth(), panel->getHeight());
  13261. frame.setOpaque (true);
  13262. frame.addAndMakeVisible (*panel);
  13263. panel->setTopLeftPosition (0, 0);
  13264. offline.dispatchPendingMessages();
  13265. juce::StringArray commands;
  13266. script.readLines (commands);
  13267. for (const auto& raw : commands)
  13268. {
  13269. const auto command = raw.trim();
  13270. if (command.isEmpty() || command.startsWith ("#"))
  13271. {
  13272. lines.add (command);
  13273. continue;
  13274. }
  13275. if (command.startsWith ("shot "))
  13276. {
  13277. frame.setSize (panel->getWidth(), panel->getHeight()); // (round 190hg: the display modes resize the editor)
  13278. // (round 190jd: at the shot scale, --shot-scale / LYNX_SHOT_SCALE, with its suffix; scale 1 = the same pixels)
  13279. const auto image = lynx::shot::paint (frame, lynx::theme::panel);
  13280. const auto file = lynx::shot::file (juce::File (prefix + command.fromFirstOccurrenceOf (" ", false, false).trim() + ".png"));
  13281. file.deleteFile();
  13282. juce::PNGImageFormat png;
  13283. if (auto out = file.createOutputStream())
  13284. png.writeImageToStream (image, *out);
  13285. lines.add (command + " -> " + file.getFileName());
  13286. continue;
  13287. }
  13288. if (command.startsWith ("menushot ")) // round 190jd: the deck's Snap menu as a picture
  13289. {
  13290. const auto file = prefix + command.fromFirstOccurrenceOf (" ", false, false).trim() + ".png";
  13291. saveMenus (juce::StringArray { "Slicex deck: Snap" }, std::vector<juce::PopupMenu> { lynx::slicexSnapMenuForSnapshot (*panel) }, file);
  13292. lines.add (command + " -> " + juce::File (file).getFileName());
  13293. continue;
  13294. }
  13295. const auto result = lynx::slicexEditorTest (*panel, command);
  13296. offline.dispatchPendingMessages();
  13297. lines.add (command + " -> " + result);
  13298. }
  13299. }
  13300. }
  13301. report.replaceWithText (lines.joinIntoString ("\n") + "\nresult=DONE\n");
  13302. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  13303. quit();
  13304. }
  13305. // --slicexkeytest (round 190ac): see the command line above
  13306. void runSlicexKeyTest (const juce::File& report)
  13307. {
  13308. engine = std::make_unique<lynx::AudioEngine>();
  13309. engine->getDeviceManager().closeAudioDevice(); // the engine's callback is driven by hand below
  13310. struct StandIn final : juce::AudioIODevice
  13311. {
  13312. StandIn() : juce::AudioIODevice ("slicexkey", "test") {}
  13313. juce::StringArray getOutputChannelNames() override { return { "L", "R" }; }
  13314. juce::StringArray getInputChannelNames() override { return {}; }
  13315. juce::Array<double> getAvailableSampleRates() override { return { 48000.0 }; }
  13316. juce::Array<int> getAvailableBufferSizes() override { return { 512 }; }
  13317. int getDefaultBufferSize() override { return 512; }
  13318. juce::String open (const juce::BigInteger&, const juce::BigInteger&, double, int) override { return {}; }
  13319. void close() override {}
  13320. bool isOpen() override { return true; }
  13321. void start (juce::AudioIODeviceCallback*) override {}
  13322. void stop() override {}
  13323. bool isPlaying() override { return true; }
  13324. juce::String getLastError() override { return {}; }
  13325. int getCurrentBufferSizeSamples() override { return 512; }
  13326. double getCurrentSampleRate() override { return 48000.0; }
  13327. int getCurrentBitDepth() override { return 32; }
  13328. juce::BigInteger getActiveOutputChannels() const override
  13329. {
  13330. juce::BigInteger b;
  13331. b.setRange (0, 2, true);
  13332. return b;
  13333. }
  13334. juce::BigInteger getActiveInputChannels() const override { return {}; }
  13335. int getOutputLatencyInSamples() override { return 0; }
  13336. int getInputLatencyInSamples() override { return 0; }
  13337. };
  13338. auto device = std::make_shared<StandIn>();
  13339. auto text = std::make_shared<juce::String>();
  13340. auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
  13341. // 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
  13342. // × region number), so the region a key played can be read from the output
  13343. constexpr int rate = 48000, regionFrames = rate / 4;
  13344. const auto wavFile = report.getSiblingFile ("slicexkey-deck.wav");
  13345. {
  13346. juce::MemoryOutputStream w;
  13347. auto chunk = [&w] (const char* id, const juce::MemoryBlock& body) {
  13348. w.write (id, 4);
  13349. w.writeInt ((int) body.getSize());
  13350. w.write (body.getData(), body.getSize());
  13351. };
  13352. juce::MemoryOutputStream fmt, data, cue;
  13353. fmt.writeShort (1);
  13354. fmt.writeShort (1);
  13355. fmt.writeInt (rate);
  13356. fmt.writeInt (rate * 2);
  13357. fmt.writeShort (2);
  13358. fmt.writeShort (16);
  13359. for (int i = 0; i < 4 * regionFrames; ++i)
  13360. data.writeShort ((short) std::lround (12000.0 * std::sin (juce::MathConstants<double>::twoPi * 200.0 * (double) (i / regionFrames + 1) * (double) i / rate)));
  13361. cue.writeInt (4);
  13362. for (int k = 0; k < 4; ++k)
  13363. {
  13364. cue.writeInt (k + 1);
  13365. cue.writeInt (k * regionFrames);
  13366. cue.write ("data", 4);
  13367. cue.writeInt (0);
  13368. cue.writeInt (0);
  13369. cue.writeInt (k * regionFrames);
  13370. }
  13371. juce::MemoryOutputStream riff;
  13372. riff.write ("WAVE", 4);
  13373. w.reset();
  13374. chunk ("fmt ", fmt.getMemoryBlock());
  13375. chunk ("data", data.getMemoryBlock());
  13376. chunk ("cue ", cue.getMemoryBlock());
  13377. riff.write (w.getData(), w.getDataSize());
  13378. juce::MemoryOutputStream file;
  13379. file.write ("RIFF", 4);
  13380. file.writeInt ((int) riff.getDataSize());
  13381. file.write (riff.getData(), riff.getDataSize());
  13382. wavFile.replaceWithData (file.getData(), file.getDataSize());
  13383. }
  13384. lynx::Song song;
  13385. song.bpm = 120.0;
  13386. song.mixer = lynx::Song::defaultMixer (2);
  13387. song.channels.resize (1);
  13388. auto& channel = song.channels[0];
  13389. channel.instrument = lynx::InstrumentKind::slicex;
  13390. channel.mixerTrack = 1;
  13391. channel.samplePath = wavFile.getFullPathName().toStdString();
  13392. {
  13393. auto state = lynx::slicex::fresh();
  13394. lynx::slicex::setDeckFile (state, 0, channel.samplePath, 4);
  13395. lynx::slicex::setDeckBeats (state, 0, 0.0, 2.0);
  13396. channel.pluginState = lynx::slicex::write (state);
  13397. }
  13398. song.patterns.emplace_back();
  13399. engine->setSong (song);
  13400. auto& callback = engine->deviceCallback();
  13401. callback.audioDeviceAboutToStart (device.get());
  13402. 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");
  13403. juce::Timer::callAfterDelay (2000, [this, device, step] {
  13404. if (engine == nullptr)
  13405. return;
  13406. auto& cb = engine->deviceCallback();
  13407. auto pump = [&cb] (int blocks) {
  13408. std::vector<float> l (512), r (512), out;
  13409. float* outs[] = { l.data(), r.data() };
  13410. juce::AudioIODeviceCallbackContext context;
  13411. for (int k = 0; k < blocks; ++k)
  13412. {
  13413. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, 512, context);
  13414. out.insert (out.end(), l.begin(), l.end());
  13415. }
  13416. return out;
  13417. };
  13418. auto rms = [] (const std::vector<float>& x, int from, int count) {
  13419. double sum = 0.0;
  13420. for (int i = from; i < from + count && i < (int) x.size(); ++i)
  13421. sum += (double) x[(std::size_t) i] * x[(std::size_t) i];
  13422. return std::sqrt (sum / juce::jmax (1, count));
  13423. };
  13424. // the tone's frequency from its rising zero crossings over a stretch
  13425. auto hertz = [] (const std::vector<float>& x, int from, int count) {
  13426. int crossings = 0, first = -1, last = -1;
  13427. for (int i = from + 1; i < from + count && i < (int) x.size(); ++i)
  13428. if (x[(std::size_t) i - 1] < 0.0f && x[(std::size_t) i] >= 0.0f)
  13429. {
  13430. first = first < 0 ? i : first;
  13431. last = i;
  13432. ++crossings;
  13433. }
  13434. return crossings > 1 ? 48000.0 * (double) (crossings - 1) / (double) (last - first) : 0.0;
  13435. };
  13436. bool ok = true;
  13437. auto check = [&ok, step] (bool good, const juce::String& what) {
  13438. ok = ok && good;
  13439. step ((good ? "ok " : "FAIL ") + what);
  13440. };
  13441. const auto idle = pump (20);
  13442. engine->getMeters().takePeak (1, 0);
  13443. check (rms (idle, 0, (int) idle.size()) < 1.0e-6, "idle: rms " + juce::String (rms (idle, 0, (int) idle.size()), 9));
  13444. // 4 regions map to keys 60…63 (FL's automatic map); the editor's click: velocity 100 / 128
  13445. engine->sendLiveNote (0, 60, 0.78125f, true);
  13446. const auto first = pump (16); // 8192 frames = 171 ms, inside region 1 (250 ms)
  13447. const auto meter = engine->getMeters().takePeak (1, 0);
  13448. 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");
  13449. check (std::abs (hertz (first, 1024, 6000) - 200.0) < 4.0, "key 60 plays region 1 (200 Hz)");
  13450. check (meter > 0.01f, "mixer track 1 meter peak " + juce::String (meter, 6));
  13451. engine->sendLiveNote (0, 60, 0.0f, false);
  13452. const auto tail = pump (60);
  13453. 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));
  13454. engine->sendLiveNote (0, 62, 0.78125f, true);
  13455. const auto third = pump (16);
  13456. check (rms (third, 1024, 6000) > 0.01 && std::abs (hertz (third, 1024, 6000) - 600.0) < 8.0,
  13457. "key 62 plays region 3 (600 Hz): rms " + juce::String (rms (third, 1024, 6000), 6) + ", " + juce::String (hertz (third, 1024, 6000), 1) + " Hz");
  13458. engine->sendLiveNote (0, 62, 0.0f, false);
  13459. engine->sendLiveNote (0, 72, 0.78125f, true); // a key without a region
  13460. const auto none = pump (60);
  13461. 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));
  13462. engine->sendLiveNote (0, 72, 0.0f, false);
  13463. step (ok ? "result=OK" : "result=FAILED");
  13464. setApplicationReturnValue (ok ? 0 : 1);
  13465. quit();
  13466. });
  13467. }
  13468. // --renderaheadtest (round 190gq): see the command line above
  13469. void runRenderAheadTest (const juce::File& report, const juce::StringArray& projects, int block, double seconds)
  13470. {
  13471. struct StandIn final : juce::AudioIODevice
  13472. {
  13473. explicit StandIn (int b) : juce::AudioIODevice ("renderahead", "test"), block (b) {}
  13474. const int block;
  13475. juce::StringArray getOutputChannelNames() override { return { "L", "R" }; }
  13476. juce::StringArray getInputChannelNames() override { return {}; }
  13477. juce::Array<double> getAvailableSampleRates() override { return { 48000.0 }; }
  13478. juce::Array<int> getAvailableBufferSizes() override { return { block }; }
  13479. int getDefaultBufferSize() override { return block; }
  13480. juce::String open (const juce::BigInteger&, const juce::BigInteger&, double, int) override { return {}; }
  13481. void close() override {}
  13482. bool isOpen() override { return true; }
  13483. void start (juce::AudioIODeviceCallback*) override {}
  13484. void stop() override {}
  13485. bool isPlaying() override { return true; }
  13486. juce::String getLastError() override { return {}; }
  13487. int getCurrentBufferSizeSamples() override { return block; }
  13488. double getCurrentSampleRate() override { return 48000.0; }
  13489. int getCurrentBitDepth() override { return 32; }
  13490. juce::BigInteger getActiveOutputChannels() const override
  13491. {
  13492. juce::BigInteger b;
  13493. b.setRange (0, 2, true);
  13494. return b;
  13495. }
  13496. juce::BigInteger getActiveInputChannels() const override { return {}; }
  13497. int getOutputLatencyInSamples() override { return 0; }
  13498. int getInputLatencyInSamples() override { return 0; }
  13499. };
  13500. struct Scenario
  13501. {
  13502. juce::String name;
  13503. juce::File file; // a project, or none: the showcase song
  13504. int mode = 0; // 0 Song mode from the start, 1 a loop region, 2 Pattern mode
  13505. };
  13506. auto scenarios = std::make_shared<std::vector<Scenario>>();
  13507. scenarios->push_back ({ "showcase, Song mode", {}, 0 });
  13508. scenarios->push_back ({ "showcase, a loop region wrapping mid-block", {}, 1 });
  13509. scenarios->push_back ({ "showcase, Pattern mode", {}, 2 });
  13510. for (const auto& p : projects)
  13511. scenarios->push_back ({ juce::File (p).getFileName(), juce::File (p), 0 });
  13512. auto text = std::make_shared<juce::String>();
  13513. auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
  13514. step ("render-ahead test: blocks of " + juce::String (block) + " at 48 kHz, " + juce::String (seconds, 1) + " s per run");
  13515. auto outputs = std::make_shared<std::vector<std::vector<float>>>();
  13516. auto ok = std::make_shared<bool> (true);
  13517. auto run = std::make_shared<std::function<void (std::size_t, int)>>();
  13518. *run = [this, scenarios, step, outputs, ok, run, block, seconds, report] (std::size_t index, int pass) {
  13519. if (index >= scenarios->size())
  13520. {
  13521. lynx::renderAheadOption().store (true);
  13522. step (juce::String ("result=") + (*ok ? "OK" : "FAIL"));
  13523. setApplicationReturnValue (*ok ? 0 : 1);
  13524. engine.reset();
  13525. quit();
  13526. return;
  13527. }
  13528. const auto& sc = (*scenarios)[index];
  13529. lynx::renderAheadOption().store (pass == 1);
  13530. engine = std::make_unique<lynx::AudioEngine>();
  13531. engine->getDeviceManager().closeAudioDevice(); // the engine's callback is driven by hand below
  13532. engine->setRenderAheadAlways (true); // (the showcase song is light: the app would leave it real-time)
  13533. juce::String error;
  13534. auto loaded = true;
  13535. if (sc.file == juce::File())
  13536. {
  13537. auto song = lynx::makeShowcaseSong (0);
  13538. if (sc.mode == 1)
  13539. {
  13540. song.loopStart = 4 * lynx::ppq * song.beatsPerBar + 37; // (not on a block boundary)
  13541. song.loopEnd = 6 * lynx::ppq * song.beatsPerBar + 211;
  13542. song.loopOff = false;
  13543. }
  13544. if (sc.mode == 2)
  13545. song.mode = lynx::PlayMode::pattern;
  13546. engine->setSong (std::move (song));
  13547. }
  13548. else if (sc.file.hasFileExtension ("flp"))
  13549. loaded = engine->importFlpFile (sc.file, error);
  13550. else if (auto song = lynx::ProjectFile::load (sc.file, error))
  13551. engine->setSong (std::move (*song));
  13552. else
  13553. loaded = false;
  13554. if (! loaded)
  13555. {
  13556. step ("FAIL " + sc.name + ": " + error);
  13557. *ok = false;
  13558. (*run) (index + 1, 0);
  13559. return;
  13560. }
  13561. auto device = std::make_shared<StandIn> (block);
  13562. engine->deviceCallback().audioDeviceAboutToStart (device.get());
  13563. // the graph is (re)built on the message thread: the run starts once it has settled
  13564. juce::Timer::callAfterDelay (1500, [this, scenarios, step, outputs, ok, run, block, seconds, index, pass, device] {
  13565. if (engine == nullptr)
  13566. return;
  13567. const auto& sc = (*scenarios)[index];
  13568. auto& cb = engine->deviceCallback();
  13569. std::vector<float> l ((std::size_t) block), r ((std::size_t) block), out;
  13570. float* outs[] = { l.data(), r.data() };
  13571. juce::AudioIODeviceCallbackContext context;
  13572. engine->stop();
  13573. engine->seek (0.0);
  13574. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, block, context); // (the seek, stopped)
  13575. engine->play();
  13576. const auto blocks = (int) (seconds * 48000.0 / block);
  13577. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  13578. for (int k = 0; k < blocks; ++k)
  13579. {
  13580. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, block, context);
  13581. out.insert (out.end(), l.begin(), l.end());
  13582. out.insert (out.end(), r.begin(), r.end());
  13583. // (about the device's pace at the start of each second, so the render-ahead thread gets ahead)
  13584. if (k % (48000 / block) < 48000 / block / 2)
  13585. std::this_thread::sleep_for (std::chrono::microseconds ((int) (block * 1.0e6 / 48000.0 * 0.6)));
  13586. }
  13587. const auto ms = juce::Time::getMillisecondCounterHiRes() - t0;
  13588. engine->stop();
  13589. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, block, context);
  13590. const auto* st = engine->renderAheadStats();
  13591. auto n = [] (const std::atomic<std::uint64_t>& v) { return (juce::int64) v.load(); };
  13592. juce::String line = sc.name + (pass == 1 ? ", render ahead on: " : ", render ahead off: ") + juce::String (ms / 1000.0, 1) + " s";
  13593. if (st != nullptr && pass == 1)
  13594. line << "; blocks " << n (st->blocks) << ", from the ring " << n (st->fromRing) << ", waited " << n (st->waited) << ", in the callback "
  13595. << n (st->inline_) << ", dropped " << n (st->flushes) << ", drained " << n (st->drains) << ", started " << n (st->engagements)
  13596. << ", boundary mismatches " << n (st->splitMismatches) << "; ahead " << st->aheadChannels.load() << " channels / "
  13597. << st->aheadTracks.load() << " inserts, boundary " << st->boundary.load() << ", window " << st->window.load();
  13598. step (" " + line);
  13599. if (pass == 0)
  13600. {
  13601. outputs->assign (1, std::move (out));
  13602. (*run) (index, 1);
  13603. return;
  13604. }
  13605. const auto& off = outputs->front();
  13606. std::size_t first = off.size() == out.size() ? off.size() : 0;
  13607. for (std::size_t s = 0; s < std::min (off.size(), out.size()); ++s)
  13608. if (std::memcmp (&off[s], &out[s], sizeof (float)) != 0)
  13609. {
  13610. first = s;
  13611. break;
  13612. }
  13613. const auto same = off.size() == out.size() && first == off.size();
  13614. const auto clean = st != nullptr && st->flushes.load() == 0 && st->splitMismatches.load() == 0 && st->engagements.load() >= 1
  13615. && st->fromRing.load() > st->blocks.load() / 4;
  13616. *ok = *ok && same && clean;
  13617. 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))
  13618. + (clean ? "" : ", render-ahead counters off (see above)"));
  13619. (*run) (index + 1, 0);
  13620. });
  13621. };
  13622. (*run) (0, 0);
  13623. }
  13624. void runClipLoopTest (const juce::File& report, const juce::File& wavFile)
  13625. {
  13626. engine = std::make_unique<lynx::AudioEngine>();
  13627. engine->getDeviceManager().closeAudioDevice(); // the engine's callback is driven by hand below
  13628. struct StandIn final : juce::AudioIODevice
  13629. {
  13630. StandIn() : juce::AudioIODevice ("cliploop", "test") {}
  13631. juce::StringArray getOutputChannelNames() override { return { "L", "R" }; }
  13632. juce::StringArray getInputChannelNames() override { return {}; }
  13633. juce::Array<double> getAvailableSampleRates() override { return { 48000.0 }; }
  13634. juce::Array<int> getAvailableBufferSizes() override { return { 512 }; }
  13635. int getDefaultBufferSize() override { return 512; }
  13636. juce::String open (const juce::BigInteger&, const juce::BigInteger&, double, int) override { return {}; }
  13637. void close() override {}
  13638. bool isOpen() override { return true; }
  13639. void start (juce::AudioIODeviceCallback*) override {}
  13640. void stop() override {}
  13641. bool isPlaying() override { return true; }
  13642. juce::String getLastError() override { return {}; }
  13643. int getCurrentBufferSizeSamples() override { return 512; }
  13644. double getCurrentSampleRate() override { return 48000.0; }
  13645. int getCurrentBitDepth() override { return 32; }
  13646. juce::BigInteger getActiveOutputChannels() const override
  13647. {
  13648. juce::BigInteger b;
  13649. b.setRange (0, 2, true);
  13650. return b;
  13651. }
  13652. juce::BigInteger getActiveInputChannels() const override { return {}; }
  13653. int getOutputLatencyInSamples() override { return 0; }
  13654. int getInputLatencyInSamples() override { return 0; }
  13655. };
  13656. auto device = std::make_shared<StandIn>();
  13657. auto text = std::make_shared<juce::String>();
  13658. auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
  13659. constexpr int bar = 96000, beat = bar / 4; // 120 BPM, 48 kHz
  13660. const auto ppq = (double) lynx::ppq;
  13661. lynx::Song song;
  13662. song.bpm = 120.0;
  13663. song.mixer = lynx::Song::defaultMixer (2);
  13664. song.channels.resize (1); // the synth of a new channel: deterministic
  13665. song.channels[0].mixerTrack = 1;
  13666. auto& pattern = song.patterns.emplace_back(); // 1 bar: C5 on beat 0, C6 on beat 2
  13667. for (auto [b, key] : { std::pair { 0, 60 }, std::pair { 2, 72 } })
  13668. {
  13669. lynx::Note n;
  13670. n.start = b * lynx::ppq;
  13671. n.length = lynx::ppq / 4;
  13672. n.key = key;
  13673. pattern.notes.push_back (n);
  13674. }
  13675. lynx::Clip clip;
  13676. clip.pattern = 0;
  13677. clip.length = 16 * lynx::ppq; // stretched to 4 bars
  13678. song.playlist.push_back (clip);
  13679. song.mode = lynx::PlayMode::song;
  13680. {
  13681. // the Windows GUI check's project: the same song with a 1-bar clip, to stretch with the mouse
  13682. auto gui = song;
  13683. gui.playlist[0].length = 4 * lynx::ppq;
  13684. juce::String error;
  13685. lynx::ProjectFile::save (gui, report.getSiblingFile ("cliploop-gui.lynx"), error);
  13686. }
  13687. engine->setSong (song);
  13688. auto& callback = engine->deviceCallback();
  13689. callback.audioDeviceAboutToStart (device.get());
  13690. step ("song=1-bar synth pattern, clip stretched to 4 bars, 120 BPM, 48 kHz, blocks of 512");
  13691. // the graph is (re)built on the message thread: the scenarios run once it has settled
  13692. juce::Timer::callAfterDelay (1500, [this, device, step, wavFile, ppq] {
  13693. if (engine == nullptr)
  13694. return;
  13695. auto& cb = engine->deviceCallback();
  13696. // plays `samples` from tick `from` through the device callback; `between` runs after each block (block index)
  13697. auto play = [this, &cb] (double from, int samples, const std::function<void (int)>& between = {}) {
  13698. engine->stop();
  13699. engine->seek (from);
  13700. std::vector<float> l (512), r (512), out;
  13701. float* outs[] = { l.data(), r.data() };
  13702. juce::AudioIODeviceCallbackContext context;
  13703. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, 512, context); // (the seek, stopped)
  13704. engine->play();
  13705. for (int k = 0; (int) out.size() < samples; ++k)
  13706. {
  13707. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, 512, context);
  13708. out.insert (out.end(), l.begin(), l.end());
  13709. if (between)
  13710. between (k);
  13711. }
  13712. engine->stop();
  13713. for (int k = 0; k < 400; ++k) // the tails of the scenario die out
  13714. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, 512, context);
  13715. out.resize ((std::size_t) samples);
  13716. return out;
  13717. };
  13718. auto rms = [] (const std::vector<float>& x, int from, int count) {
  13719. double sum = 0.0;
  13720. for (int i = from; i < from + count && i < (int) x.size(); ++i)
  13721. sum += (double) x[(std::size_t) i] * x[(std::size_t) i];
  13722. return std::sqrt (sum / juce::jmax (1, count));
  13723. };
  13724. auto diff = [] (const std::vector<float>& a, int aFrom, const std::vector<float>& b, int bFrom, int count) {
  13725. double m = 0.0;
  13726. for (int i = 0; i < count && aFrom + i < (int) a.size() && bFrom + i < (int) b.size(); ++i)
  13727. m = juce::jmax (m, (double) std::abs (a[(std::size_t) (aFrom + i)] - b[(std::size_t) (bFrom + i)]));
  13728. return m;
  13729. };
  13730. auto num = [] (double v) { return juce::String (v, 6); };
  13731. bool ok = true;
  13732. auto check = [&ok, step] (bool good, const juce::String& what) {
  13733. ok = ok && good;
  13734. step ((good ? "ok " : "FAIL ") + what);
  13735. };
  13736. lynx::setStretchedClipsLoop (true);
  13737. const auto a = play (0.0, 4 * bar);
  13738. const auto bar1 = rms (a, 0, bar);
  13739. check (bar1 > 0.01, "play from the start: bar 1 RMS " + num (bar1));
  13740. for (int k = 1; k < 4; ++k)
  13741. {
  13742. const auto rk = rms (a, k * bar, bar), d = diff (a, k * bar, a, 0, bar);
  13743. check (std::abs (rk / bar1 - 1.0) < 1.0e-3 && d < 1.0e-4,
  13744. "bar " + juce::String (k + 1) + " RMS " + num (rk) + " (x" + num (rk / bar1) + " of bar 1), max |bar - bar 1| " + juce::String (d, 9));
  13745. }
  13746. {
  13747. const auto x = play (10 * ppq, bar + bar / 2);
  13748. const auto d = juce::jmax (diff (x, 0, a, 2 * beat, bar / 2), diff (x, bar / 2, a, 0, bar));
  13749. check (rms (x, 0, bar / 2) > 0.01 && d < 1.0e-4,
  13750. "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));
  13751. }
  13752. {
  13753. // a seek while playing, after 6.99 beats, to bar 4 beat 3 (a ruler click)
  13754. const auto jumpBlock = 7 * beat / 512 - 1;
  13755. const auto x = play (0.0, 2 * bar, [this, jumpBlock, ppq] (int k) {
  13756. if (k == jumpBlock)
  13757. engine->seek (14 * ppq);
  13758. });
  13759. // (the best of 0-2 samples late: anything but 0 fails)
  13760. const auto at = (jumpBlock + 1) * 512;
  13761. int lag = 0;
  13762. auto d = 1.0e9;
  13763. for (int l = 0; l <= 2; ++l)
  13764. if (const auto dl = diff (x, at + l, a, 2 * beat, beat - 2); dl < d)
  13765. d = dl, lag = l;
  13766. d = lag == 0 ? d : 1.0;
  13767. const auto ratio = rms (x, at, beat) / rms (a, 2 * beat, beat);
  13768. check (std::abs (ratio - 1.0) < 1.0e-3 && d < 1.0e-4,
  13769. "jump mid-clip to bar 4 beat 3: RMS " + num (rms (x, at, beat)) + " (x" + num (ratio) + " of bar 1 beat 3), max diff "
  13770. + juce::String (d, 9) + " (" + juce::String (lag) + " sample(s) late)");
  13771. }
  13772. {
  13773. engine->editSong ([ppq] (lynx::Song& s) {
  13774. s.loopStart = (std::int64_t) (4 * ppq);
  13775. s.loopEnd = (std::int64_t) (12 * ppq);
  13776. }, false);
  13777. const auto x = play (0.0, 7 * bar);
  13778. double d = 0.0;
  13779. juce::String lags;
  13780. for (int k = 1; k < 7; ++k) // (the best of 0-2 samples late after a wrap, as after a jump)
  13781. {
  13782. auto best = 1.0e9;
  13783. int lag = 0;
  13784. for (int l = 0; l <= 2; ++l)
  13785. if (const auto dl = diff (x, k * bar + l, a, 0, bar - 2); dl < best)
  13786. best = dl, lag = l;
  13787. d = juce::jmax (d, lag == 0 ? best : 1.0); // a sample gained at a wrap fails (round 167q loopwrap)
  13788. lags << (k > 1 ? "," : "") << lag;
  13789. }
  13790. const auto r = rms (x, bar, 6 * bar);
  13791. check (std::abs (r / bar1 - 1.0) < 1.0e-3 && d < 1.0e-4,
  13792. "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)
  13793. + " (samples late, bars 2-7: " + lags + ")");
  13794. engine->editSong ([] (lynx::Song& s) { s.loopStart = s.loopEnd = 0; }, false);
  13795. }
  13796. {
  13797. // 100 wraps of a 1-bar loop region (bar 2): every pass on its sample, none gained (round 167q loopwrap: each
  13798. // wrap used to play one sample more)
  13799. engine->editSong ([ppq] (lynx::Song& s) {
  13800. s.loopStart = (std::int64_t) (4 * ppq);
  13801. s.loopEnd = (std::int64_t) (8 * ppq);
  13802. }, false);
  13803. const auto x = play (0.0, 101 * bar);
  13804. double d = 0.0;
  13805. int worst = 0;
  13806. for (int k = 1; k <= 100; ++k)
  13807. if (const auto dk = diff (x, k * bar, a, 0, bar); dk > d)
  13808. d = dk, worst = k + 1;
  13809. check (d < 1.0e-4, "loop region bar 2, 100 wraps: max diff of every pass vs bar 1 " + juce::String (d, 9)
  13810. + (d < 1.0e-4 ? juce::String() : " (worst: bar " + juce::String (worst) + ")"));
  13811. engine->editSong ([] (lynx::Song& s) { s.loopStart = s.loopEnd = 0; }, false);
  13812. }
  13813. lynx::setStretchedClipsLoop (false);
  13814. {
  13815. const auto x = play (0.0, 4 * bar);
  13816. const auto r = juce::jmax (rms (x, bar, bar), juce::jmax (rms (x, 2 * bar, bar), rms (x, 3 * bar, bar)));
  13817. 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));
  13818. }
  13819. lynx::setStretchedClipsLoop (true);
  13820. cb.audioDeviceStopped();
  13821. // the export: a WAV of the 4 bars, read back from the file
  13822. if (wavFile != juce::File())
  13823. {
  13824. for (const auto loops : { true, false })
  13825. {
  13826. lynx::setStretchedClipsLoop (loops);
  13827. const auto file = loops ? wavFile : wavFile.getSiblingFile (wavFile.getFileNameWithoutExtension() + "-off.wav");
  13828. file.deleteFile();
  13829. {
  13830. juce::WavAudioFormat wav;
  13831. std::unique_ptr<juce::AudioFormatWriter> writer (wav.createWriterFor (file.createOutputStream().release(), 48000.0, 2, 32, {}, 0));
  13832. engine->stop();
  13833. engine->seek (0.0);
  13834. lynx::AudioEngine::RenderOptions o;
  13835. o.seconds = 8.0;
  13836. o.sampleRate = 48000.0;
  13837. o.output = writer.get();
  13838. engine->renderOffline (o);
  13839. }
  13840. juce::WavAudioFormat wav;
  13841. std::unique_ptr<juce::AudioFormatReader> reader (wav.createReaderFor (file.createInputStream().release(), true));
  13842. std::vector<float> x;
  13843. if (reader != nullptr)
  13844. {
  13845. juce::AudioBuffer<float> buffer (2, (int) reader->lengthInSamples);
  13846. reader->read (&buffer, 0, (int) reader->lengthInSamples, 0, true, true);
  13847. x.assign (buffer.getReadPointer (0), buffer.getReadPointer (0) + buffer.getNumSamples());
  13848. }
  13849. const auto b1 = rms (x, 0, bar);
  13850. juce::String line = juce::String (loops ? "export" : "export, option off") + " (" + file.getFileName() + ", " + juce::String ((int) x.size()) + " samples): bar 1 RMS " + num (b1);
  13851. bool good = x.size() >= (std::size_t) 4 * bar && b1 > 0.01;
  13852. for (int k = 1; k < 4; ++k)
  13853. {
  13854. const auto rk = rms (x, k * bar, bar);
  13855. line << ", bar " << (k + 1) << " " << num (rk);
  13856. 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);
  13857. }
  13858. if (loops)
  13859. 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);
  13860. check (good, line);
  13861. }
  13862. lynx::setStretchedClipsLoop (true);
  13863. }
  13864. step (ok ? "result=OK" : "result=FAILED");
  13865. setApplicationReturnValue (ok ? 0 : 1);
  13866. quit();
  13867. });
  13868. }
  13869. // --rectest (round 163): see the command line above. Writes report lines step by step (a driver that ends the
  13870. // process leaves what was done).
  13871. void runRecordTest (const juce::File& report, double seconds, const juce::String& deviceType, const juce::String& deviceName,
  13872. const juce::String& inputName, int mode, int pdcSamples, int bufferSize)
  13873. {
  13874. engine = std::make_unique<lynx::AudioEngine>();
  13875. lynx::videoview::install (*engine); // (Fruity Video Player channels: their sound tracks)
  13876. savedDeviceState = engine->getDeviceManager().createStateXml();
  13877. auto text = std::make_shared<juce::String>();
  13878. auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
  13879. auto finish = [this, step] (int code) {
  13880. restoreSavedDeviceState();
  13881. setApplicationReturnValue (code);
  13882. quit();
  13883. };
  13884. auto& devices = engine->getDeviceManager();
  13885. if (deviceType.isNotEmpty() && devices.getCurrentAudioDeviceType() != deviceType)
  13886. devices.setCurrentAudioDeviceType (deviceType, true);
  13887. {
  13888. auto setup = devices.getAudioDeviceSetup();
  13889. if (deviceName.isNotEmpty())
  13890. setup.outputDeviceName = deviceName;
  13891. if (bufferSize > 0)
  13892. setup.bufferSize = bufferSize;
  13893. if (const auto error = devices.setAudioDeviceSetup (setup, true); error.isNotEmpty())
  13894. step ("device_error=" + error);
  13895. }
  13896. if (const auto r = engine->openAudioInput (inputName.isNotEmpty() ? inputName : deviceName); r.issue != lynx::AudioEngine::InputIssue::none)
  13897. step ("input_error=" + juce::String ((int) r.issue) + " " + r.detail);
  13898. // takes go next to the report, not into the user's recordings folder
  13899. engine->setRecordingTarget (report.getSiblingFile (report.getFileNameWithoutExtension() + "-takes"), {});
  13900. auto* device = devices.getCurrentAudioDevice();
  13901. if (device == nullptr || engine->getInputChannelNames().empty())
  13902. {
  13903. step ("result=ERROR no device / no input");
  13904. finish (1);
  13905. return;
  13906. }
  13907. const auto rate = device->getCurrentSampleRate();
  13908. step ("device=" + device->getTypeName() + " | " + device->getName() + " | " + juce::String (rate) + " Hz | block " + juce::String (device->getCurrentBufferSizeSamples())
  13909. + " | driver latency in " + juce::String (device->getInputLatencyInSamples()) + " out " + juce::String (device->getOutputLatencyInSamples()));
  13910. // a click (the ping's pulse) on every beat at 120 bpm: beat k at sample k * rate / 2
  13911. const auto beats = (int) std::ceil (seconds * 2.0) + 8;
  13912. const auto clickFile = report.getSiblingFile (report.getFileNameWithoutExtension() + "-clicks.wav");
  13913. {
  13914. lynx::takes::WavTakeWriter w;
  13915. w.open (clickFile.getFullPathName().toStdString(), rate, 1, lynx::takes::SampleFormat::float32);
  13916. const auto total = (juce::int64) std::llround ((double) beats * rate / 2.0);
  13917. std::vector<float> block (4096);
  13918. for (juce::int64 at = 0; at < total; at += (juce::int64) block.size())
  13919. {
  13920. std::fill (block.begin(), block.end(), 0.0f);
  13921. for (int k = 0; k < (int) block.size(); ++k)
  13922. {
  13923. const auto f = at + k;
  13924. const auto beat = (juce::int64) std::floor ((double) f / (rate / 2.0));
  13925. const auto rel = f - (juce::int64) std::llround ((double) beat * rate / 2.0);
  13926. static constexpr float shape[] { 0.25f, 0.75f, 1.0f, 0.75f, 0.25f };
  13927. if (rel >= 0 && rel < 5)
  13928. block[(std::size_t) k] = 0.5f * shape[rel];
  13929. }
  13930. const float* d[] { block.data() };
  13931. w.write (d, (int) std::min<juce::int64> ((juce::int64) block.size(), total - at));
  13932. }
  13933. w.close();
  13934. }
  13935. lynx::Song song = lynx::Song::makeDefault();
  13936. song.bpm = 120.0;
  13937. song.mode = lynx::PlayMode::song;
  13938. song.playlist.clear();
  13939. lynx::ChannelDef c;
  13940. c.name = "Clicks";
  13941. c.instrument = lynx::InstrumentKind::audioClip;
  13942. c.samplePath = clickFile.getFullPathName().toStdString();
  13943. c.mixerTrack = 0;
  13944. c.volume = 1.0f;
  13945. song.channels.push_back (c);
  13946. lynx::Clip clip;
  13947. clip.kind = lynx::ClipKind::audio;
  13948. clip.channel = (int) song.channels.size() - 1;
  13949. clip.track = 0;
  13950. clip.start = 0;
  13951. clip.length = (std::int64_t) beats * lynx::ppq;
  13952. song.playlist.push_back (clip);
  13953. if (mode == 1) // loop recording, bars 2-4
  13954. {
  13955. song.loopStart = 4 * lynx::ppq;
  13956. song.loopEnd = 16 * lynx::ppq;
  13957. }
  13958. else if (mode == 2) // punch in/out, bars 3-4
  13959. {
  13960. song.loopStart = 8 * lynx::ppq;
  13961. song.loopEnd = 16 * lynx::ppq;
  13962. }
  13963. if (song.mixer.size() > 1)
  13964. {
  13965. song.mixer[1].name = "Loop In";
  13966. song.mixer[1].monitor = lynx::InputMonitor::off; // (the loopback must not hear itself)
  13967. }
  13968. engine->setSong (std::move (song));
  13969. engine->setInsertInput (1, 0, false);
  13970. juce::ignoreUnused (pdcSamples);
  13971. // 1) the ping
  13972. if (const auto error = engine->startLatencyPing(); error.isNotEmpty())
  13973. step ("ping_error=" + error);
  13974. juce::Timer::callAfterDelay (3500, [this, step, finish, seconds, rate, report, mode] {
  13975. if (engine == nullptr)
  13976. return;
  13977. if (engine->isPinging())
  13978. engine->cancelLatencyPing();
  13979. const auto r = engine->finishLatencyPing();
  13980. step ("ping=" + juce::String (r.ok ? "ok" : "FAILED " + juce::String (r.problem)) + " samples " + juce::String (r.samples) + " spread " + juce::String (r.spread)
  13981. + " found " + juce::String (r.found) + "/" + juce::String (r.sent) + " peak " + juce::String (juce::Decibels::gainToDecibels (r.peak, -150.0f), 1) + " dB");
  13982. const auto l = engine->currentLatency();
  13983. step ("compensation=" + juce::String (l.total()) + " (round trip " + juce::String (l.roundTrip()) + ", manual " + juce::String (l.manual) + ", pdc " + juce::String (l.pdc) + ")");
  13984. // 2) record
  13985. engine->setInsertArmed (1, true);
  13986. auto o = engine->getRecordOptions();
  13987. o.recordAudio = true;
  13988. o.countInBars = 0;
  13989. o.waitForInput = false;
  13990. o.punchLoopRegion = mode == 2;
  13991. o.preRollBars = mode == 2 ? 1 : 0;
  13992. o.postRollBars = mode == 2 ? 1 : 0;
  13993. // (round 177c: LYNX_RECTEST_BLEND_OFF=1: Blend off; LYNX_RECTEST_LAST_PASS=1: "only the last pass plays")
  13994. o.mode = juce::SystemStats::getEnvironmentVariable ("LYNX_RECTEST_BLEND_OFF", {}) == "1" ? lynx::RecordMode::replace
  13995. : lynx::RecordMode::overdub;
  13996. o.lastLoopPassPlays = juce::SystemStats::getEnvironmentVariable ("LYNX_RECTEST_LAST_PASS", {}) == "1";
  13997. engine->setRecordOptions (o);
  13998. engine->stop();
  13999. engine->rewind();
  14000. engine->setRecording (true);
  14001. juce::Timer::callAfterDelay (300, [this, step, finish, seconds, rate, report, mode] {
  14002. if (engine == nullptr)
  14003. return;
  14004. engine->startPlayback(); // (as the Play button: pre-roll / punch)
  14005. juce::Timer::callAfterDelay ((int) (seconds * 1000.0), [this, step, finish, seconds, rate, report, mode] {
  14006. if (engine == nullptr)
  14007. return;
  14008. if (mode == 2)
  14009. step (juce::String ("stopped_by_post_roll=") + (engine->getTransport().playing.load() ? "no" : "yes"));
  14010. engine->stop();
  14011. juce::Timer::callAfterDelay (500, [this, step, finish, seconds, rate, report, mode] {
  14012. if (engine == nullptr)
  14013. return;
  14014. engine->setRecording (false);
  14015. const auto& s = engine->getSong();
  14016. const auto tps = 120.0 * lynx::ppq / (60.0 * rate);
  14017. int take = -1;
  14018. for (int ch = 0; ch < (int) s.channels.size(); ++ch)
  14019. if (s.channels[(std::size_t) ch].instrument == lynx::InstrumentKind::audioClip && s.channels[(std::size_t) ch].name != "Clicks")
  14020. take = ch;
  14021. if (take < 0)
  14022. {
  14023. step ("result=ERROR no take (" + engine->getLastRecordingError() + ")");
  14024. finish (1);
  14025. return;
  14026. }
  14027. std::vector<std::vector<float>> audio;
  14028. double takeRate = 0.0;
  14029. const auto& path = s.channels[(std::size_t) take].samplePath;
  14030. lynx::takes::readWav (path, audio, &takeRate);
  14031. const auto frames = audio.empty() ? (juce::int64) 0 : (juce::int64) audio[0].size();
  14032. step ("take=" + juce::String::fromUTF8 (path.c_str()) + " frames " + juce::String (frames) + " (" + juce::String ((double) frames / rate, 3)
  14033. + " s of " + juce::String (seconds, 1) + " s played) lost " + juce::String (engine->getLostRecordingFrames()));
  14034. // the clicks in the file (peaks above -12 dBFS, one per 1/8 s at most)
  14035. std::vector<juce::int64> peaks;
  14036. if (! audio.empty())
  14037. for (juce::int64 f = 1; f + 1 < frames; ++f)
  14038. {
  14039. const auto x = std::abs (audio[0][(std::size_t) f]);
  14040. if (x > 0.25f && x >= std::abs (audio[0][(std::size_t) f - 1]) && x > std::abs (audio[0][(std::size_t) f + 1])
  14041. && (peaks.empty() || f - peaks.back() > (juce::int64) (rate / 8)))
  14042. peaks.push_back (f);
  14043. }
  14044. // every clip of the take: each click inside it against the nearest beat
  14045. int clips = 0, checked = 0, muted = 0;
  14046. double worst = 0.0, sum = 0.0;
  14047. for (const auto& c : s.playlist)
  14048. {
  14049. if (c.kind != lynx::ClipKind::audio || c.channel != take)
  14050. continue;
  14051. ++clips;
  14052. muted += c.muted ? 1 : 0;
  14053. const auto skip = ((double) c.offset + (double) c.offsetFraction) / tps; // file samples before the clip start
  14054. for (const auto f : peaks)
  14055. {
  14056. const auto intoClip = (double) f - skip;
  14057. if (intoClip < 0.0 || intoClip * tps >= (double) c.length)
  14058. continue;
  14059. const auto songTick = (double) c.start + intoClip * tps - 2.0 * tps; // (the pulse's peak is its 3rd sample)
  14060. const auto beat = std::round (songTick / lynx::ppq) * lynx::ppq;
  14061. const auto error = (songTick - beat) / tps;
  14062. worst = std::max (worst, std::abs (error));
  14063. sum += error;
  14064. ++checked;
  14065. }
  14066. step ("clip track " + juce::String (c.track) + " start " + juce::String ((juce::int64) c.start) + " length " + juce::String ((juce::int64) c.length)
  14067. + " offset " + juce::String ((juce::int64) c.offset) + juce::String (c.offsetFraction >= 0.0f ? "+" : "") + juce::String (c.offsetFraction, 4)
  14068. + (c.muted ? " (muted lane)" : ""));
  14069. }
  14070. step ("clicks_in_file=" + juce::String ((int) peaks.size()) + " checked=" + juce::String (checked) + " clips=" + juce::String (clips)
  14071. + " muted_lanes=" + juce::String (muted));
  14072. step ("placement_error_samples=max " + juce::String (worst, 3) + " mean " + juce::String (checked > 0 ? sum / checked : 0.0, 3));
  14073. auto ok = checked > 0 && worst <= 1.0 && engine->getLostRecordingFrames() == 0;
  14074. if (mode == 2) // one clip, exactly the punch range, its 8 beats
  14075. {
  14076. const auto& sp = engine->getSong();
  14077. bool exact = false;
  14078. for (const auto& c : sp.playlist)
  14079. if (c.kind == lynx::ClipKind::audio && c.channel == take)
  14080. exact = c.start == sp.loopStart && c.start + c.length == sp.loopEnd;
  14081. step (juce::String ("punch_clip_matches_range=") + (exact ? "yes" : "no"));
  14082. ok = ok && clips == 1 && exact && checked == 8;
  14083. }
  14084. report.getSiblingFile (report.getFileNameWithoutExtension() + "-project.lynx").replaceWithText (lynx::ProjectFile::toJson (engine->getSong()));
  14085. step (juce::String ("result=") + (ok ? "OK" : "FAILED"));
  14086. finish (ok ? 0 : 1);
  14087. });
  14088. });
  14089. });
  14090. });
  14091. }
  14092. // --hwinserttest (round 164d): see the command line above.
  14093. void runHwInsertTest (const juce::File& report, double seconds, const juce::String& deviceType, const juce::String& deviceName,
  14094. const juce::String& inputName, int bufferSize, bool inPatcher = false, juce::File bounceFile = {})
  14095. {
  14096. engine = std::make_unique<lynx::AudioEngine>();
  14097. lynx::videoview::install (*engine); // (Fruity Video Player channels: their sound tracks)
  14098. savedDeviceState = engine->getDeviceManager().createStateXml();
  14099. auto text = std::make_shared<juce::String>();
  14100. auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
  14101. auto finish = [this] (int code) {
  14102. if (engine != nullptr)
  14103. engine->getMeters().capture.setSource (lynx::AudioCapture::off);
  14104. restoreSavedDeviceState();
  14105. setApplicationReturnValue (code);
  14106. quit();
  14107. };
  14108. auto& devices = engine->getDeviceManager();
  14109. if (deviceType.isNotEmpty() && devices.getCurrentAudioDeviceType() != deviceType)
  14110. devices.setCurrentAudioDeviceType (deviceType, true);
  14111. {
  14112. auto setup = devices.getAudioDeviceSetup();
  14113. if (deviceName.isNotEmpty())
  14114. setup.outputDeviceName = deviceName;
  14115. if (bufferSize > 0)
  14116. setup.bufferSize = bufferSize;
  14117. if (const auto error = devices.setAudioDeviceSetup (setup, true); error.isNotEmpty())
  14118. step ("device_error=" + error);
  14119. }
  14120. if (const auto r = engine->openAudioInput (inputName.isNotEmpty() ? inputName : deviceName); r.issue != lynx::AudioEngine::InputIssue::none)
  14121. step ("input_error=" + juce::String ((int) r.issue) + " " + r.detail);
  14122. auto* device = devices.getCurrentAudioDevice();
  14123. if (device == nullptr || engine->getInputChannelNames().empty())
  14124. {
  14125. step ("result=ERROR no device / no input");
  14126. finish (1);
  14127. return;
  14128. }
  14129. const auto rate = device->getCurrentSampleRate();
  14130. step ("device=" + device->getTypeName() + " | " + device->getName() + " | " + juce::String (rate) + " Hz | block " + juce::String (device->getCurrentBufferSizeSamples()));
  14131. // the click track: the ping's pulse on every beat at 120 bpm
  14132. const auto beats = (int) std::ceil (seconds * 2.0) + 8;
  14133. const auto clickFile = report.getSiblingFile (report.getFileNameWithoutExtension() + "-clicks.wav");
  14134. {
  14135. lynx::takes::WavTakeWriter w;
  14136. w.open (clickFile.getFullPathName().toStdString(), rate, 1, lynx::takes::SampleFormat::float32);
  14137. const auto total = (juce::int64) std::llround ((double) beats * rate / 2.0);
  14138. std::vector<float> block (4096);
  14139. for (juce::int64 at = 0; at < total; at += (juce::int64) block.size())
  14140. {
  14141. std::fill (block.begin(), block.end(), 0.0f);
  14142. for (int k = 0; k < (int) block.size(); ++k)
  14143. {
  14144. const auto f = at + k;
  14145. const auto beat = (juce::int64) std::floor ((double) f / (rate / 2.0));
  14146. const auto rel = f - (juce::int64) std::llround ((double) beat * rate / 2.0);
  14147. static constexpr float shape[] { 0.25f, 0.75f, 1.0f, 0.75f, 0.25f };
  14148. if (rel >= 0 && rel < 5)
  14149. block[(std::size_t) k] = 0.5f * shape[rel];
  14150. }
  14151. const float* d[] { block.data() };
  14152. w.write (d, (int) std::min<juce::int64> ((juce::int64) block.size(), total - at));
  14153. }
  14154. w.close();
  14155. }
  14156. lynx::Song song = lynx::Song::makeDefault();
  14157. song.bpm = 120.0;
  14158. song.mode = lynx::PlayMode::song;
  14159. song.playlist.clear();
  14160. song.channels.clear();
  14161. for (int k = 0; k < 2; ++k)
  14162. {
  14163. lynx::ChannelDef c;
  14164. c.name = k == 0 ? "Wet" : "Dry";
  14165. c.instrument = lynx::InstrumentKind::audioClip;
  14166. c.samplePath = clickFile.getFullPathName().toStdString();
  14167. c.mixerTrack = k + 1;
  14168. c.volume = 1.0f;
  14169. song.channels.push_back (c);
  14170. lynx::Clip clip;
  14171. clip.kind = lynx::ClipKind::audio;
  14172. clip.channel = k;
  14173. clip.track = k;
  14174. clip.start = 0;
  14175. clip.length = (std::int64_t) beats * lynx::ppq;
  14176. song.playlist.push_back (clip);
  14177. }
  14178. song.mixer[0].outputChannel = lynx::outputNone; // (the cable carries the send only)
  14179. for (auto& fx : song.mixer[0].effects) // (no Master effects: the default limiter's PDC would hide nothing, but keep it plain)
  14180. fx.enabled = false;
  14181. song.mixer[1].pan = -1.0f;
  14182. song.mixer[2].pan = 1.0f;
  14183. auto hw = lynx::makeEffectSlot (lynx::EffectKind::hardwareInsert);
  14184. hw.params[lynx::hwinsert::output] = lynx::hwinsert::channelValue (0);
  14185. hw.params[lynx::hwinsert::input] = lynx::hwinsert::channelValue (0);
  14186. hw.params[lynx::hwinsert::inputStereo] = 1.0f;
  14187. song.mixer[1].effects.clear();
  14188. lynx::AudioEngine::HardwareInsertRef ref { false, 1, 0, {} };
  14189. if (inPatcher) // (round 165c) From LYNX -> Hardware Insert -> To LYNX
  14190. {
  14191. auto slot = lynx::makeEffectSlot (lynx::EffectKind::patcher);
  14192. lynx::PatchNode node;
  14193. node.effect = hw;
  14194. slot.patcher.nodes = { node };
  14195. lynx::PatchWire in, out;
  14196. in.from = lynx::patchFromHost;
  14197. in.to = 0;
  14198. out.from = 0;
  14199. out.to = lynx::patchToHost;
  14200. slot.patcher.wires = { in, out };
  14201. song.mixer[1].effects.push_back (slot);
  14202. ref.nodes = { 0 };
  14203. }
  14204. else
  14205. song.mixer[1].effects.push_back (hw);
  14206. engine->setSong (std::move (song));
  14207. step (juce::String ("insert=") + (inPatcher ? "inside a Patcher on Insert 1" : "Insert 1 slot 1"));
  14208. const auto meter = [this, ref] (int output) {
  14209. const auto fx = engine->runningHardwareInsert (ref);
  14210. return fx != nullptr ? fx->controlOutput (output) : 0.0f;
  14211. };
  14212. // 1) the insert's ping (as its Ping button: a momentary value flipped)
  14213. juce::Timer::callAfterDelay (500, [this, report, step, finish, seconds, rate, meter, ref, inPatcher, bounceFile] {
  14214. if (engine == nullptr)
  14215. return;
  14216. engine->pingHardwareInserts ({ ref });
  14217. juce::Timer::callAfterDelay (3500, [this, report, step, finish, seconds, rate, meter, ref, inPatcher, bounceFile] {
  14218. if (engine == nullptr)
  14219. return;
  14220. // (round 165c) the engine makes a ping's result the slot's round trip with the device setup it belongs to; the
  14221. // new round trip rebuilds the insert (its latency), so the result is read from the slot
  14222. const auto* slot = lynx::AudioEngine::locateHardwareInsert (const_cast<lynx::Song&> (engine->getSong()), ref);
  14223. const auto samples = slot != nullptr ? lynx::hwinsert::roundTripOf (slot->params[lynx::hwinsert::roundTrip]) : 0;
  14224. const auto setup = slot != nullptr ? lynx::hwinsert::measuredSetup (*slot) : std::string();
  14225. const auto state = meter (lynx::hwinsert::pingState);
  14226. const auto ok = samples > 0 && setup == engine->currentSetupKey();
  14227. step ("ping_round_trip=" + juce::String (samples) + " measured_setup=" + juce::String (setup) + (ok ? " (ok)" : " (FAILED)")
  14228. + " live_ping_state=" + juce::String (state, 3) + " status_flags=" + juce::String (juce::roundToInt (meter (lynx::hwinsert::status) * 16.0f)));
  14229. if (! ok)
  14230. {
  14231. step ("result=FAILED ping");
  14232. finish (1);
  14233. return;
  14234. }
  14235. // a stale setup is noticed: another setup key on the slot gives the notice, the real one none
  14236. step ("stale_now=" + juce::String ((int) engine->staleHardwareInserts().size()));
  14237. // 2) play, capturing the Master
  14238. juce::Timer::callAfterDelay (500, [this, report, step, finish, seconds, rate, samples, ref, inPatcher, bounceFile] {
  14239. if (engine == nullptr)
  14240. return;
  14241. step ("pdc_total=" + juce::String (engine->getLatencySamples()) + " (expected " + juce::String (samples) + ")");
  14242. // saved in the project: the slot comes back the same (routing, round trip), and its latency with it — also an
  14243. // odd round trip (12345 samples: the project keeps it to the sample)
  14244. if (! inPatcher)
  14245. {
  14246. auto odd = engine->getSong();
  14247. odd.mixer[1].effects[0].params[lynx::hwinsert::roundTrip] = lynx::hwinsert::roundTripValue (12345);
  14248. juce::String error;
  14249. auto same = true;
  14250. for (const auto* song : { &engine->getSong(), (const lynx::Song*) &odd })
  14251. {
  14252. const auto file = report.getSiblingFile (report.getFileNameWithoutExtension() + (song == &odd ? "-odd.lynx" : ".lynx"));
  14253. const auto saved = lynx::ProjectFile::save (*song, file, error);
  14254. const auto loaded = saved ? lynx::ProjectFile::load (file, error) : std::nullopt;
  14255. same = same && loaded && loaded->mixer.size() > 1 && ! loaded->mixer[1].effects.empty()
  14256. && loaded->mixer[1].effects[0].kind == lynx::EffectKind::hardwareInsert
  14257. && loaded->mixer[1].effects[0].params == song->mixer[1].effects[0].params
  14258. && lynx::makeEffect (loaded->mixer[1].effects[0])->latencySamples() == (song == &odd ? 12345 : samples);
  14259. }
  14260. const auto file = report.getSiblingFile (report.getFileNameWithoutExtension() + ".lynx");
  14261. step (juce::String ("project_round_trip=") + (same ? "same" : "DIFFERENT " + error) + " (" + file.getFileName() + ")");
  14262. if (! same)
  14263. {
  14264. step ("result=FAILED project");
  14265. finish (1);
  14266. return;
  14267. }
  14268. }
  14269. auto left = std::make_shared<std::vector<float>>(), right = std::make_shared<std::vector<float>>();
  14270. engine->stop();
  14271. engine->rewind();
  14272. engine->getMeters().capture.setSource (0);
  14273. engine->play();
  14274. auto pulls = std::make_shared<int> ((int) (seconds * 5.0));
  14275. auto pull = std::make_shared<std::function<void()>>();
  14276. *pull = [this, report, step, finish, seconds, rate, samples, left, right, pulls, pull, ref, inPatcher, bounceFile] {
  14277. if (engine == nullptr)
  14278. return;
  14279. engine->getMeters().capture.pull (*left, *right);
  14280. if (*pulls == 10) // the insert's editor while it plays (next to the report)
  14281. for (const auto scale : { 1.0f, 1.5f })
  14282. {
  14283. auto editor = inPatcher ? lynx::makeNodeEffectEditor (
  14284. *engine, [ref] (lynx::Song& s) { return lynx::AudioEngine::locateHardwareInsert (s, ref); },
  14285. [this, ref] { return engine->runningHardwareInsert (ref); }, "Insert 1 (Patcher)", scale)
  14286. : lynx::makeNativeEffectEditor (*engine, 1, 0, scale, 0);
  14287. juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
  14288. {
  14289. juce::Graphics g (image);
  14290. g.fillAll (lynx::theme::panel);
  14291. editor->paintEntireComponent (g, false);
  14292. }
  14293. const auto file = report.getSiblingFile (report.getFileNameWithoutExtension() + (scale > 1.0f ? "-editor150.png" : "-editor.png"));
  14294. file.deleteFile();
  14295. juce::PNGImageFormat png;
  14296. if (auto stream = file.createOutputStream())
  14297. png.writeImageToStream (image, *stream);
  14298. }
  14299. if (--*pulls > 0)
  14300. {
  14301. juce::Timer::callAfterDelay (200, *pull);
  14302. return;
  14303. }
  14304. engine->stop();
  14305. const auto dropped = engine->getMeters().capture.droppedFrames();
  14306. engine->getMeters().capture.setSource (lynx::AudioCapture::off);
  14307. // the clicks of each side (peaks above -12 dBFS, one per 1/8 s at most)
  14308. auto peaksOf = [rate] (const std::vector<float>& x) {
  14309. std::vector<juce::int64> peaks;
  14310. for (std::size_t f = 1; f + 1 < x.size(); ++f)
  14311. 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])
  14312. && (peaks.empty() || (juce::int64) f - peaks.back() > (juce::int64) (rate / 8)))
  14313. peaks.push_back ((juce::int64) f);
  14314. return peaks;
  14315. };
  14316. const auto wet = peaksOf (*left), dry = peaksOf (*right);
  14317. int pairs = 0;
  14318. juce::int64 worst = 0;
  14319. double gainSum = 0.0, residual = 0.0, energy = 0.0;
  14320. for (const auto w : wet)
  14321. {
  14322. 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); });
  14323. if (best == dry.end() || std::abs (*best - w) > (juce::int64) (rate / 8))
  14324. continue;
  14325. ++pairs;
  14326. worst = std::max (worst, std::abs (*best - w));
  14327. gainSum += (*left)[(std::size_t) w] / (*right)[(std::size_t) *best];
  14328. }
  14329. const auto gain = pairs > 0 ? gainSum / pairs : 1.0;
  14330. // dry clicks with no wet click beside them (a dropout of the cable / device), listed
  14331. juce::String unmatched;
  14332. for (const auto d : dry)
  14333. if (std::none_of (wet.begin(), wet.end(), [d, rate] (juce::int64 w) { return std::abs (w - d) <= (juce::int64) (rate / 8); }))
  14334. unmatched << " " << (juce::int64) d << " (" << juce::String ((*left)[(std::size_t) d], 3) << ")";
  14335. if (unmatched.isNotEmpty())
  14336. step ("dry_clicks_without_wet=" + unmatched);
  14337. // the null test: left − gain · right around each click (both sides aligned → only the cable's colour remains)
  14338. for (const auto w : wet)
  14339. for (juce::int64 f = std::max<juce::int64> (0, w - 16); f < std::min<juce::int64> ((juce::int64) left->size(), w + 16); ++f)
  14340. {
  14341. const auto d = (double) (*left)[(std::size_t) f] - gain * (double) (*right)[(std::size_t) f];
  14342. residual += d * d;
  14343. energy += (double) (*left)[(std::size_t) f] * (*left)[(std::size_t) f];
  14344. }
  14345. const auto nullDb = energy > 0.0 ? 10.0 * std::log10 (std::max (1e-30, residual / energy)) : 0.0;
  14346. step ("captured=" + juce::String ((int) left->size()) + " frames dropped=" + juce::String (dropped) + " wet_clicks=" + juce::String ((int) wet.size())
  14347. + " dry_clicks=" + juce::String ((int) dry.size()) + " pairs=" + juce::String (pairs));
  14348. step ("alignment_error_samples=max " + juce::String ((int) worst) + " cable_gain=" + juce::String (gain, 4) + " null_residual_db=" + juce::String (nullDb, 1));
  14349. auto* dev = engine->getDeviceManager().getCurrentAudioDevice();
  14350. const auto xruns = dev != nullptr ? dev->getXRunCount() : -1;
  14351. step ("device_xruns=" + juce::String (xruns) + " (a dropout loses what was on the cable then: its clicks are excused)");
  14352. const auto excused = xruns > 0 ? 2 * xruns : 0;
  14353. const auto ok = pairs >= (int) (seconds * 2.0) - 2 - excused && worst == 0 && dropped == 0 && engine->getLatencySamples() == samples;
  14354. step (juce::String ("result=") + (ok ? "OK" : "FAILED"));
  14355. // (round 165c) then the re-ping notice after a buffer size change
  14356. auto then = [this, ref, step, finish] (int code) {
  14357. if (code != 0)
  14358. finish (code);
  14359. else
  14360. runRepingCheck (ref, step, finish);
  14361. };
  14362. if (! ok)
  14363. {
  14364. finish (1);
  14365. return;
  14366. }
  14367. if (bounceFile == juce::File())
  14368. then (0);
  14369. else
  14370. runBounceCheck (bounceFile, step, then);
  14371. };
  14372. juce::Timer::callAfterDelay (200, *pull);
  14373. });
  14374. });
  14375. });
  14376. }
  14377. // --hwinserttest --bounce (round 165c): Export › "Render through the hardware in real time" of the test song next to
  14378. // the offline export of the same song. Through the loopback cable (gain 1) the return is the send delayed by the
  14379. // pinged round trip, so the real-time file must equal the offline one (which passes the dry signal at that delay)
  14380. // to float rounding, with the wet clicks (left) on the dry clicks' samples (right).
  14381. // --hwinserttest (round 165c): the buffer size changes (another round trip on the device): the engine notices the
  14382. // insert measured for the old setup (the app's "Ping now?" prompt), "Ping now" measures it again for the new one
  14383. void runRepingCheck (lynx::AudioEngine::HardwareInsertRef ref, std::function<void (const juce::String&)> step, std::function<void (int)> finish)
  14384. {
  14385. auto& devices = engine->getDeviceManager();
  14386. auto setup = devices.getAudioDeviceSetup();
  14387. const auto before = setup.bufferSize;
  14388. setup.bufferSize = before == 512 ? 256 : 512;
  14389. if (const auto error = devices.setAudioDeviceSetup (setup, true); error.isNotEmpty())
  14390. step ("reping_device_error=" + error);
  14391. engine->takeHardwareInsertNotice(); // (whatever was pending before the change)
  14392. juce::Timer::callAfterDelay (1500, [this, ref, step, finish, before] {
  14393. if (engine == nullptr)
  14394. return;
  14395. auto* device = engine->getDeviceManager().getCurrentAudioDevice();
  14396. const auto block = device != nullptr ? device->getCurrentBufferSizeSamples() : 0;
  14397. const auto notice = engine->takeHardwareInsertNotice();
  14398. step ("reping_buffer=" + juce::String (before) + "->" + juce::String (block) + " notice=" + juce::String ((int) notice.size())
  14399. + " stale=" + juce::String ((int) engine->staleHardwareInserts().size()));
  14400. if (notice.size() != 1 || ! (notice[0] == ref))
  14401. {
  14402. step ("result_reping=FAILED (no notice)");
  14403. finish (1);
  14404. return;
  14405. }
  14406. engine->pingHardwareInserts (notice); // ("Ping now")
  14407. juce::Timer::callAfterDelay (3500, [this, ref, step, finish, block] {
  14408. if (engine == nullptr)
  14409. return;
  14410. const auto* slot = lynx::AudioEngine::locateHardwareInsert (const_cast<lynx::Song&> (engine->getSong()), ref);
  14411. const auto samples = slot != nullptr ? lynx::hwinsert::roundTripOf (slot->params[lynx::hwinsert::roundTrip]) : 0;
  14412. const auto stale = (int) engine->staleHardwareInserts().size();
  14413. step ("reping_round_trip=" + juce::String (samples) + " pdc_total=" + juce::String (engine->getLatencySamples()) + " stale=" + juce::String (stale));
  14414. const auto ok = stale == 0 && samples > 0 && engine->getLatencySamples() == samples;
  14415. step (juce::String ("result_reping=") + (ok ? "OK" : "FAILED") + " (device block " + juce::String (block) + ")");
  14416. finish (ok ? 0 : 1);
  14417. });
  14418. });
  14419. }
  14420. void runBounceCheck (const juce::File& bounceFile, std::function<void (const juce::String&)> step, std::function<void (int)> finish)
  14421. {
  14422. // the Export window as the user sees it with the real-time option ticked (next to the report)
  14423. lynx::showExportDialog (*engine, bounceFile.getParentDirectory(), "bounce", 0);
  14424. for (int k = 0; k < juce::TopLevelWindow::getNumTopLevelWindows(); ++k)
  14425. if (auto* w = juce::TopLevelWindow::getTopLevelWindow (k))
  14426. {
  14427. std::function<juce::ToggleButton* (juce::Component&)> find = [&find] (juce::Component& c) -> juce::ToggleButton* {
  14428. if (auto* t = dynamic_cast<juce::ToggleButton*> (&c); t != nullptr && t->getButtonText() == lynx::tr ("Render through the hardware in real time"))
  14429. return t;
  14430. for (auto* child : c.getChildren())
  14431. if (auto* t = find (*child))
  14432. return t;
  14433. return nullptr;
  14434. };
  14435. if (auto* toggle = find (*w))
  14436. {
  14437. step (juce::String ("export_option_visible=") + (toggle->isVisible() ? "yes" : "NO"));
  14438. toggle->setToggleState (true, juce::sendNotificationSync); // (calls its onClick, as a click)
  14439. auto* c = dynamic_cast<juce::DocumentWindow*> (w) != nullptr ? static_cast<juce::DocumentWindow*> (w)->getContentComponent() : w;
  14440. if (c != nullptr)
  14441. {
  14442. const auto file = bounceFile.getSiblingFile (bounceFile.getFileNameWithoutExtension() + "-export.png");
  14443. file.deleteFile();
  14444. juce::FileOutputStream out (file);
  14445. juce::PNGImageFormat png;
  14446. if (out.openedOk())
  14447. png.writeImageToStream (c->createComponentSnapshot (c->getLocalBounds()), out);
  14448. }
  14449. delete w;
  14450. break;
  14451. }
  14452. }
  14453. lynx::exportopts::Options o;
  14454. o.format = lynx::exportopts::Format::wav;
  14455. o.wavBits = 32;
  14456. o.dither = lynx::exportopts::DitherMode::none;
  14457. o.tail = lynx::exportopts::TailMode::cut;
  14458. o.range = lynx::exportopts::Range::song;
  14459. o.trimPdc = true;
  14460. o.hqAllPlugins = false;
  14461. o.pluginWarmUp = false;
  14462. const auto offlineFile = bounceFile.getSiblingFile (bounceFile.getFileNameWithoutExtension() + "-offline.wav");
  14463. auto realtimeJob = std::make_shared<lynx::ExportJob> (*engine, o, bounceFile);
  14464. o.sampleRate = engine->getTransport().sampleRate.load();
  14465. auto offlineJob = std::make_shared<lynx::ExportJob> (engine->getSong(), o, offlineFile);
  14466. struct Shared
  14467. {
  14468. std::atomic<int> done { 0 };
  14469. bool okRealtime = false, okOffline = false;
  14470. juce::String errorRealtime, errorOffline;
  14471. double lastProgress = 0.0;
  14472. double started = juce::Time::getMillisecondCounterHiRes();
  14473. };
  14474. auto shared = std::make_shared<Shared>();
  14475. // (the jobs stay owned by the message thread's poll below: they are destroyed there)
  14476. juce::Thread::launch ([rt = realtimeJob.get(), off = offlineJob.get(), shared] {
  14477. shared->okRealtime = rt->run ([shared] (double p) { shared->lastProgress = p; return true; }, shared->errorRealtime);
  14478. shared->okOffline = off->run ({}, shared->errorOffline);
  14479. shared->done.store (1);
  14480. });
  14481. auto poll = std::make_shared<std::function<void()>>();
  14482. *poll = [this, poll, shared, realtimeJob, offlineJob, bounceFile, offlineFile, step, finish] {
  14483. if (shared->done.load() == 0)
  14484. {
  14485. juce::Timer::callAfterDelay (100, *poll);
  14486. return;
  14487. }
  14488. const auto seconds = (juce::Time::getMillisecondCounterHiRes() - shared->started) / 1000.0;
  14489. step ("bounce_realtime=" + juce::String (shared->okRealtime ? "ok" : "FAILED " + shared->errorRealtime) + " offline="
  14490. + juce::String (shared->okOffline ? "ok" : "FAILED " + shared->errorOffline) + " took=" + juce::String (seconds, 1) + " s (music "
  14491. + juce::String (realtimeJob->getMusicSeconds(), 1) + " s)" + (realtimeJob->getNotice().isNotEmpty() ? " notice=" + realtimeJob->getNotice() : juce::String()));
  14492. juce::AudioFormatManager formats;
  14493. formats.registerBasicFormats();
  14494. std::unique_ptr<juce::AudioFormatReader> a (formats.createReaderFor (bounceFile)), b (formats.createReaderFor (offlineFile));
  14495. if (! shared->okRealtime || ! shared->okOffline || a == nullptr || b == nullptr)
  14496. {
  14497. step ("result=FAILED bounce");
  14498. finish (1);
  14499. return;
  14500. }
  14501. const auto frames = (int) std::min (a->lengthInSamples, b->lengthInSamples);
  14502. juce::AudioBuffer<float> x (2, frames), y (2, frames);
  14503. a->read (&x, 0, frames, 0, true, true);
  14504. b->read (&y, 0, frames, 0, true, true);
  14505. double residual = 0.0, energy = 0.0, wetDry = 0.0;
  14506. for (int ch = 0; ch < 2; ++ch)
  14507. for (int i = 0; i < frames; ++i)
  14508. {
  14509. const double d = x.getSample (ch, i) - y.getSample (ch, i);
  14510. residual += d * d;
  14511. energy += (double) y.getSample (ch, i) * y.getSample (ch, i);
  14512. }
  14513. for (int i = 0; i < frames; ++i) // the wet side against the dry side of the real-time file
  14514. wetDry += std::pow ((double) x.getSample (0, i) - x.getSample (1, i), 2.0);
  14515. const auto db = [energy] (double r) { return energy > 0.0 ? 10.0 * std::log10 (std::max (1e-30, r / energy)) : 0.0; };
  14516. step ("bounce_frames=" + juce::String ((juce::int64) a->lengthInSamples) + " offline_frames=" + juce::String ((juce::int64) b->lengthInSamples)
  14517. + " rate=" + juce::String (a->sampleRate) + " bounce_vs_offline_db=" + juce::String (db (residual), 1)
  14518. + " wet_vs_dry_db=" + juce::String (db (2.0 * wetDry), 1) + " peak=" + juce::String (realtimeJob->getPeak(), 3));
  14519. const auto ok = std::abs (a->lengthInSamples - b->lengthInSamples) <= 1 && db (residual) < -100.0 && realtimeJob->getPeak() > 0.1f;
  14520. step (juce::String ("result_bounce=") + (ok ? "OK" : "FAILED"));
  14521. finish (ok ? 0 : 1);
  14522. };
  14523. juce::Timer::callAfterDelay (100, *poll);
  14524. }
  14525. // --rtstress --record: stops recording (the take becomes a clip of the song, as in the app), moves the take's WAV to
  14526. // `target` and describes it: length against the time played, channels, peak, the latencies the driver reported.
  14527. juce::String finishStressTake (const juce::File& target, double seconds)
  14528. {
  14529. juce::String text;
  14530. auto* device = engine->getDeviceManager().getCurrentAudioDevice();
  14531. text << " recording: input " << (device != nullptr ? device->getActiveInputChannels().countNumberOfSetBits() : 0) << " channel(s)";
  14532. if (device != nullptr)
  14533. text << ", input latency " << device->getInputLatencyInSamples() << " + output latency " << device->getOutputLatencyInSamples() << " samples";
  14534. engine->setRecording (false); // closes the take: a clip of the song
  14535. juce::File take;
  14536. for (const auto& c : engine->getSong().channels)
  14537. if (c.instrument == lynx::InstrumentKind::audioClip)
  14538. take = juce::File (juce::String::fromUTF8 (c.samplePath.c_str()));
  14539. if (! take.existsAsFile())
  14540. return text + "\n recording: no take (" + engine->getLastRecordingError() + ")\n";
  14541. target.deleteFile();
  14542. if (! take.moveFileTo (target))
  14543. take.copyFileTo (target);
  14544. juce::AudioFormatManager formats;
  14545. formats.registerBasicFormats();
  14546. if (std::unique_ptr<juce::AudioFormatReader> reader (formats.createReaderFor (target)); reader != nullptr)
  14547. {
  14548. juce::AudioBuffer<float> audio ((int) reader->numChannels, (int) reader->lengthInSamples);
  14549. reader->read (&audio, 0, (int) reader->lengthInSamples, 0, true, true);
  14550. const auto peak = audio.getMagnitude (0, audio.getNumSamples());
  14551. const auto length = (double) reader->lengthInSamples / reader->sampleRate;
  14552. text << "\n recording: take " << juce::String (length, 3) << " s of " << juce::String (seconds, 0) << " s played, "
  14553. << (int) reader->numChannels << " ch @ " << (int) reader->sampleRate << " Hz, peak "
  14554. << juce::String (juce::Decibels::gainToDecibels (peak, -150.0f), 1) << " dBFS -> " << target.getFullPathName() << "\n";
  14555. }
  14556. else
  14557. text << "\n recording: take unreadable (" << target.getFullPathName() << ")\n";
  14558. return text;
  14559. }
  14560. // LYNX.exe --render project.(flp|lynx) output.wav [seconds]
  14561. // Exports the current pattern to 24-bit WAV (for an imported .flp, the one with the most notes).
  14562. void runRender (const juce::String& inputPath, const juce::String& outputPath, double seconds)
  14563. {
  14564. lynx::AudioEngine offline (false);
  14565. const juce::File input (inputPath);
  14566. juce::String error, report;
  14567. bool ok = false;
  14568. if (input.hasFileExtension ("flp;als;flm;songtmpl;band;blx")) // (round 190ic: a GarageBand .band folder too)
  14569. ok = offline.importFlpFile (input, error);
  14570. else if (auto song = lynx::ProjectFile::load (input, error))
  14571. {
  14572. offline.setSong (std::move (*song));
  14573. ok = true;
  14574. }
  14575. int samplers = 0, samplersLoaded = 0;
  14576. if (ok)
  14577. {
  14578. for (const auto& c : offline.getSong().channels)
  14579. if (c.instrument == lynx::InstrumentKind::sampler || c.instrument == lynx::InstrumentKind::audioClip)
  14580. {
  14581. ++samplers;
  14582. samplersLoaded += offline.getSampleLibrary().load (juce::String::fromUTF8 (c.samplePath.c_str())) != nullptr;
  14583. }
  14584. const juce::File output (outputPath);
  14585. output.deleteFile();
  14586. juce::WavAudioFormat wav;
  14587. std::unique_ptr<juce::AudioFormatWriter> writer (
  14588. wav.createWriterFor (output.createOutputStream().release(), 44100.0, 2, 24, {}, 0));
  14589. if (writer == nullptr)
  14590. {
  14591. ok = false;
  14592. error = lynx::utf8 ("could not create ") + outputPath;
  14593. }
  14594. else
  14595. {
  14596. const auto peak = offline.renderOffline (seconds > 0.0 ? seconds : 10.0, 44100.0, writer.get());
  14597. report << "peak=" << peak << "\n";
  14598. ok = peak > 0.001f;
  14599. }
  14600. }
  14601. report << "samples=" << samplersLoaded << "/" << samplers << "\n"
  14602. << "result=" << (ok ? "OK" : "ERROR " + error) << "\n";
  14603. juce::File (outputPath + ".txt").replaceWithText (report);
  14604. setApplicationReturnValue (ok ? 0 : 1);
  14605. quit();
  14606. }
  14607. // LYNX.exe --export-flp project.(lynx|flp|als) output.(flp|zip) [--substitute] (round 171e): File › Export › FL Studio
  14608. // project without the window (option A unless --substitute; the renders next to a .flp in "<name> audio"); the
  14609. // report goes to output.txt
  14610. void runAlsExport (const juce::String& inputPath, const juce::String& folderPath, bool live11, bool reference)
  14611. {
  14612. juce::String error;
  14613. juce::StringArray notes;
  14614. juce::File als;
  14615. {
  14616. lynx::AudioEngine loader (false);
  14617. const juce::File input (inputPath);
  14618. bool ok = false;
  14619. // --scan: the targeted plugin scan an open runs first (child processes), so the set's plugins load
  14620. if (juce::JUCEApplication::getCommandLineParameterArray().contains ("--scan") && input.hasFileExtension ("flp;als;flm;songtmpl"))
  14621. {
  14622. juce::MemoryBlock data;
  14623. if (input.loadFileAsData (data))
  14624. {
  14625. const std::vector<std::uint8_t> bytes (static_cast<const std::uint8_t*> (data.getData()),
  14626. static_cast<const std::uint8_t*> (data.getData()) + data.getSize());
  14627. try
  14628. {
  14629. const auto uses = input.hasFileExtension ("als") ? lynx::alsForeignPlugins (bytes)
  14630. : lynx::flpForeignPlugins (flp::parseProject ({ bytes.data(), bytes.size() }));
  14631. loader.getPluginHost().scanFiles (loader.getPluginHost().filesToScanFor (uses), {});
  14632. }
  14633. catch (const std::exception&)
  14634. {
  14635. }
  14636. }
  14637. }
  14638. if (input.hasFileExtension ("flp;als;flm;songtmpl;band;blx"))
  14639. ok = loader.importFlpFile (input, error);
  14640. else if (auto song = lynx::ProjectFile::load (input, error))
  14641. {
  14642. loader.setSong (std::move (*song));
  14643. ok = true;
  14644. }
  14645. if (ok)
  14646. {
  14647. loader.capturePluginStates();
  14648. const juce::File folder (folderPath);
  14649. folder.createDirectory();
  14650. als = lynx::writeAlsProject (loader.getSong(), &loader.getPluginHost(), live11 ? lynx::AlsVersion::live11 : lynx::AlsVersion::live12, ! reference, folder,
  14651. input.getFileNameWithoutExtension(), notes, error);
  14652. }
  14653. }
  14654. juce::String report;
  14655. report << (als != juce::File() ? "ok " + als.getFullPathName() : "error=" + error) << "\n" << notes.joinIntoString ("\n") << "\n";
  14656. juce::File (folderPath).getChildFile ("export-als.txt").replaceWithText (report);
  14657. setApplicationReturnValue (als != juce::File() ? 0 : 1);
  14658. quit();
  14659. }
  14660. // --versionsshot <prefix> (round 190ap): everything the round adds, offscreen (no window on the desktop):
  14661. // -versions.png / -versions-unsaved.png the Versions panel (a project with versions, backups and labels; a new one)
  14662. // -menu-file.png / -menu-file-pluginsoff.png the File menu, and as it is while the plugins are off
  14663. // -pluginsoff-window.png / -pluginsoff-mixer.png a project opened without its third-party plugins (the tags)
  14664. // -pluginsoff-panel.png / -pluginsoff-panel-one.png the list, all off, then after "Switch on" for one
  14665. // -export-default.png / -export.png the Export window as it opens, and with the additions in use
  14666. bool runLinkShot (const juce::String& prefix)
  14667. {
  14668. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  14669. juce::StringArray report;
  14670. bool allOk = true;
  14671. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  14672. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  14673. allOk = allOk && ok;
  14674. };
  14675. const auto shoot = [&prefix] (juce::Component& c, const char* name) {
  14676. savePng (c.createComponentSnapshot (c.getLocalBounds()), prefix + "-" + name + ".png");
  14677. };
  14678. using lynx::AutomationTarget;
  14679. using lynx::AutomationTargetKind;
  14680. using lynx::MidiLink;
  14681. lynx::AudioEngine engine (false);
  14682. const AutomationTarget volume { AutomationTargetKind::channelVolume, 0 }, pan { AutomationTargetKind::channelPan, 0 },
  14683. insert { AutomationTargetKind::mixerVolume, 1 };
  14684. // ---- the window as it opens on a control with no link (FL's defaults)
  14685. {
  14686. auto panel = lynx::makeRemoteControlPanel (engine, { volume }, false);
  14687. shoot (*panel, "remote-default");
  14688. check ("default_state", lynx::remoteControlPanelState (*panel).startsWith ("-1|1|-1|Input|"), lynx::remoteControlPanelState (*panel));
  14689. // Auto detect: the controller that sends next fills the fields
  14690. engine.injectControllerForTest (74, 2, 100, 5);
  14691. lynx::remoteControlPanelPoll (*panel);
  14692. check ("auto_detect", lynx::remoteControlPanelState (*panel).startsWith ("5|3|74|"), lynx::remoteControlPanelState (*panel));
  14693. // a formula preset, smoothing; Accept writes the link
  14694. lynx::remoteControlPanelSetController (*panel, -1, 1, 7);
  14695. lynx::remoteControlPanelSetFormula (*panel, "Tension(Input,10)");
  14696. lynx::remoteControlPanelSetSmoothing (*panel, true, 469);
  14697. shoot (*panel, "remote-formula-smoothing");
  14698. lynx::remoteControlPanelPress (*panel, 2);
  14699. const auto& links = engine.getSong().midiLinks;
  14700. check ("accept_writes_link", links.size() == 1 && links[0].cc == 7 && links[0].channel == 0 && links[0].port == -1
  14701. && links[0].formula == "Tension(Input,10)" && links[0].smooth && links[0].target == volume);
  14702. }
  14703. // ---- a broken formula: the message, the red text
  14704. {
  14705. auto panel = lynx::makeRemoteControlPanel (engine, { volume }, false);
  14706. lynx::remoteControlPanelSetFormula (*panel, "Min(Input*2,");
  14707. shoot (*panel, "remote-formula-error");
  14708. check ("formula_error_shown", ! lynx::remoteControlPanelState (*panel).contains ("Compiled ok."), lynx::remoteControlPanelState (*panel));
  14709. }
  14710. // ---- the engine: formula, port, conflicts, omni
  14711. {
  14712. engine.editSong ([&] (lynx::Song& s) {
  14713. s.midiLinks.clear();
  14714. MidiLink inverted { 20, 0, volume };
  14715. inverted.formula = "1-Input";
  14716. MidiLink ported { 21, 0, pan };
  14717. ported.port = 3;
  14718. s.midiLinks = { inverted, ported };
  14719. });
  14720. engine.injectControllerForTest (20, 0, 127);
  14721. check ("formula_inverts", std::abs (engine.currentTargetValue (volume)) < 0.01f, juce::String (engine.currentTargetValue (volume)));
  14722. engine.injectControllerForTest (20, 0, 0);
  14723. check ("formula_inverts_back", std::abs (engine.currentTargetValue (volume) - 1.0f) < 0.01f, juce::String (engine.currentTargetValue (volume)));
  14724. const auto panBefore = engine.currentTargetValue (pan);
  14725. engine.injectControllerForTest (21, 0, 127); // no port: not this link's device
  14726. check ("port_must_match", std::abs (engine.currentTargetValue (pan) - panBefore) < 0.001f);
  14727. engine.injectControllerForTest (21, 0, 127, 3);
  14728. check ("port_matches", std::abs (engine.currentTargetValue (pan) - 1.0f) < 0.01f, juce::String (engine.currentTargetValue (pan)));
  14729. // the window on a control whose controller another control uses: Remove conflicts in red; Accept removes it
  14730. auto panel = lynx::makeRemoteControlPanel (engine, { insert }, false);
  14731. lynx::remoteControlPanelSetController (*panel, -1, 1, 20);
  14732. shoot (*panel, "remote-conflict");
  14733. check ("conflict_counted", lynx::remoteControlPanelState (*panel).contains ("|1|"), lynx::remoteControlPanelState (*panel));
  14734. lynx::remoteControlPanelPress (*panel, 2);
  14735. const auto& links = engine.getSong().midiLinks;
  14736. check ("conflict_removed", links.size() == 2
  14737. && std::none_of (links.begin(), links.end(), [&] (const MidiLink& l) { return l.target == volume; })
  14738. && std::any_of (links.begin(), links.end(), [&] (const MidiLink& l) { return l.target == insert && l.cc == 20; }));
  14739. engine.undo();
  14740. check ("accept_is_one_undo_step", engine.getSong().midiLinks.size() == 2 && engine.getSong().midiLinks[0].target == volume);
  14741. }
  14742. // ---- an existing link opened again: "Link 1" / "New link"
  14743. {
  14744. auto panel = lynx::makeRemoteControlPanel (engine, { volume }, false);
  14745. shoot (*panel, "remote-existing-link");
  14746. check ("existing_link_loaded", lynx::remoteControlPanelState (*panel).startsWith ("-1|1|20|1-Input|"), lynx::remoteControlPanelState (*panel));
  14747. // Reset, then Accept: a link without a controller is removed
  14748. lynx::remoteControlPanelPress (*panel, 0);
  14749. check ("reset_state", lynx::remoteControlPanelState (*panel).startsWith ("-1|1|-1|Input|"), lynx::remoteControlPanelState (*panel));
  14750. lynx::remoteControlPanelPress (*panel, 2);
  14751. const auto& links = engine.getSong().midiLinks;
  14752. check ("reset_accept_unlinks", std::none_of (links.begin(), links.end(), [&] (const MidiLink& l) { return l.target == volume; }));
  14753. }
  14754. // ---- several controls ("Link to controllers..."): Accept and Skip step through them
  14755. {
  14756. auto panel = lynx::makeRemoteControlPanel (engine, { volume, pan, insert }, false, [] {});
  14757. shoot (*panel, "remote-multilink");
  14758. const auto parameter = [&panel] { return juce::StringArray::fromTokens (lynx::remoteControlPanelState (*panel), "|", "")[6]; };
  14759. const auto first = parameter();
  14760. check ("multilink_caption_and_skip", first.startsWith ("1/3") && first.contains (lynx::tr ("Channel volume"))
  14761. && lynx::remoteControlPanelState (*panel).contains ("S|omni"),
  14762. lynx::remoteControlPanelState (*panel));
  14763. lynx::remoteControlPanelSetController (*panel, -1, 1, 30);
  14764. lynx::remoteControlPanelPress (*panel, 2); // Accept: volume linked, on to pan
  14765. const auto second = parameter();
  14766. lynx::remoteControlPanelPress (*panel, 1); // Skip: pan untouched, on to the insert
  14767. const auto third = parameter();
  14768. const auto beforeLast = lynx::remoteControlPanelFinished (*panel);
  14769. lynx::remoteControlPanelPress (*panel, 1); // Skip on the last one: done
  14770. const auto closed = ! beforeLast && lynx::remoteControlPanelFinished (*panel);
  14771. const auto& links = engine.getSong().midiLinks;
  14772. check ("multilink_steps", first != second && second != third && closed
  14773. && std::any_of (links.begin(), links.end(), [&] (const MidiLink& l) { return l.target == volume && l.cc == 30; }),
  14774. first + " > " + second + " > " + third);
  14775. }
  14776. // ---- Global link settings
  14777. {
  14778. auto panel = lynx::makeRemoteControlPanel (engine, { volume }, true);
  14779. shoot (*panel, "global-default");
  14780. lynx::remoteControlPanelSetController (*panel, 2, 1, 11);
  14781. lynx::remoteControlPanelSetFormula (*panel, "Input*0.5");
  14782. lynx::remoteControlPanelPress (*panel, 2);
  14783. const auto global = engine.globalLinkOf (volume);
  14784. check ("global_link_written", global && global->cc == 11 && global->port == 2 && global->formula == "Input*0.5");
  14785. const auto text = engine.getMidiPrefs().toText();
  14786. const auto back = lynx::prefs::MidiPrefs::fromText (text);
  14787. check ("global_link_settings_round_trip", back.globalLinks == engine.getMidiPrefs().globalLinks && text.find ("linkset=2|0|469|Input*0.5") != std::string::npos);
  14788. auto again = lynx::makeRemoteControlPanel (engine, { volume }, true);
  14789. shoot (*again, "global-existing-link");
  14790. engine.setGlobalLink (volume, std::nullopt);
  14791. check ("global_link_removed", ! engine.globalLinkOf (volume));
  14792. }
  14793. // ---- the project file: links with settings come back; a project of an older version loads the same
  14794. {
  14795. lynx::Song song = engine.getSong();
  14796. MidiLink plain { 7, -1, volume };
  14797. MidiLink rich { 74, 2, pan };
  14798. rich.port = 4;
  14799. rich.formula = "Min(Input*1.1,0.5)+Max(Input*1.1,0.6)-0.6";
  14800. rich.smooth = true;
  14801. rich.smoothing = -300;
  14802. rich.omni = true;
  14803. song.midiLinks = { plain, rich };
  14804. juce::String error;
  14805. const auto json = lynx::ProjectFile::toJson (song);
  14806. const auto back = lynx::ProjectFile::fromJson (json, error);
  14807. check ("project_round_trip", back && back->midiLinks == song.midiLinks, error);
  14808. // without settings the file holds only the list older versions wrote
  14809. song.midiLinks = { plain };
  14810. const auto plainJson = lynx::ProjectFile::toJson (song);
  14811. check ("plain_links_write_the_old_form", ! plainJson.contains ("midiLinkSettings") && plainJson.contains ("midiLinks"));
  14812. const auto plainBack = lynx::ProjectFile::fromJson (plainJson, error);
  14813. check ("old_project_loads_the_same", plainBack && plainBack->midiLinks.size() == 1 && plainBack->midiLinks[0] == plain
  14814. && ! plainBack->midiLinks[0].hasSettings());
  14815. // what an older version does with a new file: it reads "midiLinks" alone, so the links stay (plain)
  14816. auto parsed = juce::JSON::parse (json);
  14817. if (auto* o = parsed.getDynamicObject())
  14818. o->removeProperty ("midiLinkSettings");
  14819. const auto stripped = lynx::ProjectFile::fromJson (juce::JSON::toString (parsed), error);
  14820. check ("older_version_keeps_the_links", stripped && stripped->midiLinks.size() == 2 && stripped->midiLinks[1].cc == 74
  14821. && ! stripped->midiLinks[1].hasSettings());
  14822. }
  14823. // ---- round 190cs: FL's live answers (live check 190cq) and the note / button link modes
  14824. {
  14825. const auto state = [] (juce::Component& p) { return lynx::remoteControlPanelState (p); };
  14826. engine.editSong ([] (lynx::Song& s) { s.midiLinks.clear(); });
  14827. // the layout FL shows: no assignment list without a link, no Skip outside Multilink, no internal
  14828. // controller group without a controller in the project; the parameter caption in FL's words
  14829. auto fresh = lynx::makeRemoteControlPanel (engine, { volume }, false);
  14830. shoot (*fresh, "cs-remote-default");
  14831. check ("cs_layout_without_link", state (*fresh).contains ("|" + lynx::tr ("Channel volume") + "|") && state (*fresh).contains ("|shown=POC|"), state (*fresh));
  14832. // Omni: enabled on a mixer track's volume (FL: "Insert 1 - Volume"), greyed on the tempo
  14833. auto onInsert = lynx::makeRemoteControlPanel (engine, { insert }, false);
  14834. auto onTempo = lynx::makeRemoteControlPanel (engine, { AutomationTarget { AutomationTargetKind::tempo, 0 } }, false);
  14835. shoot (*onInsert, "cs-remote-omni-insert");
  14836. check ("cs_omni_mixer_track", state (*onInsert).contains ("|omni=on|") && state (*onTempo).contains ("|omni=off|"),
  14837. state (*onInsert) + " / " + state (*onTempo));
  14838. // the formula compiles on Enter only; FL's messages and colours
  14839. lynx::remoteControlPanelSetFormula (*fresh, "1-Input^2", false);
  14840. check ("cs_no_compile_while_typing", state (*fresh).contains ("|" + lynx::tr ("(default 1:1 mapping)") + "|"), state (*fresh));
  14841. lynx::remoteControlPanelSetFormula (*fresh, "-Input^2");
  14842. shoot (*fresh, "cs-remote-compiled");
  14843. check ("cs_compiled_on_enter", state (*fresh).contains ("|" + lynx::tr ("Compiled ok.") + "|"), state (*fresh));
  14844. const std::pair<const char*, const char*> errors[] { { "Input*", "Syntax error: function or operand" },
  14845. { "foo(Input)", "Invalid identifier: foo" },
  14846. { "Sin(Input", "Unequal brackets" },
  14847. { "Input 2", "input two space limited" } };
  14848. for (const auto& [text, expected] : errors)
  14849. {
  14850. lynx::remoteControlPanelSetFormula (*fresh, text);
  14851. check ("cs_fl_error_text", state (*fresh).contains (expected), state (*fresh));
  14852. }
  14853. lynx::remoteControlPanelSetFormula (*fresh, "foo(Input)");
  14854. shoot (*fresh, "cs-remote-error");
  14855. // Accept with that formula: the link is made, the formula is not kept (FL reopens it as "Input")
  14856. lynx::remoteControlPanelSetController (*fresh, -1, 1, 7);
  14857. lynx::remoteControlPanelPress (*fresh, 2);
  14858. check ("cs_bad_formula_accept_is_input", engine.getSong().midiLinks.size() == 1 && engine.getSong().midiLinks[0].cc == 7
  14859. && engine.getSong().midiLinks[0].formula.empty());
  14860. auto reopened = lynx::makeRemoteControlPanel (engine, { volume }, false);
  14861. shoot (*reopened, "cs-remote-reopened");
  14862. check ("cs_reopened_shows_input_and_link_list", state (*reopened).startsWith ("-1|1|7|Input|" + lynx::tr ("(default 1:1 mapping)") + "|")
  14863. && state (*reopened).contains ("|shown=PAOC|"),
  14864. state (*reopened));
  14865. // the internal controller group appears with a controller in the project, with "Record automation"
  14866. engine.editSong ([] (lynx::Song& s) {
  14867. lynx::EffectSlot peak;
  14868. peak.kind = lynx::EffectKind::peakController;
  14869. s.mixer[0].effects.push_back (peak);
  14870. });
  14871. auto withController = lynx::makeRemoteControlPanel (engine, { volume }, false);
  14872. lynx::remoteControlPanelSetInternal (*withController, 1, true);
  14873. shoot (*withController, "cs-remote-internal");
  14874. check ("cs_internal_group_shown", state (*withController).contains ("|shown=PAIOC|") && state (*withController).startsWith ("-1|1|-1|"),
  14875. state (*withController));
  14876. lynx::remoteControlPanelPress (*withController, 2);
  14877. const auto& autos = engine.getSong().automations;
  14878. check ("cs_record_automation_kept", std::any_of (autos.begin(), autos.end(), [&] (const lynx::Automation& a) {
  14879. return a.isLive() && a.target == volume && a.recordLive;
  14880. }));
  14881. engine.editSong ([] (lynx::Song& s) {
  14882. s.mixer[0].effects.pop_back();
  14883. s.automations.clear();
  14884. s.midiLinks.clear();
  14885. });
  14886. // the global window: no parameter list, Omni, Remove conflicts or Skip; Mode is there
  14887. auto globalPanel = lynx::makeRemoteControlPanel (engine, { volume }, true);
  14888. shoot (*globalPanel, "cs-global-default");
  14889. check ("cs_global_layout", state (*globalPanel).contains ("|shown=|"), state (*globalPanel));
  14890. // a key link in each Mode: note 60 = FL's controller number 256 + 60
  14891. const auto key = lynx::linkNoteBase + 60;
  14892. auto modePanel = lynx::makeRemoteControlPanel (engine, { volume }, false);
  14893. lynx::remoteControlPanelSetController (*modePanel, -1, 1, key);
  14894. lynx::remoteControlPanelSetMode (*modePanel, 2);
  14895. shoot (*modePanel, "cs-remote-note-latch");
  14896. lynx::remoteControlPanelPress (*modePanel, 2);
  14897. check ("cs_note_link_written", engine.getSong().midiLinks.size() == 1 && engine.getSong().midiLinks[0].cc == key
  14898. && engine.getSong().midiLinks[0].mode == 2);
  14899. const auto play = [&engine, key, volume] (int velocity) {
  14900. engine.injectControllerForTest (key, 0, velocity);
  14901. return engine.currentTargetValue (volume);
  14902. };
  14903. const auto setMode = [&engine] (int mode) {
  14904. engine.editSong ([mode] (lynx::Song& s) { s.midiLinks[0].mode = mode; });
  14905. engine.editSong ([] (lynx::Song& s) { s.setTargetValue ({ AutomationTargetKind::channelVolume, 0 }, 0.25f); });
  14906. };
  14907. setMode (2); // Latch: press switches, release does nothing
  14908. const auto l1 = play (100), l1off = play (0), l2 = play (90), l2off = play (0);
  14909. check ("cs_mode_latch", std::abs (l1 - 1.0f) < 1e-4f && std::abs (l1off - 1.0f) < 1e-4f && l2 < 1e-4f && l2off < 1e-4f,
  14910. juce::String (l1) + " " + juce::String (l1off) + " " + juce::String (l2) + " " + juce::String (l2off));
  14911. setMode (1); // Hold: the velocity while held, back to 0 on release
  14912. const auto h1 = play (100), h1off = play (0);
  14913. check ("cs_mode_hold", std::abs (h1 - 100.0f / 127.0f) < 1e-4f && h1off < 1e-4f, juce::String (h1) + " " + juce::String (h1off));
  14914. setMode (0); // Default: as Hold for a key
  14915. const auto d1 = play (64), d1off = play (0);
  14916. check ("cs_mode_default", std::abs (d1 - 64.0f / 127.0f) < 1e-4f && d1off < 1e-4f, juce::String (d1) + " " + juce::String (d1off));
  14917. setMode (3); // Inc: each press adds 1/128
  14918. const auto i1 = play (100), i1off = play (0), i2 = play (20);
  14919. check ("cs_mode_inc", std::abs (i1 - (0.25f + 1.0f / 128.0f)) < 1e-4f && std::abs (i1off - i1) < 1e-6f
  14920. && std::abs (i2 - (0.25f + 2.0f / 128.0f)) < 1e-4f,
  14921. juce::String (i1) + " " + juce::String (i2));
  14922. setMode (4); // Stay: the velocity, kept after the release
  14923. const auto s1 = play (100), s1off = play (0);
  14924. 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));
  14925. // the project file keeps the key link and its mode; an older reader skips it
  14926. lynx::Song song = engine.getSong();
  14927. song.midiLinks[0].mode = 2;
  14928. MidiLink cc7 { 7, 0, pan };
  14929. cc7.mode = 4;
  14930. song.midiLinks.insert (song.midiLinks.begin(), cc7);
  14931. juce::String error;
  14932. const auto json = lynx::ProjectFile::toJson (song);
  14933. const auto back = lynx::ProjectFile::fromJson (json, error);
  14934. check ("cs_note_link_round_trip", back && back->midiLinks == song.midiLinks && json.contains ("midiNoteLinks"), error);
  14935. auto parsed = juce::JSON::parse (json);
  14936. if (auto* o = parsed.getDynamicObject())
  14937. {
  14938. o->removeProperty ("midiNoteLinks");
  14939. o->removeProperty ("midiLinkSettings");
  14940. }
  14941. const auto older = lynx::ProjectFile::fromJson (juce::JSON::toString (parsed), error);
  14942. check ("cs_older_reader_keeps_cc_links_only", older && older->midiLinks.size() == 1 && older->midiLinks[0].cc == 7);
  14943. // "Record automation" of an internal-controller link, saved only when on
  14944. lynx::Automation live;
  14945. live.target = volume;
  14946. live.source.track = 0;
  14947. live.recordLive = true;
  14948. song.automations = { live };
  14949. const auto withLive = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  14950. live.recordLive = false;
  14951. song.automations = { live };
  14952. check ("cs_record_automation_round_trip", withLive && withLive->automations.size() == 1 && withLive->automations[0].recordLive
  14953. && ! lynx::ProjectFile::toJson (song).contains ("recordLive"));
  14954. engine.editSong ([] (lynx::Song& s) { s.midiLinks.clear(); });
  14955. }
  14956. // ---- menus: the control menu, the formula presets, the controller list, the Multilink items
  14957. {
  14958. juce::PopupMenu control;
  14959. lynx::addAutomationItem (control, engine, volume, true);
  14960. engine.setMultilink (true);
  14961. engine.noteTweaked (volume);
  14962. engine.noteTweaked (pan);
  14963. juce::PopupMenu multilink;
  14964. lynx::addMultilinkControlsItems (multilink, engine);
  14965. check ("multilink_queue", engine.multilinkTargets().size() == 2);
  14966. engine.setMultilink (false);
  14967. saveMenus (juce::StringArray { "Control menu", "Formula presets", "Multilink" },
  14968. std::vector<juce::PopupMenu> { control, lynx::remoteControlFormulaMenu ([] (const juce::String&) {}), multilink },
  14969. prefix + "-menus.png");
  14970. saveMenus (juce::StringArray { "Ctrl menu" }, std::vector<juce::PopupMenu> { lynx::remoteControlControllerMenu ([] (int) {}) },
  14971. prefix + "-ctrl-menu.png");
  14972. // the Mode list as its box pops it up (round 190cs)
  14973. juce::PopupMenu modes;
  14974. for (const char* m : { "Default", "Hold", "Latch", "Inc", "Stay" })
  14975. modes.addItem (lynx::tr (m), true, juce::String (m) == "Default", [] {});
  14976. saveMenus (juce::StringArray { "Mode" }, std::vector<juce::PopupMenu> { modes }, prefix + "-mode-menu.png");
  14977. }
  14978. // ---- Settings > MIDI: the input's Port box, the link list with a link's settings
  14979. {
  14980. engine.editSong ([&] (lynx::Song& s) {
  14981. MidiLink l { 74, 2, pan };
  14982. l.port = 4;
  14983. l.formula = "1-Input";
  14984. l.smooth = true;
  14985. s.midiLinks = { MidiLink { 7, 0, volume }, l };
  14986. });
  14987. auto page = lynx::makeMidiPage (engine, {}, false);
  14988. page->setSize (760, 900);
  14989. shoot (*page, "settings-midi");
  14990. }
  14991. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\nresult=" + (allOk ? "OK" : "FAIL") + "\n");
  14992. return allOk;
  14993. }
  14994. // A stand-in hosted plugin for the shot route: three parameters, its state = their values
  14995. struct FlCtlShotPlugin final : juce::AudioPluginInstance
  14996. {
  14997. FlCtlShotPlugin()
  14998. {
  14999. for (const char* n : { "Cutoff", "Resonance", "Drive" })
  15000. addHostedParameter (std::make_unique<juce::AudioParameterFloat> (juce::ParameterID (n, 1), n, 0.0f, 1.0f, 0.5f));
  15001. }
  15002. const juce::String getName() const override { return "Shot plugin"; }
  15003. void prepareToPlay (double, int) override {}
  15004. void releaseResources() override {}
  15005. void processBlock (juce::AudioBuffer<float>&, juce::MidiBuffer&) override {}
  15006. double getTailLengthSeconds() const override { return 0.0; }
  15007. bool acceptsMidi() const override { return false; }
  15008. bool producesMidi() const override { return false; }
  15009. juce::AudioProcessorEditor* createEditor() override { return nullptr; }
  15010. bool hasEditor() const override { return false; }
  15011. int getNumPrograms() override { return 1; }
  15012. int getCurrentProgram() override { return 0; }
  15013. void setCurrentProgram (int) override {}
  15014. const juce::String getProgramName (int) override { return {}; }
  15015. void changeProgramName (int, const juce::String&) override {}
  15016. void getStateInformation (juce::MemoryBlock& b) override
  15017. {
  15018. for (auto* p : getParameters())
  15019. {
  15020. const float v = static_cast<juce::AudioParameterFloat*> (p)->get();
  15021. b.append (&v, sizeof (float));
  15022. }
  15023. }
  15024. void setStateInformation (const void* data, int size) override
  15025. {
  15026. const auto& list = getParameters();
  15027. for (int i = 0; i < list.size() && (i + 1) * (int) sizeof (float) <= size; ++i)
  15028. *static_cast<juce::AudioParameterFloat*> (list[i]) = static_cast<const float*> (data)[i];
  15029. }
  15030. void fillInPluginDescription (juce::PluginDescription& d) const override
  15031. {
  15032. d.name = getName();
  15033. d.pluginFormatName = "Shot";
  15034. d.fileOrIdentifier = "shot";
  15035. }
  15036. };
  15037. static juce::File writeShotSample (const juce::File& file, double hz)
  15038. {
  15039. juce::AudioBuffer<float> buffer (1, 22050);
  15040. for (int i = 0; i < buffer.getNumSamples(); ++i)
  15041. buffer.setSample (0, i, (float) (std::sin (juce::MathConstants<double>::twoPi * hz * i / 44100.0) * std::exp (-i / 6000.0)));
  15042. file.deleteFile();
  15043. juce::WavAudioFormat wav;
  15044. if (auto out = std::unique_ptr<juce::AudioFormatWriter> (wav.createWriterFor (file.createOutputStream().release(), 44100.0, 1, 16, {}, 0)))
  15045. out->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
  15046. return file;
  15047. }
  15048. static bool clickMenuItem (const juce::PopupMenu& menu, const juce::String& text)
  15049. {
  15050. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  15051. if (it.getItem().text == text && it.getItem().isEnabled && it.getItem().action != nullptr)
  15052. {
  15053. it.getItem().action();
  15054. return true;
  15055. }
  15056. return false;
  15057. }
  15058. // --samplerpageshot <prefix> (round 190dh): FL's Sampler page offscreen — the page as FL's shot (dock188a) shows it,
  15059. // the legacy effects, a small window, a zoomed waveform — and its laws turned as a user would; prefix-checks.txt
  15060. bool runSamplerPageShot (const juce::String& prefix)
  15061. {
  15062. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  15063. juce::StringArray report;
  15064. bool allOk = true;
  15065. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  15066. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  15067. allOk = allOk && ok;
  15068. };
  15069. const auto shoot = [&prefix] (juce::Component& c, const char* name) {
  15070. savePng (c.createComponentSnapshot (c.getLocalBounds()), prefix + "-" + name + ".png");
  15071. };
  15072. lynx::AudioEngine engine (false);
  15073. const auto folder = juce::File (prefix).getParentDirectory().getChildFile ("sampler-samples");
  15074. folder.createDirectory();
  15075. // an 808-like kick, 1 s (FL's shot: "Basic 808 Kick.wav")
  15076. const auto kick = folder.getChildFile ("Basic 808 Kick.wav");
  15077. {
  15078. juce::AudioBuffer<float> buffer (1, 44100);
  15079. double phase = 0.0;
  15080. for (int i = 0; i < buffer.getNumSamples(); ++i)
  15081. {
  15082. const auto t = i / 44100.0;
  15083. phase += juce::MathConstants<double>::twoPi * (48.0 + 90.0 * std::exp (-t * 30.0)) / 44100.0;
  15084. buffer.setSample (0, i, (float) (0.9 * std::sin (phase) * std::exp (-t * 3.2)));
  15085. }
  15086. kick.deleteFile();
  15087. juce::WavAudioFormat wav;
  15088. if (auto out = std::unique_ptr<juce::AudioFormatWriter> (wav.createWriterFor (kick.createOutputStream().release(), 44100.0, 1, 16, {}, 0)))
  15089. out->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
  15090. }
  15091. engine.editSong ([&] (lynx::Song& s) {
  15092. if (s.channels.empty())
  15093. s.channels.resize (1);
  15094. lynx::audioclips::loadSampleInto (s.channels[0], kick.getFullPathName().toStdString(), "808 Kick");
  15095. // FL's shot: Resample and Load regions on, Use loop points on, declicking "Out only (no bleeding)"
  15096. s.channels[0].sampler.resampleOnLoad = true;
  15097. });
  15098. const auto sampler = [&engine] { return engine.getSong().channels[0].sampler; };
  15099. auto frame = lynx::makeChannelFrame (engine, 0, 0);
  15100. frame->setSize (frame->getWidth() > 0 ? frame->getWidth() : 700, frame->getHeight() > 0 ? frame->getHeight() : 720);
  15101. frame->createComponentSnapshot (frame->getLocalBounds()); // (starts the waveform's analysis)
  15102. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (8000);
  15103. shoot (*frame, "sampler-page");
  15104. report.add ("page size " + juce::String (frame->getWidth()) + "x" + juce::String (frame->getHeight()));
  15105. // ---- the laws, turned on the page
  15106. auto& f = *frame;
  15107. lynx::samplerPageTurn (f, "pingPong", 1.0);
  15108. check ("ping_pong", sampler().precompute.pingPong);
  15109. lynx::samplerPageTurn (f, "pingPong", 0.0);
  15110. lynx::samplerPageTurn (f, "loopStart", 5000.0);
  15111. check ("loop_start", sampler().loopStart == 5000 && sampler().loopEnd == 5001, juce::String (sampler().loopStart) + "/" + juce::String (sampler().loopEnd));
  15112. lynx::samplerPageTurn (f, "loopEnd", 15000.0);
  15113. check ("loop_end", sampler().loopStart == 5000 && sampler().loopEnd == 15000);
  15114. lynx::samplerPageTurn (f, "loopStart", 20000.0, true); // Shift: the loop moves
  15115. check ("loop_shift_moves", sampler().loopStart == 20000 && sampler().loopEnd == 30000, juce::String (sampler().loopStart) + "/" + juce::String (sampler().loopEnd));
  15116. check ("keep_on_disk_greyed_with_loop", lynx::samplerPageQuery (f, "keepOnDisk") == "0");
  15117. lynx::samplerPageTurn (f, "useLoops", 0.0);
  15118. check ("keep_on_disk_back", lynx::samplerPageQuery (f, "keepOnDisk") == "1" && ! sampler().useLoopPoints);
  15119. check ("not_cut_yet", ! lynx::channelCutsItself (engine.getSong().channels[0]));
  15120. lynx::samplerPageTurn (f, "useLoops", 1.0);
  15121. check ("use_loops_cuts_itself", sampler().useLoopPoints && lynx::channelCutsItself (engine.getSong().channels[0]));
  15122. engine.editSong ([] (lynx::Song& s) {
  15123. lynx::setChannelCutsItself (s.channels[0], 0, false);
  15124. s.channels[0].sampler.useLoopPoints = false;
  15125. });
  15126. lynx::samplerPageTurn (f, "crossfade", 300.0); // (Use loop points off: the crossfade switches it on)
  15127. check ("crossfade_switches_loops_on", sampler().precompute.crossfade == 300 && sampler().useLoopPoints);
  15128. lynx::samplerPageTurn (f, "crossfade", 0.0);
  15129. lynx::samplerPageTurn (f, "pitch", 300.0); // (Resample: FL switches to Auto)
  15130. check ("pitch_resample_to_auto", sampler().keepPitch && sampler().flStretchMode == 5 && sampler().flStretchPitch == 300
  15131. && lynx::samplerPageQuery (f, "mode") == lynx::tr ("General"),
  15132. lynx::samplerPageQuery (f, "mode") + " " + juce::String (sampler().pitch));
  15133. lynx::samplerPageTurn (f, "pitch", 0.0);
  15134. lynx::samplerPageTurn (f, "mode", 1.0); // Resample
  15135. check ("mode_resample", ! sampler().keepPitch && std::abs (sampler().pitch) < 1.0e-4f);
  15136. lynx::samplerPageTurn (f, "time", 4.0);
  15137. lynx::samplerPageTurn (f, "mul", 10000.0);
  15138. check ("time_mul", std::abs (sampler().stretchBeats - 8.0f) < 1.0e-3f && sampler().stretchMul == 10000, juce::String (sampler().stretchBeats));
  15139. lynx::samplerPageTurn (f, "mul", 0.0);
  15140. lynx::samplerPageTurn (f, "time", 0.0);
  15141. lynx::samplerPageTurn (f, "length", 0.5);
  15142. lynx::samplerPageTurn (f, "smpStart", 0.5);
  15143. check ("smp_start_keeps_length", std::abs (sampler().regionStart - 0.5f) < 1.0e-3f && std::abs (sampler().regionEnd - 0.75f) < 1.0e-3f,
  15144. juce::String (sampler().regionStart) + "-" + juce::String (sampler().regionEnd));
  15145. lynx::samplerPageTurn (f, "smpStart", 0.0);
  15146. lynx::samplerPageTurn (f, "length", 1.0);
  15147. lynx::samplerPageTurn (f, "declick", 4.0);
  15148. check ("declick_mode", sampler().declickMode == 4);
  15149. lynx::samplerPageTurn (f, "declick", 0.0);
  15150. // ---- the .lynx keeps what the page set
  15151. {
  15152. lynx::samplerPageTurn (f, "mul", -5000.0);
  15153. lynx::samplerPageTurn (f, "keepOnDisk", 1.0);
  15154. juce::String error;
  15155. const auto json = lynx::ProjectFile::toJson (engine.getSong(), false);
  15156. const auto back = lynx::ProjectFile::fromJson (json, error);
  15157. check ("lynx_round_trip", back.has_value() && back->channels[0].sampler == engine.getSong().channels[0].sampler, error);
  15158. lynx::samplerPageTurn (f, "mul", 0.0);
  15159. lynx::samplerPageTurn (f, "keepOnDisk", 0.0);
  15160. }
  15161. // ---- shots: FL's state again (loop points from the file: none), the legacy panel, a zoom, a small window
  15162. engine.editSong ([] (lynx::Song& s) {
  15163. auto& ch = s.channels[0];
  15164. ch.sampler.loopStart = ch.sampler.loopEnd = -1;
  15165. ch.sampler.useLoopPoints = true;
  15166. ch.sampler.precompute = {};
  15167. });
  15168. lynx::samplerPageTurn (f, "show", 0.0); // (no control: the page shows the channel again)
  15169. frame->createComponentSnapshot (frame->getLocalBounds());
  15170. shoot (*frame, "sampler-page-fl-state");
  15171. lynx::samplerPageTurn (f, "legacy", 1.0);
  15172. check ("legacy_panel", lynx::samplerPageQuery (f, "legacy") == "1");
  15173. shoot (*frame, "sampler-page-legacy");
  15174. lynx::samplerPageTurn (f, "legacy", 0.0);
  15175. lynx::samplerPageTurn (f, "zoom", 0.25);
  15176. check ("zoom_scroll", lynx::samplerPageQuery (f, "scroll") == "0.250", lynx::samplerPageQuery (f, "scroll"));
  15177. shoot (*frame, "sampler-page-zoom");
  15178. lynx::samplerPageTurn (f, "zoom", 1.0);
  15179. frame->setSize (520, 470);
  15180. frame->createComponentSnapshot (frame->getLocalBounds());
  15181. shoot (*frame, "sampler-page-small");
  15182. report.add (juce::String ("result=") + (allOk ? "OK" : "FAIL"));
  15183. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\n");
  15184. return allOk;
  15185. }
  15186. bool runFlCtlShot (const juce::String& prefix)
  15187. {
  15188. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  15189. juce::StringArray report;
  15190. bool allOk = true;
  15191. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  15192. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  15193. allOk = allOk && ok;
  15194. };
  15195. const auto shoot = [&prefix] (juce::Component& c, const char* name) {
  15196. savePng (c.createComponentSnapshot (c.getLocalBounds()), prefix + "-" + name + ".png");
  15197. };
  15198. using lynx::AutomationTarget;
  15199. using lynx::AutomationTargetKind;
  15200. lynx::AudioEngine engine (false);
  15201. engine.editSong ([] (lynx::Song& s) {
  15202. if (s.channels.size() < 3)
  15203. s.channels.resize (3);
  15204. if (s.patterns.empty())
  15205. s.patterns.resize (1);
  15206. s.currentPattern = 0;
  15207. });
  15208. const AutomationTarget volume { AutomationTargetKind::channelVolume, 0 }, pan { AutomationTargetKind::channelPan, 0 };
  15209. // ---- FL's multilink menu: on with two queued controls, off with the last tweaked parameters
  15210. {
  15211. engine.setMultilink (true);
  15212. engine.noteTweaked (volume);
  15213. engine.noteTweaked (pan);
  15214. auto on = lynx::multilinkButtonMenu (engine);
  15215. juce::PopupMenu::MenuItemIterator first (on);
  15216. first.next();
  15217. check ("ml_caption_on", first.getItem().isSectionHeader && first.getItem().text == lynx::tr ("{0} parameters selected", { "2" }), first.getItem().text);
  15218. // Init pattern: the values at the pattern's start; ends multilink
  15219. const auto v0 = engine.currentTargetValue (volume);
  15220. lynx::runMultilinkAction (engine, lynx::mlmenu::Action::initPattern, engine.multilinkTargets(), 0);
  15221. const auto& lanes = engine.getSong().patterns[0].events;
  15222. check ("ml_init_pattern", lanes.size() == 2 && ! lanes[0].events.empty() && lanes[0].events[0].tick == 0
  15223. && std::abs (lanes[0].events[0].value - v0) < 1.0e-6f && ! engine.isMultilinkOn());
  15224. // Randomize keeps multilink on; Humanize moves at most an eighth
  15225. engine.setMultilink (true);
  15226. engine.noteTweaked (volume);
  15227. engine.noteTweaked (pan);
  15228. lynx::runMultilinkAction (engine, lynx::mlmenu::Action::randomize, engine.multilinkTargets(), 1234);
  15229. check ("ml_randomize_keeps_queue", engine.isMultilinkOn() && engine.multilinkTargets().size() == 2);
  15230. const auto before = engine.currentTargetValue (volume);
  15231. lynx::runMultilinkAction (engine, lynx::mlmenu::Action::humanize, engine.multilinkTargets(), 99);
  15232. check ("ml_humanize_small", std::abs (engine.currentTargetValue (volume) - before) <= 0.1251f && engine.isMultilinkOn(),
  15233. juce::String (before) + " -> " + juce::String (engine.currentTargetValue (volume)));
  15234. lynx::runMultilinkAction (engine, lynx::mlmenu::Action::initSong, engine.multilinkTargets(), 0);
  15235. check ("ml_init_song", engine.getSong().findInitialValue (volume) >= 0 && ! engine.isMultilinkOn());
  15236. // off: the last two tweaked parameters, no Cancel
  15237. auto off = lynx::multilinkButtonMenu (engine);
  15238. bool hasCancel = false;
  15239. for (juce::PopupMenu::MenuItemIterator it (off); it.next();)
  15240. hasCancel = hasCancel || it.getItem().text == lynx::tr ("Cancel");
  15241. juce::PopupMenu::MenuItemIterator offFirst (off);
  15242. offFirst.next();
  15243. check ("ml_off_caption", offFirst.getItem().text == lynx::tr ("Last 2 tweaked parameters") && ! hasCancel, offFirst.getItem().text);
  15244. // LYNX's own one-step items stay, after FL's items below a line (greyed while multilink is off)
  15245. juce::String last;
  15246. bool lineBefore = false, prevLine = false;
  15247. for (juce::PopupMenu::MenuItemIterator it (on); it.next();)
  15248. {
  15249. if (it.getItem().text == lynx::tr ("Link to controller"))
  15250. lineBefore = prevLine;
  15251. prevLine = it.getItem().isSeparator;
  15252. last = it.getItem().text;
  15253. }
  15254. check ("ml_lynx_items_after_fl", lineBefore && last == lynx::tr ("Override global links"), last);
  15255. saveMenus (juce::StringArray { "Multilink on (2 queued)", "Multilink off" }, std::vector<juce::PopupMenu> { on, off },
  15256. prefix + "-multilink-menu.png");
  15257. }
  15258. // ---- the plugin menu's spare state and Parameters > Link all parameters...
  15259. {
  15260. FlCtlShotPlugin plugin;
  15261. juce::PopupMenu menu;
  15262. lynx::addPluginWrapperItems (menu, engine, plugin, { AutomationTargetKind::channelParam, 1, 0, 0 });
  15263. saveMenus (juce::StringArray { "Plugin menu: spare state and parameters" }, std::vector<juce::PopupMenu> { menu }, prefix + "-plugin-menu.png");
  15264. const auto targets = lynx::allPluginParameterTargets (plugin, { AutomationTargetKind::channelParam, 1, 0, 0 });
  15265. check ("link_all_parameters", targets.size() == 3 && targets[2].param == 2 && targets[2].index == 1);
  15266. auto* cutoff = static_cast<juce::AudioParameterFloat*> (plugin.getParameters()[0]);
  15267. *cutoff = 0.2f;
  15268. check ("spare_store", clickMenuItem (menu, lynx::tr ("Store in spare state")));
  15269. *cutoff = 0.9f;
  15270. juce::PopupMenu again;
  15271. lynx::addPluginWrapperItems (again, engine, plugin, { AutomationTargetKind::channelParam, 1, 0, 0 });
  15272. check ("spare_flip", clickMenuItem (again, lynx::tr ("Flip with spare state")) && std::abs (cutoff->get() - 0.2f) < 1.0e-6f, juce::String (cutoff->get()));
  15273. 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()));
  15274. lynx::sparestate::shared().forget (&plugin);
  15275. }
  15276. // ---- the sampler's File row: Load (history menu, wheel), Locate, Remove
  15277. {
  15278. const auto folder = juce::File (prefix).getParentDirectory().getChildFile ("flctl-samples");
  15279. folder.createDirectory();
  15280. const auto a = writeShotSample (folder.getChildFile ("Kick 1.wav"), 60.0), b = writeShotSample (folder.getChildFile ("Snare 2.wav"), 200.0),
  15281. c = writeShotSample (folder.getChildFile ("Hat 3.wav"), 900.0);
  15282. lynx::samplehistory::list().clear();
  15283. engine.editSong ([&] (lynx::Song& s) {
  15284. for (const auto& f : { c, b, a }) // (each load goes into the history, newest first)
  15285. lynx::audioclips::loadSampleInto (s.channels[1], f.getFullPathName().toStdString(), f.getFileNameWithoutExtension().toStdString());
  15286. });
  15287. check ("history_order", lynx::samplehistory::list().size() == 3 && lynx::samplehistory::list().front() == a.getFullPathName().toStdString());
  15288. juce::File located;
  15289. lynx::locateInBrowserHandler() = [&located] (const juce::File& f) { located = f; };
  15290. auto frame = lynx::makeChannelFrame (engine, 1, 0);
  15291. frame->setSize (frame->getWidth() > 0 ? frame->getWidth() : 600, frame->getHeight() > 0 ? frame->getHeight() : 820);
  15292. frame->createComponentSnapshot (frame->getLocalBounds()); // (starts the waveform's analysis)
  15293. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (8000);
  15294. shoot (*frame, "sampler-file-row");
  15295. const auto history = lynx::samplerHistoryMenu (*frame);
  15296. check ("history_menu", history.has_value() && history->getNumItems() == 4); // (caption + three samples)
  15297. if (history)
  15298. saveMenus (juce::StringArray { "Load: Sample history" }, std::vector<juce::PopupMenu> { *history }, prefix + "-sample-history.png");
  15299. lynx::samplerFileRowPress (*frame, 0); // wheel down: the next (older) sample
  15300. check ("wheel_down", engine.getSong().channels[1].samplePath == b.getFullPathName().toStdString(), juce::String (engine.getSong().channels[1].samplePath));
  15301. lynx::samplerFileRowPress (*frame, 1); // wheel up: back
  15302. check ("wheel_up", engine.getSong().channels[1].samplePath == a.getFullPathName().toStdString());
  15303. lynx::samplerFileRowPress (*frame, 2);
  15304. check ("locate", located == a, located.getFullPathName());
  15305. lynx::samplerFileRowPress (*frame, 3);
  15306. check ("remove", engine.getSong().channels[1].samplePath.empty());
  15307. engine.undo();
  15308. check ("remove_undo", engine.getSong().channels[1].samplePath == a.getFullPathName().toStdString());
  15309. lynx::locateInBrowserHandler() = nullptr;
  15310. }
  15311. // ---- a sampler running FL's voice: FL's Envelope / instrument page with the tensions, the predelay and presets
  15312. {
  15313. engine.editSong ([] (lynx::Song& s) {
  15314. auto& ch = s.channels[2];
  15315. ch.instrument = lynx::InstrumentKind::sampler;
  15316. ch.name = "FL sampler";
  15317. const auto snap = lynx::flvp::defaultSnapshot();
  15318. ch.sampler.flChannel.assign (90, 0);
  15319. std::memcpy (ch.sampler.flChannel.data(), snap.data(), 85 * 4);
  15320. std::memcpy (&ch.sampler.flChannel[85], snap.data() + 0x15c, 4);
  15321. std::memcpy (&ch.sampler.flChannel[86], snap.data() + 0x160, 4);
  15322. std::memcpy (&ch.sampler.flChannel[87], snap.data() + 0x168, 4);
  15323. ch.sampler.flChannel[88] = 96;
  15324. ch.sampler.flChannel[89] = 0;
  15325. auto& vol = ch.sampler.flChannel; // the volume envelope on, bent
  15326. vol[17 + 1] = -1;
  15327. vol[17 + 2] = 4000; // predelay
  15328. vol[17 + 14] = -70; // attack tension
  15329. vol[17 + 15] = 60; // decay tension
  15330. vol[17 + 16] = -40; // release tension
  15331. });
  15332. auto frame = lynx::makeChannelFrame (engine, 2, 1);
  15333. frame->setSize (frame->getWidth() > 0 ? frame->getWidth() : 600, frame->getHeight() > 0 ? frame->getHeight() : 560);
  15334. shoot (*frame, "sampler-fl-envelope");
  15335. check ("fl_page_shown", lynx::flVoicePresetsMenu (*frame).has_value());
  15336. lynx::flVoicePresetFolder().deleteRecursively();
  15337. check ("preset_save", lynx::flVoiceSavePreset (*frame, "Bent volume")
  15338. && lynx::flVoicePresetFolder().getChildFile ("Bent volume.CHENV").getSize() == 68);
  15339. if (const auto menu = lynx::flVoicePresetsMenu (*frame))
  15340. saveMenus (juce::StringArray { "Channel envelope presets" }, std::vector<juce::PopupMenu> { *menu }, prefix + "-envelope-presets.png");
  15341. // the preset into the pitch target: its record becomes the saved one
  15342. lynx::showFlVoiceTarget (*frame, lynx::flvoice::pitch);
  15343. const auto loaded = lynx::flVoiceLoadPreset (*frame, lynx::flVoicePresetFolder().getChildFile ("Bent volume.CHENV"));
  15344. const auto& fl = engine.getSong().channels[2].sampler.flChannel;
  15345. check ("preset_load", loaded && fl.size() == 90 && fl[68 + 2] == 4000 && fl[68 + 14] == -70 && fl[68 + 16] == -40 && fl[88] == 96);
  15346. engine.undo();
  15347. check ("preset_load_undo", engine.getSong().channels[2].sampler.flChannel[68 + 14] != -70);
  15348. }
  15349. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\nresult=" + (allOk ? "OK" : "FAIL") + "\n");
  15350. return allOk;
  15351. }
  15352. // --flplshot (round 190dx): see the dispatch above
  15353. bool runHdrShot190ft (const juce::String& prefix)
  15354. {
  15355. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  15356. juce::StringArray report;
  15357. bool allOk = true;
  15358. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  15359. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  15360. allOk = allOk && ok;
  15361. };
  15362. const auto list = [] (const std::vector<int>& v) {
  15363. juce::StringArray out;
  15364. for (auto i : v)
  15365. out.add (juce::String (i));
  15366. return out.joinIntoString (",");
  15367. };
  15368. lynx::AudioEngine engine (false);
  15369. lynx::MainComponent ui (engine, false);
  15370. ui.setSize (1600, 900);
  15371. {
  15372. auto song = lynx::Song::makeDefault();
  15373. song.playlist.clear();
  15374. for (int t = 0; t < 6; ++t)
  15375. {
  15376. if ((int) song.playlistTracks.size() <= t)
  15377. song.playlistTracks.resize ((std::size_t) t + 1);
  15378. song.playlistTracks[(std::size_t) t].name = juce::String ("Track " + juce::String (t + 1)).toStdString();
  15379. for (int k = 0; k < 2; ++k)
  15380. {
  15381. lynx::Clip c;
  15382. c.kind = lynx::ClipKind::pattern;
  15383. c.pattern = 0;
  15384. c.track = t;
  15385. c.start = (std::int64_t) (k * 4 + t % 3) * lynx::ppq;
  15386. c.length = 2 * lynx::ppq;
  15387. song.playlist.push_back (c);
  15388. }
  15389. }
  15390. if (song.mixer.size() < 4)
  15391. song.mixer.resize (4);
  15392. song.playlistTracks[2].mode = lynx::PlaylistTrackMode::audio; // an audio track linked to mixer track 3
  15393. song.playlistTracks[2].mixerTrack = 3;
  15394. song.playlistTracks[2].name = "Vox";
  15395. engine.setSong (std::move (song));
  15396. }
  15397. engine.dispatchPendingMessages();
  15398. ui.selectTabForSnapshot (2);
  15399. engine.dispatchPendingMessages();
  15400. auto& pl = ui.getPlaylistForSnapshot();
  15401. pl.setSize (juce::jmax (pl.getWidth(), 900), juce::jmax (pl.getHeight(), 600));
  15402. auto source = juce::Desktop::getInstance().getMainMouseSource();
  15403. const auto now = juce::Time::getCurrentTime();
  15404. const juce::ModifierKeys left (juce::ModifierKeys::leftButtonModifier);
  15405. const int ctrl = juce::ModifierKeys::commandModifier; // (FL's Ctrl: Cmd on a Mac)
  15406. const int shift = juce::ModifierKeys::shiftModifier;
  15407. const int alt = juce::ModifierKeys::altModifier;
  15408. const auto event = [&] (juce::Component& c, juce::Point<int> p, juce::ModifierKeys mods, juce::Point<int> down, int clicks, bool dragged) {
  15409. 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);
  15410. };
  15411. // a press (and release) at p with the modifiers; `to`: a drag there before the release
  15412. const auto press = [&] (juce::Component& c, juce::Point<int> p, juce::ModifierKeys mods, std::optional<juce::Point<int>> to = {}, int clicks = 1) {
  15413. const auto down = mods.withFlags (juce::ModifierKeys::leftButtonModifier);
  15414. c.mouseMove (event (c, p, mods, p, 1, false));
  15415. c.mouseDown (event (c, p, down, p, clicks, false));
  15416. if (to)
  15417. c.mouseDrag (event (c, *to, down, p, clicks, true));
  15418. c.mouseUp (event (c, to ? *to : p, mods, p, clicks, to.has_value()));
  15419. };
  15420. const auto headerPoint = [&] (int track) { const auto r = pl.trackRowForSnapshot (track); return juce::Point<int> (40, r.getY() + juce::jmin (10, r.getHeight() / 3)); };
  15421. const auto bandPoint = [&] (int track) { const auto r = pl.trackRowForSnapshot (track); return juce::Point<int> (40, r.getBottom() - 2); };
  15422. const auto clipsOn = [&] (const std::vector<int>& tracks) {
  15423. std::vector<int> out;
  15424. const auto& song = engine.getSong();
  15425. for (int i = 0; i < (int) song.playlist.size(); ++i)
  15426. if (std::find (tracks.begin(), tracks.end(), song.playlist[(std::size_t) i].track) != tracks.end())
  15427. out.push_back (i);
  15428. return out;
  15429. };
  15430. const auto sortedClips = [&] { auto v = pl.getSelectedClips(); std::sort (v.begin(), v.end()); return v; };
  15431. const auto headerShot = [&] (const juce::String& name, int rows) {
  15432. const auto bottom = pl.trackRowForSnapshot (rows).getY();
  15433. savePng (pl.createComponentSnapshot ({ 0, 0, juce::jmin (pl.getWidth(), 760), juce::jmin (pl.getHeight(), bottom + 12) }), prefix + name);
  15434. };
  15435. // ---- 1. selection (AUTracksPanelMouseDown / FUN_012e83e0)
  15436. press (pl, headerPoint (1), {});
  15437. check ("click_selects_alone", pl.selectedTracksForSnapshot() == std::vector<int> { 1 }, list (pl.selectedTracksForSnapshot()));
  15438. pl.selectClipsForSnapshot ({});
  15439. // LYNX extra (issue #163): Ctrl+click adds / removes one track, its clips follow
  15440. press (pl, headerPoint (3), ctrl);
  15441. check ("ctrl_click_adds_lynx", pl.selectedTracksForSnapshot() == std::vector<int> { 1, 3 } && sortedClips() == clipsOn ({ 3 }),
  15442. list (pl.selectedTracksForSnapshot()) + " clips " + list (sortedClips()));
  15443. press (pl, headerPoint (5), ctrl);
  15444. press (pl, headerPoint (1), ctrl);
  15445. check ("ctrl_click_removes_lynx", pl.selectedTracksForSnapshot() == std::vector<int> { 3, 5 } && sortedClips() == clipsOn ({ 3, 5 }),
  15446. list (pl.selectedTracksForSnapshot()) + " clips " + list (sortedClips()));
  15447. // FL's own toggle: Ctrl+Shift+click (its clips are added)
  15448. press (pl, headerPoint (1), ctrl | shift);
  15449. check ("ctrl_shift_click_adds", pl.selectedTracksForSnapshot() == std::vector<int> { 1, 3, 5 }, list (pl.selectedTracksForSnapshot()));
  15450. check ("ctrl_shift_click_adds_clips", sortedClips() == clipsOn ({ 1, 3, 5 }), list (sortedClips()));
  15451. press (pl, headerPoint (3), ctrl | shift);
  15452. check ("ctrl_shift_click_removes", pl.selectedTracksForSnapshot() == std::vector<int> { 1, 5 }, list (pl.selectedTracksForSnapshot()));
  15453. press (pl, headerPoint (3), ctrl | shift);
  15454. check ("ctrl_shift_click_adds_again", pl.selectedTracksForSnapshot() == std::vector<int> { 1, 3, 5 }, list (pl.selectedTracksForSnapshot()));
  15455. pl.selectClipsForSnapshot ({});
  15456. headerShot ("-ctrl-multiselect.png", 6);
  15457. press (pl, headerPoint (0), ctrl, headerPoint (2));
  15458. check ("ctrl_drag_range_with_clips", pl.selectedTracksForSnapshot() == std::vector<int> { 0, 1, 2 } && sortedClips() == clipsOn ({ 0, 1, 2 }),
  15459. list (pl.selectedTracksForSnapshot()) + " clips " + list (sortedClips()));
  15460. press (pl, headerPoint (1), shift); // LYNX's own Shift+click range (from the last clicked track, 0)
  15461. check ("lynx_shift_range_kept", pl.selectedTracksForSnapshot() == std::vector<int> { 0, 1 }, list (pl.selectedTracksForSnapshot()));
  15462. {
  15463. int linked = -1;
  15464. auto old = pl.onLinkedMixerTrack;
  15465. pl.onLinkedMixerTrack = [&linked] (int insert) { linked = insert; };
  15466. press (pl, headerPoint (2), {});
  15467. check ("audio_track_click_links_mixer_track", linked == 3, juce::String (linked));
  15468. pl.onLinkedMixerTrack = old;
  15469. }
  15470. // ---- 2. the resize band (FUN_00ea93a0, AUTracksPanelMouseMove)
  15471. const auto heightOf = [&] (int t) { return pl.trackRowForSnapshot (t).getHeight(); };
  15472. const auto& tracks = [&]() -> const std::vector<lynx::PlaylistTrack>& { return engine.getSong().playlistTracks; };
  15473. press (pl, headerPoint (4), {}); // (track 4 alone selected)
  15474. {
  15475. const auto start = bandPoint (4);
  15476. press (pl, start, {}, start + juce::Point<int> (0, 41));
  15477. 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)
  15478. headerShot ("-resized.png", 6);
  15479. const auto again = bandPoint (4);
  15480. press (pl, again, {}, again + juce::Point<int> (0, -100)); // (above the row's top, but less than 32 px)
  15481. check ("drag_stops_at_16", heightOf (4) == 16, juce::String (heightOf (4)));
  15482. press (pl, bandPoint (4), alt);
  15483. check ("alt_click_resets", tracks()[4].height == 0 && tracks()[4].lockedHeight == -1 && heightOf (4) == 48, juce::String (heightOf (4)));
  15484. press (pl, bandPoint (4), {}, {}, 2); // the second press of a double click
  15485. check ("double_click_locks_small", tracks()[4].lockedHeight == 1 && heightOf (4) == 16, juce::String (tracks()[4].lockedHeight));
  15486. press (pl, bandPoint (4), {});
  15487. check ("click_on_locked_band_unlocks", tracks()[4].lockedHeight == -1 && heightOf (4) == 48, juce::String (tracks()[4].lockedHeight));
  15488. const auto top = pl.trackRowForSnapshot (4).getY();
  15489. const auto b = bandPoint (4);
  15490. press (pl, b, {}, juce::Point<int> (b.x, top - 40));
  15491. check ("drag_past_the_top_groups", tracks()[4].grouped && tracks()[4].height == 0, juce::String ((int) tracks()[4].grouped));
  15492. const auto b2 = bandPoint (4);
  15493. press (pl, b2, {}, juce::Point<int> (b2.x, pl.trackRowForSnapshot (4).getY() - 40));
  15494. check ("again_ungroups", ! tracks()[4].grouped, juce::String ((int) tracks()[4].grouped));
  15495. }
  15496. {
  15497. // every selected track: the same height, from the first one's top to the mouse
  15498. press (pl, headerPoint (1), {});
  15499. press (pl, headerPoint (2), ctrl | shift);
  15500. press (pl, headerPoint (3), ctrl | shift);
  15501. const auto top = pl.trackRowForSnapshot (1).getY();
  15502. const auto b = bandPoint (2);
  15503. press (pl, b, {}, juce::Point<int> (b.x, top + 2 * 50));
  15504. check ("selected_tracks_share_the_height", tracks()[1].height == 50 && tracks()[2].height == 50 && tracks()[3].height == 50,
  15505. juce::String (tracks()[1].height) + "," + juce::String (tracks()[2].height) + "," + juce::String (tracks()[3].height));
  15506. headerShot ("-selected-resized.png", 6);
  15507. }
  15508. // ---- 3. saved: .lynx round trip and the .flp size factor
  15509. {
  15510. engine.editSong ([] (lynx::Song& s) { s.playlistTracks[5].height = 300; s.playlistTracks[0].lockedHeight = 60; });
  15511. const auto json = lynx::ProjectFile::toJson (engine.getSong());
  15512. juce::String error;
  15513. const auto back = lynx::ProjectFile::fromJson (json, error);
  15514. check ("lynx_round_trip", back && back->playlistTracks.size() > 5 && back->playlistTracks[5].height == 300 && back->playlistTracks[1].height == 50
  15515. && back->playlistTracks[0].lockedHeight == 60, error);
  15516. lynx::flpexport::Options options;
  15517. lynx::flpexport::Report flpReport;
  15518. const auto project = flp::parseProject (lynx::flpexport::exportFlp (engine.getSong(), options, flpReport));
  15519. float size5 = -1.0f, size1 = -1.0f;
  15520. for (const auto& arrangement : project.arrangements)
  15521. for (const auto& t : arrangement.tracks)
  15522. {
  15523. if (t.index == 5) size5 = t.heightScale;
  15524. if (t.index == 1) size1 = t.heightScale;
  15525. }
  15526. 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,
  15527. juce::String (size5) + " " + juce::String (size1));
  15528. }
  15529. // ---- 4. the mixer strips (round 170b's FL rules): Ctrl+click alone, Ctrl+Shift+click adds / removes
  15530. {
  15531. ui.selectTabForSnapshot (3);
  15532. engine.editSong ([] (lynx::Song& s) { if (s.mixer.size() < 9) s.mixer.resize (9); });
  15533. engine.dispatchPendingMessages();
  15534. auto& mixer = ui.getMixerForSnapshot();
  15535. mixer.setSize (1400, 640);
  15536. auto& strips = mixer.getStripsForSnapshot();
  15537. strips.setSize (juce::jmax (strips.getWidth(), 1300), juce::jmax (strips.getHeight(), 560));
  15538. const auto at = [&] (int t) { return juce::Point<int> (strips.stripLeft (t) + 8, strips.getHeight() / 2 + 40); };
  15539. press (strips, at (2), {});
  15540. check ("mixer_click_alone", strips.getSelection() == std::vector<int> { 2 }, list (strips.getSelection()));
  15541. // LYNX extra (issue #163): Ctrl+click adds / removes one insert
  15542. press (strips, at (4), ctrl);
  15543. press (strips, at (6), ctrl);
  15544. check ("mixer_ctrl_click_adds_lynx", strips.getSelection() == std::vector<int> { 2, 4, 6 }, list (strips.getSelection()));
  15545. press (strips, at (4), ctrl);
  15546. check ("mixer_ctrl_click_removes_lynx", strips.getSelection() == std::vector<int> { 2, 6 }, list (strips.getSelection()));
  15547. // FL: Ctrl+Shift+click adds / removes too
  15548. press (strips, at (5), ctrl | shift);
  15549. check ("mixer_ctrl_shift_click_adds", strips.getSelection() == std::vector<int> { 2, 5, 6 }, list (strips.getSelection()));
  15550. savePng (mixer.createComponentSnapshot ({ 0, 0, juce::jmin (mixer.getWidth(), 900), mixer.getHeight() }), prefix + "-mixer-ctrl-multiselect.png");
  15551. // FL: Ctrl+drag across the strips = the range from the press, alone
  15552. press (strips, at (3), ctrl, at (4));
  15553. check ("mixer_ctrl_drag_range", strips.getSelection() == std::vector<int> { 3, 4 }, list (strips.getSelection()));
  15554. }
  15555. // ---- 5. round 190gw (live check 190gu B1): FL's default row, the left lock strip, the right selection strip
  15556. {
  15557. ui.selectTabForSnapshot (2);
  15558. auto song = lynx::Song::makeDefault();
  15559. song.playlist.clear();
  15560. song.playlistTracks.assign (6, {});
  15561. for (int t = 0; t < 6; ++t)
  15562. song.playlistTracks[(std::size_t) t].name = juce::String ("Track " + juce::String (t + 1)).toStdString();
  15563. engine.setSong (std::move (song));
  15564. engine.dispatchPendingMessages();
  15565. pl.setSize (juce::jmax (pl.getWidth(), 900), juce::jmax (pl.getHeight(), 600));
  15566. check ("gw_default_row_48", heightOf (0) == 48 && heightOf (5) == 48, juce::String (heightOf (0)));
  15567. const auto rowMid = [&] (int t) { const auto r = pl.trackRowForSnapshot (t); return r.getY() + r.getHeight() / 2 - 4; };
  15568. const auto stripX = pl.headerWidthForSnapshot() - 4;
  15569. // the left strip (x < 10): the row flips to the smallest size and back; nothing selects
  15570. press (pl, { 2, rowMid (2) }, {});
  15571. check ("gw_left_strip_smallest", heightOf (2) == 16 && tracks()[2].lockedHeight == 1, juce::String (heightOf (2)));
  15572. press (pl, { 2, rowMid (2) }, {});
  15573. check ("gw_left_strip_back", heightOf (2) == 48 && tracks()[2].lockedHeight == -1, juce::String (heightOf (2)));
  15574. // the right strip: click = alone, Shift+click toggles, right-click toggles with no menu
  15575. press (pl, { stripX, rowMid (0) }, {});
  15576. check ("gw_strip_click_alone", pl.selectedTracksForSnapshot() == std::vector<int> { 0 }, list (pl.selectedTracksForSnapshot()));
  15577. press (pl, { stripX, rowMid (1) }, shift);
  15578. check ("gw_strip_shift_click_adds", pl.selectedTracksForSnapshot() == std::vector<int> { 0, 1 }, list (pl.selectedTracksForSnapshot()));
  15579. headerShot ("-gw-strip-two-selected.png", 6);
  15580. press (pl, { stripX, rowMid (0) }, shift);
  15581. check ("gw_strip_shift_click_removes", pl.selectedTracksForSnapshot() == std::vector<int> { 1 }, list (pl.selectedTracksForSnapshot()));
  15582. {
  15583. const juce::Point<int> p { stripX, rowMid (4) };
  15584. const juce::ModifierKeys right (juce::ModifierKeys::rightButtonModifier);
  15585. pl.mouseDown (event (pl, p, right, p, 1, false));
  15586. pl.mouseUp (event (pl, p, {}, p, 1, false));
  15587. }
  15588. check ("gw_strip_right_click_adds", pl.selectedTracksForSnapshot() == std::vector<int> { 1, 4 }, list (pl.selectedTracksForSnapshot()));
  15589. // a drag down the strip: the tracks crossed join (FUN_012e8740)
  15590. press (pl, { stripX, rowMid (0) }, {}, juce::Point<int> (stripX, rowMid (4)));
  15591. check ("gw_strip_drag_range", pl.selectedTracksForSnapshot() == std::vector<int> { 0, 1, 2, 3, 4 }, list (pl.selectedTracksForSnapshot()));
  15592. headerShot ("-gw-strip-range.png", 6);
  15593. // a double click: the track alone <-> every track
  15594. press (pl, { stripX, rowMid (2) }, {});
  15595. press (pl, { stripX, rowMid (2) }, {}, {}, 2);
  15596. check ("gw_strip_double_click_all", (int) pl.selectedTracksForSnapshot().size() == pl.numTracksForSnapshot(), list (pl.selectedTracksForSnapshot()));
  15597. press (pl, { stripX, rowMid (1) }, {});
  15598. // .lynx: the new default row is saved; a project from before (no key) keeps LYNX's old 38 px row
  15599. juce::String error;
  15600. const auto json = lynx::ProjectFile::toJson (engine.getSong());
  15601. const auto back = lynx::ProjectFile::fromJson (json, error);
  15602. check ("gw_lynx_row_saved", back && back->playlistRowHeight == 48, error);
  15603. auto parsed = juce::JSON::parse (json);
  15604. if (auto* o = parsed.getDynamicObject())
  15605. o->removeProperty ("playlistRowHeight");
  15606. const auto old = lynx::ProjectFile::fromJson (juce::JSON::toString (parsed), error);
  15607. check ("gw_old_lynx_keeps_38", old && old->playlistRowHeight == 38, error);
  15608. engine.setSong (*old);
  15609. engine.dispatchPendingMessages();
  15610. check ("gw_old_lynx_rows_38", heightOf (0) == 38, juce::String (heightOf (0)));
  15611. // an automation clip with two target links (Crossfade with) comes back with its links and formulas
  15612. auto linked = lynx::Song::makeDefault();
  15613. linked.channels.resize (2);
  15614. lynx::Automation a;
  15615. a.links = { { { lynx::AutomationTargetKind::channelAdjust, 0, 0, lynx::leveladjust::volume }, lynx::clipops::crossfadeOutFormula },
  15616. { { lynx::AutomationTargetKind::channelAdjust, 1, 0, lynx::leveladjust::volume }, lynx::clipops::crossfadeInFormula } };
  15617. a.target = a.links[0].target;
  15618. a.points = { { 0, 1.0f, 0.0f }, { 384, 0.0f, 0.0f } };
  15619. linked.automations.push_back (a);
  15620. const auto linkedBack = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (linked), error);
  15621. check ("gw_lynx_links_round_trip", linkedBack && linkedBack->automations.size() == linked.automations.size()
  15622. && linkedBack->automations.back().links == a.links && linkedBack->automations.back().target == a.target, error);
  15623. // Sampler › Open in new Fruity Slicer / Slicex channel: named after the sample, " #n" when taken
  15624. const auto wav = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-190gw").getChildFile ("Basic 808 Clap.wav");
  15625. wav.getParentDirectory().createDirectory();
  15626. {
  15627. juce::AudioBuffer<float> b (1, 4410);
  15628. for (int i = 0; i < b.getNumSamples(); ++i)
  15629. b.setSample (0, i, 0.5f * std::sin ((float) i * 0.2f) * (1.0f - (float) i / (float) b.getNumSamples()));
  15630. wav.deleteFile();
  15631. juce::WavAudioFormat format;
  15632. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream());
  15633. if (auto* w = format.createWriterFor (out.get(), 44100.0, 1, 16, {}, 0))
  15634. {
  15635. out.release();
  15636. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  15637. writer->writeFromAudioSampleBuffer (b, 0, b.getNumSamples());
  15638. }
  15639. }
  15640. engine.editSong ([] (lynx::Song& s) {
  15641. s.channels.resize (1);
  15642. s.channels[0] = {};
  15643. s.channels[0].name = "Basic 808 Clap";
  15644. });
  15645. engine.dispatchPendingMessages();
  15646. if (lynx::openInNewChannelHandler())
  15647. {
  15648. lynx::openInNewChannelHandler() (wav, lynx::InstrumentKind::fruityslicer);
  15649. lynx::openInNewChannelHandler() (wav, lynx::InstrumentKind::slicex);
  15650. }
  15651. engine.dispatchPendingMessages();
  15652. const auto& ch = engine.getSong().channels;
  15653. 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"
  15654. && ch[1].instrument == lynx::InstrumentKind::fruityslicer && ch[2].instrument == lynx::InstrumentKind::slicex,
  15655. ch.size() >= 3 ? juce::String::fromUTF8 (ch[1].name.c_str()) + " | " + juce::String::fromUTF8 (ch[2].name.c_str()) : juce::String ((int) ch.size()));
  15656. wav.getParentDirectory().deleteRecursively();
  15657. // the mixer's two boxes (live check 190gu B4): "Insert multiple..." asks "Number of tracks to add" (1),
  15658. // "Add multiple..." "Enter the number of mixer tracks to add" (10)
  15659. for (const auto adding : { false, true })
  15660. {
  15661. auto box = lynx::MixerStrips::makeInsertMultipleBox (adding);
  15662. const auto text = box->getTextEditorContents ("count");
  15663. check (adding ? "gw_add_multiple_box" : "gw_insert_multiple_box", text == (adding ? "10" : "1"), text);
  15664. if (box->getWidth() > 0 && box->getHeight() > 0)
  15665. savePng (box->createComponentSnapshot (box->getLocalBounds()), prefix + (adding ? "-gw-add-multiple-box.png" : "-gw-insert-multiple-box.png"));
  15666. }
  15667. }
  15668. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\nresult=" + (allOk ? "OK" : "FAIL") + "\n");
  15669. return allOk;
  15670. }
  15671. #include "FoldersShot190jf.inc" // round 190jf (slice B17)
  15672. // --userfixshot190ib (round 190ib): see the dispatch above
  15673. bool runUserFixShot190ib (const juce::String& prefix)
  15674. {
  15675. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  15676. juce::StringArray report;
  15677. bool allOk = true;
  15678. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  15679. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  15680. allOk = allOk && ok;
  15681. };
  15682. lynx::AudioEngine engine (false);
  15683. lynx::MainComponent ui (engine, false);
  15684. ui.setSize (1600, 900);
  15685. engine.dispatchPendingMessages();
  15686. // ---- #182: a real JUCE popup menu inside a host component, keys sent to its window as the keyboard would
  15687. juce::Component host;
  15688. host.setSize (560, 900);
  15689. const auto typeInto = [&host] (const juce::String& text) {
  15690. auto* menuWindow = host.getNumChildComponents() > 0 ? host.getChildComponent (host.getNumChildComponents() - 1) : nullptr;
  15691. for (auto c : text)
  15692. if (menuWindow != nullptr)
  15693. menuWindow->keyPressed (juce::KeyPress ((int) juce::CharacterFunctions::toLowerCase (c), 0, c));
  15694. return menuWindow != nullptr;
  15695. };
  15696. const auto shotMenu = [&host, &prefix] (const juce::String& name) {
  15697. savePng (host.createComponentSnapshot (host.getLocalBounds()), prefix + name);
  15698. };
  15699. {
  15700. auto& pl = ui.getPlaylistForSnapshot();
  15701. pl.editMenu().showMenuAsync (juce::PopupMenu::Options().withParentComponent (&host).withTargetScreenArea ({ 8, 8, 1, 1 }));
  15702. check ("menu_shown", host.getNumChildComponents() > 0, juce::String (host.getNumChildComponents()));
  15703. shotMenu ("-menu-0.png");
  15704. typeInto ("d");
  15705. shotMenu ("-menu-d.png"); // the first item starting with D
  15706. typeInto ("d");
  15707. shotMenu ("-menu-dd.png"); // D again: the next one
  15708. juce::Time::waitForMillisecondCounter (juce::Time::getMillisecondCounter() + 1100); // (a pause: a new prefix)
  15709. typeInto ("drop a");
  15710. shotMenu ("-menu-drop-a.png"); // "Drop audio on track headers"
  15711. juce::PopupMenu::dismissAllActiveMenus();
  15712. }
  15713. {
  15714. auto& pr = ui.getPianoRollForSnapshot();
  15715. pr.moreMenuForSnapshot().showMenuAsync (juce::PopupMenu::Options().withParentComponent (&host).withTargetScreenArea ({ 8, 8, 1, 1 }));
  15716. juce::Time::waitForMillisecondCounter (juce::Time::getMillisecondCounter() + 1100);
  15717. typeInto ("preview");
  15718. shotMenu ("-pianoroll-preview.png"); // #183's item, reached by typing its name
  15719. juce::PopupMenu::dismissAllActiveMenus();
  15720. check ("preview_while_playing_off_by_default", ! lynx::PianoRollComponent::previewWhilePlaying);
  15721. }
  15722. // ---- #181: Ctrl+, (Cmd+, on macOS) through the main window's key handling opens Settings, again closes it
  15723. const auto ctrlComma = juce::KeyPress (',', juce::ModifierKeys::commandModifier, ',');
  15724. check ("settings_closed_first", lynx::shownSettingsPage() < 0);
  15725. ui.keyPressed (ctrlComma);
  15726. check ("ctrl_comma_opens_settings", lynx::shownSettingsPage() == (int) lynx::SettingsPage::general, juce::String (lynx::shownSettingsPage()));
  15727. ui.keyPressed (ctrlComma);
  15728. check ("ctrl_comma_again_closes_it", lynx::shownSettingsPage() < 0, juce::String (lynx::shownSettingsPage()));
  15729. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\nresult=" + (allOk ? "OK" : "FAIL") + "\n");
  15730. return allOk;
  15731. }
  15732. // --issuesshot190ht (round 190ht): see the dispatch above
  15733. bool runIssuesShot190ht (const juce::String& prefix)
  15734. {
  15735. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  15736. juce::StringArray report;
  15737. bool allOk = true;
  15738. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  15739. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  15740. allOk = allOk && ok;
  15741. };
  15742. using namespace lynx;
  15743. AudioEngine engine (false);
  15744. MainComponent ui (engine, false);
  15745. ui.setSize (1600, 900);
  15746. const auto bar = (std::int64_t) 4 * ppq;
  15747. {
  15748. // Kick (1 bar), Bass (2 bars, a long note across its second bar), Lead (1 bar), Pad (1 bar): blocks in rows
  15749. auto song = Song::makeDefault();
  15750. song.playlist.clear();
  15751. song.patterns.clear();
  15752. const auto pattern = [&song] (const char* name, std::uint32_t colour, int channel, std::int64_t length) {
  15753. auto& p = song.patterns.emplace_back();
  15754. p.name = name;
  15755. p.colour = colour;
  15756. for (int step : { 0, 4, 8, 12 })
  15757. p.toggleStep (channel, step);
  15758. p.lengthTicks = length;
  15759. return (int) song.patterns.size() - 1;
  15760. };
  15761. pattern ("Kick", 0xFFD85A3C, 0, bar);
  15762. const auto bass = pattern ("Bass", 0xFF3C8DD8, 1, 0);
  15763. Note longNote;
  15764. longNote.channel = 1;
  15765. longNote.start = 6 * ppq;
  15766. longNote.length = 2 * ppq;
  15767. song.patterns[(std::size_t) bass].notes.push_back (longNote);
  15768. song.patterns[(std::size_t) bass].sortNotes();
  15769. pattern ("Lead", 0xFF8A5CD8, 2, bar);
  15770. pattern ("Pad", 0xFF5CB85C, 3, bar);
  15771. song.patternBlocksOn = true;
  15772. for (int b = 0; b < 8; ++b)
  15773. patternblocks::place (song, 0, b * bar);
  15774. patternblocks::place (song, 1, 0);
  15775. patternblocks::place (song, 1, 4 * bar);
  15776. for (int b = 2; b < 6; ++b)
  15777. patternblocks::place (song, 2, b * bar);
  15778. patternblocks::place (song, 3, 0);
  15779. engine.setSong (std::move (song));
  15780. }
  15781. engine.dispatchPendingMessages();
  15782. ui.selectTabForSnapshot (2);
  15783. engine.dispatchPendingMessages();
  15784. auto& pl = ui.getPlaylistForSnapshot();
  15785. pl.setSize (juce::jmax (pl.getWidth(), 1000), juce::jmax (pl.getHeight(), 640));
  15786. pl.setViewForSnapshot (90.0, 0, 0); // (bar 1 at the left edge)
  15787. pl.setBlocksHeight (6 + 5 * 18 + 6);
  15788. engine.dispatchPendingMessages();
  15789. const auto& song = [&]() -> const Song& { return engine.getSong(); };
  15790. auto* blocks = pl.getBlocksViewForSnapshot();
  15791. check ("blocks_view", blocks != nullptr && blocks->isVisible());
  15792. if (blocks == nullptr)
  15793. {
  15794. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\nresult=FAIL\n");
  15795. return false;
  15796. }
  15797. const auto shotBlocks = [&] (const juce::String& name) {
  15798. engine.dispatchPendingMessages();
  15799. const auto area = blocks->getBoundsInParent().withWidth (juce::jmin (pl.getWidth(), 900)).expanded (0, 2).getIntersection (pl.getLocalBounds());
  15800. savePng (pl.createComponentSnapshot (area), prefix + name);
  15801. };
  15802. auto source = juce::Desktop::getInstance().getMainMouseSource();
  15803. const juce::ModifierKeys left (juce::ModifierKeys::leftButtonModifier), right (juce::ModifierKeys::rightButtonModifier);
  15804. juce::Point<float> pressedAt;
  15805. const auto bEvent = [&] (int row, std::int64_t tick, juce::ModifierKeys mods, int clicks = 1) {
  15806. const auto at = blocks->pointForSnapshot (row, tick).toFloat();
  15807. const auto now = juce::Time::getCurrentTime();
  15808. return juce::MouseEvent (source, at, mods, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, blocks, blocks, now, pressedAt, now, clicks, at != pressedAt);
  15809. };
  15810. const auto bPress = [&] (int row, std::int64_t tick, juce::ModifierKeys mods) {
  15811. pressedAt = blocks->pointForSnapshot (row, tick).toFloat();
  15812. blocks->mouseDown (bEvent (row, tick, mods));
  15813. };
  15814. const auto bDrag = [&] (int row, std::int64_t tick, juce::ModifierKeys mods) { blocks->mouseDrag (bEvent (row, tick, mods)); };
  15815. const auto bRelease = [&] (int row, std::int64_t tick, juce::ModifierKeys mods = {}) {
  15816. blocks->mouseUp (bEvent (row, tick, mods));
  15817. engine.dispatchPendingMessages();
  15818. };
  15819. const auto blockOf = [&] (int row, std::int64_t start) -> const PatternBlock* {
  15820. const auto i = patternblocks::indexOf (song(), { row, start });
  15821. return i < 0 ? nullptr : &song().blocks[(std::size_t) i];
  15822. };
  15823. const auto mutedAt = [&] (int row, std::int64_t start) { const auto* x = blockOf (row, start); return x != nullptr && x->muted; };
  15824. const auto playingAt = [&] (int row, std::int64_t start) { const auto* x = blockOf (row, start); return x != nullptr && ! x->muted; };
  15825. const auto mutedCount = [&] {
  15826. int n = 0;
  15827. for (const auto& b : song().blocks)
  15828. n += b.muted ? 1 : 0;
  15829. return n;
  15830. };
  15831. shotBlocks ("-blocks-before.png");
  15832. // ---- #127 Mute: a click mutes the block, a drag down across rows mutes the blocks it crosses (any row)
  15833. pl.setToolForSnapshot (EditTool::mute);
  15834. bPress (0, 2 * bar + 40, left);
  15835. bRelease (0, 2 * bar + 40);
  15836. check ("mute_click", blockOf (0, 2 * bar) != nullptr && mutedAt (0, 2 * bar) && mutedCount() == 1);
  15837. bPress (0, 4 * bar + 40, left);
  15838. bDrag (1, 4 * bar + 60, left);
  15839. bDrag (2, 4 * bar + 80, left);
  15840. bRelease (2, 4 * bar + 80);
  15841. check ("mute_drag_across_rows", mutedAt (0, 4 * bar) && blockOf (1, 4 * bar) != nullptr && mutedAt (1, 4 * bar)
  15842. && mutedAt (2, 4 * bar) && playingAt (3, 0) && mutedCount() == 4,
  15843. juce::String (mutedCount()));
  15844. shotBlocks ("-blocks-mute.png");
  15845. // a sweep that starts on a muted block unmutes
  15846. bPress (0, 2 * bar + 40, left);
  15847. bDrag (0, 3 * bar + 40, left);
  15848. bRelease (0, 3 * bar + 40);
  15849. check ("mute_sweep_from_muted_unmutes", playingAt (0, 2 * bar) && playingAt (0, 3 * bar) && mutedCount() == 3,
  15850. juce::String (mutedCount()));
  15851. // the right button erases, as with every tool but Select / Slice / Zoom
  15852. bPress (3, 40, right);
  15853. bRelease (3, 40);
  15854. check ("mute_right_click_erases", blockOf (3, 0) == nullptr);
  15855. engine.undo();
  15856. engine.dispatchPendingMessages();
  15857. check ("undo_erase", blockOf (3, 0) != nullptr);
  15858. // the muted blocks play nothing: their clips in the playback copy are muted
  15859. {
  15860. auto copy = song();
  15861. patternblocks::expandSong (copy);
  15862. int mutedClips = 0;
  15863. for (const auto& c : copy.playlist)
  15864. mutedClips += c.muted ? 1 : 0;
  15865. check ("muted_blocks_play_muted_clips", mutedClips == 3, juce::String (mutedClips));
  15866. juce::String error;
  15867. const auto back = ProjectFile::fromJson (ProjectFile::toJson (song()), error);
  15868. check ("muted_blocks_saved", back && back->blocks == song().blocks, error);
  15869. }
  15870. // ---- #127 Select: a box over rows 0-2, bars 5-6 selects every block it meets; Pencil moves them together
  15871. pl.setToolForSnapshot (EditTool::lasso);
  15872. bPress (0, 4 * bar + 40, left);
  15873. bDrag (2, 5 * bar + 40, left);
  15874. shotBlocks ("-blocks-select-box.png");
  15875. bRelease (2, 5 * bar + 40);
  15876. const auto selection = blocks->selectionForSnapshot();
  15877. check ("select_box_any_row", selection.size() == 5 && patternblocks::contains (selection, { 0, 4 * bar }) && patternblocks::contains (selection, { 1, 4 * bar })
  15878. && patternblocks::contains (selection, { 2, 5 * bar }),
  15879. juce::String ((int) selection.size()));
  15880. pl.setToolForSnapshot (EditTool::pencil);
  15881. // (Kick's bars 7 and 8 are in the way of a 2-bar move: move the group by 1 bar after clearing them)
  15882. engine.editSong ([bar] (Song& s) { patternblocks::eraseRange (s, 0, 6 * bar, 8 * bar); });
  15883. engine.dispatchPendingMessages();
  15884. bPress (1, 4 * bar + 40, left);
  15885. bDrag (1, 6 * bar + 40, left);
  15886. bRelease (1, 6 * bar + 40);
  15887. check ("pencil_moves_the_selection", blockOf (1, 6 * bar) != nullptr && blockOf (0, 6 * bar) != nullptr && blockOf (0, 7 * bar) != nullptr
  15888. && blockOf (2, 6 * bar) != nullptr && blockOf (2, 7 * bar) != nullptr && blockOf (1, 4 * bar) == nullptr
  15889. && blocks->selectionForSnapshot().size() == 5);
  15890. shotBlocks ("-blocks-select-moved.png");
  15891. // a press on a block outside the selection moves that block alone and drops the selection
  15892. bPress (3, 40, left);
  15893. bDrag (3, bar + 40, left);
  15894. bRelease (3, bar + 40);
  15895. check ("pencil_unselected_block_alone", blockOf (3, bar) != nullptr && blockOf (0, 6 * bar) != nullptr && blocks->selectionForSnapshot().empty());
  15896. // the right button selects too (FL 10: either button)
  15897. pl.setToolForSnapshot (EditTool::lasso);
  15898. bPress (3, bar + 40, right);
  15899. bRelease (3, bar + 40);
  15900. check ("select_click_right_button", blocks->selectionForSnapshot().size() == 1 && blockOf (3, bar) != nullptr);
  15901. // ---- #127 Slice: a click on Bass's first block at bar 2 beat 4 cuts the pattern; a new pattern takes the rest
  15902. pl.setToolForSnapshot (EditTool::knife);
  15903. const auto patternsBefore = song().patterns.size();
  15904. const juce::ModifierKeys freeLeft (juce::ModifierKeys::leftButtonModifier | juce::ModifierKeys::altModifier); // (Alt: no snap)
  15905. bPress (1, bar + 3 * ppq, freeLeft);
  15906. bDrag (2, bar + 3 * ppq, freeLeft); // (a vertical drag: the row under the mouse when released is cut)
  15907. bRelease (1, bar + 3 * ppq);
  15908. check ("slice_adds_a_pattern", song().patterns.size() == patternsBefore + 1 && song().patterns[2].name == "Bass #2",
  15909. juce::String ((int) song().patterns.size()));
  15910. check ("slice_trims_the_long_note", song().patterns[1].notes.back().start == 6 * ppq && song().patterns[1].notes.back().length >= ppq
  15911. && song().patterns[1].notes.back().length < ppq + ppq / 4 && song().patterns[2].notes.empty(),
  15912. juce::String (song().patterns[1].notes.back().length));
  15913. check ("slice_new_blocks_where_bass_ends", blockOf (2, 2 * bar) != nullptr && blockOf (2, 8 * bar) != nullptr);
  15914. shotBlocks ("-blocks-slice.png");
  15915. engine.undo();
  15916. engine.dispatchPendingMessages();
  15917. check ("undo_slice", song().patterns.size() == patternsBefore && song().patterns[2].name == "Lead");
  15918. // ---- #127 Zoom: a drag zooms to the range, a click goes back
  15919. pl.setToolForSnapshot (EditTool::zoom);
  15920. const auto zoomBefore = pl.xOfTickForSnapshot ((double) (4 * bar)) - pl.xOfTickForSnapshot (0.0);
  15921. bPress (0, 2 * bar, left);
  15922. bDrag (0, 4 * bar, left);
  15923. bRelease (0, 4 * bar);
  15924. const auto zoomed = pl.xOfTickForSnapshot ((double) (4 * bar)) - pl.xOfTickForSnapshot (0.0);
  15925. check ("zoom_drag_zooms_in", zoomed > zoomBefore * 1.5, juce::String (zoomed) + " vs " + juce::String (zoomBefore));
  15926. pressedAt = blocks->pointForSnapshot (0, 3 * bar).toFloat();
  15927. blocks->mouseDown (bEvent (0, 3 * bar, right));
  15928. blocks->mouseUp (bEvent (0, 3 * bar, {}));
  15929. const auto back = pl.xOfTickForSnapshot ((double) (4 * bar)) - pl.xOfTickForSnapshot (0.0);
  15930. check ("zoom_click_goes_back", std::abs (back - zoomBefore) < 0.5, juce::String (back));
  15931. // hints name each tool's gesture
  15932. pl.setToolForSnapshot (EditTool::mute);
  15933. check ("hint_mute", blocks->hintAt (blocks->pointForSnapshot (0, 40)).text.contains ("mutes"));
  15934. pl.setToolForSnapshot (EditTool::pencil);
  15935. // ---- #154: linked tracks, then the insert effects list on their headers
  15936. engine.editSong ([bar] (Song& s) {
  15937. s.patternBlocksOn = false;
  15938. s.blocks.clear();
  15939. s.playlist.clear();
  15940. ChannelDef vox;
  15941. vox.name = "Lead vocal";
  15942. vox.instrument = InstrumentKind::audioClip;
  15943. vox.samplePath = "/shots/Lead vocal.wav";
  15944. vox.mixerTrack = 12;
  15945. s.channels.push_back (vox);
  15946. const auto voxChannel = (int) s.channels.size() - 1;
  15947. s.mixer[12].name = "Vox chain";
  15948. for (auto k : { EffectKind::parametricEq, EffectKind::compressor, EffectKind::delay, EffectKind::reverb })
  15949. s.mixer[12].effects.push_back (makeEffectSlot (k));
  15950. s.mixer[12].effects[2].enabled = false;
  15951. s.channels[0].mixerTrack = 3;
  15952. s.mixer[3].name = "Kick";
  15953. s.mixer[3].effects.push_back (makeEffectSlot (EffectKind::compressor));
  15954. const auto clip = [&s, bar] (int track, ClipKind kind, int source, int at, int bars) {
  15955. Clip c;
  15956. c.kind = kind;
  15957. c.track = track;
  15958. c.start = at * bar;
  15959. c.length = bars * bar;
  15960. (kind == ClipKind::pattern ? c.pattern : c.channel) = source;
  15961. s.playlist.push_back (c);
  15962. };
  15963. clip (0, ClipKind::pattern, 0, 0, 4);
  15964. clip (1, ClipKind::audio, voxChannel, 0, 8);
  15965. s.playlistTracks.resize (4);
  15966. s.playlistTracks[1].height = 70;
  15967. });
  15968. engine.dispatchPendingMessages();
  15969. // (rollup 0.1.30: since round 190ib, switching the link on asks first when it moves inserts or routes channels;
  15970. // this run accepts, as the user clicking "Link")
  15971. PlaylistComponent::answerLinkConfirmation = [] (const autolink::Report&) { return true; };
  15972. pl.runAction ("playlist.linkTracks");
  15973. PlaylistComponent::answerLinkConfirmation = nullptr;
  15974. engine.dispatchPendingMessages();
  15975. // (rollup 0.1.30: round 190ib links Playlist track N to insert N, moving the inserts there: the Vox chain and
  15976. // the Kick follow their tracks, so the checks read the inserts the tracks are linked to)
  15977. const auto vox = song().playlistTracks.size() > 1 ? song().playlistTracks[1].mixerTrack : -1;
  15978. const auto kick = song().playlistTracks.size() > 0 ? song().playlistTracks[0].mixerTrack : -1;
  15979. check ("linked", song().linkTracksToMixer && vox > 0 && song().mixer[(std::size_t) vox].name == "Vox chain" && pl.headerWidthForSnapshot() == PlaylistComponent::linkedHeaderWidth,
  15980. juce::String (pl.headerWidthForSnapshot()));
  15981. check ("inserts_off_by_default", ! PlaylistComponent::showTrackInserts && pl.insertsListForSnapshot (1).isEmpty());
  15982. const auto shotRows = [&] (const juce::String& name, int rows) {
  15983. engine.dispatchPendingMessages();
  15984. const auto bottom = pl.trackRowForSnapshot (rows).getY();
  15985. savePng (pl.createComponentSnapshot ({ 0, 0, juce::jmin (pl.getWidth(), 820), juce::jmin (pl.getHeight(), bottom + 12) }), prefix + name);
  15986. };
  15987. shotRows ("-inserts-off.png", 3);
  15988. pl.runAction ("playlist.trackInserts");
  15989. engine.dispatchPendingMessages();
  15990. check ("inserts_on_widens_linked_headers", PlaylistComponent::showTrackInserts
  15991. && pl.headerWidthForSnapshot() == PlaylistComponent::linkedHeaderWidth + PlaylistComponent::insertsColumnWidth,
  15992. juce::String (pl.headerWidthForSnapshot()));
  15993. const auto list = [&] (int t) { return pl.insertsListForSnapshot (t); };
  15994. check ("list_on_linked_tracks_only", ! list (0).isEmpty() && ! list (1).isEmpty() && list (2).isEmpty(),
  15995. list (0).toString() + " / " + list (1).toString());
  15996. shotRows ("-inserts-on.png", 3);
  15997. // a row's hint names the effect
  15998. const auto rowPoint = [&] (int t, int row, bool dot) {
  15999. const auto r = list (t);
  16000. return juce::Point<int> (dot ? r.getX() + 5 : r.getX() + 40, r.getY() + row * 13 + 6);
  16001. };
  16002. const auto hintOf = [&] (juce::Point<int> p) { return pl.hintAt (p); };
  16003. check ("hint_names_the_effect", hintOf (rowPoint (1, 1, false)).value == quickpick::slotName (engine, song().mixer[(std::size_t) vox].effects[1]),
  16004. hintOf (rowPoint (1, 1, false)).value);
  16005. check ("hint_add_row", hintOf (rowPoint (0, 1, false)).text.contains ("add an effect"));
  16006. const auto now = juce::Time::getCurrentTime();
  16007. const int ctrl = juce::ModifierKeys::commandModifier;
  16008. const auto event = [&] (juce::Point<int> p, juce::ModifierKeys mods, juce::Point<int> down, int clicks, bool dragged) {
  16009. 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);
  16010. };
  16011. const auto press = [&] (juce::Point<int> p, juce::ModifierKeys mods, std::optional<juce::Point<int>> to = {}) {
  16012. const auto down = mods.withFlags (juce::ModifierKeys::leftButtonModifier);
  16013. pl.mouseMove (event (p, mods, p, 1, false));
  16014. pl.mouseDown (event (p, down, p, 1, false));
  16015. if (to)
  16016. {
  16017. pl.mouseDrag (event ((p + *to) / 2, down, p, 1, true));
  16018. pl.mouseDrag (event (*to, down, p, 1, true));
  16019. }
  16020. pl.mouseUp (event (to ? *to : p, mods, p, 1, to.has_value()));
  16021. engine.dispatchPendingMessages();
  16022. };
  16023. const auto kinds = [&] (int insert) {
  16024. juce::StringArray k;
  16025. for (const auto& fx : song().mixer[(std::size_t) insert].effects)
  16026. k.add (juce::String ((int) fx.kind) + (fx.enabled ? "" : "-"));
  16027. return k.joinIntoString (",");
  16028. };
  16029. const auto eq = juce::String ((int) EffectKind::parametricEq), comp = juce::String ((int) EffectKind::compressor),
  16030. delay = juce::String ((int) EffectKind::delay), verb = juce::String ((int) EffectKind::reverb);
  16031. // the dot bypasses / un-bypasses, as the Mixer slot's LED (one undo step each)
  16032. press (rowPoint (1, 0, true), {});
  16033. check ("dot_bypasses", ! song().mixer[(std::size_t) vox].effects[0].enabled);
  16034. press (rowPoint (1, 2, true), {});
  16035. check ("dot_switches_on", song().mixer[(std::size_t) vox].effects[2].enabled);
  16036. engine.undo();
  16037. engine.dispatchPendingMessages();
  16038. check ("undo_dot", ! song().mixer[(std::size_t) vox].effects[2].enabled && ! song().mixer[(std::size_t) vox].effects[0].enabled);
  16039. press (rowPoint (1, 0, true), {});
  16040. shotRows ("-inserts-bypass.png", 3);
  16041. // drag the reverb (row 4) above the EQ: the chain order changes, as the Device View's drag
  16042. const auto before = kinds (vox);
  16043. press (rowPoint (1, 3, false), {}, rowPoint (1, 0, false) - juce::Point<int> (0, 4));
  16044. check ("drag_reorders", kinds (vox) == verb + "," + eq + "," + comp + "," + delay + "-", before + " -> " + kinds (vox));
  16045. // Ctrl + drag copies (the compressor, under the delay)
  16046. press (rowPoint (1, 2, false), juce::ModifierKeys (ctrl), rowPoint (1, 4, false) - juce::Point<int> (0, 4));
  16047. check ("ctrl_drag_copies", kinds (vox) == verb + "," + eq + "," + comp + "," + delay + "-," + comp, kinds (vox));
  16048. // onto another linked track's list: it moves to that insert (the Kick's)
  16049. press (rowPoint (1, 1, false), {}, rowPoint (0, 0, false));
  16050. check ("drag_to_another_track_moves", kinds (kick) == comp + "," + eq && kinds (vox) == verb + "," + comp + "," + delay + "-," + comp,
  16051. kinds (kick) + " | " + kinds (vox));
  16052. // the wheel scrolls a list longer than its track (Kick's 4 effects + "add" in a 3-row header)
  16053. engine.editSong ([kick] (Song& s) {
  16054. s.mixer[(std::size_t) kick].effects.push_back (makeEffectSlot (EffectKind::delay));
  16055. s.mixer[(std::size_t) kick].effects.push_back (makeEffectSlot (EffectKind::reverb));
  16056. });
  16057. engine.dispatchPendingMessages();
  16058. const auto firstName = hintOf (rowPoint (0, 0, false)).value;
  16059. const auto rowsShown = list (0).getHeight() / 13;
  16060. pl.mouseWheelMove (event (rowPoint (0, 0, false), {}, rowPoint (0, 0, false), 0, false), juce::MouseWheelDetails { 0.0f, -0.5f, false, false, false });
  16061. const auto afterWheel = hintOf (rowPoint (0, 0, false));
  16062. check ("wheel_scrolls_a_long_list", rowsShown < 5 && afterWheel.value != firstName
  16063. && afterWheel.value == quickpick::slotName (engine, song().mixer[(std::size_t) kick].effects[1]),
  16064. juce::String (rowsShown) + " rows, " + firstName + " -> " + afterWheel.value);
  16065. shotRows ("-inserts-edited.png", 3);
  16066. // a view option: not saved with the project
  16067. check ("option_not_in_project", ! ProjectFile::toJson (song()).contains ("trackInserts"));
  16068. // off again: the linked headers' own width
  16069. pl.runAction ("playlist.trackInserts");
  16070. engine.dispatchPendingMessages();
  16071. check ("inserts_off_again", ! PlaylistComponent::showTrackInserts && pl.headerWidthForSnapshot() == PlaylistComponent::linkedHeaderWidth);
  16072. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\nresult=" + (allOk ? "OK" : "FAIL") + "\n");
  16073. return allOk;
  16074. }
  16075. #include "WorkflowShot190iu.inc" // round 190iu
  16076. #include "PlaylistShot190jq.inc" // round 190jq
  16077. #include "IssuesShot190jz.inc" // round 190jz
  16078. #include "DetailsShot190kn.inc" // round 190kn
  16079. #include "DetailsShot190ld.inc" // round 190ld
  16080. #include "DetailsShot190lr.inc" // round 190lr
  16081. #include "DetailsShot190lx.inc" // round 190lx
  16082. #include "DetailsShot190mf.inc" // round 190mf
  16083. #include "DetailsShot190mk.inc" // round 190mk
  16084. #include "DetailsShot190mp.inc" // round 190mp
  16085. #include "DetailsShot190mr.inc" // round 190mr
  16086. #include "DetailsShot190mv.inc" // round 190mv
  16087. #include "DetailsShot190my.inc" // round 190my
  16088. // --trackautoshot190gz (round 190gz): see the dispatch above
  16089. bool runTrackAutoShot190gz (const juce::String& prefix)
  16090. {
  16091. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  16092. juce::StringArray report;
  16093. bool allOk = true;
  16094. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  16095. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  16096. allOk = allOk && ok;
  16097. };
  16098. lynx::AudioEngine engine (false);
  16099. lynx::MainComponent ui (engine, false);
  16100. ui.setSize (1600, 900);
  16101. {
  16102. // a small song in FL's shape: Kick and Synth patterns, a drum loop, a vocal on its prepared insert, a mixed beat
  16103. using namespace lynx;
  16104. auto song = Song::makeDefault();
  16105. song.playlist.clear();
  16106. song.patterns.clear();
  16107. for (auto& c : song.channels)
  16108. c.mixerTrack = 0; // (FL's new channels play on the Master)
  16109. song.channels[4].mixerTrack = 9; // the Synth on a bus the user made
  16110. song.mixer[9].name = "Synth bus";
  16111. const auto audio = [&song] (const char* name, int mixer) {
  16112. ChannelDef c;
  16113. c.name = name;
  16114. c.instrument = InstrumentKind::audioClip;
  16115. c.samplePath = std::string ("/shots/") + name + ".wav";
  16116. c.mixerTrack = mixer;
  16117. song.channels.push_back (c);
  16118. return (int) song.channels.size() - 1;
  16119. };
  16120. const auto loop = audio ("Drum loop", 0);
  16121. const auto vox = audio ("Lead vocal", 12);
  16122. song.mixer[12].name = "Vox chain";
  16123. song.mixer[12].colour = 0xFF3C8DD8;
  16124. song.mixer[12].effects.push_back (makeEffectSlot (EffectKind::parametricEq));
  16125. const auto pattern = [&song] (const char* name, std::vector<int> channels, std::uint32_t colour) {
  16126. auto& p = song.patterns.emplace_back();
  16127. p.name = name;
  16128. p.colour = colour;
  16129. for (const auto c : channels)
  16130. for (int step : { 0, 4, 8, 12 })
  16131. p.toggleStep (c, step);
  16132. return (int) song.patterns.size() - 1;
  16133. };
  16134. const auto kick = pattern ("Kick", { 0 }, 0xFFD85A3C);
  16135. const auto lead = pattern ("Lead", { 4 }, 0xFF8A5CD8);
  16136. const auto beat = pattern ("Beat", { 1, 2, 3 }, 0xFF5CB85C);
  16137. const auto clip = [&song] (int track, ClipKind kind, int source, int bar, int bars) {
  16138. Clip c;
  16139. c.kind = kind;
  16140. c.track = track;
  16141. c.start = (std::int64_t) bar * 4 * ppq;
  16142. c.length = (std::int64_t) bars * 4 * ppq;
  16143. (kind == ClipKind::pattern ? c.pattern : c.channel) = source;
  16144. song.playlist.push_back (c);
  16145. };
  16146. for (int bar = 0; bar < 8; bar += 2)
  16147. {
  16148. clip (0, ClipKind::pattern, kick, bar, 2);
  16149. clip (2, ClipKind::pattern, beat, bar, 2);
  16150. }
  16151. clip (1, ClipKind::audio, loop, 0, 8);
  16152. clip (3, ClipKind::pattern, lead, 2, 4);
  16153. clip (4, ClipKind::audio, vox, 4, 4);
  16154. clip (6, ClipKind::pattern, kick, 4, 2); // (round 190ib: Track 7 only repeats Track 1's Kick)
  16155. song.playlistTracks.resize (8);
  16156. engine.setSong (std::move (song));
  16157. }
  16158. engine.dispatchPendingMessages();
  16159. ui.selectTabForSnapshot (2);
  16160. engine.dispatchPendingMessages();
  16161. auto& pl = ui.getPlaylistForSnapshot();
  16162. pl.setSize (juce::jmax (pl.getWidth(), 1000), juce::jmax (pl.getHeight(), 640));
  16163. pl.setViewForSnapshot (120.0, 1, 0);
  16164. const auto shotRows = [&] (const juce::String& name, int rows) {
  16165. const auto bottom = pl.trackRowForSnapshot (rows).getY();
  16166. savePng (pl.createComponentSnapshot ({ 0, 0, juce::jmin (pl.getWidth(), 820), juce::jmin (pl.getHeight(), bottom + 12) }), prefix + name);
  16167. };
  16168. const auto& song = [&]() -> const lynx::Song& { return engine.getSong(); };
  16169. const auto mode = [&] (int t) { return t < (int) song().playlistTracks.size() ? song().playlistTracks[(std::size_t) t].mode : lynx::PlaylistTrackMode::unassigned; };
  16170. const auto mixerOf = [&] (int t) { return t < (int) song().playlistTracks.size() ? song().playlistTracks[(std::size_t) t].mixerTrack : -1; };
  16171. // ---- 1. FL's default: tracks and inserts apart, FL's narrow headers
  16172. check ("off_by_default", ! song().linkTracksToMixer && pl.headerWidthForSnapshot() == lynx::PlaylistComponent::flHeaderWidthNow(),
  16173. juce::String (pl.headerWidthForSnapshot()));
  16174. shotRows ("-off.png", 7);
  16175. // ---- 2. the switch (Playlist › Edit, Track mode, Settings › Project): it lists what it changes and asks (round
  16176. // 190ib: inserts move, channels are routed), then it is one undo step
  16177. lynx::autolink::Report plan;
  16178. bool asked = false;
  16179. lynx::PlaylistComponent::answerLinkConfirmation = [&] (const lynx::autolink::Report& r) {
  16180. plan = r;
  16181. asked = true;
  16182. return true;
  16183. };
  16184. {
  16185. const auto text = lynx::PlaylistComponent::describeLinkPlan (song(), lynx::autolink::planOn (song()));
  16186. juce::AlertWindow box (lynx::tr ("Link Playlist tracks to mixer tracks"), text, juce::MessageBoxIconType::QuestionIcon);
  16187. box.addButton (lynx::tr ("Link"), 1);
  16188. box.addButton (lynx::tr ("Cancel"), 0);
  16189. box.sendLookAndFeelChange();
  16190. savePng (lynx::shot::snapshot (box), prefix + "-confirm.png");
  16191. }
  16192. pl.runAction ("playlist.linkTracks");
  16193. engine.dispatchPendingMessages();
  16194. const auto moved = [&plan] (int from, int to) {
  16195. return std::any_of (plan.changes.begin(), plan.changes.end(), [=] (const lynx::autolink::Change& c) {
  16196. return c.kind == lynx::autolink::Change::Kind::moveInsert && c.from == from && c.to == to;
  16197. });
  16198. };
  16199. check ("asked_first_with_the_moves", asked && moved (9, 4) && moved (12, 5) && plan.repeats.size() == 1 && ! plan.changesSound(),
  16200. juce::String ((int) plan.changes.size()));
  16201. check ("switch_on", song().linkTracksToMixer && pl.headerWidthForSnapshot() == lynx::PlaylistComponent::linkedHeaderWidth,
  16202. juce::String (pl.headerWidthForSnapshot()));
  16203. check ("kick_instrument_track_insert_1", mode (0) == lynx::PlaylistTrackMode::instrument && mixerOf (0) == 1 && song().channels[0].mixerTrack == 1,
  16204. juce::String (mixerOf (0)));
  16205. check ("loop_audio_track_insert_2", mode (1) == lynx::PlaylistTrackMode::audio && mixerOf (1) == 2 && song().mixer[2].name == "Drum loop",
  16206. juce::String (mixerOf (1)));
  16207. // (round 190ib: Track N = insert N for every track with content of its own)
  16208. check ("beat_track_insert_3", mode (2) == lynx::PlaylistTrackMode::audio && mixerOf (2) == 3 && song().channels[1].mixerTrack == 3
  16209. && song().channels[2].mixerTrack == 3 && song().channels[3].mixerTrack == 3,
  16210. juce::String (mixerOf (2)));
  16211. check ("synth_bus_moves_to_insert_4", mode (3) == lynx::PlaylistTrackMode::instrument && song().channels[4].mixerTrack == 4
  16212. && song().mixer[4].name == "Synth bus" && song().playlistTracks[3].name == "Synth bus",
  16213. juce::String (song().channels[4].mixerTrack));
  16214. check ("vocal_chain_moves_to_insert_5", mode (4) == lynx::PlaylistTrackMode::audio && mixerOf (4) == 5 && song().mixer[5].effects.size() == 1
  16215. && song().mixer[5].name == "Vox chain",
  16216. juce::String (mixerOf (4)));
  16217. check ("empty_and_repeat_tracks_stay", mode (5) == lynx::PlaylistTrackMode::unassigned && mode (6) == lynx::PlaylistTrackMode::unassigned
  16218. && lynx::autolink::repeatedTracks (song())[6] == 0);
  16219. shotRows ("-on.png", 7);
  16220. // one undo step: Undo brings FL's tracks back, Redo the links
  16221. engine.undo();
  16222. engine.dispatchPendingMessages();
  16223. check ("undo_switch_on", ! song().linkTracksToMixer && mode (0) == lynx::PlaylistTrackMode::unassigned && mode (1) == lynx::PlaylistTrackMode::unassigned
  16224. && song().channels[0].mixerTrack == 0 && pl.headerWidthForSnapshot() == lynx::PlaylistComponent::flHeaderWidthNow());
  16225. engine.redo();
  16226. engine.dispatchPendingMessages();
  16227. check ("redo_switch_on", song().linkTracksToMixer && mixerOf (1) == 2 && pl.headerWidthForSnapshot() == lynx::PlaylistComponent::linkedHeaderWidth);
  16228. auto source = juce::Desktop::getInstance().getMainMouseSource();
  16229. const auto now = juce::Time::getCurrentTime();
  16230. const int ctrl = juce::ModifierKeys::commandModifier;
  16231. const auto event = [&] (juce::Point<int> p, juce::ModifierKeys mods, juce::Point<int> down, int clicks, bool dragged) {
  16232. 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);
  16233. };
  16234. const auto press = [&] (juce::Point<int> p, juce::ModifierKeys mods, std::optional<juce::Point<int>> to = {}) {
  16235. const auto down = mods.withFlags (juce::ModifierKeys::leftButtonModifier);
  16236. pl.mouseMove (event (p, mods, p, 1, false));
  16237. pl.mouseDown (event (p, down, p, 1, false));
  16238. if (to)
  16239. pl.mouseDrag (event (*to, down, p, 1, true));
  16240. pl.mouseUp (event (to ? *to : p, mods, p, 1, to.has_value()));
  16241. engine.flushLevels();
  16242. engine.dispatchPendingMessages();
  16243. };
  16244. const auto doubleClick = [&] (juce::Point<int> p) {
  16245. const auto down = juce::ModifierKeys (juce::ModifierKeys::leftButtonModifier);
  16246. pl.mouseDown (event (p, down, p, 2, false));
  16247. pl.mouseDoubleClick (event (p, down, p, 2, false));
  16248. pl.mouseUp (event (p, {}, p, 2, false));
  16249. engine.flushLevels();
  16250. engine.dispatchPendingMessages();
  16251. };
  16252. // the controls are found where they are drawn: M right of the plate, S left of it, the volume bar and the pan knob
  16253. // under them (the same geometry the header paints with)
  16254. const auto row = [&] (int t) { return pl.trackRowForSnapshot (t); };
  16255. const int w = pl.headerWidthForSnapshot();
  16256. const auto mAt = [&] (int t) { const auto r = row (t); return juce::Point<int> (w - 13 - 9, r.getY() + 11); }; // (meter column 9 px)
  16257. const auto sAt = [&] (int t) { return mAt (t) - juce::Point<int> (20, 0); };
  16258. const auto volumeAt = [&] (int t, float fraction) {
  16259. const auto r = row (t);
  16260. const auto left = 8, width = w - 9 - 2 - 32;
  16261. return juce::Point<int> (left + juce::roundToInt (fraction * (float) width), r.getY() + 26);
  16262. };
  16263. const auto panAt = [&] (int t) { const auto r = row (t); return juce::Point<int> (w - 9 - 6 - 7, r.getY() + 26); };
  16264. const auto& insert2 = [&]() -> const lynx::MixerTrack& { return song().mixer[2]; };
  16265. // ---- 3. the linked headers' controls act on the track's mixer track
  16266. press (mAt (1), {});
  16267. check ("m_mutes_the_insert", insert2().muted, juce::String ((int) insert2().muted));
  16268. press (mAt (1), {});
  16269. check ("m_again_unmutes", ! insert2().muted);
  16270. press (sAt (1), {});
  16271. check ("s_solos_the_insert", insert2().solo);
  16272. press (sAt (1), {});
  16273. press (volumeAt (1, 0.25f), {});
  16274. check ("volume_click_sets_the_level", std::abs (insert2().volume - 0.25f) < 0.03f, juce::String (insert2().volume, 3));
  16275. press (volumeAt (1, 0.25f), {}, volumeAt (1, 0.5f));
  16276. check ("volume_drag", std::abs (insert2().volume - 0.5f) < 0.03f, juce::String (insert2().volume, 3));
  16277. doubleClick (volumeAt (1, 0.5f));
  16278. check ("volume_double_click_0_db", insert2().volume == lynx::unityFader, juce::String (insert2().volume, 3));
  16279. press (panAt (1), {}, panAt (1) - juce::Point<int> (0, 40));
  16280. check ("pan_drag_up", std::abs (insert2().pan - 0.5f) < 0.02f, juce::String (insert2().pan, 3));
  16281. shotRows ("-controls.png", 7);
  16282. doubleClick (panAt (1));
  16283. check ("pan_double_click_centre", insert2().pan == 0.0f, juce::String (insert2().pan, 3));
  16284. // an instrument track's header acts on its channel's insert (Synth: insert 4 since round 190ib)
  16285. press (volumeAt (3, 0.4f), {});
  16286. check ("instrument_track_volume_on_its_insert", std::abs (song().mixer[4].volume - 0.4f) < 0.03f, juce::String (song().mixer[4].volume, 3));
  16287. engine.editSong ([] (lynx::Song& s) { s.mixer[4].volume = lynx::unityFader; });
  16288. // FL's track mute and solo stay on the Playlist track: Ctrl+click on M solos it, a muted track lights M and the
  16289. // first click unmutes it
  16290. press (mAt (1), ctrl);
  16291. check ("ctrl_m_solos_the_playlist_track", song().isTrackMuted (0) && ! song().isTrackMuted (1) && ! insert2().solo);
  16292. press (mAt (1), ctrl);
  16293. engine.editSong ([] (lynx::Song& s) {
  16294. for (auto& t : s.playlistTracks)
  16295. t.muted = false;
  16296. s.playlistTracks[1].muted = true;
  16297. });
  16298. press (mAt (1), {});
  16299. check ("m_unmutes_a_muted_playlist_track_first", ! song().isTrackMuted (1) && ! insert2().muted);
  16300. // a track that only repeats another keeps FL's LED (Track 7, Track 1's Kick): a click mutes the Playlist track
  16301. press (juce::Point<int> (w - 9 - 11, row (6).getCentreY()), {});
  16302. check ("unlinked_led_is_fl", song().isTrackMuted (6));
  16303. engine.editSong ([] (lynx::Song& s) { s.playlistTracks[6].muted = false; });
  16304. // round 190ib: a linked track and its insert keep one name, whichever is renamed
  16305. engine.editSong ([] (lynx::Song& s) { s.mixer[3].name = "Drums"; });
  16306. check ("insert_rename_renames_the_track", song().playlistTracks[2].name == "Drums");
  16307. engine.editSong ([] (lynx::Song& s) { s.playlistTracks[2].name = "Beat"; });
  16308. check ("track_rename_renames_the_insert", song().mixer[3].name == "Beat");
  16309. // ---- 4. new content follows: a sample on empty Track 6 makes it an audio track (insert 6)
  16310. engine.editSong ([] (lynx::Song& s) {
  16311. lynx::ChannelDef c;
  16312. c.name = "Guitar";
  16313. c.instrument = lynx::InstrumentKind::audioClip;
  16314. c.samplePath = "/shots/Guitar.wav";
  16315. s.channels.push_back (c);
  16316. lynx::Clip clip;
  16317. clip.kind = lynx::ClipKind::audio;
  16318. clip.channel = (int) s.channels.size() - 1;
  16319. clip.track = 5;
  16320. clip.start = 4 * 4 * lynx::ppq;
  16321. clip.length = 4 * 4 * lynx::ppq;
  16322. s.playlist.push_back (clip);
  16323. });
  16324. check ("new_sample_links_its_track", mode (5) == lynx::PlaylistTrackMode::audio && mixerOf (5) == 6 && song().channels.back().mixerTrack == 6,
  16325. juce::String (mixerOf (5)));
  16326. engine.undo();
  16327. check ("undo_takes_the_clip_and_the_link", mode (5) == lynx::PlaylistTrackMode::unassigned && song().channels.back().name != "Guitar");
  16328. // ---- 5. row heights (round 190ft): short rows keep M / S; from 34 px the volume and pan; tall rows the input
  16329. const auto heights = [&] (std::vector<std::pair<int, int>> rows) {
  16330. engine.editSong ([rows] (lynx::Song& s) {
  16331. for (const auto& [t, h] : rows)
  16332. s.playlistTracks[(std::size_t) t].height = h;
  16333. });
  16334. engine.dispatchPendingMessages();
  16335. };
  16336. heights ({ { 0, 16 }, { 1, 24 }, { 4, 80 } });
  16337. shotRows ("-heights.png", 7);
  16338. {
  16339. const auto r = row (1);
  16340. const auto before = insert2().volume;
  16341. press (juce::Point<int> (20, r.getY() + 12), {}); // (no volume bar on a 24 px row: the press selects)
  16342. check ("short_row_has_no_volume_bar", insert2().volume == before && pl.selectedTracksForSnapshot() == std::vector<int> { 1 });
  16343. press (juce::Point<int> (w - 22, r.getY() + 12), {});
  16344. check ("short_row_m_still_works", insert2().muted);
  16345. press (juce::Point<int> (w - 22, r.getY() + 12), {});
  16346. }
  16347. heights ({ { 0, 0 }, { 1, 0 }, { 4, 0 } });
  16348. // ---- 6. saved: .lynx keeps the switch; the links themselves are FL track modes
  16349. {
  16350. juce::String error;
  16351. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song()), error);
  16352. check ("lynx_round_trip", back && back->linkTracksToMixer && back->playlistTracks.size() > 4 && back->playlistTracks[1].mixerTrack == 2
  16353. && back->playlistTracks[0].mode == lynx::PlaylistTrackMode::instrument, error);
  16354. auto plain = song();
  16355. plain.linkTracksToMixer = false;
  16356. const auto json = lynx::ProjectFile::toJson (plain);
  16357. check ("off_not_saved", ! json.contains ("linkTracksToMixer"));
  16358. }
  16359. // ---- 7. off: FL's headers again (the links stay)
  16360. lynx::PlaylistComponent::answerLinkConfirmation = nullptr;
  16361. pl.runAction ("playlist.linkTracks");
  16362. engine.dispatchPendingMessages();
  16363. check ("switch_off_fl_headers", ! song().linkTracksToMixer && pl.headerWidthForSnapshot() == lynx::PlaylistComponent::flHeaderWidthNow()
  16364. && mode (1) == lynx::PlaylistTrackMode::audio);
  16365. shotRows ("-off-after.png", 7);
  16366. // ---- 8. Settings › Project's switches
  16367. {
  16368. auto panel = lynx::makeSettingsPanel (engine, lynx::SettingsPage::project);
  16369. panel->setSize (760, 720);
  16370. savePng (lynx::shot::snapshot (*panel), prefix + "-settings-project.png");
  16371. }
  16372. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\nresult=" + (allOk ? "OK" : "FAIL") + "\n");
  16373. return allOk;
  16374. }
  16375. bool runFlPlShot (const juce::String& prefix)
  16376. {
  16377. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  16378. juce::StringArray report;
  16379. bool allOk = true;
  16380. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  16381. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  16382. allOk = allOk && ok;
  16383. };
  16384. const auto plain = [] (juce::String t) {
  16385. // (without the shortcut column and the mnemonic: the mark, or the " (K)" a translation without the letter gets)
  16386. t = t.upToFirstOccurrenceOf ("\t", false, false);
  16387. if (const auto at = t.indexOf (juce::String (" (") + juce::String::charToString (1)); at >= 0)
  16388. t = t.substring (0, at);
  16389. return t.removeCharacters (juce::String ("&_") + juce::String::charToString (1));
  16390. };
  16391. const auto findSub = [&plain] (const juce::PopupMenu& menu, const juce::String& text) -> const juce::PopupMenu* {
  16392. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  16393. if (it.getItem().subMenu != nullptr && plain (it.getItem().text) == plain (text))
  16394. return it.getItem().subMenu.get();
  16395. return nullptr;
  16396. };
  16397. const auto texts = [&plain] (const juce::PopupMenu& menu, int count) {
  16398. juce::StringArray out;
  16399. for (juce::PopupMenu::MenuItemIterator it (menu); it.next() && out.size() < count;)
  16400. out.add (it.getItem().isSeparator ? juce::String ("-") : it.getItem().isSectionHeader ? "[" + plain (it.getItem().text) + "]" : plain (it.getItem().text));
  16401. return out;
  16402. };
  16403. const auto modelTexts = [] (const std::vector<lynx::fltrackmenus::Entry>& model) {
  16404. juce::StringArray out;
  16405. for (const auto& e : model)
  16406. if (e.kind != lynx::fltrackmenus::Entry::Kind::list)
  16407. out.add (e.kind == lynx::fltrackmenus::Entry::Kind::separator ? juce::String ("-")
  16408. : e.kind == lynx::fltrackmenus::Entry::Kind::caption ? "[" + lynx::tr (e.text) + "]"
  16409. : lynx::tr (e.text));
  16410. return out;
  16411. };
  16412. const auto click = [&plain] (const juce::PopupMenu& menu, const juce::String& text) {
  16413. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  16414. if (plain (it.getItem().text) == plain (text) && it.getItem().isEnabled && it.getItem().action != nullptr)
  16415. {
  16416. it.getItem().action();
  16417. return true;
  16418. }
  16419. return false;
  16420. };
  16421. lynx::AudioEngine engine (false);
  16422. lynx::MainComponent ui (engine, false);
  16423. ui.setSize (1600, 900);
  16424. int vox = -1;
  16425. {
  16426. auto song = lynx::Song::makeDefault();
  16427. song.channels.push_back ({});
  16428. song.channels.back().name = "Vox";
  16429. song.channels.back().instrument = lynx::InstrumentKind::audioClip;
  16430. song.channels.back().volume = 0.6f;
  16431. song.channels.back().samplePath = writeShotSample (juce::File (prefix + "-vox.wav"), 330.0).getFullPathName().toStdString();
  16432. vox = (int) song.channels.size() - 1;
  16433. lynx::Clip c;
  16434. c.kind = lynx::ClipKind::audio;
  16435. c.channel = vox;
  16436. c.track = 3;
  16437. c.start = 4 * lynx::ppq;
  16438. c.length = 2 * lynx::ppq;
  16439. song.playlist.push_back (c);
  16440. engine.setSong (std::move (song));
  16441. }
  16442. engine.dispatchPendingMessages();
  16443. auto& playlist = ui.getPlaylistForSnapshot();
  16444. // ---- 1. the audio clip menu: Preview first, Automate › Panning / Volume
  16445. {
  16446. const auto menu = playlist.getClipMenuForSnapshot (0);
  16447. juce::PopupMenu::MenuItemIterator it (menu);
  16448. it.next(); // (the "Audio clip" title band)
  16449. it.next();
  16450. check ("clip_menu_preview_first", plain (it.getItem().text) == lynx::tr ("Preview"), it.getItem().text);
  16451. const auto* automate = findSub (menu, lynx::tr ("Automate"));
  16452. check ("clip_menu_automate", automate != nullptr && texts (*automate, 9) == modelTexts (lynx::fltrackmenus::automate()),
  16453. automate != nullptr ? texts (*automate, 9).joinIntoString ("|") : juce::String ("missing"));
  16454. saveMenus (juce::StringArray { "Audio clip menu", "Automate" }, std::vector<juce::PopupMenu> { menu, automate != nullptr ? *automate : juce::PopupMenu() },
  16455. prefix + "-clip-menu.png");
  16456. const auto before = engine.getSong().automations.size();
  16457. check ("automate_volume_runs", automate != nullptr && click (*automate, lynx::tr ("Volume")));
  16458. const auto& song = engine.getSong();
  16459. // (round 190dz: the Levels adjustment's volume multiplier, neutral = 0.5 of its 0…200 % travel)
  16460. const auto ok = song.automations.size() == before + 1 && song.automations.back().target.kind == lynx::AutomationTargetKind::channelAdjust
  16461. && song.automations.back().target.param == lynx::leveladjust::volume
  16462. && song.automations.back().target.index == vox && song.automations.back().points.size() == 2
  16463. && song.automations.back().points[1].tick == 2 * lynx::ppq && std::abs (song.automations.back().points[0].value - 0.5f) < 1.0e-6f;
  16464. const auto* clip = ok ? &song.playlist.back() : nullptr;
  16465. check ("automate_volume_clip", ok && clip->kind == lynx::ClipKind::automation && clip->track == 3 && clip->start == 4 * lynx::ppq
  16466. && clip->length == 2 * lynx::ppq,
  16467. ok ? juce::String::fromUTF8 (song.automations.back().name.c_str()) : juce::String());
  16468. engine.undo();
  16469. check ("automate_undo", engine.getSong().automations.size() == before);
  16470. // Preview: the clip's own audio (FL plays it through its channel); LYNX renders it for the preview output
  16471. const auto rendered = engine.renderClipAudio (0);
  16472. check ("preview_renders_the_clip", ! rendered.left.empty(), juce::String ((int) rendered.left.size()) + " frames");
  16473. }
  16474. // ---- 2. the Playlist's "+": its menu, a right click's audio track, the corner
  16475. {
  16476. const auto menu = playlist.getAddTrackMenuForSnapshot();
  16477. check ("add_menu_head", texts (menu, 5) == modelTexts (lynx::fltrackmenus::addTrack()), texts (menu, 5).joinIntoString ("|"));
  16478. saveMenus (juce::StringArray { "Playlist +" }, std::vector<juce::PopupMenu> { menu }, prefix + "-add-track-menu.png");
  16479. ui.selectTabForSnapshot (2);
  16480. engine.dispatchPendingMessages();
  16481. auto* button = playlist.getAddTrackButtonForSnapshot();
  16482. check ("add_button_in_corner", button != nullptr && button->isVisible() && button->getX() == 7 && button->getWidth() == 21 && button->getHeight() == 18
  16483. && button->getBottom() <= lynx::PlaylistComponent::headerHeight);
  16484. savePng (playlist.createComponentSnapshot (juce::Rectangle<int> (0, 0, juce::jmin (560, playlist.getWidth()), juce::jmin (260, playlist.getHeight()))),
  16485. prefix + "-playlist-corner.png");
  16486. const auto track = playlist.addAudioTrackNow();
  16487. const auto& song = engine.getSong();
  16488. check ("add_audio_track", track == 0 && song.playlistTracks.size() > 0 && song.playlistTracks[0].mode == lynx::PlaylistTrackMode::audio
  16489. && song.playlistTracks[0].mixerTrack > 0,
  16490. juce::String (track));
  16491. engine.undo();
  16492. }
  16493. // ---- 3. Track mode › Instrument track ›
  16494. {
  16495. const auto menu = playlist.getTrackMenuForSnapshot (5);
  16496. const auto* modes = findSub (menu, lynx::tr ("Track mode"));
  16497. const auto* instrument = modes != nullptr ? findSub (*modes, lynx::tr ("Instrument track")) : nullptr;
  16498. check ("instrument_track_head", instrument != nullptr && texts (*instrument, 4) == modelTexts (lynx::fltrackmenus::instrumentTrack()),
  16499. instrument != nullptr ? texts (*instrument, 4).joinIntoString ("|") : juce::String ("missing"));
  16500. const auto* existing = instrument != nullptr ? findSub (*instrument, lynx::tr ("Use existing channel")) : nullptr;
  16501. check ("use_existing_lists_generators", existing != nullptr && existing->getNumItems() == 5, existing != nullptr ? juce::String (existing->getNumItems()) : juce::String());
  16502. std::vector<juce::PopupMenu> menus { modes != nullptr ? *modes : juce::PopupMenu(), instrument != nullptr ? *instrument : juce::PopupMenu(),
  16503. existing != nullptr ? *existing : juce::PopupMenu() };
  16504. saveMenus (juce::StringArray { "Track mode", "Instrument track", "Use existing channel" }, menus, prefix + "-instrument-track-menu.png");
  16505. lynx::ChannelDef synth;
  16506. synth.name = "Lead";
  16507. synth.instrument = lynx::InstrumentKind::synth;
  16508. const auto channels = engine.getSong().channels.size();
  16509. int made = -1;
  16510. engine.editSong ([&] (lynx::Song& s) { made = lynx::trackmodes::addInstrumentTrack (s, synth, 5); });
  16511. check ("instrument_track_new_channel", made == (int) channels && engine.getSong().playlistTracks.size() > 5
  16512. && engine.getSong().playlistTracks[5].channel == made);
  16513. engine.undo();
  16514. }
  16515. // ---- 4. the Channel rack menu: Assign to new instrument track / Unassign
  16516. {
  16517. auto& rack = ui.getRackForSnapshot();
  16518. const auto menu = rack.getChannelMenuForSnapshot (1);
  16519. saveMenus (juce::StringArray { "Channel menu" }, std::vector<juce::PopupMenu> { menu }, prefix + "-channel-menu.png");
  16520. check ("assign_runs", click (menu, lynx::tr ("Assign to new instrument track")));
  16521. const auto tracks = lynx::trackmodes::instrumentTracksOf (engine.getSong(), 1);
  16522. check ("assign_first_free_track", tracks == std::vector<int> { 0 }, juce::String (tracks.empty() ? -1 : tracks.front()));
  16523. const auto again = rack.getChannelMenuForSnapshot (1);
  16524. check ("unassign_offered", click (again, lynx::tr ("Unassign from instrument track")) && lynx::trackmodes::instrumentTracksOf (engine.getSong(), 1).empty());
  16525. bool greyed = false;
  16526. const auto voxMenu = rack.getChannelMenuForSnapshot (vox);
  16527. for (juce::PopupMenu::MenuItemIterator it (voxMenu); it.next();)
  16528. if (plain (it.getItem().text) == plain (lynx::tr ("Assign to new instrument track")))
  16529. greyed = ! it.getItem().isEnabled;
  16530. check ("assign_greyed_for_audio_clip_channel", greyed);
  16531. }
  16532. // ---- 5. Tools › One-click audio recording
  16533. std::fprintf (stderr, "flplshot: tools\n");
  16534. {
  16535. const auto names = ui.getMenuNamesForSnapshot();
  16536. const auto tools = ui.getMenuForSnapshot (names.indexOf (lynx::tr ("Tools")));
  16537. const auto* oneClick = findSub (tools, lynx::tr ("One-click audio recording"));
  16538. check ("one_click_submenu", oneClick != nullptr && texts (*oneClick, 3) == modelTexts (lynx::fltrackmenus::oneClickRecording()),
  16539. oneClick != nullptr ? texts (*oneClick, 3).joinIntoString ("|") : juce::String ("missing"));
  16540. saveMenus (juce::StringArray { "Tools", "One-click audio recording" }, std::vector<juce::PopupMenu> { tools, oneClick != nullptr ? *oneClick : juce::PopupMenu() },
  16541. prefix + "-tools-one-click.png");
  16542. const auto plan = lynx::oneclick::plan (engine.getSong(), {}, 2, lynx::oneclick::Into::playlist);
  16543. check ("one_click_plan", plan.insert == 2 && plan.armInsert && plan.askInput && plan.songMode);
  16544. }
  16545. // ---- 6. Mixer › Disk recording › Latency compensation
  16546. {
  16547. auto& strips = ui.getMixerForSnapshot().getStripsForSnapshot();
  16548. const auto menu = strips.buildMenu (1);
  16549. const auto* disk = findSub (menu, lynx::tr ("Disk recording"));
  16550. int after = -1, at = -1, i = 0;
  16551. bool ticked = false;
  16552. if (disk != nullptr)
  16553. for (juce::PopupMenu::MenuItemIterator it (*disk); it.next(); ++i)
  16554. {
  16555. if (plain (it.getItem().text) == plain (lynx::tr ("Auto-create audio clip (the rendered files go on the Playlist)")))
  16556. after = i;
  16557. if (plain (it.getItem().text) == plain (lynx::tr ("Latency compensation")))
  16558. {
  16559. at = i;
  16560. ticked = it.getItem().isTicked;
  16561. }
  16562. }
  16563. check ("latency_comp_item", disk != nullptr && after >= 0 && at == after + 1 && ticked && engine.getRecordOptions().latencyCompensation,
  16564. juce::String (after) + " " + juce::String (at));
  16565. saveMenus (juce::StringArray { "Disk recording" }, std::vector<juce::PopupMenu> { disk != nullptr ? *disk : juce::PopupMenu() },
  16566. prefix + "-disk-recording.png");
  16567. check ("latency_comp_toggles", disk != nullptr && click (*disk, lynx::tr ("Latency compensation")) && ! engine.getRecordOptions().latencyCompensation);
  16568. }
  16569. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\nresult=" + (allOk ? "OK" : "FAIL") + "\n");
  16570. return allOk;
  16571. }
  16572. // --flclipshot (round 190dz): see the dispatch above
  16573. // a menu as JUCE lays it out with explicit column breaks (PopupMenu::addColumnBreak): the columns side by side on
  16574. // one menu background; custom items (the title band) are painted by their own component
  16575. static juce::Image columnMenuImage (const juce::PopupMenu& menu)
  16576. {
  16577. auto& lf = juce::LookAndFeel::getDefaultLookAndFeel();
  16578. const auto border = lf.getPopupMenuBorderSize();
  16579. struct Row
  16580. {
  16581. const juce::PopupMenu::Item* item;
  16582. int height;
  16583. };
  16584. std::vector<std::vector<Row>> columns (1);
  16585. std::vector<int> widths (1, 160);
  16586. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  16587. {
  16588. const auto& item = it.getItem();
  16589. int w = 0, h = 0;
  16590. if (item.customComponent != nullptr)
  16591. item.customComponent->getIdealSize (w, h);
  16592. else
  16593. {
  16594. lf.getIdealPopupMenuItemSize (item.text.upToFirstOccurrenceOf ("\t", false, false), item.isSeparator, item.isSectionHeader ? -1 : 0, w, h);
  16595. if (item.isSectionHeader)
  16596. h += h / 2; // as JUCE does
  16597. if (item.text.containsChar ('\t'))
  16598. w += 90;
  16599. }
  16600. columns.back().push_back ({ &item, h });
  16601. widths.back() = juce::jmax (widths.back(), w + 10);
  16602. if (item.shouldBreakAfter)
  16603. {
  16604. columns.emplace_back();
  16605. widths.push_back (160);
  16606. }
  16607. }
  16608. int width = 0, height = 0;
  16609. for (std::size_t c = 0; c < columns.size(); ++c)
  16610. {
  16611. width += widths[c];
  16612. int h = 2 * border;
  16613. for (const auto& row : columns[c])
  16614. h += row.height;
  16615. height = juce::jmax (height, h);
  16616. }
  16617. auto image = lynx::shot::canvas (width, height);
  16618. juce::Graphics g (image);
  16619. lynx::shot::logical (g);
  16620. lf.drawPopupMenuBackground (g, width, height);
  16621. int x = 0;
  16622. for (std::size_t c = 0; c < columns.size(); ++c)
  16623. {
  16624. int y = border;
  16625. for (const auto& row : columns[c])
  16626. {
  16627. const auto& item = *row.item;
  16628. const juce::Rectangle<int> r (x, y, widths[c], row.height);
  16629. if (item.customComponent != nullptr)
  16630. {
  16631. juce::Graphics::ScopedSaveState state (g);
  16632. g.setOrigin (r.getPosition());
  16633. item.customComponent->setSize (r.getWidth(), r.getHeight());
  16634. item.customComponent->paintEntireComponent (g, false);
  16635. }
  16636. else if (item.isSectionHeader)
  16637. lf.drawPopupMenuSectionHeader (g, r, item.text);
  16638. else
  16639. {
  16640. juce::Graphics::ScopedSaveState state (g);
  16641. g.setOrigin (r.getPosition());
  16642. lf.drawPopupMenuItem (g, r.withPosition (0, 0), item.isSeparator, item.isEnabled, false, item.isTicked, item.subMenu != nullptr,
  16643. item.text.upToFirstOccurrenceOf ("\t", false, false), item.text.fromFirstOccurrenceOf ("\t", false, false),
  16644. item.image.get(), nullptr);
  16645. }
  16646. y += row.height;
  16647. }
  16648. x += widths[c];
  16649. if (c + 1 < columns.size()) // (JUCE's column separator)
  16650. {
  16651. g.setColour (lf.findColour (juce::PopupMenu::textColourId).withAlpha (0.15f));
  16652. g.fillRect (x - 1, border, 1, height - 2 * border);
  16653. }
  16654. }
  16655. return image;
  16656. }
  16657. // --genpresetshot (round 190fs): see the dispatch above
  16658. bool runGenPresetShot (const juce::String& prefix)
  16659. {
  16660. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  16661. juce::StringArray report;
  16662. bool allOk = true;
  16663. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  16664. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  16665. allOk = allOk && ok;
  16666. };
  16667. const auto shoot = [&prefix] (juce::Component& c, const char* name) {
  16668. savePng (c.createComponentSnapshot (c.getLocalBounds()), prefix + "-" + name + ".png");
  16669. };
  16670. const auto plain = [] (juce::String t) { return t.upToFirstOccurrenceOf ("\t", false, false).removeCharacters ("&"); };
  16671. const auto texts = [&plain] (const juce::PopupMenu& menu) {
  16672. juce::StringArray out;
  16673. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  16674. out.add (it.getItem().isSeparator ? juce::String ("-") : it.getItem().isSectionHeader ? "[" + plain (it.getItem().text) + "]" : plain (it.getItem().text));
  16675. return out;
  16676. };
  16677. const auto click = [&plain] (const juce::PopupMenu& menu, const juce::String& text) {
  16678. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  16679. if (plain (it.getItem().text) == plain (text) && it.getItem().isEnabled && it.getItem().action != nullptr)
  16680. {
  16681. it.getItem().action();
  16682. return true;
  16683. }
  16684. return false;
  16685. };
  16686. const auto sameSound = [] (const lynx::ChannelDef& a, const lynx::ChannelDef& b) { return lynx::genpresets::sameSound (a, b); };
  16687. lynx::AudioEngine engine (false);
  16688. const auto& fl = lynx::flStudioAccess();
  16689. auto dx = lynx::natives::makeChannel (lynx::InstrumentKind::dx10, fl);
  16690. auto osc = lynx::natives::makeChannel (lynx::InstrumentKind::threeosc, fl);
  16691. check ("channels_made", dx.has_value() && osc.has_value());
  16692. if (! dx || ! osc)
  16693. {
  16694. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\n");
  16695. return false;
  16696. }
  16697. engine.editSong ([&] (lynx::Song& s) {
  16698. s.channels.clear();
  16699. s.channels.push_back (*dx);
  16700. s.channels.back().mixerTrack = 1;
  16701. s.channels.push_back (*osc);
  16702. s.channels.back().mixerTrack = 2;
  16703. lynx::ChannelDef synth;
  16704. synth.instrument = lynx::InstrumentKind::synth;
  16705. synth.name = "Synth";
  16706. synth.mixerTrack = 3;
  16707. s.channels.push_back (synth);
  16708. });
  16709. const auto channel = [&engine] (int i) { return engine.getSong().channels[(std::size_t) i]; };
  16710. // ---- 1. Fruity DX10: the preset box before and after "Save preset..."
  16711. {
  16712. auto frame = lynx::makeChannelFrame (engine, 0, 0);
  16713. frame->setSize (juce::jmax (500, frame->getWidth()), juce::jmax (300, frame->getHeight()));
  16714. auto menu = lynx::channelPresetMenu (*frame);
  16715. check ("dx10_menu", menu.has_value());
  16716. const auto before = menu ? texts (*menu) : juce::StringArray();
  16717. check ("dx10_menu_has_save", before.contains (lynx::tr ("Save preset...")) && before.contains (lynx::tr ("Show the presets folder"))
  16718. && ! before.contains ("[" + lynx::tr ("Your presets") + "]"), before.joinIntoString ("|"));
  16719. if (menu)
  16720. saveMenus (juce::StringArray { "Fruity DX10 presets" }, std::vector<juce::PopupMenu> { *menu }, prefix + "-dx10-menu-before.png");
  16721. // a sound of its own: the bank's 4th preset, then a knob moved (a sound no factory preset has)
  16722. const auto mine = [&] {
  16723. auto c = channel (0);
  16724. if (auto b = lynx::banks::withPreset (c, 3))
  16725. c = *b;
  16726. if (! c.pluginState.empty())
  16727. c.pluginState[c.pluginState.size() / 2] ^= 0x5a;
  16728. return c;
  16729. }();
  16730. engine.editSong ([&] (lynx::Song& s) { s.channels[0] = mine; });
  16731. check ("dx10_saved", lynx::channelPresetSave (*frame, "My FM Bell"));
  16732. const auto file = lynx::genpresetui::folderFor (lynx::InstrumentKind::dx10).getChildFile ("My FM Bell.lynxpreset");
  16733. check ("dx10_file", file.existsAsFile() && lynx::genpresetui::isPresetFile (file), file.getFullPathName());
  16734. check ("dx10_box_shows_it", lynx::channelPresetName (*frame) == "My FM Bell", lynx::channelPresetName (*frame));
  16735. menu = lynx::channelPresetMenu (*frame);
  16736. const auto after = menu ? texts (*menu) : juce::StringArray();
  16737. check ("dx10_menu_your_presets", after.contains ("[" + lynx::tr ("Your presets") + "]") && after.contains ("My FM Bell")
  16738. && after.contains (lynx::tr ("Delete preset \"{0}\"", { "My FM Bell" })), after.joinIntoString ("|"));
  16739. if (menu)
  16740. saveMenus (juce::StringArray { "Fruity DX10 presets" }, std::vector<juce::PopupMenu> { *menu }, prefix + "-dx10-menu.png");
  16741. shoot (*frame, "dx10-window");
  16742. // another sound, then the user's preset from the menu: the saved sound back, one undo step, project changed
  16743. if (auto other = lynx::banks::withPreset (channel (0), 0))
  16744. engine.editSong ([&] (lynx::Song& s) { s.channels[0] = *other; });
  16745. check ("dx10_other_sound", ! sameSound (channel (0), mine));
  16746. engine.markSaved();
  16747. menu = lynx::channelPresetMenu (*frame);
  16748. check ("dx10_load_click", menu.has_value() && click (*menu, "My FM Bell"));
  16749. check ("dx10_loaded_identical", sameSound (channel (0), mine) && channel (0).pluginState == mine.pluginState);
  16750. check ("dx10_loaded_name_and_insert", channel (0).name == "My FM Bell" && channel (0).mixerTrack == 1,
  16751. juce::String::fromUTF8 (channel (0).name.c_str()));
  16752. check ("dx10_project_changed", engine.isModified());
  16753. engine.undo();
  16754. check ("dx10_one_undo_step", ! sameSound (channel (0), mine));
  16755. engine.redo();
  16756. check ("dx10_redo", sameSound (channel (0), mine));
  16757. // the Browser: a new channel with the preset's generator, sound and name
  16758. juce::String error;
  16759. const auto count = engine.getSong().channels.size();
  16760. check ("browser_new_channel", lynx::genpresetui::addChannel (engine, file, error) && engine.getSong().channels.size() == count + 1, error);
  16761. const auto added = engine.getSong().channels.back();
  16762. check ("browser_channel_sound", added.instrument == lynx::InstrumentKind::dx10 && sameSound (added, mine) && added.name == "My FM Bell");
  16763. engine.undo();
  16764. check ("browser_channel_undo", engine.getSong().channels.size() == count);
  16765. }
  16766. // ---- 2. 3x Osc: save, the menu, delete
  16767. {
  16768. auto frame = lynx::makeChannelFrame (engine, 1, 0);
  16769. frame->setSize (juce::jmax (500, frame->getWidth()), juce::jmax (300, frame->getHeight()));
  16770. check ("3xosc_saved", lynx::channelPresetSave (*frame, "Wide Saw Lead") && lynx::channelPresetSave (*frame, "Sub Bass"));
  16771. auto menu = lynx::channelPresetMenu (*frame);
  16772. const auto items = menu ? texts (*menu) : juce::StringArray();
  16773. check ("3xosc_menu", items.contains ("Wide Saw Lead") && items.contains ("Sub Bass") && items.contains (lynx::tr ("Save preset...")),
  16774. items.joinIntoString ("|"));
  16775. if (menu)
  16776. saveMenus (juce::StringArray { "3x Osc presets" }, std::vector<juce::PopupMenu> { *menu }, prefix + "-3xosc-menu.png");
  16777. shoot (*frame, "3xosc-window");
  16778. check ("3xosc_delete", menu.has_value() && click (*menu, lynx::tr ("Delete preset \"{0}\"", { "Sub Bass" })));
  16779. check ("3xosc_deleted", lynx::genpresetui::userPresets (lynx::InstrumentKind::threeosc).size() == 1
  16780. && ! lynx::genpresetui::folderFor (lynx::InstrumentKind::threeosc).getChildFile ("Sub Bass.lynxpreset").exists());
  16781. menu = lynx::channelPresetMenu (*frame);
  16782. const auto left = menu ? texts (*menu) : juce::StringArray();
  16783. check ("3xosc_menu_after_delete", left.contains ("Wide Saw Lead") && ! left.contains ("Sub Bass"), left.joinIntoString ("|"));
  16784. }
  16785. // ---- 3. LYNX's synth: its "Presets..." box
  16786. {
  16787. engine.editSong ([] (lynx::Song& s) { s.channels[2].synth.cutoff = 777.0f; });
  16788. auto frame = lynx::makeChannelFrame (engine, 2, 0);
  16789. frame->setSize (juce::jmax (500, frame->getWidth()), juce::jmax (300, frame->getHeight()));
  16790. check ("synth_saved", lynx::channelPresetSave (*frame, "Dark Pad"));
  16791. const auto menu = lynx::channelPresetMenu (*frame);
  16792. const auto items = menu ? texts (*menu) : juce::StringArray();
  16793. check ("synth_menu", items.contains ("Dark Pad") && items.contains (lynx::tr ("Save preset...")) && items.contains (lynx::tr ("Show the presets folder")),
  16794. items.joinIntoString ("|"));
  16795. if (menu)
  16796. saveMenus (juce::StringArray { "Synth presets" }, std::vector<juce::PopupMenu> { *menu }, prefix + "-synth-menu.png");
  16797. const auto saved = lynx::genpresetui::read (lynx::genpresetui::folderFor (lynx::InstrumentKind::synth).getChildFile ("Dark Pad.lynxpreset"));
  16798. check ("synth_file", saved.has_value() && saved->sound.synth.cutoff == 777.0f);
  16799. }
  16800. // ---- 4. the name box (the hosted plugins' and the effects' "Save preset" box)
  16801. {
  16802. auto box = lynx::genpresetui::makeNameBox ("My FM Bell");
  16803. box->setSize (juce::jmax (360, box->getWidth()), juce::jmax (150, box->getHeight()));
  16804. shoot (*box, "save-name-box");
  16805. check ("name_box", box->getTextEditorContents ("name") == "My FM Bell");
  16806. }
  16807. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\n");
  16808. return allOk;
  16809. }
  16810. // --flfixshot (round 190ey): see the dispatch above
  16811. bool runFlFixShot (const juce::String& prefix)
  16812. {
  16813. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  16814. juce::StringArray report;
  16815. bool allOk = true;
  16816. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  16817. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  16818. allOk = allOk && ok;
  16819. };
  16820. const auto shoot = [&prefix] (juce::Component& c, const char* name) {
  16821. savePng (c.createComponentSnapshot (c.getLocalBounds()), prefix + "-" + name + ".png");
  16822. };
  16823. const auto plain = [] (juce::String t) {
  16824. t = t.upToFirstOccurrenceOf ("\t", false, false);
  16825. if (const auto at = t.indexOf (juce::String (" (") + juce::String::charToString (1)); at >= 0)
  16826. t = t.substring (0, at);
  16827. return t.removeCharacters (juce::String ("&_") + juce::String::charToString (1));
  16828. };
  16829. const auto texts = [&plain] (const juce::PopupMenu& menu) {
  16830. juce::StringArray out;
  16831. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  16832. out.add (it.getItem().isSeparator ? juce::String ("-") : it.getItem().isSectionHeader ? "[" + plain (it.getItem().text) + "]" : plain (it.getItem().text));
  16833. return out;
  16834. };
  16835. const auto findSub = [&plain] (const juce::PopupMenu& menu, const juce::String& text) -> const juce::PopupMenu* {
  16836. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  16837. if (it.getItem().subMenu != nullptr && plain (it.getItem().text) == plain (text))
  16838. return it.getItem().subMenu.get();
  16839. return nullptr;
  16840. };
  16841. const auto click = [&plain] (const juce::PopupMenu& menu, const juce::String& text) {
  16842. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  16843. if (plain (it.getItem().text) == plain (text) && it.getItem().isEnabled && it.getItem().action != nullptr)
  16844. {
  16845. it.getItem().action();
  16846. return true;
  16847. }
  16848. return false;
  16849. };
  16850. const auto folder = juce::File (prefix).getParentDirectory().getChildFile ("flfix-samples");
  16851. folder.createDirectory();
  16852. const auto writeWav = [] (const juce::File& file, double rate, int frames, double hz) {
  16853. juce::AudioBuffer<float> buffer (1, frames);
  16854. for (int i = 0; i < frames; ++i)
  16855. buffer.setSample (0, i, (float) (0.8 * std::sin (juce::MathConstants<double>::twoPi * hz * i / rate) * std::exp (-i / (rate * 0.12))));
  16856. file.deleteFile();
  16857. juce::WavAudioFormat wav;
  16858. if (auto out = std::unique_ptr<juce::AudioFormatWriter> (wav.createWriterFor (file.createOutputStream().release(), rate, 1, 16, {}, 0)))
  16859. out->writeFromAudioSampleBuffer (buffer, 0, frames);
  16860. return file;
  16861. };
  16862. // ---- 1. the Sampler page (SMP-1 / 4 / 5 / 7, CTL-4)
  16863. {
  16864. lynx::AudioEngine engine (false);
  16865. const auto clap = writeWav (folder.getChildFile ("Basic 808 Clap.wav"), 44100.0, 11600, 180.0);
  16866. const auto loop48 = writeWav (folder.getChildFile ("Loop 48k.wav"), 48000.0, 48000, 220.0);
  16867. engine.editSong ([&] (lynx::Song& s) {
  16868. if (s.channels.empty())
  16869. s.channels.resize (1);
  16870. lynx::audioclips::loadSampleInto (s.channels[0], clap.getFullPathName().toStdString(), "808 Clap");
  16871. });
  16872. const auto sampler = [&engine] { return engine.getSong().channels[0].sampler; };
  16873. auto frame = lynx::makeChannelFrame (engine, 0, 0);
  16874. frame->setSize (frame->getWidth() > 0 ? frame->getWidth() : 700, frame->getHeight() > 0 ? frame->getHeight() : 720);
  16875. frame->createComponentSnapshot (frame->getLocalBounds());
  16876. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (8000);
  16877. auto& f = *frame;
  16878. lynx::samplerPageTurn (f, "show", 0.0);
  16879. const auto rate = engine.getTransport().sampleRate.load();
  16880. check ("resample_greyed_at_project_rate", lynx::samplerPageQuery (f, "resample") == (std::abs (rate - 44100.0) < 0.5 ? "0" : "1"), juce::String (rate));
  16881. check ("load_regions_greyed_without_regions", lynx::samplerPageQuery (f, "loadRegions") == "0");
  16882. check ("load_markers_greyed_without_markers", lynx::samplerPageQuery (f, "loadMarkers") == "0");
  16883. check ("bit_depth_16", lynx::samplerPageQuery (f, "corner") == "16", lynx::samplerPageQuery (f, "corner"));
  16884. check ("wave_hint_summary", lynx::samplerPageQuery (f, "waveHint").startsWith ("44100Hz, 16Bit int mono, 0:263"), lynx::samplerPageQuery (f, "waveHint"));
  16885. shoot (f, "sampler-44k");
  16886. // SMP-5: MUL's text
  16887. lynx::samplerPageTurn (f, "mul", 800.0);
  16888. check ("mul_text", lynx::samplerPageQuery (f, "mulText") == "105.70%", lynx::samplerPageQuery (f, "mulText"));
  16889. lynx::samplerPageTurn (f, "mul", 0.0);
  16890. // SMP-4: CROSSFADE on a loopless sample: Use loop points on, the loop = the whole sample, the box reads 32
  16891. engine.editSong ([] (lynx::Song& s) { s.channels[0].sampler.useLoopPoints = false; });
  16892. lynx::samplerPageTurn (f, "crossfade", 120.0);
  16893. check ("crossfade_loops_whole_sample", sampler().useLoopPoints && sampler().loopStart == 0 && sampler().loopEnd == 11599,
  16894. juce::String (sampler().loopStart) + ".." + juce::String (sampler().loopEnd));
  16895. check ("bit_depth_32_precomputed", lynx::samplerPageQuery (f, "corner") == "32", lynx::samplerPageQuery (f, "corner"));
  16896. frame->createComponentSnapshot (frame->getLocalBounds());
  16897. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (8000);
  16898. shoot (f, "sampler-crossfade-red-loop");
  16899. lynx::samplerPageTurn (f, "crossfade", 0.0);
  16900. // SMP-3: a loop set with END alone, drawn red (FL: 0..276)
  16901. engine.editSong ([] (lynx::Song& s) {
  16902. s.channels[0].sampler.loopStart = 0;
  16903. s.channels[0].sampler.loopEnd = 2400;
  16904. });
  16905. lynx::samplerPageTurn (f, "show", 0.0);
  16906. shoot (f, "sampler-end-loop-red");
  16907. // round 190gw (live check 190gu B3): the waveform menu's Spectrum view / Multichannel waveform view, on a stereo
  16908. // clap-like noise burst (left and right differ) with no loop, as FL's shot
  16909. {
  16910. const auto noisy = folder.getChildFile ("Noise Clap.wav");
  16911. juce::AudioBuffer<float> b (2, 44100);
  16912. juce::Random random (190);
  16913. for (int i = 0; i < b.getNumSamples(); ++i)
  16914. for (int c = 0; c < 2; ++c)
  16915. b.setSample (c, i, (float) ((random.nextFloat() * 2.0f - 1.0f) * 0.9 * std::exp (-i / (44100.0 * (c == 0 ? 0.10 : 0.18)))
  16916. * (i > 1500 * c ? 1.0 : 0.15)));
  16917. noisy.deleteFile();
  16918. juce::WavAudioFormat wav;
  16919. if (auto out = std::unique_ptr<juce::AudioFormatWriter> (wav.createWriterFor (noisy.createOutputStream().release(), 44100.0, 2, 16, {}, 0)))
  16920. out->writeFromAudioSampleBuffer (b, 0, b.getNumSamples());
  16921. const auto before = engine.getSong().channels[0];
  16922. engine.editSong ([&] (lynx::Song& s) {
  16923. s.channels[0].samplePath = noisy.getFullPathName().toStdString();
  16924. s.channels[0].sampler.loopStart = s.channels[0].sampler.loopEnd = -1;
  16925. s.channels[0].sampler.useLoopPoints = false;
  16926. });
  16927. lynx::samplerPageTurn (f, "show", 0.0);
  16928. frame->createComponentSnapshot (frame->getLocalBounds()); // (starts the new file's waveform)
  16929. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (8000);
  16930. lynx::samplerpage::waveViews().spectrum = true;
  16931. lynx::samplerPageTurn (f, "show", 0.0);
  16932. shoot (f, "sampler-spectrum-view");
  16933. lynx::samplerpage::waveViews() = { false, true };
  16934. lynx::samplerPageTurn (f, "show", 0.0);
  16935. shoot (f, "sampler-multichannel-view");
  16936. lynx::samplerpage::waveViews() = {};
  16937. engine.editSong ([&before] (lynx::Song& s) { s.channels[0] = before; });
  16938. lynx::samplerPageTurn (f, "show", 0.0);
  16939. frame->createComponentSnapshot (frame->getLocalBounds());
  16940. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (8000);
  16941. }
  16942. // SMP-7: the waveform menu
  16943. const auto waveMenu = lynx::samplerWaveMenu (f);
  16944. juce::StringArray expected { lynx::tr ("Reload"), lynx::tr ("Save as..."), lynx::tr ("Locate file"), lynx::tr ("Copy audio to clipboard"),
  16945. lynx::tr ("Paste audio from clipboard"), "-", lynx::tr ("Edit in audio editor"),
  16946. lynx::tr ("Edit in pitch corrector"), lynx::tr ("Edit in time warper"), "-", // (round 190gw)
  16947. lynx::tr ("Open in new sampler channel"), lynx::tr ("Open in new Fruity Granulizer channel"),
  16948. lynx::tr ("Open in new Fruity Slicer channel"), lynx::tr ("Open in new Slicex channel"), "-", // (round 190gk)
  16949. lynx::tr ("Detect tempo") };
  16950. if (lynx::fileProperties) // (round 190gk: Windows only)
  16951. expected.add (lynx::tr ("Get properties"));
  16952. expected.addArray (juce::StringArray { "-", lynx::tr ("Spectrum view"), lynx::tr ("Multichannel waveform view") }); // (round 190gw)
  16953. check ("wave_menu_items", waveMenu.has_value() && texts (*waveMenu) == expected, waveMenu.has_value() ? texts (*waveMenu).joinIntoString ("|") : juce::String ("none"));
  16954. if (waveMenu.has_value())
  16955. saveMenus (juce::StringArray { "Sampler waveform" }, std::vector<juce::PopupMenu> { *waveMenu }, prefix + "-wave-menu.png");
  16956. check ("copy_audio_to_clipboard", waveMenu.has_value() && click (*waveMenu, lynx::tr ("Copy audio to clipboard"))
  16957. && lynx::audioclipboard::editor().frames() == 11600);
  16958. // SMP-1: a 48 kHz sample in this project: Resample enabled
  16959. lynx::samplerPageTurn (f, "show", 0.0);
  16960. engine.editSong ([&] (lynx::Song& s) { s.channels[0].samplePath = loop48.getFullPathName().toStdString(); });
  16961. lynx::samplerPageTurn (f, "show", 0.0);
  16962. check ("resample_enabled_48k", lynx::samplerPageQuery (f, "resample") == (std::abs (rate - 48000.0) < 0.5 ? "0" : "1"), juce::String (rate));
  16963. frame->createComponentSnapshot (frame->getLocalBounds()); // (starts the new file's waveform)
  16964. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (8000);
  16965. shoot (f, "sampler-48k");
  16966. // CTL-4: Remove sample renames the channel "Sampler"
  16967. lynx::samplerFileRowPress (f, 3);
  16968. check ("remove_sample_renames", engine.getSong().channels[0].name == "Sampler" && engine.getSong().channels[0].samplePath.empty(),
  16969. juce::String::fromUTF8 (engine.getSong().channels[0].name.c_str()));
  16970. lynx::samplerPageTurn (f, "show", 0.0);
  16971. check ("no_sample_content_greyed", lynx::samplerPageQuery (f, "keepOnDisk") == "0" && lynx::samplerPageQuery (f, "resample") == "0");
  16972. shoot (f, "sampler-removed");
  16973. }
  16974. // ---- 2. the Multilink button's menu with multilink off (CTL-1)
  16975. lynx::AudioEngine engine (false);
  16976. lynx::MainComponent ui (engine, false);
  16977. ui.setSize (1600, 900);
  16978. {
  16979. using lynx::AutomationTarget;
  16980. using lynx::AutomationTargetKind;
  16981. engine.editSong ([] (lynx::Song& s) {
  16982. if (s.channels.empty())
  16983. s.channels.resize (1);
  16984. s.channels[0].name = "808 Kick";
  16985. });
  16986. engine.setMultilink (false);
  16987. engine.noteTweaked ({ AutomationTargetKind::channelVolume, 0 });
  16988. engine.noteTweaked ({ AutomationTargetKind::channelPan, 0 });
  16989. const auto menu = ui.getMultilinkMenuForSnapshot();
  16990. juce::PopupMenu::MenuItemIterator first (menu);
  16991. first.next();
  16992. const auto caption = first.getItem().text;
  16993. bool columnBreak = false, lynxLines = false;
  16994. juce::String rightCaption;
  16995. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  16996. {
  16997. if (columnBreak && rightCaption.isEmpty() && it.getItem().isSectionHeader)
  16998. rightCaption = it.getItem().text;
  16999. columnBreak = columnBreak || it.getItem().shouldBreakAfter;
  17000. lynxLines = lynxLines || it.getItem().text == lynx::tr ("Link to controller");
  17001. }
  17002. check ("ml_off_left_column_named", first.getItem().isSectionHeader && caption == lynx::describeAutomationTarget (engine, { AutomationTargetKind::channelPan, 0 }), caption);
  17003. check ("ml_off_two_columns", columnBreak && rightCaption == lynx::tr ("Last 2 tweaked parameters"), rightCaption);
  17004. check ("ml_off_no_lynx_greyed_lines", ! lynxLines);
  17005. savePng (columnMenuImage (menu), prefix + "-multilink-off-menu.png");
  17006. }
  17007. // ---- 3. the Playlist (PL-1 / 2 / 3 / 6 / 7 / 8)
  17008. auto& playlist = ui.getPlaylistForSnapshot();
  17009. {
  17010. auto song = lynx::Song::makeDefault();
  17011. lynx::ChannelDef bass;
  17012. bass.name = "Amount Too - Bass";
  17013. bass.instrument = lynx::InstrumentKind::audioClip;
  17014. bass.samplePath = writeWav (folder.getChildFile ("bass.wav"), 44100.0, 88200, 82.0).getFullPathName().toStdString();
  17015. bass.misc.levels.volume = 1.468f;
  17016. song.channels.push_back (bass);
  17017. lynx::Clip c;
  17018. c.kind = lynx::ClipKind::audio;
  17019. c.channel = (int) song.channels.size() - 1;
  17020. c.track = 3;
  17021. c.start = 4 * lynx::ppq;
  17022. c.length = 2 * lynx::ppq;
  17023. song.playlist.push_back (c);
  17024. engine.setSong (std::move (song));
  17025. }
  17026. engine.dispatchPendingMessages();
  17027. const auto clipIndex = (int) engine.getSong().playlist.size() - 1;
  17028. {
  17029. const auto menu = playlist.getClipMenuForSnapshot (clipIndex);
  17030. const auto* automate = findSub (menu, lynx::tr ("Automate"));
  17031. check ("automate_volume_runs", automate != nullptr && click (*automate, lynx::tr ("Volume")));
  17032. const auto& song = engine.getSong();
  17033. const auto made = (int) song.automations.size() - 1;
  17034. check ("automate_makes_current_clip", made >= 0 && playlist.brush.kind == lynx::ClipKind::automation && playlist.brush.index == made,
  17035. juce::String (playlist.brush.index));
  17036. // (PL-2: Levels VOL 147 %, FL's clip plays unity)
  17037. check ("automate_volume_unity", made >= 0 && song.automations.back().points[0].value == 0.5f
  17038. && lynx::lasttweak::valueText (song, song.automations.back().target, song.automations.back().points[0].value) == "100% 0.0dB 1.00");
  17039. const auto again = playlist.getClipMenuForSnapshot (clipIndex);
  17040. const auto* automate2 = findSub (again, lynx::tr ("Automate"));
  17041. check ("automate_second_is_2", automate2 != nullptr && click (*automate2, lynx::tr ("Volume"))
  17042. && juce::String::fromUTF8 (engine.getSong().automations.back().name.c_str()).endsWith (" #2"),
  17043. juce::String::fromUTF8 (engine.getSong().automations.back().name.c_str()));
  17044. // PL-7: Fade in / out curve
  17045. const auto* fadeIn = findSub (menu, lynx::tr ("Fade in curve"));
  17046. const auto* fadeOut = findSub (menu, lynx::tr ("Fade out curve"));
  17047. const juce::StringArray curve { lynx::tr ("Reset"), lynx::tr ("Normalize"), lynx::tr ("Normalize selection as a group"), lynx::tr ("Create crossfade"),
  17048. lynx::tr ("Manual"), "[" + lynx::tr ("Declicker") + "]", lynx::tr ("Automatic"), lynx::tr ("Disabled"), lynx::tr ("Enabled"),
  17049. "[" + lynx::tr ("Curve shape") + "]", lynx::tr ("Smooth curve"), lynx::tr ("Single curve") };
  17050. check ("fade_curve_submenus", fadeIn != nullptr && fadeOut != nullptr && texts (*fadeIn) == curve && texts (*fadeOut) == curve,
  17051. fadeIn != nullptr ? texts (*fadeIn).joinIntoString ("|") : juce::String ("missing"));
  17052. if (fadeOut != nullptr)
  17053. saveMenus (juce::StringArray { "Audio clip menu", "Fade out curve" }, std::vector<juce::PopupMenu> { menu, *fadeOut }, prefix + "-fade-curve-menu.png");
  17054. // PL-8: Detect tempo is one item now
  17055. bool detectItem = false;
  17056. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  17057. if (plain (it.getItem().text) == plain (lynx::tr ("Detect tempo")))
  17058. detectItem = it.getItem().subMenu == nullptr && it.getItem().action != nullptr;
  17059. check ("detect_tempo_item", detectItem);
  17060. // PL-3: Preview through the channel; transport start ends it
  17061. check ("preview_through_channel", engine.previewClipThroughChannel ((std::size_t) clipIndex) && engine.isClipPreviewing());
  17062. engine.play();
  17063. check ("preview_stops_on_transport", ! engine.isClipPreviewing());
  17064. engine.stop();
  17065. check ("preview_again_then_stop", engine.previewClipThroughChannel ((std::size_t) clipIndex) && engine.isClipPreviewing());
  17066. engine.stop();
  17067. check ("preview_stops_on_stop", ! engine.isClipPreviewing());
  17068. }
  17069. // PL-8: the dialog
  17070. {
  17071. lynx::ui::TempoDetectionRequest r;
  17072. r.name = "Amount Too - Bass";
  17073. // (a drum-like loop at 117.5 BPM, 100 beats as in FL's dialog: clicks on every beat)
  17074. {
  17075. auto beats = std::make_shared<lynx::SampleData>();
  17076. beats->sampleRate = 44100.0;
  17077. const auto period = 44100.0 * 60.0 / 117.5;
  17078. beats->left.assign ((std::size_t) std::llround (period * 100.0), 0.0f);
  17079. for (int b = 0; b < 100; ++b)
  17080. for (int i = 0; i < 2000; ++i)
  17081. if (const auto at = (std::size_t) std::llround (b * period) + (std::size_t) i; at < beats->left.size())
  17082. beats->left[at] = (float) (0.9 * std::sin (i * 0.09) * std::exp (-i / 400.0));
  17083. r.sample = beats;
  17084. }
  17085. r.projectBpm = 100.0;
  17086. double applied = -1.0;
  17087. r.apply = [&applied] (double beats) { applied = beats; };
  17088. auto panel = lynx::ui::makeTempoDetectionPanel (r);
  17089. panel->setSize (panel->getWidth(), panel->getHeight());
  17090. shoot (*panel, "tempo-detection");
  17091. report.add ("tempo dialog title: " + lynx::ui::tempoDetectionTitle (r.name));
  17092. const auto project = lynx::ui::pressTempoDetectionButton (*panel, panel->getNumChildComponents() - 3);
  17093. const auto seconds = (double) r.sample->frames() / r.sample->sampleRate; // (100 beats at 117.5 BPM)
  17094. check ("tempo_project_button", std::abs (applied - seconds * 100.0 / 60.0) < 1.0e-6, project + " -> " + juce::String (applied));
  17095. const auto none = lynx::ui::pressTempoDetectionButton (*panel, panel->getNumChildComponents() - 2);
  17096. check ("tempo_no_tempo_button", applied == 0.0, none);
  17097. }
  17098. // ---- 4. issue #152's question (ISS152-1): FL's message with "Remember my choice"
  17099. {
  17100. auto box = lynx::makeFlMessageDialog ({ lynx::tr ("External input"),
  17101. 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?"),
  17102. { lynx::tr ("Yes"), lynx::tr ("No") }, true });
  17103. shoot (*box, "external-input-question");
  17104. bool listed = false;
  17105. for (const auto& m : lynx::messages::all())
  17106. listed = listed || juce::String (m.id) == "RecAutoSwitchExternalInput";
  17107. check ("external_input_in_manage_messages", listed);
  17108. }
  17109. // ---- 5. round 190gk: FL's Start in the render window; the Sampler's "Open in new Fruity Slicer / Slicex channel";
  17110. // a Gross Beat slot picked by MIDI becomes its parameter
  17111. {
  17112. lynx::AudioEngine engine (false);
  17113. auto panel = lynx::makeClipRenderPanel (engine);
  17114. panel->setSize (panel->getWidth() > 0 ? panel->getWidth() : 640, panel->getHeight() > 0 ? panel->getHeight() : 480);
  17115. juce::String button;
  17116. for (auto* c : panel->getChildren())
  17117. if (auto* b = dynamic_cast<juce::TextButton*> (c); b != nullptr && b->isVisible() && b->getTooltip() == lynx::tr ("Start rendering"))
  17118. button = b->getButtonText();
  17119. check ("render_button_start", button == lynx::trc ("@render button: Start") && button == "Start", button);
  17120. shoot (*panel, "fltails190gk-render-start");
  17121. const auto clap = writeWav (folder.getChildFile ("Slice me.wav"), 44100.0, 44100, 140.0);
  17122. engine.editSong ([] (lynx::Song& s) {
  17123. s.channels.resize (2);
  17124. s.channels[0] = {};
  17125. s.channels[0].instrument = lynx::InstrumentKind::fruityslicer;
  17126. s.channels[0].name = "Fruity Slicer";
  17127. s.channels[1] = {};
  17128. s.channels[1].instrument = lynx::InstrumentKind::slicex;
  17129. s.channels[1].name = "Slicex";
  17130. });
  17131. const auto locate = [] (int index) {
  17132. return [index] (lynx::Song& s) -> lynx::ChannelDef* { return index < (int) s.channels.size() ? &s.channels[(std::size_t) index] : nullptr; };
  17133. };
  17134. lynx::loadSampleWhenOpened (0, clap.getFullPathName());
  17135. auto slicer = lynx::makeFruitySlicerEditor (engine, locate (0), 0);
  17136. const auto& fs = engine.getSong().channels[0];
  17137. check ("open_in_new_fruity_slicer", fs.samplePath == clap.getFullPathName().toStdString() && ! fs.pluginState.empty(), juce::String (fs.samplePath));
  17138. lynx::loadSlicexSampleWhenOpened (1, clap.getFullPathName());
  17139. auto slicex = lynx::makeSlicexEditor (engine, locate (1), 1);
  17140. const auto& sx = engine.getSong().channels[1];
  17141. check ("open_in_new_slicex", sx.samplePath == clap.getFullPathName().toStdString() && ! sx.pluginState.empty(), juce::String (sx.samplePath));
  17142. auto again = lynx::makeSlicexEditor (engine, locate (1), 1); // (the request is used once)
  17143. check ("open_in_new_used_once", engine.getSong().channels[1].samplePath == sx.samplePath);
  17144. // Gross Beat on insert 1: two notes on its MIDI input, one block, the engine's timer step
  17145. engine.editSong ([] (lynx::Song& s) {
  17146. if (s.mixer.size() < 2)
  17147. s.mixer.resize (2);
  17148. s.mixer[1].effects = { lynx::makeEffectSlot (lynx::EffectKind::grossBeat) };
  17149. });
  17150. engine.dispatchPendingMessages();
  17151. auto fx = engine.getEffect (1, 0);
  17152. check ("gb_running", fx != nullptr);
  17153. if (fx != nullptr)
  17154. {
  17155. std::vector<float> l (512, 0.1f), r (512, 0.1f);
  17156. fx->prepare (44100.0);
  17157. fx->setSongPosition (0.0);
  17158. fx->midiNote (60 + 9, 100, 0);
  17159. fx->midiNote (24 + 3, 100, 0);
  17160. fx->process (l.data(), r.data(), 512, engine.getSong().mixer[1].effects[0].params, 120.0);
  17161. engine.pumpGrossBeatPicks();
  17162. const auto& p = engine.getSong().mixer[1].effects[0].params;
  17163. check ("gb_midi_pick_sets_parameters", lynx::grossbeat::rawFromParam (0, p[0]) == 9 && lynx::grossbeat::rawFromParam (1, p[1]) == 3,
  17164. juce::String (lynx::grossbeat::rawFromParam (0, p[0])) + " " + juce::String (lynx::grossbeat::rawFromParam (1, p[1])));
  17165. }
  17166. }
  17167. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\nresult=" + (allOk ? "OK" : "FAIL") + "\n");
  17168. return allOk;
  17169. }
  17170. // --grooveshot190fm (round 190fm): see the dispatch above
  17171. bool runGrooveShot190fm (const juce::String& prefix)
  17172. {
  17173. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  17174. juce::StringArray report;
  17175. bool allOk = true;
  17176. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  17177. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  17178. allOk = allOk && ok;
  17179. };
  17180. const auto plain = [] (juce::String t) {
  17181. t = t.upToFirstOccurrenceOf ("\t", false, false);
  17182. return t.removeCharacters (juce::String ("&_") + juce::String::charToString (1));
  17183. };
  17184. const auto sub = [&plain] (const juce::PopupMenu& menu, const juce::String& start) -> const juce::PopupMenu* {
  17185. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  17186. if (it.getItem().subMenu != nullptr && plain (it.getItem().text).startsWith (start))
  17187. return it.getItem().subMenu.get();
  17188. return nullptr;
  17189. };
  17190. const auto item = [&plain] (const juce::PopupMenu& menu, const juce::String& text) -> const juce::PopupMenu::Item* {
  17191. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  17192. if (plain (it.getItem().text) == text)
  17193. return &it.getItem();
  17194. return nullptr;
  17195. };
  17196. lynx::AudioEngine engine (false);
  17197. lynx::MainComponent ui (engine, false);
  17198. ui.setSize (1600, 900);
  17199. std::uint32_t classic = 0;
  17200. {
  17201. auto song = lynx::Song::makeDefault();
  17202. song.mode = lynx::PlayMode::song;
  17203. song.playlist.push_back ({ 0, 0, 0, 4 * lynx::ppq, 0 });
  17204. song.playlist.push_back ({ 0, 1, 4 * lynx::ppq, 4 * lynx::ppq, 0 });
  17205. for (const auto& e : lynx::groove::factoryBank())
  17206. if (juce::String (e.folder) == "Classic swing" && e.groove.base == lynx::GrooveBase::sixteenth
  17207. && (e.groove.name == "Swing 16ths 54 %" || e.groove.name == "Swing 16ths 58 %" || e.groove.name == "Swing 16ths 62 %"
  17208. || e.groove.name == "Swing 16ths 71 %"))
  17209. {
  17210. const auto id = lynx::groove::add (song.grooves, e.groove);
  17211. if (e.groove.name == "Swing 16ths 58 %")
  17212. classic = id;
  17213. }
  17214. song.playlist[0].groove = classic;
  17215. engine.setSong (std::move (song));
  17216. }
  17217. engine.dispatchPendingMessages();
  17218. auto& playlist = ui.getPlaylistForSnapshot();
  17219. const auto menu = playlist.getClipMenuForSnapshot (0);
  17220. const auto* chooser = sub (menu, lynx::tr ("Groove"));
  17221. check ("groove_chooser_in_clip_menu", chooser != nullptr);
  17222. const auto* add = chooser != nullptr ? sub (*chooser, lynx::tr ("Add a groove")) : nullptr;
  17223. const auto* folder = add != nullptr ? sub (*add, lynx::tr ("Classic swing")) : nullptr;
  17224. check ("classic_swing_folder", folder != nullptr && folder->getNumItems() == 27, folder != nullptr ? juce::String (folder->getNumItems()) : juce::String ("missing"));
  17225. const auto* commit = item (menu, lynx::tr ("Commit groove"));
  17226. check ("commit_enabled_with_a_groove", commit != nullptr && commit->isEnabled);
  17227. check ("extract_present", item (menu, lynx::tr ("Extract groove")) != nullptr);
  17228. {
  17229. juce::StringArray names { "Pattern clip menu" };
  17230. std::vector<juce::PopupMenu> menus { menu };
  17231. if (chooser != nullptr)
  17232. {
  17233. names.add ("Groove");
  17234. menus.push_back (*chooser);
  17235. }
  17236. if (add != nullptr)
  17237. {
  17238. names.add ("Add a groove");
  17239. menus.push_back (*add);
  17240. }
  17241. if (folder != nullptr)
  17242. {
  17243. names.add ("Classic swing");
  17244. menus.push_back (*folder);
  17245. }
  17246. saveMenus (names, menus, prefix + "-playlist-clip-menu.png");
  17247. }
  17248. // the second clip (no groove): Commit is off; choosing a groove from the menu sets it
  17249. {
  17250. const auto other = playlist.getClipMenuForSnapshot (1);
  17251. const auto* c2 = item (other, lynx::tr ("Commit groove"));
  17252. check ("commit_disabled_without_a_groove", c2 != nullptr && ! c2->isEnabled);
  17253. const auto* ch2 = sub (other, lynx::tr ("Groove"));
  17254. const auto* pick = ch2 != nullptr ? item (*ch2, "Swing 16ths 71 %") : nullptr;
  17255. if (pick != nullptr && pick->action != nullptr)
  17256. pick->action();
  17257. const auto& song = engine.getSong();
  17258. check ("chooser_sets_the_clip_groove", song.playlist.size() == 2 && lynx::groove::ofClip (song, song.playlist[1]) != nullptr
  17259. && lynx::groove::ofClip (song, song.playlist[1])->name == "Swing 16ths 71 %");
  17260. }
  17261. // the pool with the classic grooves
  17262. {
  17263. auto pool = lynx::makeGroovePool (engine);
  17264. pool->setSize (900, lynx::groovePoolHeight (engine));
  17265. savePng (pool->createComponentSnapshot (pool->getLocalBounds()), prefix + "-pool.png");
  17266. }
  17267. // .lynx: a Playlist clip's groove comes back; a project without one writes nothing new
  17268. {
  17269. juce::String error;
  17270. const auto& song = engine.getSong();
  17271. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  17272. check ("lynx_round_trip", back && back->playlist.size() == 2 && back->playlist[0].groove == song.playlist[0].groove
  17273. && back->playlist[1].groove == song.playlist[1].groove && back->grooves == song.grooves,
  17274. error);
  17275. auto old = lynx::Song::makeDefault();
  17276. old.playlist.push_back ({ 0, 0, 0, 4 * lynx::ppq, 0 });
  17277. const auto json = lynx::ProjectFile::toJson (old, false);
  17278. const auto reloaded = lynx::ProjectFile::fromJson (json, error);
  17279. check ("old_project_unchanged", reloaded && lynx::ProjectFile::toJson (*reloaded, false) == json && reloaded->playlist[0].groove == 0);
  17280. }
  17281. // Commit from the menu: the clip's pattern (shared with the second clip) is copied, the groove is off
  17282. {
  17283. const auto patterns = engine.getSong().patterns.size();
  17284. const auto again = playlist.getClipMenuForSnapshot (0);
  17285. if (const auto* c = item (again, lynx::tr ("Commit groove")); c != nullptr && c->action != nullptr)
  17286. c->action();
  17287. const auto& song = engine.getSong();
  17288. check ("commit_runs", song.playlist[0].groove == 0 && song.patterns.size() == patterns + 1 && song.playlist[0].pattern == (int) patterns);
  17289. }
  17290. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\n" + (allOk ? "ALL OK" : "SOME FAILED") + "\n");
  17291. return allOk;
  17292. }
  17293. bool runFlClipShot (const juce::String& prefix)
  17294. {
  17295. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  17296. juce::StringArray report;
  17297. bool allOk = true;
  17298. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  17299. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  17300. allOk = allOk && ok;
  17301. };
  17302. const auto plain = [] (juce::String t) {
  17303. t = t.upToFirstOccurrenceOf ("\t", false, false);
  17304. if (const auto at = t.indexOf (juce::String (" (") + juce::String::charToString (1)); at >= 0)
  17305. t = t.substring (0, at);
  17306. return t.removeCharacters (juce::String ("&_") + juce::String::charToString (1));
  17307. };
  17308. const auto find = [&plain] (const juce::PopupMenu& menu, const juce::String& text) -> const juce::PopupMenu::Item* {
  17309. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  17310. if (plain (it.getItem().text) == plain (text))
  17311. return &it.getItem();
  17312. return nullptr;
  17313. };
  17314. const auto click = [&find] (const juce::PopupMenu& menu, const juce::String& text) {
  17315. const auto* item = find (menu, text);
  17316. if (item == nullptr || ! item->isEnabled || item->action == nullptr)
  17317. return false;
  17318. item->action();
  17319. return true;
  17320. };
  17321. lynx::AudioEngine engine (false);
  17322. lynx::MainComponent ui (engine, false);
  17323. ui.setSize (1600, 900);
  17324. int vox = -1;
  17325. {
  17326. auto song = lynx::Song::makeDefault();
  17327. song.channels.push_back ({});
  17328. song.channels.back().name = "Vox";
  17329. song.channels.back().instrument = lynx::InstrumentKind::audioClip;
  17330. song.channels.back().samplePath = writeShotSample (juce::File (prefix + "-vox.wav"), 330.0).getFullPathName().toStdString();
  17331. vox = (int) song.channels.size() - 1;
  17332. lynx::Clip c;
  17333. c.kind = lynx::ClipKind::audio;
  17334. c.channel = vox;
  17335. c.track = 3;
  17336. c.start = 4 * lynx::ppq;
  17337. c.length = 2 * lynx::ppq;
  17338. c.fadeIn = lynx::ppq / 4;
  17339. song.playlist.push_back (c);
  17340. engine.setSong (std::move (song));
  17341. }
  17342. engine.dispatchPendingMessages();
  17343. auto& playlist = ui.getPlaylistForSnapshot();
  17344. // ---- 1. the audio clip menu: FL's order, sections and columns, then LYNX's own items
  17345. {
  17346. const auto menu = playlist.getClipMenuForSnapshot (0);
  17347. juce::StringArray got, want;
  17348. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  17349. {
  17350. const auto& item = it.getItem();
  17351. got.add (item.customComponent != nullptr ? "[" + lynx::tr ("Audio clip") + "]"
  17352. : item.isSeparator ? juce::String ("-")
  17353. : item.isSectionHeader ? "[" + plain (item.text) + "]"
  17354. : plain (item.text));
  17355. }
  17356. for (const auto& e : lynx::flclipmenu::shown (true, false))
  17357. if (e.kind != lynx::flclipmenu::Entry::Kind::columnBreak)
  17358. want.add (e.kind == lynx::flclipmenu::Entry::Kind::separator ? juce::String ("-")
  17359. : e.kind == lynx::flclipmenu::Entry::Kind::header ? "[" + lynx::tr (e.text.c_str()) + "]"
  17360. : lynx::tr (e.text.c_str()));
  17361. want.add ("[" + lynx::tr ("LYNX extras") + "]"); // (round 190gi; round 190jv: in a third column)
  17362. for (const auto& x : lynx::flclipmenu::lynxExtras())
  17363. want.add (lynx::tr (x.c_str()));
  17364. check ("clip_menu_fl_order", got == want, got.joinIntoString ("|"));
  17365. // FL's two columns (Chop | Sample), then LYNX's own items in a third (round 190jv)
  17366. juce::StringArray breaks;
  17367. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  17368. if (it.getItem().shouldBreakAfter)
  17369. breaks.add (it.getItem().isSectionHeader || it.getItem().customComponent != nullptr ? "?" : plain (it.getItem().text));
  17370. check ("clip_menu_two_columns", breaks.size() == 2 && breaks[0] == lynx::tr ("Chop") && breaks[1] == lynx::tr ("Fade out curve"),
  17371. breaks.joinIntoString ("|"));
  17372. const auto* crossfade = find (menu, lynx::tr ("Crossfade with"));
  17373. check ("crossfade_with_greyed", crossfade != nullptr && ! crossfade->isEnabled);
  17374. const auto* region = find (menu, lynx::tr ("Select region"));
  17375. const auto* full = region != nullptr && region->subMenu != nullptr ? find (*region->subMenu, lynx::tr ("Full")) : nullptr;
  17376. check ("select_region_full_ticked", full != nullptr && full->isTicked);
  17377. const auto* chop = find (menu, lynx::tr ("Chop"));
  17378. check ("chop_time_based", chop != nullptr && chop->subMenu != nullptr && find (*chop->subMenu, lynx::tr ("Chop in 32nd beats")) != nullptr
  17379. && find (*chop->subMenu, lynx::tr ("Chop to grid")) != nullptr);
  17380. savePng (columnMenuImage (menu), prefix + "-clip-menu.png");
  17381. std::fprintf (stderr, "flclipshot: menu saved\n");
  17382. // Muted is a check; Reset fades clears the fades; Select all similar clips selects
  17383. check ("muted_toggles", click (menu, lynx::tr ("Muted")) && engine.getSong().playlist[0].muted);
  17384. const auto again = playlist.getClipMenuForSnapshot (0);
  17385. const auto* muted = find (again, lynx::tr ("Muted"));
  17386. check ("muted_ticked", muted != nullptr && muted->isTicked);
  17387. check ("reset_fades", click (again, lynx::tr ("Reset fades")) && engine.getSong().playlist[0].fadeIn == 0);
  17388. engine.undo();
  17389. engine.undo();
  17390. engine.dispatchPendingMessages();
  17391. std::fprintf (stderr, "flclipshot: automate\n");
  17392. // Automate › Volume / Panning: the clip channel's Levels adjustment (FL's channel parameters 0x11 / 0x10)
  17393. const auto fresh = playlist.getClipMenuForSnapshot (0);
  17394. const auto* automate = find (fresh, lynx::tr ("Automate"));
  17395. const auto before = engine.getSong().automations.size();
  17396. check ("automate_volume_runs", automate != nullptr && automate->subMenu != nullptr && click (*automate->subMenu, lynx::tr ("Volume")));
  17397. const auto& song = engine.getSong();
  17398. const auto ok = song.automations.size() == before + 1 && song.automations.back().target.kind == lynx::AutomationTargetKind::channelAdjust
  17399. && song.automations.back().target.param == lynx::leveladjust::volume && song.automations.back().target.index == vox
  17400. && std::abs (song.automations.back().points[0].value - 0.5f) < 1.0e-6f;
  17401. check ("automate_volume_is_level_adjust", ok, ok ? juce::String::fromUTF8 (song.automations.back().name.c_str()) : juce::String());
  17402. engine.undo();
  17403. engine.dispatchPendingMessages();
  17404. }
  17405. std::fprintf (stderr, "flclipshot: overlap\n");
  17406. // ---- 2. a second channel's clip overlapping: Crossfade with lists it and makes FL's crossfade clip (round 190gw)
  17407. {
  17408. engine.editSong ([vox] (lynx::Song& s) {
  17409. auto copy = s.playlist[0]; // (another audio clip channel's clip, at the same time)
  17410. s.channels.push_back (s.channels[(std::size_t) vox]);
  17411. s.channels.back().name = "Vox 2";
  17412. copy.channel = (int) s.channels.size() - 1;
  17413. copy.track = 4;
  17414. s.playlist.push_back (copy);
  17415. });
  17416. engine.dispatchPendingMessages();
  17417. const auto overlapped = playlist.getClipMenuForSnapshot (0);
  17418. const auto* with = find (overlapped, lynx::tr ("Crossfade with"));
  17419. check ("crossfade_with_lists_the_overlap", with != nullptr && with->isEnabled && with->subMenu != nullptr && find (*with->subMenu, "Vox 2") != nullptr);
  17420. const auto made = with != nullptr && with->subMenu != nullptr && click (*with->subMenu, "Vox 2");
  17421. engine.dispatchPendingMessages();
  17422. const auto& xsong = engine.getSong();
  17423. const auto xok = made && ! xsong.automations.empty() && xsong.automations.back().links.size() == 2
  17424. && juce::String::fromUTF8 (xsong.automations.back().name.c_str()).endsWith (" to Vox 2 crossfade");
  17425. check ("crossfade_with_makes_the_clip", xok, xok ? juce::String::fromUTF8 (xsong.automations.back().name.c_str()) : juce::String());
  17426. if (made)
  17427. engine.undo();
  17428. engine.undo();
  17429. engine.dispatchPendingMessages();
  17430. }
  17431. std::fprintf (stderr, "flclipshot: misc\n");
  17432. // ---- 3. the channel's Misc tab: Levels adjustment = the offsets (pan 0, volume 100 %, Mod X / Y 0 %)
  17433. {
  17434. engine.editSong ([vox] (lynx::Song& s) {
  17435. s.channels[(std::size_t) vox].misc.levels.volume = 0.5f;
  17436. s.channels[(std::size_t) vox].misc.levels.pan = -0.25f;
  17437. });
  17438. engine.dispatchPendingMessages();
  17439. auto frame = lynx::makeChannelFrame (engine, vox, -1);
  17440. frame->setSize (juce::jmax (frame->getWidth(), 800), juce::jmax (frame->getHeight(), 420));
  17441. savePng (frame->createComponentSnapshot (frame->getLocalBounds()), prefix + "-misc-levels.png");
  17442. auto synthFrame = lynx::makeChannelFrame (engine, 0, -1);
  17443. synthFrame->setSize (juce::jmax (synthFrame->getWidth(), 800), juce::jmax (synthFrame->getHeight(), 420));
  17444. savePng (synthFrame->createComponentSnapshot (synthFrame->getLocalBounds()), prefix + "-misc-levels-ch1.png");
  17445. std::fprintf (stderr, "flclipshot: round trip\n");
  17446. // the .lynx round trip of the adjustment and of an automation of it; an old project writes nothing new
  17447. juce::String error;
  17448. auto song = engine.getSong();
  17449. lynx::Automation a;
  17450. a.target = { lynx::AutomationTargetKind::channelAdjust, vox, 0, lynx::leveladjust::volume };
  17451. a.points = { { 0, 0.25f, 0.0f } };
  17452. song.automations.push_back (a);
  17453. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  17454. check ("lynx_round_trip", back && back->channels[(std::size_t) vox].misc.levels == song.channels[(std::size_t) vox].misc.levels
  17455. && back->automations.back().target == a.target,
  17456. error);
  17457. auto old = lynx::Song::makeDefault();
  17458. const auto json = lynx::ProjectFile::toJson (old, false);
  17459. const auto reloaded = lynx::ProjectFile::fromJson (json, error);
  17460. check ("old_project_unchanged", ! json.contains ("\"levels\"") && reloaded && lynx::ProjectFile::toJson (*reloaded, false) == json
  17461. && std::all_of (reloaded->channels.begin(), reloaded->channels.end(),
  17462. [] (const lynx::ChannelDef& c) { return c.misc.levels.neutral(); }));
  17463. }
  17464. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\nresult=" + (allOk ? "OK" : "FAIL") + "\n");
  17465. return allOk;
  17466. }
  17467. // --bandlab190jrshot <prefix> (round 190jr; B15, BUILD-LIST 13 / 14): a synthetic BandLab project (.blx: the revision
  17468. // JSON, a MIDI file, a WAV) opened through the real import, shown in the Simple layout; its looped regions and their
  17469. // loop handles; a loop dragged longer; the automation view with and without points and its parameter menu; the clip
  17470. // menu's loop items; the Extract stems form (Standard and 6 stems). Pictures at the --shot-scale asked for.
  17471. void runBandlab190jrShot (const juce::String& prefix)
  17472. {
  17473. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  17474. lynx::AudioEngine offline (false);
  17475. lynx::MainComponent ui (offline, false);
  17476. ui.setSize (1600, 900);
  17477. const auto note = [] (const juce::String& what) { std::fprintf (stderr, "bandlab190jrshot: %s\n", what.toRawUTF8()); };
  17478. const auto writeImage = [&prefix, &note] (const juce::Image& image, const char* name) {
  17479. note (name);
  17480. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  17481. file.deleteFile();
  17482. juce::FileOutputStream out (file);
  17483. juce::PNGImageFormat().writeImageToStream (image, out);
  17484. };
  17485. juce::String report;
  17486. const auto check = [&report, &note] (const juce::String& what, bool ok) {
  17487. note ((ok ? "ok " : "FAIL ") + what);
  17488. report << (ok ? "ok " : "FAIL ") << what << "\n";
  17489. };
  17490. // ---- 1. the project: a revision with a looped piano region, a voice take and a drum machine
  17491. const auto folder = juce::File (prefix + "-blx");
  17492. folder.deleteRecursively();
  17493. folder.getChildFile ("Audio").createDirectory();
  17494. folder.getChildFile ("MIDI").createDirectory();
  17495. {
  17496. // a 4-beat MIDI part (100 BPM: 2.4 s) and a drum beat, 480 ticks per quarter
  17497. const auto midi = [] (const std::vector<std::array<int, 4>>& notes) {
  17498. juce::MidiMessageSequence seq;
  17499. for (const auto& n : notes)
  17500. {
  17501. seq.addEvent (juce::MidiMessage::noteOn (1, n[2], (juce::uint8) n[3]), n[0]);
  17502. seq.addEvent (juce::MidiMessage::noteOff (1, n[2]), n[0] + n[1]);
  17503. }
  17504. seq.updateMatchedPairs();
  17505. juce::MidiFile file;
  17506. file.setTicksPerQuarterNote (480);
  17507. file.addTrack (seq);
  17508. juce::MemoryOutputStream out;
  17509. file.writeTo (out);
  17510. return out.getMemoryBlock();
  17511. };
  17512. const auto keysBlock = midi ({ { 0, 480, 62, 100 }, { 0, 480, 65, 90 }, { 0, 480, 69, 90 }, { 480, 240, 64, 80 },
  17513. { 960, 480, 60, 100 }, { 960, 480, 64, 90 }, { 1440, 480, 67, 90 } });
  17514. folder.getChildFile ("MIDI/s-keys.mid").replaceWithData (keysBlock.getData(), keysBlock.getSize());
  17515. const auto beat = midi ({ { 0, 120, 36, 120 }, { 480, 120, 38, 110 }, { 960, 120, 36, 120 }, { 1440, 120, 38, 110 }, { 240, 60, 42, 80 },
  17516. { 720, 60, 42, 80 }, { 1200, 60, 42, 80 }, { 1680, 60, 42, 80 } });
  17517. folder.getChildFile ("MIDI/s-beat.mid").replaceWithData (beat.getData(), beat.getSize());
  17518. // a 4.8 s "voice" (a sine with a slow swell), 44.1 kHz
  17519. juce::AudioBuffer<float> wave (1, 44100 * 48 / 10);
  17520. for (int i = 0; i < wave.getNumSamples(); ++i)
  17521. wave.setSample (0, i, 0.4f * std::sin ((float) i * 0.0627f) * (0.5f + 0.5f * std::sin ((float) i * 0.00012f)));
  17522. juce::WavAudioFormat wav;
  17523. const auto out = folder.getChildFile ("Audio/s-vox.wav");
  17524. if (auto stream = out.createOutputStream())
  17525. if (std::unique_ptr<juce::AudioFormatWriter> writer (wav.createWriterFor (stream.get(), 44100.0, 1, 16, {}, 0)); writer != nullptr)
  17526. {
  17527. stream.release();
  17528. writer->writeFromAudioSampleBuffer (wave, 0, wave.getNumSamples());
  17529. }
  17530. folder.getChildFile ("Scratch Song.blx").replaceWithText (R"({ "revision": {
  17531. "key": "D min", "volume": 1, "song": { "name": "Scratch Song" },
  17532. "metronome": { "bpm": 100, "signature": { "notesCount": 4, "noteValue": 4 } },
  17533. "auxChannels": [ { "id": "aux1", "preset": "sharedReverb", "returnLevel": 1 } ],
  17534. "samples": [ { "id": "s-keys", "isMidi": true, "duration": 2.4 }, { "id": "s-vox", "isMidi": false, "duration": 4.8 }, { "id": "s-beat", "isMidi": true } ],
  17535. "tracks": [
  17536. { "id": "t1", "order": 0, "name": "Keys", "type": "instrument", "soundbank": "studio-grand", "volume": 0.9, "colorName": "Red",
  17537. "regions": [ { "id": "r1", "sampleId": "s-keys", "name": "Chords", "startPosition": 0, "endPosition": 9.6, "loopLength": 2.4 } ] },
  17538. { "id": "t2", "order": 1, "name": "Vocal", "type": "voice", "volume": 1, "pan": -0.2, "colorName": "Blue",
  17539. "effects": [ { "slug": "compressor", "params": { "attack": 0.003, "ratio": 3, "release": 0.12, "threshold": -18 } },
  17540. { "slug": "threeBandEq", "params": { "lowGain": -2, "midGain": 1, "highGain": 3, "midFreq": 2500 } },
  17541. { "slug": "chorusPedal", "params": {} } ],
  17542. "auxSends": [ { "id": "aux1", "sendLevel": 0.3 } ],
  17543. "automation": { "volume": [ { "position": 0, "value": 0.2 }, { "position": 8, "value": 1 }, { "position": 16, "value": 0.7 } ] },
  17544. "regions": [ { "id": "r2", "sampleId": "s-vox", "name": "Take 1", "startPosition": 2.4, "endPosition": 7.2, "fadeIn": 0.2, "fadeOut": 0.5 } ] },
  17545. { "id": "t3", "order": 2, "name": "Drum Machine", "type": "drum-machine", "volume": 1, "colorName": "Violet",
  17546. "regions": [ { "id": "r3", "sampleId": "s-beat", "name": "Beat", "startPosition": 0, "endPosition": 4.8, "loopLength": 2.4 } ] }
  17547. ] } })");
  17548. }
  17549. juce::String error;
  17550. const auto blx = folder.getChildFile ("Scratch Song.blx");
  17551. const auto imported = offline.importFlpFile (blx, error);
  17552. check ("the .blx opens through the import (" + error + ")", imported);
  17553. offline.dispatchPendingMessages();
  17554. const auto& song = offline.getSong();
  17555. check ("three Simple tracks: Keys (instrument), Vocal (audio), Drum Machine (drums)",
  17556. lynx::simpletracks::kindOf (song, 0) == lynx::simpletracks::Kind::instrument && lynx::simpletracks::kindOf (song, 1) == lynx::simpletracks::Kind::audio
  17557. && lynx::simpletracks::kindOf (song, 2) == lynx::simpletracks::Kind::drums);
  17558. check ("tempo 100, key D minor", std::abs (song.bpm - 100.0) < 1e-6 && lynx::projectkey::get (song).has_value());
  17559. int keysClips = 0, beatClips = 0, voxClips = 0;
  17560. for (const auto& c : song.playlist)
  17561. {
  17562. keysClips += c.track == 0;
  17563. voxClips += c.track == 1 && c.kind == lynx::ClipKind::audio;
  17564. beatClips += c.track == 2;
  17565. }
  17566. check ("the looped Keys region: 4 passes; the beat: 2; the take: 1 audio clip", keysClips == 4 && beatClips == 2 && voxClips == 1);
  17567. const auto voxInsert = lynx::simpletracks::insertOf (song, 1);
  17568. check ("the vocal's compressor, EQ and chorus on its insert",
  17569. voxInsert > 0 && song.mixer[(std::size_t) voxInsert].effects.size() == 3);
  17570. check ("the vocal's volume automation: a lane under its track", ! song.playlistTracks[1].lanes.empty());
  17571. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  17572. offline.dispatchPendingMessages();
  17573. ui.selectTabForSnapshot (2);
  17574. if (auto* simple = ui.getSimpleWorkflowForSnapshot())
  17575. simple->hideChooser();
  17576. auto& playlist = ui.getPlaylistForSnapshot();
  17577. playlist.setViewForSnapshot (96.0, 0, 0);
  17578. offline.dispatchPendingMessages();
  17579. writeImage (lynx::shot::snapshot (ui), "blx-simple");
  17580. writeImage (lynx::shot::snapshot (playlist), "loop-handles");
  17581. // ---- 2. a loop dragged longer: the take repeated to bar 9 (as the handle's drag does it)
  17582. {
  17583. int take = -1;
  17584. for (int i = 0; i < (int) song.playlist.size(); ++i)
  17585. if (song.playlist[(std::size_t) i].track == 1 && song.playlist[(std::size_t) i].kind == lynx::ClipKind::audio)
  17586. take = i;
  17587. const auto end = (std::int64_t) lynx::ppq * 4 * 8;
  17588. offline.editSong ([take, end] (lynx::Song& s) { lynx::regionloop::loopTo (s, take, end); });
  17589. offline.dispatchPendingMessages();
  17590. const auto run = lynx::regionloop::runOf (offline.getSong(), lynx::regionloop::regionAt (offline.getSong(), 1, (std::int64_t) lynx::ppq * 4, offline.getSong().playlist[(std::size_t) take]));
  17591. check ("the take loops to bar 9 in passes of its length", run.passes() >= 3 && run.end == end);
  17592. writeImage (lynx::shot::snapshot (playlist), "loop-dragged");
  17593. auto menu = playlist.getClipMenuForSnapshot (run.clips.empty() ? take : run.clips.back());
  17594. bool hasLoop = false;
  17595. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  17596. hasLoop = hasLoop || it.getItem().text == lynx::tr ("Unloop");
  17597. check ("the Simple clip menu has Loop until next / Unloop", hasLoop);
  17598. saveMenus (juce::StringArray { "Clip" }, std::vector<juce::PopupMenu> { menu }, prefix + "-clip-menu.png");
  17599. }
  17600. // ---- 3. the automation view: the vocal's lane on its row, the others' dashed line at their level
  17601. playlist.setSimpleAutomation (true);
  17602. offline.dispatchPendingMessages();
  17603. writeImage (lynx::shot::snapshot (playlist), "automation-view");
  17604. check ("the view changes nothing in the song", offline.getSong().playlistTracks[0].lanes.empty());
  17605. playlist.setSimpleAutoTargetForSnapshot (1, { lynx::AutomationTargetKind::effectParam, voxInsert, 0, 0 }); // the compressor's threshold
  17606. writeImage (lynx::shot::snapshot (playlist), "automation-param");
  17607. playlist.setSimpleAutoTargetForSnapshot (1, { lynx::AutomationTargetKind::mixerVolume, voxInsert, 0, 0 });
  17608. saveMenus (juce::StringArray { "Volume" }, std::vector<juce::PopupMenu> { playlist.getSimpleAutoMenuForSnapshot (1) }, prefix + "-automation-menu.png");
  17609. playlist.setSimpleAutomation (false);
  17610. offline.dispatchPendingMessages();
  17611. // ---- 4. the Extract stems form
  17612. {
  17613. auto panel = lynx::makeStemOptionsPanel (lynx::stemsplit::Options {}, [] (lynx::stemsplit::Options) {});
  17614. writeImage (lynx::shot::paint (*panel, lynx::theme::colour::bg2), "stem-options");
  17615. lynx::stemsplit::Options six;
  17616. six.model = lynx::stemsplit::Model::sixStems;
  17617. six.stems = { true, true, false, true, true, true };
  17618. auto panel6 = lynx::makeStemOptionsPanel (six, [] (lynx::stemsplit::Options) {});
  17619. writeImage (lynx::shot::paint (*panel6, lynx::theme::colour::bg2), "stem-options-six");
  17620. }
  17621. juce::File (lynx::shot::fileName (prefix + "-report.txt")).replaceWithText (report);
  17622. }
  17623. // --bandlabshot <prefix> (round 190ch): the Lyrics / Notes panel (Pattern and Simple layouts, and on its own), the
  17624. // Reference match window measured on a real render and a real file, "Start from", and Clean voice, off-screen; and
  17625. // <prefix>-report.txt with what each route did (ok / FAIL lines)
  17626. void runBandlabShot (const juce::String& prefix)
  17627. {
  17628. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  17629. lynx::AudioEngine offline (false);
  17630. lynx::MainComponent ui (offline, false);
  17631. ui.setSize (1600, 900);
  17632. // (each step is named on stderr as it starts: a run that stops says where)
  17633. const auto note = [] (const juce::String& what) { std::fprintf (stderr, "bandlabshot: %s\n", what.toRawUTF8()); };
  17634. const auto shoot = [&prefix, &note] (juce::Component& c, const char* name) {
  17635. note (name);
  17636. savePng (lynx::shot::snapshot (c), prefix + "-" + name + ".png");
  17637. };
  17638. juce::String report;
  17639. const auto check = [&report, &note] (const juce::String& what, bool ok) {
  17640. note ((ok ? "ok " : "FAIL ") + what);
  17641. report << (ok ? "ok " : "FAIL ") << what << "\n";
  17642. };
  17643. const auto bar = (double) lynx::ppq * 4.0;
  17644. // ---- 1. Lyrics / Notes: the project's Comments
  17645. {
  17646. auto song = lynx::makeShowcaseSong (0);
  17647. song.info.title = "Night Drive";
  17648. 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"
  17649. "I keep driving through the night\n\n[Chorus]\nNight drive, night drive\nNothing but the white line\n\n"
  17650. "Notes: double the chorus vocal, try the second verse an octave down.";
  17651. lynx::Marker chorus;
  17652. chorus.tick = (std::int64_t) (12.0 * bar);
  17653. chorus.name = "Chorus";
  17654. song.addMarker (chorus);
  17655. offline.setSong (std::move (song));
  17656. }
  17657. note ("song set");
  17658. offline.dispatchPendingMessages();
  17659. ui.selectTabForSnapshot (2);
  17660. note ("show lyrics");
  17661. ui.showLyrics (false);
  17662. note ("lyrics shown");
  17663. if (auto* panel = ui.getLyricsPanelForSnapshot())
  17664. {
  17665. panel->showForSnapshot ({}, 6.5 * bar); // the playhead inside bar 7: that line is the one playing
  17666. shoot (ui, "lyrics-pattern");
  17667. shoot (*panel, "lyrics-panel");
  17668. const auto markersBefore = offline.getSong().markers().size();
  17669. panel->setCaretLineForSnapshot (6); // "I keep driving through the night"
  17670. panel->markAtPlayheadForSnapshot (10.0 * bar + 2.0 * lynx::ppq);
  17671. offline.dispatchPendingMessages();
  17672. ui.commitSongNotes();
  17673. const auto& s = offline.getSong();
  17674. check ("Marker at playhead stamps the line [11.3] and adds one marker",
  17675. juce::String::fromUTF8 (s.info.comments.c_str()).contains ("[11.3] I keep driving") && s.markers().size() == markersBefore + 1);
  17676. // (no audio device here: the seek is the request the audio thread takes at its next block)
  17677. const auto& seek = offline.getTransport().seekRequest;
  17678. check ("clicking the stamped line moves the playhead to bar 7", panel->jumpToLineForSnapshot (4) && std::abs (seek.load() - 6.0 * bar) < 1.0);
  17679. check ("clicking [Chorus] (no position) goes to the marker of that name, bar 13",
  17680. panel->jumpToLineForSnapshot (8) && std::abs (seek.load() - 12.0 * bar) < 1.0);
  17681. check ("a line without a position does not jump", ! panel->jumpToLineForSnapshot (9));
  17682. panel->showForSnapshot ("night", 10.5 * bar);
  17683. shoot (*panel, "lyrics-search");
  17684. // the text travels in the project file, and old readers see it as the Comments they always had
  17685. juce::String error;
  17686. const auto json = lynx::ProjectFile::toJson (offline.getSong());
  17687. const auto back = lynx::ProjectFile::fromJson (json, error);
  17688. check ("lyrics round-trip through .lynx (the Comments field)", back.has_value() && back->info.comments == offline.getSong().info.comments);
  17689. const auto text = lynx::lyrics::exportText (offline.getSong(), lynx::lyrics::Stamps::times);
  17690. juce::File (prefix + "-lyrics-export.txt").replaceWithText (juce::String::fromUTF8 (text.c_str()));
  17691. check ("export as text with times", text.find ("[0:") != std::string::npos);
  17692. panel->showForSnapshot ({}, 6.5 * bar);
  17693. }
  17694. else
  17695. check ("the docked Lyrics panel exists", false);
  17696. {
  17697. const auto names = ui.getMenuNamesForSnapshot();
  17698. const auto view = names.indexOf (lynx::tr ("View"));
  17699. saveMenus (juce::StringArray { lynx::tr ("View") }, std::vector<juce::PopupMenu> { ui.getMenuForSnapshot (juce::jmax (0, view)) }, prefix + "-menu-view.png");
  17700. }
  17701. ui.showDesktopForSnapshot (false);
  17702. check ("the panel stays docked beside the Playlist in the default desktop", ui.isLyricsShowing());
  17703. shoot (ui, "lyrics-desktop");
  17704. // ---- the Simple layout: the Lyrics button in its title tools, the chooser's "Start from" link
  17705. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  17706. offline.dispatchPendingMessages();
  17707. ui.selectTabForSnapshot (2); // (the Playlist alone, as --simpleshot shows the layout)
  17708. auto* simple = ui.getSimpleWorkflowForSnapshot();
  17709. check ("the Simple workflow exists", simple != nullptr);
  17710. if (simple != nullptr)
  17711. {
  17712. simple->hideChooser();
  17713. if (! ui.isLyricsShowing())
  17714. ui.showLyrics (false);
  17715. shoot (ui, "lyrics-simple");
  17716. ui.hideLyrics();
  17717. check ("closing the panel keeps the text", juce::String::fromUTF8 (offline.getSong().info.comments.c_str()).contains ("Night drive, night drive"));
  17718. // ---- 4. Clean voice: on a voice track, from the track's menu
  17719. lynx::simpletracks::Result voice;
  17720. offline.editSongStructural ([&voice] (lynx::Song& s) {
  17721. lynx::simpletracks::Request q;
  17722. q.kind = lynx::simpletracks::Kind::voice;
  17723. q.name = "Lead vocal";
  17724. voice = lynx::simpletracks::addTrack (s, q);
  17725. });
  17726. offline.dispatchPendingMessages();
  17727. check ("a voice track was added", voice.insert > 0);
  17728. if (voice.insert > 0)
  17729. {
  17730. auto menu = ui.getPlaylistForSnapshot().getTrackMenuForSnapshot (voice.track);
  17731. juce::StringArray names { "Track" };
  17732. std::vector<juce::PopupMenu> menus { menu };
  17733. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  17734. if (it.getItem().subMenu != nullptr && it.getItem().text == lynx::tr ("Clean voice"))
  17735. {
  17736. names.add (lynx::tr ("Clean voice"));
  17737. menus.push_back (*it.getItem().subMenu);
  17738. }
  17739. check ("the Simple track menu has Clean voice", menus.size() == 2);
  17740. saveMenus (names, menus, prefix + "-cleanvoice-menu.png");
  17741. const auto before = offline.getSong().mixer[(std::size_t) voice.insert].effects.size();
  17742. check ("Clean voice applies", lynx::ui::applyCleanVoice (offline, voice.insert, false));
  17743. offline.dispatchPendingMessages();
  17744. const auto& fx = offline.getSong().mixer[(std::size_t) voice.insert].effects;
  17745. check ("four slots in front of the track's effects", fx.size() == before + 4 && lynx::cleanvoice::slotsOf (offline.getSong(), voice.insert).size() == 4
  17746. && fx[0].kind == lynx::EffectKind::facetEq);
  17747. check ("with noise reduction: five, none doubled", lynx::ui::applyCleanVoice (offline, voice.insert, true)
  17748. && offline.getSong().mixer[(std::size_t) voice.insert].effects.size() == before + 5);
  17749. offline.dispatchPendingMessages();
  17750. juce::String error;
  17751. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (offline.getSong()), error);
  17752. check ("the chain round-trips through .lynx and is still found", back.has_value() && lynx::cleanvoice::slotsOf (*back, voice.insert).size() == 5
  17753. && back->mixer[(std::size_t) voice.insert].effects == offline.getSong().mixer[(std::size_t) voice.insert].effects);
  17754. saveMenus (juce::StringArray { lynx::tr ("Clean voice") }, std::vector<juce::PopupMenu> { lynx::ui::cleanVoiceMenu (offline, voice.insert) },
  17755. prefix + "-cleanvoice-menu-on.png");
  17756. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
  17757. offline.dispatchPendingMessages();
  17758. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::mixer });
  17759. ui.selectMixerTrackForSnapshot (voice.insert);
  17760. shoot (ui, "cleanvoice-mixer");
  17761. offline.undo(); // the second chain
  17762. offline.dispatchPendingMessages();
  17763. check ("undo brings the first chain back", lynx::cleanvoice::slotsOf (offline.getSong(), voice.insert).size() == 4);
  17764. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  17765. offline.dispatchPendingMessages();
  17766. ui.selectTabForSnapshot (2); // (the Playlist alone, as --simpleshot shows the layout)
  17767. simple = ui.getSimpleWorkflowForSnapshot();
  17768. }
  17769. }
  17770. // ---- 2. Reference match: the song's Master render against a file (pink noise with more top, at about -14 LUFS)
  17771. {
  17772. const auto file = juce::File (prefix + "-reference.wav");
  17773. file.deleteFile();
  17774. const auto rate = 44100.0;
  17775. const auto frames = (int) (20.0 * rate);
  17776. juce::AudioBuffer<float> audio (2, frames);
  17777. juce::Random random (190);
  17778. for (int ch = 0; ch < 2; ++ch)
  17779. {
  17780. double b0 = 0, b1 = 0, b2 = 0, hp = 0;
  17781. for (int i = 0; i < frames; ++i)
  17782. {
  17783. const auto w = (double) random.nextFloat() * 2.0 - 1.0;
  17784. b0 = 0.99765 * b0 + w * 0.0990460;
  17785. b1 = 0.96300 * b1 + w * 0.2965164;
  17786. b2 = 0.57000 * b2 + w * 1.0526913;
  17787. const auto pink = (b0 + b1 + b2 + w * 0.1848) * 0.071; // (about -14 LUFS: a streaming master)
  17788. hp += 0.25 * (pink - hp); // a little more top than pink noise has
  17789. audio.setSample (ch, i, (float) (pink + 0.35 * (pink - hp)));
  17790. }
  17791. }
  17792. if (auto out = file.createOutputStream())
  17793. if (auto writer = std::unique_ptr<juce::AudioFormatWriter> (juce::WavAudioFormat().createWriterFor (out.get(), rate, 2, 24, {}, 0)))
  17794. {
  17795. out.release();
  17796. writer->writeFromAudioSampleBuffer (audio, 0, frames);
  17797. }
  17798. note ("measure reference");
  17799. const auto reference = lynx::ReferenceMatchPanel::measureFile (offline, file);
  17800. note ("measure song");
  17801. const auto song = lynx::ReferenceMatchPanel::measureSong (offline.getSong(), false);
  17802. check ("the reference file was measured", reference.valid);
  17803. check ("the song's Master render was measured", song.valid);
  17804. lynx::ReferenceMatchPanel panel (offline, {});
  17805. panel.setSize (lynx::ReferenceMatchPanel::defaultWidth, lynx::ReferenceMatchPanel::defaultHeight);
  17806. panel.showForSnapshot ("Reference.wav", song, reference, nullptr);
  17807. shoot (panel, "refmatch-measured");
  17808. const auto masterBefore = offline.getSong().mixer[0].effects.size();
  17809. check ("Match adds its two slots at the end of the Master", panel.matchForSnapshot() && offline.getSong().mixer[0].effects.size() == masterBefore + 2);
  17810. offline.dispatchPendingMessages();
  17811. const auto first = lynx::ReferenceMatchPanel::measureSong (offline.getSong(), true);
  17812. panel.showForSnapshot ("Reference.wav", song, reference, &first);
  17813. panel.refresh();
  17814. shoot (panel, "refmatch-matched");
  17815. report << " first Match: " << juce::String (first.lufs, 2) << " LUFS, " << juce::String (first.truePeakDb, 2) << " dBTP, EQ output "
  17816. << juce::String (lynx::facet::outputDb (offline.getSong().mixer[0].effects[masterBefore].params[(std::size_t) lynx::facet::outputParam]), 2) << " dB\n";
  17817. // a result more than 0.5 LU from the reference (a limiter that has to hold peaks back): Match again takes
  17818. // what is missing, as the window's note says
  17819. auto after = first;
  17820. const auto secondPass = std::abs (first.lufs - reference.lufs) > 0.5;
  17821. if (secondPass)
  17822. {
  17823. check ("Match again replaces the two slots (level corrected)", panel.matchForSnapshot() && offline.getSong().mixer[0].effects.size() == masterBefore + 2);
  17824. offline.dispatchPendingMessages();
  17825. after = lynx::ReferenceMatchPanel::measureSong (offline.getSong(), true);
  17826. panel.showForSnapshot ("Reference.wav", song, reference, &after);
  17827. panel.refresh();
  17828. shoot (panel, "refmatch-matched-again");
  17829. }
  17830. report << " " << (secondPass ? "a second Match was needed for the level" : "one Match was enough for the level") << "\n";
  17831. const auto& s = panel.suggestionForSnapshot();
  17832. report << " song " << juce::String (song.lufs, 2) << " LUFS, " << juce::String (song.truePeakDb, 2) << " dBTP, width " << juce::String (song.widthPercent(), 1)
  17833. << " % | reference " << juce::String (reference.lufs, 2) << " LUFS, " << juce::String (reference.truePeakDb, 2) << " dBTP, width "
  17834. << juce::String (reference.widthPercent(), 1) << " % | after " << juce::String (after.lufs, 2) << " LUFS, " << juce::String (after.truePeakDb, 2)
  17835. << " dBTP\n next suggestion: gain " << juce::String (s.gainDb, 2) << " dB, EQ fit error " << juce::String (s.fitErrorDb, 2) << " dB\n";
  17836. double before = 0.0, now = 0.0;
  17837. int counted = 0;
  17838. {
  17839. // tone only (each curve around its own mean), over the bands both hold
  17840. double ms = 0, mr = 0, ma = 0;
  17841. const auto used = juce::jmin (song.usedBands, reference.usedBands);
  17842. for (int k = 0; k < used; ++k)
  17843. ms += song.spectrumDb[(std::size_t) k], mr += reference.spectrumDb[(std::size_t) k], ma += after.spectrumDb[(std::size_t) k];
  17844. for (int k = 2; k < used; ++k, ++counted)
  17845. {
  17846. before += std::abs ((song.spectrumDb[(std::size_t) k] - ms / used) - (reference.spectrumDb[(std::size_t) k] - mr / used));
  17847. now += std::abs ((after.spectrumDb[(std::size_t) k] - ma / used) - (reference.spectrumDb[(std::size_t) k] - mr / used));
  17848. }
  17849. }
  17850. report << " mean tone difference to the reference: " << juce::String (before / juce::jmax (1, counted), 2) << " dB before, "
  17851. << juce::String (now / juce::jmax (1, counted), 2) << " dB after one Match (each band moves 6 dB at most)\n";
  17852. check ("after Match the tone is closer to the reference", after.valid && now < before);
  17853. check ("after Match the loudness is within 1 LU of the reference", std::abs (after.lufs - reference.lufs) < 1.0);
  17854. 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);
  17855. juce::String error;
  17856. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (offline.getSong()), error);
  17857. check ("the match round-trips through .lynx as two ordinary Master slots", back.has_value() && lynx::refmatch::present (*back)
  17858. && back->mixer[0].effects == offline.getSong().mixer[0].effects);
  17859. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
  17860. offline.dispatchPendingMessages();
  17861. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::mixer });
  17862. ui.selectMixerTrackForSnapshot (0);
  17863. shoot (ui, "refmatch-mixer");
  17864. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  17865. offline.dispatchPendingMessages();
  17866. ui.selectTabForSnapshot (2); // (the Playlist alone, as --simpleshot shows the layout)
  17867. simple = ui.getSimpleWorkflowForSnapshot();
  17868. if (simple != nullptr)
  17869. {
  17870. simple->hideChooser();
  17871. simple->showFinish();
  17872. shoot (ui, "finish-dock"); // "Match a reference track..." under the saving buttons
  17873. simple->hideFinish();
  17874. }
  17875. file.deleteFile();
  17876. }
  17877. // ---- 3. Start from: the chooser's link, the list, and opening an entry
  17878. if (simple != nullptr)
  17879. {
  17880. simple->showChooser();
  17881. shoot (ui, "chooser");
  17882. simple->hideChooser();
  17883. auto* panel = dynamic_cast<lynx::StartFromPanel*> (simple->startFromForSnapshot());
  17884. check ("the Start from list opens", panel != nullptr && simple->isStartFromShowing());
  17885. if (panel != nullptr)
  17886. {
  17887. shoot (ui, "startfrom");
  17888. auto list = lynx::startfrom::entries();
  17889. check ("it lists the demo song and the templates shipped", list.size() >= 3 && list[0].kind == lynx::startfrom::Entry::Kind::demo
  17890. && (int) list.size() == panel->entryCountForSnapshot());
  17891. for (auto& e : list)
  17892. report << " " << e.name << " | " << juce::String (e.bpm, 0) << " BPM, " << e.channels << " channels, " << e.bars << " bars"
  17893. << (e.playable ? ", preview" : "") << "\n";
  17894. if (const auto demo = lynx::startfrom::songOf (list[0]))
  17895. {
  17896. const auto wav = juce::File (prefix + "-preview.wav");
  17897. const auto ok = lynx::startfrom::renderPreview (*demo, wav);
  17898. check ("the demo's preview renders (" + juce::String (wav.getSize() / 1024) + " kB)", ok && wav.getSize() > 100000);
  17899. wav.deleteFile();
  17900. }
  17901. panel->selectForSnapshot (juce::jmin (2, panel->entryCountForSnapshot() - 1));
  17902. shoot (ui, "startfrom-selected");
  17903. offline.markSaved(); // (a project with changes asks first: Save / Don't save / Cancel)
  17904. const auto opened = panel->openForSnapshot (0);
  17905. offline.dispatchPendingMessages();
  17906. check ("opening the demo starts a new project from it and closes the list",
  17907. opened && ! simple->isStartFromShowing() && offline.getSong().info.comments.empty() && ! offline.getSong().channels.empty());
  17908. shoot (ui, "startfrom-opened");
  17909. }
  17910. }
  17911. juce::File (prefix + "-report.txt").replaceWithText (report);
  17912. }
  17913. void runVersionsShot (const juce::String& prefix)
  17914. {
  17915. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  17916. const auto shoot = [&prefix] (juce::Component& c, const char* name) {
  17917. savePng (lynx::shot::snapshot (c), prefix + "-" + name + ".png");
  17918. };
  17919. // ---- the Versions panel, on files in a temporary folder
  17920. const auto root = juce::File::getSpecialLocation (juce::File::tempDirectory)
  17921. .getChildFile ("lynx-versionsshot-" + juce::String::toHexString (juce::Random::getSystemRandom().nextInt64()));
  17922. const juce::ScopeGuard cleanUp { [&root] { root.deleteRecursively(); } };
  17923. const auto project = root.getChildFile ("Night Drive"), backup = root.getChildFile ("Backup");
  17924. project.createDirectory();
  17925. backup.createDirectory();
  17926. const auto now = juce::Time::getCurrentTime();
  17927. const auto put = [&now] (const juce::File& folder, const juce::String& name, const char* kind, int kilobytes, double hoursAgo) {
  17928. const auto time = now - juce::RelativeTime::hours (hoursAgo);
  17929. const auto file = folder.getChildFile (kind == nullptr ? name + ".lynx" : name + " (" + kind + " on " + time.formatted ("%Y-%m-%d at %Hh%M") + ").lynx");
  17930. juce::MemoryBlock data ((size_t) kilobytes * 1024, true);
  17931. file.replaceWithData (data.getData(), data.getSize());
  17932. file.setLastModificationTime (time);
  17933. };
  17934. put (project, "Night Drive", nullptr, 412, 26.0 * 24.0);
  17935. put (project, "Night Drive_2", nullptr, 688, 9.0 * 24.0);
  17936. put (project, "Night Drive_3", nullptr, 731, 2.0 * 24.0);
  17937. put (project, "Night Drive_4", nullptr, 905, 1.6);
  17938. put (backup, "Night Drive_4", "autosaved", 907, 0.07);
  17939. put (backup, "Night Drive_4", "autosaved", 906, 0.4);
  17940. put (backup, "Night Drive_4", "overwritten", 890, 1.6);
  17941. put (backup, "Night Drive_4", "autosaved", 884, 3.2);
  17942. put (backup, "Night Drive_3", "overwritten", 720, 2.0 * 24.0);
  17943. put (backup, "Night Drive_2", "autosaved", 690, 8.0 * 24.0);
  17944. const lynx::VersionsContext context { project.getChildFile ("Night Drive_4.lynx"), "Night Drive_4", backup, ".lynx" };
  17945. {
  17946. const auto entries = lynx::versionEntries (context);
  17947. const auto label = [&] (const juce::String& startsWith, const char* text) {
  17948. for (const auto& e : entries)
  17949. if (juce::String::fromUTF8 (e.name.c_str()).startsWith (startsWith))
  17950. {
  17951. lynx::setVersionLabel (context, e, text);
  17952. return;
  17953. }
  17954. };
  17955. label ("Night Drive_2", "first full arrangement");
  17956. label ("Night Drive_3", "sent to the singer");
  17957. label ("Night Drive_4 (autosaved", "new bass line");
  17958. }
  17959. {
  17960. lynx::VersionsActions actions;
  17961. actions.context = [context] { return context; };
  17962. auto panel = lynx::makeVersionsPanel (actions);
  17963. shoot (*panel, "versions");
  17964. lynx::VersionsActions fresh;
  17965. fresh.context = [backup] { return lynx::VersionsContext { juce::File(), "Untitled", backup, ".lynx" }; };
  17966. auto empty = lynx::makeVersionsPanel (fresh);
  17967. shoot (*empty, "versions-unsaved");
  17968. }
  17969. // ---- the window
  17970. lynx::AudioEngine offline (false);
  17971. lynx::MainComponent ui (offline, false);
  17972. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  17973. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  17974. const auto saveFileMenu = [&] (const char* name) {
  17975. const auto index = juce::jmax (0, ui.getMenuNamesForSnapshot().indexOf (lynx::tr ("File")));
  17976. saveMenus (juce::StringArray { lynx::tr ("File") }, std::vector<juce::PopupMenu> { ui.getMenuForSnapshot (index) }, prefix + "-" + name + ".png");
  17977. };
  17978. saveFileMenu ("menu-file");
  17979. // ---- a project opened without its third-party plugins (the plugins are not installed: nothing foreign runs)
  17980. {
  17981. const auto ref = [] (const char* id, const char* name) {
  17982. lynx::PluginRef r;
  17983. r.id = id;
  17984. r.name = name;
  17985. r.state = "c2V0dGluZ3M=";
  17986. return r;
  17987. };
  17988. auto song = lynx::Song::makeDefault();
  17989. while (song.channels.size() < 4)
  17990. song.channels.push_back (song.channels.front());
  17991. while (song.mixer.size() < 5)
  17992. song.mixer.push_back (song.mixer.back());
  17993. const char* names[] = { "Lead", "Pad" };
  17994. for (int c = 0; c < 2; ++c)
  17995. {
  17996. auto& channel = song.channels[(std::size_t) (c + 2)];
  17997. channel.instrument = lynx::InstrumentKind::plugin;
  17998. channel.plugin = ref ("VST3-ShotSynth-11111111-aaaaaaaa", "Shot Synth");
  17999. channel.name = names[c];
  18000. channel.mixerTrack = c + 1;
  18001. }
  18002. lynx::EffectSlot fx;
  18003. fx.kind = lynx::EffectKind::plugin;
  18004. fx.plugin = ref ("VST3-ShotVerb-22222222-bbbbbbbb", "Shot Verb");
  18005. song.mixer[1].effects.push_back (fx);
  18006. fx.plugin = ref ("VST3-ShotComp-33333333-cccccccc", "Shot Comp");
  18007. song.mixer[2].effects.push_back (fx);
  18008. song.mixer[0].effects.push_back (fx);
  18009. offline.setSongWithPluginsOff (std::move (song));
  18010. ui.showDesktopForSnapshot (false);
  18011. shoot (ui, "pluginsoff-window");
  18012. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::channelRack, lynx::workspace::Panel::mixer });
  18013. shoot (ui, "pluginsoff-mixer"); // (the rack's and the mixer's "off" tags together)
  18014. saveFileMenu ("menu-file-pluginsoff");
  18015. auto panel = lynx::makePluginsOffPanel (offline);
  18016. shoot (*panel, "pluginsoff-panel");
  18017. offline.switchPluginOn ("VST3-ShotVerb-22222222-bbbbbbbb"); // (not installed: "Did not load")
  18018. auto after = lynx::makePluginsOffPanel (offline);
  18019. shoot (*after, "pluginsoff-panel-one");
  18020. }
  18021. // ---- the Export window: as it opens, and with a preset chosen, sections on and a last export to repeat
  18022. {
  18023. auto song = lynx::Song::makeDefault();
  18024. const auto bar = song.barTicks();
  18025. song.mode = lynx::PlayMode::song;
  18026. song.playlist.clear();
  18027. lynx::Clip clip;
  18028. clip.length = 32 * bar;
  18029. song.playlist.push_back (clip);
  18030. const char* sections[] = { "Intro", "Verse", "Chorus", "Outro" };
  18031. for (int i = 0; i < 4; ++i)
  18032. {
  18033. lynx::Marker m;
  18034. m.tick = i * 8 * bar;
  18035. m.name = sections[i];
  18036. song.addMarker (m);
  18037. }
  18038. offline.setSong (std::move (song)); // (also ends the plugins-off mode)
  18039. auto plain = lynx::makeExportPanel (offline, 0);
  18040. shoot (*plain, "export-default");
  18041. auto additions = lynx::makeExportPanelWithAdditions (offline);
  18042. shoot (*additions, "export");
  18043. }
  18044. }
  18045. void runGamepadShot (const juce::String& prefix)
  18046. {
  18047. juce::String report;
  18048. int failures = 0;
  18049. {
  18050. lynx::AudioEngine engine (false);
  18051. auto hints = lynx::makeGamepadHints();
  18052. savePng (lynx::shot::snapshot (*hints), prefix + "-hints.png");
  18053. auto prefs = engine.getMidiPrefs();
  18054. prefs.gamepad = true;
  18055. engine.setMidiPrefs (prefs, false);
  18056. auto page = lynx::makeMidiPage (engine, {}, false);
  18057. page->setSize (760, 1400);
  18058. savePng (lynx::shot::snapshot (*page), prefix + "-settings.png");
  18059. // the poller with fake states: what the handler gets
  18060. using namespace lynx::gamepad;
  18061. std::vector<std::string> got;
  18062. lynx::GamepadInput input ([&got] (const Changes& c, const State&, double dt) {
  18063. for (int i = 0; i < c.pressedCount; ++i)
  18064. got.push_back (std::string ("press ") + buttonName (c.pressed[(std::size_t) i]));
  18065. for (int i = 0; i < c.releasedCount; ++i)
  18066. got.push_back (std::string ("release ") + buttonName (c.released[(std::size_t) i]));
  18067. for (int i = 0; i < c.controllerCount; ++i)
  18068. got.push_back ("cc " + std::to_string (c.controller[(std::size_t) i]) + "=" + std::to_string (c.value[(std::size_t) i]));
  18069. if (c.connectedChanged)
  18070. got.push_back ("connected changed");
  18071. got.push_back ("dt " + std::to_string ((int) std::lround (dt * 1000)));
  18072. });
  18073. State pad;
  18074. pad.connected = true;
  18075. input.inject (pad, 1.0 / 60.0);
  18076. pad.buttons = mask (Button::a);
  18077. pad.rightTrigger = 255;
  18078. input.inject (pad, 1.0 / 60.0);
  18079. pad.buttons = 0;
  18080. input.inject (pad, 1.0 / 60.0);
  18081. const std::vector<std::string> expected { "connected changed", "dt 17", "press A", "cc 102=127", "cc 21=127", "dt 17",
  18082. "release A", "cc 102=0", "dt 17" };
  18083. for (const auto& line : got)
  18084. report << line << "\n";
  18085. if (got != expected)
  18086. {
  18087. ++failures;
  18088. report << "FAILED: the poller's changes differ from the expected ones\n";
  18089. }
  18090. report << "xinput " << (input.available() ? "loaded" : "not available") << "\n";
  18091. }
  18092. report << (failures == 0 ? "gamepad OK" : "gamepad FAILED") << "\n";
  18093. juce::File (prefix + "-gamepad.txt").replaceWithText (report);
  18094. setApplicationReturnValue (failures == 0 ? 0 : 1);
  18095. quit();
  18096. }
  18097. void runBundleExport (const juce::String& inputPath, const juce::String& folderPath, bool zip, bool mixdown, const juce::String& shotPrefix)
  18098. {
  18099. juce::String error;
  18100. bool ok = false;
  18101. lynx::otherapps::Result result;
  18102. {
  18103. lynx::AudioEngine loader (false);
  18104. const juce::File input (inputPath);
  18105. if (input.hasFileExtension ("flp;als"))
  18106. ok = loader.importFlpFile (input, error);
  18107. else if (auto song = lynx::ProjectFile::load (input, error))
  18108. {
  18109. loader.setSong (std::move (*song));
  18110. ok = true;
  18111. }
  18112. if (ok)
  18113. {
  18114. loader.capturePluginStates();
  18115. lynx::otherapps::Context context;
  18116. context.host = &loader.getPluginHost();
  18117. context.flOptions = lynx::flstudio::optionsFor (context.host, lynx::flpexport::LynxOnly::renderAudio, loader.getSong());
  18118. context.render = [] (const lynx::Song& s, const lynx::exportopts::Options& o, const juce::File& file,
  18119. const std::function<bool (double)>& progress, juce::String& err) {
  18120. lynx::ExportJob job (s, o, file);
  18121. return job.run (progress, err);
  18122. };
  18123. context.onMessageThread = [] (std::function<void()> f) { f(); };
  18124. lynx::exportbundle::Options options;
  18125. options.zip = zip;
  18126. options.mixdown = mixdown;
  18127. const auto name = input.getFileNameWithoutExtension();
  18128. const auto shot = [&shotPrefix] (juce::Component& c, const juce::String& suffix) {
  18129. if (shotPrefix.isNotEmpty())
  18130. savePng (lynx::shot::snapshot (c), shotPrefix + suffix);
  18131. };
  18132. if (auto panel = lynx::makeOtherAppsExportPanel (loader, name))
  18133. shot (*panel, "-panel.png");
  18134. ok = lynx::otherapps::write (loader.getSong(), name, options, juce::File (folderPath), context, result);
  18135. if (auto report = lynx::makeOtherAppsReportPanel (result.folder, result.written, result.failed))
  18136. shot (*report, "-report.png");
  18137. }
  18138. }
  18139. juce::String report;
  18140. report << (ok ? "ok " + result.folder.getFullPathName() : "error=" + error) << "\n";
  18141. for (const auto& w : result.written)
  18142. report << "written " << w << "\n";
  18143. for (const auto& f : result.failed)
  18144. report << "failed " << f << "\n";
  18145. juce::File (folderPath).getChildFile ("export-bundle.txt").replaceWithText (report);
  18146. setApplicationReturnValue (ok && result.failed.isEmpty() ? 0 : 1);
  18147. quit();
  18148. }
  18149. void runFlExport (const juce::String& inputPath, const juce::String& outputPath, bool substitute)
  18150. {
  18151. juce::String error;
  18152. bool ok = false;
  18153. lynx::flstudio::Written written;
  18154. {
  18155. lynx::AudioEngine loader (false);
  18156. const juce::File input (inputPath);
  18157. // a Live set opens through the same import as an .flp (as File › Open does, and --export-als accepts an .flp)
  18158. if (input.hasFileExtension ("flp;als"))
  18159. ok = loader.importFlpFile (input, error);
  18160. else if (auto song = lynx::ProjectFile::load (input, error))
  18161. {
  18162. loader.setSong (std::move (*song));
  18163. ok = true;
  18164. }
  18165. if (ok)
  18166. {
  18167. const juce::File output (outputPath);
  18168. const auto zip = output.hasFileExtension ("zip");
  18169. const auto mode = substitute ? lynx::flpexport::LynxOnly::substitute : lynx::flpexport::LynxOnly::renderAudio;
  18170. loader.capturePluginStates();
  18171. auto options = lynx::flstudio::optionsFor (&loader.getPluginHost(), mode, loader.getSong());
  18172. // --flp-ppq N: the file's PPQ (tests; default: 96 when the notes and clips fit it)
  18173. if (const auto args = juce::JUCEApplication::getCommandLineParameterArray(); args.contains ("--flp-ppq"))
  18174. options.ppq = juce::jlimit (0, 960, args[args.indexOf ("--flp-ppq") + 1].getIntValue());
  18175. const auto renderDir = zip ? juce::File::getSpecialLocation (juce::File::tempDirectory).getNonexistentChildFile ("LYNX FL export", {}, false)
  18176. : output.getSiblingFile (output.getFileNameWithoutExtension() + " audio");
  18177. ok = lynx::flstudio::exportProject (loader.getSong(), options, output, zip, renderDir, 44100.0,
  18178. [] (const lynx::Song& s, const lynx::ExportSettings& settings, const juce::File& wav,
  18179. const std::function<bool (double)>& progress, juce::String& err) {
  18180. lynx::ExportJob job (s, settings, wav);
  18181. return job.run (progress, err);
  18182. },
  18183. {}, written, error);
  18184. if (zip)
  18185. renderDir.deleteRecursively();
  18186. }
  18187. }
  18188. juce::String report;
  18189. report << (ok ? "ok" : "error=" + error) << "\n"
  18190. << "exact=" << (int) written.report.exact.size() << " rendered=" << (int) written.report.rendered.size()
  18191. << " substituted=" << (int) written.report.substituted.size() << " dropped=" << (int) written.report.dropped.size()
  18192. << " samples=" << written.samples << "\n\n"
  18193. << lynx::flstudio::reportText (written) << "\n";
  18194. juce::File (outputPath + ".txt").replaceWithText (report);
  18195. setApplicationReturnValue (ok ? 0 : 1);
  18196. quit();
  18197. }
  18198. // LYNX.exe --export project.(flp|als|lynx) output.(wav|flac|ogg|mp3|aif|aiff|m4a|aac) [--pattern] [--insert N] [--rate N]
  18199. // Same path as "Export" in the UI: the whole song (or the current pattern) with its tail. .aif / .aiff: 24-bit AIFF;
  18200. // .m4a: AAC at 192 kbps through the system's encoder (engine/AacEncoder.h; .aac writes the same MPEG-4 file under the
  18201. // name .m4a). M4A is not available on Linux: the export stops with that message.
  18202. void runExport (const juce::String& inputPath, const juce::String& outputPath, bool patternOnly, int insert)
  18203. {
  18204. juce::String error, report;
  18205. bool ok = false;
  18206. const auto started = juce::Time::getMillisecondCounterHiRes();
  18207. lynx::loadtrace::begin (inputPath.toStdString()); // phase times (round 112): report lines + load.log
  18208. {
  18209. lynx::AudioEngine loader (false);
  18210. const juce::File input (inputPath);
  18211. // --find-plugins: first the targeted scan opening the project in the app runs (its plugins not known yet)
  18212. if (input.hasFileExtension ("flp") && juce::JUCEApplication::getCommandLineParameters().contains ("--find-plugins"))
  18213. {
  18214. juce::MemoryBlock data;
  18215. if (input.loadFileAsData (data))
  18216. try
  18217. {
  18218. const auto uses = lynx::flpForeignPlugins (flp::parseProject ({ static_cast<const std::uint8_t*> (data.getData()), data.getSize() }));
  18219. auto& host = loader.getPluginHost();
  18220. const auto listed = std::chrono::steady_clock::now();
  18221. const auto files = host.filesToScanFor (uses);
  18222. lynx::loadtrace::add ("plugin_scan_list", lynx::loadtrace::msSince (listed));
  18223. report << "scanned=" << files.joinIntoString (";") << "\n";
  18224. const auto scanned = std::chrono::steady_clock::now();
  18225. host.scanFiles (files, {});
  18226. lynx::loadtrace::add ("plugin_scan", lynx::loadtrace::msSince (scanned), files.size());
  18227. }
  18228. catch (const flp::Error&)
  18229. {
  18230. }
  18231. }
  18232. if (input.hasFileExtension ("flp;als")) // a Live set opens through the same import (round 182b)
  18233. ok = loader.importFlpFile (input, error);
  18234. else if (auto song = lynx::ProjectFile::load (input, error))
  18235. {
  18236. loader.setSong (std::move (*song));
  18237. ok = true;
  18238. }
  18239. // M4A without a system AAC encoder (Linux): said before anything is rendered
  18240. if (ok && juce::File (outputPath).hasFileExtension ("m4a;aac") && ! lynx::aac::available())
  18241. {
  18242. ok = false;
  18243. error = juce::String::fromUTF8 (lynx::aac::unavailableReason().c_str());
  18244. }
  18245. if (ok)
  18246. {
  18247. // (an .aac name gets the MPEG-4 file it holds: .m4a)
  18248. const juce::File output (juce::File (outputPath).hasFileExtension ("aac") ? juce::File (outputPath).withFileExtension ("m4a") : juce::File (outputPath));
  18249. lynx::ExportSettings settings;
  18250. settings.wholeSong = ! patternOnly;
  18251. settings.format = output.hasFileExtension ("flac") ? lynx::ExportSettings::Format::flac24
  18252. : output.hasFileExtension ("ogg") ? lynx::ExportSettings::Format::ogg
  18253. : lynx::ExportSettings::Format::wav24;
  18254. // --insert N: only that insert's output (what "Render to audio" records)
  18255. if (juce::JUCEApplication::getCommandLineParameters().contains ("--no-effects")
  18256. || juce::JUCEApplication::getCommandLineParameters().contains ("--sem-efeitos")) // performance diagnostics; --sem-efeitos: legacy alias
  18257. loader.editSong ([] (lynx::Song& s) {
  18258. for (auto& t : s.mixer)
  18259. t.effects.clear();
  18260. }, false);
  18261. if (juce::JUCEApplication::getCommandLineParameters().contains ("--no-automation")
  18262. || juce::JUCEApplication::getCommandLineParameters().contains ("--sem-automacao")) // --sem-automacao: legacy alias
  18263. loader.editSong ([] (lynx::Song& s) { s.automations.clear(); }, false);
  18264. const auto loaded = juce::Time::getMillisecondCounterHiRes();
  18265. // .mp3: the Export window's MP3 (320 kbps); everything else as before
  18266. auto options = settings.toOptions();
  18267. // --save-tempo: FL's "Tempo information" (acid chunk) on (round 167l: compare with FL's AcidBox render; --export)
  18268. if (juce::JUCEApplication::getCommandLineParameters().contains ("--save-tempo"))
  18269. options.saveTempo = true;
  18270. // --no-warmup: the export's plugin warm-up off (round 155: compare the start of the file)
  18271. if (juce::JUCEApplication::getCommandLineParameters().contains ("--no-warmup"))
  18272. options.pluginWarmUp = false;
  18273. // --rate N: render at another sample rate (round 157b: samples resampled as at a 48 kHz device)
  18274. if (const auto args = juce::JUCEApplication::getCommandLineParameterArray(); args.contains ("--rate"))
  18275. if (const auto rate = args[args.indexOf ("--rate") + 1].getDoubleValue(); rate >= 8000.0 && rate <= 384000.0)
  18276. options.sampleRate = rate;
  18277. if (output.hasFileExtension ("mp3"))
  18278. {
  18279. options.format = lynx::exportopts::Format::mp3;
  18280. options.mp3Kbps = 320;
  18281. }
  18282. else if (output.hasFileExtension ("aif;aiff")) // (as the .wav: 24 bits, no dither)
  18283. {
  18284. options.format = lynx::exportopts::Format::aiff;
  18285. options.aiffBits = 24;
  18286. }
  18287. else if (output.hasFileExtension ("m4a"))
  18288. {
  18289. options.format = lynx::exportopts::Format::aac;
  18290. options.aacKbps = 192;
  18291. }
  18292. lynx::ExportJob job (insert > 0 ? lynx::makeBounceSong (loader.getSong(), insert) : loader.getSong(), options, output);
  18293. job.setExtraData (true);
  18294. const auto prepared = juce::Time::getMillisecondCounterHiRes();
  18295. lynx::loadtrace::end();
  18296. int lastPercent = -1;
  18297. ok = job.run ([&lastPercent] (double p) {
  18298. lastPercent = (int) (p * 100.0);
  18299. return true;
  18300. }, error);
  18301. auto joined = [] (const std::map<std::string, int>& items) {
  18302. juce::StringArray names;
  18303. for (const auto& [name, count] : items)
  18304. names.add (juce::String::fromUTF8 (name.c_str()) + "x" + juce::String (count));
  18305. return names.joinIntoString (", ");
  18306. };
  18307. const auto& importReport = loader.getImportReport();
  18308. report << "converted=" << joined (importReport.converted) << "\n"
  18309. << "approximated=" << joined (importReport.approximated) << "\n"
  18310. << "unsupported=" << joined (importReport.unsupported) << "\n"
  18311. << "dropped_effects=" << joined (importReport.droppedEffects) << "\n"
  18312. << "partial_effects=" << joined (importReport.partialEffects) << "\n"
  18313. << "missing_samples=" << importReport.missingSamples << "\n";
  18314. // third-party plugins: how each was found, or what plays in its place (diagnostics for level differences)
  18315. for (const auto& line : loader.getMatchedPlugins())
  18316. report << "plugin_found=" << line << "\n";
  18317. for (const auto& m : loader.getMissingPluginDetails())
  18318. report << "plugin_missing=" << juce::String::fromUTF8 (m.name.c_str()) << " -> "
  18319. << juce::String::fromUTF8 (m.replacement.c_str()).replace ("{0}", juce::String::fromUTF8 (m.replacementArg.c_str())) << "\n";
  18320. {
  18321. const auto& song = loader.getSong();
  18322. for (std::size_t t = 0; t < song.mixer.size(); ++t)
  18323. {
  18324. const auto& track = song.mixer[t];
  18325. if (track.effects.empty() && track.sends.empty())
  18326. continue;
  18327. report << "insert " << (int) t << " vol=" << juce::String (track.volume / lynx::unityFader, 3)
  18328. << (track.muted ? " muted" : "") << (track.toMaster ? "" : " noMaster");
  18329. for (const auto& s : track.sends)
  18330. report << " send>" << s.target << "@" << juce::String (s.level, 3);
  18331. report << " |";
  18332. for (const auto& fx : track.effects)
  18333. report << " [" << (fx.kind == lynx::EffectKind::plugin ? juce::String::fromUTF8 (fx.plugin.name.c_str())
  18334. : juce::String::fromUTF8 (lynx::effectInfo (fx.kind).name))
  18335. << (fx.isSubstitute() ? " (substitute)" : "") << (fx.enabled ? "" : " off")
  18336. << (fx.mix < 0.999f ? " mix=" + juce::String (fx.mix, 2) : juce::String()) << "]";
  18337. report << "\n";
  18338. }
  18339. }
  18340. report << juce::String (lynx::loadtrace::reportLines());
  18341. lynx::PluginHost::settingsFolder().getChildFile ("load.log").replaceWithText (juce::String (lynx::loadtrace::table()));
  18342. report << "open_ms=" << juce::roundToInt (loaded - started) << "\n"
  18343. << "prepare_ms=" << juce::roundToInt (prepared - loaded) << "\n"
  18344. << "render_ms=" << juce::roundToInt (juce::Time::getMillisecondCounterHiRes() - prepared) << "\n"
  18345. << "graph_ms=" << juce::roundToInt (job.getEngine().getLastRenderStats().graphMs) << "\n"
  18346. << "write_ms=" << juce::roundToInt (job.getEngine().getLastRenderStats().writeMs) << "\n"
  18347. << "warmup_blocks=" << job.getEngine().getLastRenderStats().warmUp.blocks << "\n"
  18348. << "warmup_ms=" << juce::roundToInt (job.getEngine().getLastRenderStats().warmUp.wallSeconds * 1000.0) << "\n"
  18349. << "warmup_changes=" << job.getEngine().getLastRenderStats().warmUp.signatureChanges << "\n"
  18350. << "warmup_timed_out=" << (job.getEngine().getLastRenderStats().warmUp.timedOut ? 1 : 0) << "\n"
  18351. << "pdc_trim=" << job.getEngine().getLastRenderStats().trimmedSamples << "\n"
  18352. << "song_seconds=" << job.getMusicSeconds() << "\n"
  18353. << "peak=" << job.getPeak() << "\n"
  18354. << "final_progress=" << lastPercent << "\n"
  18355. << "bytes=" << output.getSize() << "\n"
  18356. << "file=" << output.getFullPathName() << "\n";
  18357. ok = ok && job.getPeak() > 0.001f;
  18358. }
  18359. }
  18360. report << "result=" << (ok ? "OK" : "ERROR " + error) << "\n";
  18361. juce::File (outputPath + ".txt").replaceWithText (report);
  18362. setApplicationReturnValue (ok ? 0 : 1);
  18363. quit();
  18364. }
  18365. // LYNX.exe --snapshot prefix [project]: draws the window off-screen and writes
  18366. // prefix-rack.png, -pianoroll.png and -playlist.png (to check the UI without touching the screen).
  18367. // --editorcpu: one editor after another; each phase runs 2 s to settle and 8 s measured
  18368. struct EditorCpuRun final : juce::Timer
  18369. {
  18370. struct Case { lynx::EffectKind kind; const char* name; int type; bool demo; }; // type 0 native, 1 display-first, 2 Facet EQ
  18371. std::vector<Case> cases;
  18372. std::size_t at = 0;
  18373. int phase = 0;
  18374. double t0 = 0.0, c0 = 0.0;
  18375. juce::String report;
  18376. juce::File out;
  18377. std::unique_ptr<lynx::AudioEngine> engine;
  18378. std::unique_ptr<juce::DocumentWindow> window;
  18379. std::function<void()> done;
  18380. void start()
  18381. {
  18382. engine = std::make_unique<lynx::AudioEngine> (false);
  18383. report << "editor\tmode\tcpu % of one core\n";
  18384. open();
  18385. startTimer (250);
  18386. }
  18387. void open()
  18388. {
  18389. window.reset();
  18390. if (at >= cases.size()) { out.replaceWithText (report); stopTimer(); if (done) done(); return; }
  18391. const auto& c = cases[at];
  18392. lynx::Song song;
  18393. song.mixer.resize (2);
  18394. song.mixer[0].name = "Master";
  18395. song.mixer[1].name = "Insert 1";
  18396. song.mixer[1].effects.push_back (lynx::makeEffectSlot (c.kind));
  18397. engine->setSong (std::move (song));
  18398. engine->dispatchPendingMessages();
  18399. lynx::setNativeEditorDemo (c.demo);
  18400. auto editor = c.type == 1 ? lynx::makeProEditor (*engine, 1, 0, c.demo) : c.type == 2 ? lynx::makeFacetEqEditor (*engine, 1, 0, c.demo)
  18401. : lynx::makeNativeEffectEditor (*engine, 1, 0, 1.0f, 0);
  18402. window = std::make_unique<juce::DocumentWindow> (juce::String ("LYNX editor CPU - ") + c.name, lynx::theme::colour::bg1, 0);
  18403. window->setUsingNativeTitleBar (true);
  18404. window->setContentOwned (editor.release(), true);
  18405. const auto area = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea;
  18406. window->setTopLeftPosition (area.getRight() - window->getWidth() - 8, area.getBottom() - window->getHeight() - 8);
  18407. window->setVisible (true);
  18408. phase = 0;
  18409. t0 = juce::Time::getMillisecondCounterHiRes();
  18410. }
  18411. void timerCallback() override
  18412. {
  18413. const auto now = juce::Time::getMillisecondCounterHiRes();
  18414. if (phase == 0 && now - t0 > 2000.0) { phase = 1; t0 = now; c0 = lynx::processCpuSeconds(); return; }
  18415. if (phase == 1 && now - t0 > 8000.0)
  18416. {
  18417. const auto cpu = (lynx::processCpuSeconds() - c0) / ((now - t0) * 0.001) * 100.0;
  18418. const auto& c = cases[at];
  18419. report << c.name << "\t" << (c.demo ? "animating" : "idle") << "\t" << juce::String (cpu, 2) << "\n";
  18420. ++at;
  18421. open();
  18422. }
  18423. }
  18424. };
  18425. std::unique_ptr<EditorCpuRun> editorCpu;
  18426. void runEditorCpu (const juce::String& path)
  18427. {
  18428. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  18429. editorCpu = std::make_unique<EditorCpuRun>();
  18430. editorCpu->out = juce::File (path);
  18431. using K = lynx::EffectKind;
  18432. for (const auto demo : { false, true })
  18433. for (const auto& c : std::vector<EditorCpuRun::Case> { { K::facetEq, "Facet EQ", 2, demo }, { K::crestCompressor, "Crest Compressor", 1, demo },
  18434. { K::apexLimiter, "Apex Limiter", 1, demo }, { K::prismMultiband, "Prism Multiband", 1, demo },
  18435. { K::epochVerb, "Epoch Verb", 0, demo }, { K::glowLeveler, "Glow Leveler", 0, demo },
  18436. { K::fruityLimiter, "Fruity Limiter", 0, demo }, { K::lynxTune, "LYNX Tune", 0, demo } })
  18437. editorCpu->cases.push_back (c);
  18438. editorCpu->done = [this] { juce::MessageManager::callAsync ([this] { editorCpu.reset(); quit(); }); };
  18439. editorCpu->start();
  18440. }
  18441. struct ParityShow
  18442. {
  18443. std::unique_ptr<lynx::AudioEngine> engine;
  18444. std::unique_ptr<juce::Component> editor;
  18445. std::unique_ptr<juce::DocumentWindow> window;
  18446. ~ParityShow() { window.reset(); editor.reset(); engine.reset(); }
  18447. };
  18448. std::shared_ptr<ParityShow> parityShow;
  18449. bool parityShotFailed = false; // --parityshot: the effect name matched no built-in effect
  18450. void runParityShot (const juce::String& path, const juce::String& effectName, const juce::String& paramsFile)
  18451. {
  18452. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  18453. int kindIndex = -1;
  18454. for (int k = 0; k <= (int) lynx::lastEffectKind; ++k)
  18455. if (juce::String::fromUTF8 (lynx::effectInfo ((lynx::EffectKind) k).name).equalsIgnoreCase (effectName))
  18456. kindIndex = k;
  18457. if (kindIndex < 0)
  18458. {
  18459. // round tp172b7: say so and fail (a silent exit 0 hid a split effect name in a launch script)
  18460. std::fprintf (stderr, "unknown effect: %s\n", effectName.toRawUTF8());
  18461. std::fflush (stderr);
  18462. parityShotFailed = true;
  18463. return;
  18464. }
  18465. const auto kind = (lynx::EffectKind) kindIndex;
  18466. auto fx = lynx::makeEffectSlot (kind);
  18467. // round 190jd: LYNX_PARITYSHOT_VIEW=1 = the editor display's second view (Fruity Limiter: LYNX's transfer curve)
  18468. fx.displayView = (std::uint8_t) juce::jlimit (0, 1, juce::SystemStats::getEnvironmentVariable ("LYNX_PARITYSHOT_VIEW", "0").getIntValue());
  18469. if (paramsFile.isNotEmpty())
  18470. for (const auto& line : juce::StringArray::fromLines (juce::File (paramsFile).loadFileAsString()))
  18471. {
  18472. const auto t = juce::StringArray::fromTokens (line, " \t", "");
  18473. const auto index = t.size() >= 2 ? t[0].getIntValue() : -1;
  18474. if (index >= 0 && index < lynx::maxEffectParams)
  18475. fx.params[(std::size_t) index] = t[1].getFloatValue();
  18476. }
  18477. auto offlineOwner = std::make_unique<lynx::AudioEngine> (false); // (kept alive by LYNX_PARITYSHOT_SHOW's window)
  18478. auto& offline = *offlineOwner;
  18479. auto song = lynx::Song::makeDefault();
  18480. song.mixer.resize (2);
  18481. song.mixer[0].name = "Master";
  18482. song.mixer[1].name = "Insert 1";
  18483. song.mixer[1].effects.assign (1, fx);
  18484. for (auto& c : song.channels)
  18485. c.mixerTrack = 1;
  18486. offline.setSong (std::move (song));
  18487. offline.dispatchPendingMessages();
  18488. const bool facet = kind == lynx::EffectKind::facetEq;
  18489. // round tp172b4: the originals are pictured idle (nothing playing), so the display-first editors are too: no demo
  18490. // history unless LYNX_PARITYSHOT_DEMO=1 asks for the running display
  18491. const bool demoDisplay = juce::SystemStats::getEnvironmentVariable ("LYNX_PARITYSHOT_DEMO", {}) == "1";
  18492. // (Ember in its Classic voicing: the Classic panel, as the mixer opens it)
  18493. const bool pro = lynx::ProEditorWindows::handles (kind)
  18494. && ! (kind == lynx::EffectKind::ember && fx.params[(std::size_t) lynx::mixsuite::ember::voicing] > 0.5f);
  18495. auto editor = facet ? lynx::makeFacetEqEditor (offline, 1, 0, false)
  18496. : pro ? lynx::makeProEditor (offline, 1, 0, demoDisplay) : lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
  18497. if (editor == nullptr)
  18498. return;
  18499. if (! pro) // the demo song through the effect, the editor ticked 30 times a second of audio as its timer would
  18500. {
  18501. lynx::AudioEngine::RenderOptions o;
  18502. o.seconds = 3.0;
  18503. o.sampleRate = 48000.0;
  18504. o.pluginWarmUp = false;
  18505. int sinceTick = 0;
  18506. o.capture = [&] (const float*, const float*, int n) {
  18507. sinceTick += n;
  18508. if (sinceTick < 1600) return;
  18509. sinceTick = 0;
  18510. if (facet) lynx::tickFacetEqEditor (*editor);
  18511. else lynx::tickNativeEffectEditor (*editor);
  18512. };
  18513. offline.renderOffline (o);
  18514. }
  18515. // round tp172b5: LYNX_PARITYSHOT_CLICKS drives the editor before the picture (the originals' pictures have their
  18516. // panels open), tokens in order: "x,y" a click, then the pointer leaves; "h:x,y" the pointer rests there (a hover);
  18517. // "d:x,y,x2,y2" a drag from there to there, the button still down in the picture
  18518. for (const auto& token : juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_PARITYSHOT_CLICKS", {}), " ", ""))
  18519. {
  18520. const auto hover = token.startsWith ("h:"), drag = token.startsWith ("d:");
  18521. const auto xy = juce::StringArray::fromTokens (hover || drag ? token.substring (2) : token, ",", "");
  18522. if (xy.size() < (drag ? 4 : 2))
  18523. continue;
  18524. const juce::Point<int> at (xy[0].getIntValue(), xy[1].getIntValue());
  18525. editor->setVisible (true); // (getComponentAt finds nothing in a hidden component; it never goes on screen)
  18526. auto* target = editor->getComponentAt (at);
  18527. if (target == nullptr)
  18528. continue;
  18529. const auto local = target->getLocalPoint (editor.get(), at).toFloat();
  18530. const auto now = juce::Time::getCurrentTime();
  18531. auto source = juce::Desktop::getInstance().getMainMouseSource();
  18532. const juce::ModifierKeys left (juce::ModifierKeys::leftButtonModifier);
  18533. const auto event = [&] (juce::Point<float> p, juce::ModifierKeys mods, bool dragged) {
  18534. return juce::MouseEvent (source, p, mods, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, target, target, now, local, now, 1, dragged);
  18535. };
  18536. target->mouseMove (event (local, {}, false));
  18537. if (hover)
  18538. continue;
  18539. target->mouseDown (event (local, left, false));
  18540. if (drag)
  18541. {
  18542. const auto end = target->getLocalPoint (editor.get(), juce::Point<int> (xy[2].getIntValue(), xy[3].getIntValue())).toFloat();
  18543. target->mouseDrag (event (end, left, true));
  18544. continue;
  18545. }
  18546. target->mouseUp (event (local, {}, false));
  18547. target->mouseExit (event ({ -1000.0f, -1000.0f }, {}, false));
  18548. offline.dispatchPendingMessages(); // (round 190jd: an edit the click made, e.g. a display view, reaches the slot)
  18549. }
  18550. // round tp172b6: LYNX_PARITYSHOT_SHOW=1 puts the same editor in a real window and keeps it open (for a guarded GUI check
  18551. // of its pop-up menus, which the offscreen picture cannot hold); closing the window quits
  18552. if (juce::SystemStats::getEnvironmentVariable ("LYNX_PARITYSHOT_SHOW", {}) == "1")
  18553. {
  18554. struct ShowWindow final : juce::DocumentWindow
  18555. {
  18556. ShowWindow() : juce::DocumentWindow ("LYNX parity check", juce::Colours::black, juce::DocumentWindow::closeButton) {}
  18557. void closeButtonPressed() override { juce::JUCEApplication::getInstance()->systemRequestedQuit(); }
  18558. };
  18559. parityShow = std::make_shared<ParityShow>();
  18560. parityShow->engine = std::move (offlineOwner);
  18561. parityShow->editor = std::move (editor);
  18562. auto window = std::make_unique<ShowWindow>();
  18563. window->setUsingNativeTitleBar (true);
  18564. window->setContentNonOwned (parityShow->editor.get(), true);
  18565. window->setTopLeftPosition (80, 80);
  18566. window->setVisible (true);
  18567. parityShow->window = std::move (window);
  18568. return;
  18569. }
  18570. // round 190ar: LYNX_PARITYSHOT_SCALE=2 draws the same editor at twice the pixel density (as on a 200 % display);
  18571. // round 190bi: the shared shot scale (--shot-scale, LYNX_SHOT_SCALE, LYNX_PARITYSHOT_SCALE as before)
  18572. const auto shotScale = lynx::shot::scale();
  18573. juce::Image image (juce::Image::ARGB, juce::roundToInt ((float) editor->getWidth() * shotScale), juce::roundToInt ((float) editor->getHeight() * shotScale), true);
  18574. {
  18575. juce::Graphics g (image);
  18576. g.fillAll (lynx::theme::panel);
  18577. g.addTransform (juce::AffineTransform::scale (shotScale));
  18578. editor->paintEntireComponent (g, false);
  18579. }
  18580. const auto file = lynx::shot::file (juce::File (path));
  18581. file.deleteFile();
  18582. juce::PNGImageFormat png;
  18583. if (auto stream = file.createOutputStream())
  18584. png.writeImageToStream (image, *stream);
  18585. }
  18586. // an Audio Effect Rack shaped like Live's reference (REA_rodada183c §8): two chains with chain-select zones and fades,
  18587. // four named macros (one on a chain's volume, one on two parameters), two variations, every view open
  18588. static lynx::EffectSlot shotRack()
  18589. {
  18590. auto slot = lynx::rack::makeRackSlot (lynx::RackDoc::Kind::audioEffect);
  18591. auto& doc = slot.patcher;
  18592. doc.rack[0].chains[0].name = "Vocoder";
  18593. lynx::PatchNode vocoder, eq, verb;
  18594. vocoder.effect = lynx::makeEffectSlot (lynx::EffectKind::vocodex);
  18595. eq.effect = lynx::makeEffectSlot (lynx::EffectKind::parametricEq);
  18596. verb.effect = lynx::makeEffectSlot (lynx::EffectKind::reeverb2);
  18597. const auto nVoc = lynx::rack::addDevice (doc, 0, vocoder);
  18598. const auto nEq = lynx::rack::addDevice (doc, 0, eq);
  18599. lynx::rack::addChain (doc, "dry bypass");
  18600. lynx::rack::addDevice (doc, 1, verb);
  18601. doc.rack[0].chains[0].select = { 0, 79, 0, 63 };
  18602. doc.rack[0].chains[1].select = { 32, 127, 48, 127 };
  18603. lynx::rack::setChainVolume (doc, 0, 0.33f);
  18604. lynx::rack::setChainVolume (doc, 1, 0.5f);
  18605. const char* names[] { "Sibilance", "Intensity", "Formant Shift", "Bright Level" };
  18606. for (int m = 0; m < 4; ++m)
  18607. doc.rack[0].macros[(std::size_t) m].name = names[m];
  18608. lynx::RackMapping vol;
  18609. vol.target = lynx::RackMapping::Target::chainVolume, vol.chain = 0, vol.min = 0.0f, vol.max = lynx::rack::unityVolume;
  18610. lynx::rack::map (doc, 0, vol);
  18611. lynx::RackMapping a, b, c, d;
  18612. a.node = nVoc, a.param = 0;
  18613. b.node = nVoc, b.param = 1, b.min = 0.2f, b.max = 0.8f;
  18614. c.node = nEq, c.param = 0, c.min = 0.3f, c.max = 0.9f;
  18615. d.node = nEq, d.param = 1;
  18616. lynx::rack::map (doc, 1, a);
  18617. lynx::rack::map (doc, 2, b);
  18618. lynx::rack::map (doc, 3, c);
  18619. lynx::rack::map (doc, 3, d);
  18620. lynx::rack::setMacro (doc, 0, 60.0f);
  18621. lynx::rack::setMacro (doc, 1, 40.0f);
  18622. lynx::rack::setMacro (doc, 2, 70.0f);
  18623. lynx::rack::setMacro (doc, 3, 86.0f);
  18624. lynx::rack::storeVariation (doc);
  18625. lynx::rack::renameVariation (doc, 0, "Verse");
  18626. lynx::rack::setMacro (doc, 3, 120.0f);
  18627. lynx::rack::storeVariation (doc);
  18628. lynx::rack::renameVariation (doc, 1, "Drop");
  18629. lynx::rack::launchVariation (doc, 0);
  18630. auto& r = doc.rack[0];
  18631. r.showMacros = r.showChains = r.showDevices = r.showVariations = true;
  18632. r.zoneEditor = 2;
  18633. r.selectedChain = 0;
  18634. lynx::rack::setSelector (doc, 56.0f);
  18635. lynx::rack::compile (doc);
  18636. return slot;
  18637. }
  18638. bool runRackShots (const juce::File& out, const juce::String& liveSet = {})
  18639. {
  18640. out.createDirectory();
  18641. lynx::AudioEngine offline (false);
  18642. auto save = [&] (juce::Component& c, const juce::String& name) {
  18643. auto image = lynx::shot::paint (c, lynx::theme::panel);
  18644. const auto f = lynx::shot::file (out.getChildFile (name));
  18645. f.deleteFile();
  18646. juce::PNGImageFormat png;
  18647. if (auto stream = f.createOutputStream())
  18648. return png.writeImageToStream (image, *stream);
  18649. return false;
  18650. };
  18651. auto song = lynx::Song::makeDefault();
  18652. song.mixer.resize (3);
  18653. song.mixer[1].name = "Vocal Main";
  18654. auto slot = shotRack();
  18655. song.mixer[1].effects = { slot };
  18656. // an Instrument Rack: three chains split over the keyboard
  18657. lynx::ChannelDef inst;
  18658. inst.name = "Keys Rack";
  18659. inst.instrument = lynx::InstrumentKind::patcher;
  18660. inst.patcher = lynx::rack::makeRack (lynx::RackDoc::Kind::instrument);
  18661. for (int k = 0; k < 3; ++k)
  18662. {
  18663. if (k > 0)
  18664. lynx::rack::addChain (inst.patcher);
  18665. lynx::PatchNode synth;
  18666. synth.generator = true;
  18667. synth.channel.instrument = lynx::InstrumentKind::synth;
  18668. synth.channel.name = "Synth";
  18669. lynx::rack::addDevice (inst.patcher, k, synth);
  18670. }
  18671. inst.patcher.rack[0].chains[0].key = { 0, 52, 0, 47 };
  18672. inst.patcher.rack[0].chains[1].key = { 48, 76, 53, 71 };
  18673. inst.patcher.rack[0].chains[2].key = { 72, 127, 77, 127 };
  18674. inst.patcher.rack[0].chains[0].name = "Low";
  18675. inst.patcher.rack[0].chains[1].name = "Mid";
  18676. inst.patcher.rack[0].chains[2].name = "High";
  18677. inst.patcher.rack[0].showChains = inst.patcher.rack[0].showDevices = true;
  18678. inst.patcher.rack[0].zoneEditor = 0;
  18679. lynx::rack::compile (inst.patcher);
  18680. song.channels.push_back (inst);
  18681. const auto channel = (int) song.channels.size() - 1;
  18682. offline.setSong (std::move (song));
  18683. offline.dispatchPendingMessages();
  18684. bool ok = true;
  18685. // [set.als]: a Live set's racks as LYNX imports them, the one with the most chains drawn with its title bar (the
  18686. // like-for-like pair with Live's own picture of that set)
  18687. if (liveSet.isNotEmpty())
  18688. {
  18689. juce::MemoryBlock bytes;
  18690. juce::File (liveSet).loadFileAsData (bytes);
  18691. const std::vector<std::uint8_t> data ((const std::uint8_t*) bytes.getData(), (const std::uint8_t*) bytes.getData() + bytes.getSize());
  18692. lynx::AlsImportOptions o;
  18693. o.common.projectFolder = juce::File (liveSet).getParentDirectory().getFullPathName().toStdString();
  18694. std::string error;
  18695. if (auto imported = lynx::importAls (data, o, &error))
  18696. {
  18697. int bestTrack = -1, bestSlot = -1;
  18698. std::size_t most = 0;
  18699. for (int t = 0; t < (int) imported->mixer.size(); ++t)
  18700. for (int s = 0; s < (int) imported->mixer[(std::size_t) t].effects.size(); ++s)
  18701. 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)
  18702. most = fx.patcher.rack[0].chains.size(), bestTrack = t, bestSlot = s;
  18703. if (bestTrack >= 0)
  18704. {
  18705. offline.setSong (std::move (*imported));
  18706. offline.dispatchPendingMessages();
  18707. auto view = lynx::RackWindows::makeSlotView (offline, bestTrack, bestSlot, true);
  18708. view->setSize (view->preferredWidth (228), 228);
  18709. ok = save (*view, "rack-live-import.png") && ok;
  18710. view->setMapMode (true);
  18711. view->setSize (view->preferredWidth (228), 228);
  18712. ok = save (*view, "rack-live-import-map.png") && ok;
  18713. return ok;
  18714. }
  18715. }
  18716. return false;
  18717. }
  18718. {
  18719. auto view = lynx::RackWindows::makeSlotView (offline, 1, 0, false);
  18720. view->setSize (view->preferredWidth (206), 206);
  18721. ok = save (*view, "rack-deviceview.png") && ok;
  18722. }
  18723. {
  18724. auto view = lynx::RackWindows::makeSlotView (offline, 1, 0, true);
  18725. view->setMapMode (true);
  18726. view->setSize (view->preferredWidth (228), 228);
  18727. ok = save (*view, "rack-mapmode.png") && ok;
  18728. }
  18729. {
  18730. auto view = lynx::RackWindows::makeChannelView (offline, channel, true);
  18731. view->setSize (view->preferredWidth (228), 228);
  18732. ok = save (*view, "rack-instrument.png") && ok;
  18733. }
  18734. return ok;
  18735. }
  18736. void runEq166fShots (const juce::String& folder)
  18737. {
  18738. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  18739. const juce::File out (folder);
  18740. out.createDirectory();
  18741. lynx::AudioEngine offline (false);
  18742. auto save = [&] (juce::Component& editor, const juce::String& name) {
  18743. auto image = lynx::shot::paint (editor, lynx::theme::panel);
  18744. const auto f = lynx::shot::file (out.getChildFile (name));
  18745. f.deleteFile();
  18746. juce::PNGImageFormat png;
  18747. if (auto stream = f.createOutputStream())
  18748. png.writeImageToStream (image, *stream);
  18749. };
  18750. // a song whose demo beat plays into insert 1 (the source) and, for Facet's target, its other half into insert 2
  18751. auto songWith = [] (const lynx::EffectSlot& fx, bool split) {
  18752. auto song = lynx::Song::makeDefault();
  18753. song.mixer.resize (3);
  18754. song.mixer[0].name = "Master";
  18755. song.mixer[1].name = "Vocal";
  18756. song.mixer[2].name = "Reference mix";
  18757. song.mixer[1].effects.assign (1, fx);
  18758. for (std::size_t c = 0; c < song.channels.size(); ++c)
  18759. song.channels[c].mixerTrack = split && c % 2 == 1 ? 2 : 1;
  18760. return song;
  18761. };
  18762. auto feed = [&] (juce::Component& editor, bool facet, int frames) {
  18763. // one continuous render of the song, the editor ticked 30 times a second of audio, as its timer would
  18764. lynx::AudioEngine::RenderOptions o;
  18765. o.seconds = frames / 30.0;
  18766. o.sampleRate = 48000.0;
  18767. o.pluginWarmUp = false;
  18768. int sinceTick = 0;
  18769. o.capture = [&] (const float*, const float*, int n) {
  18770. sinceTick += n;
  18771. if (sinceTick < 1600) return;
  18772. sinceTick = 0;
  18773. if (facet) lynx::tickFacetEqEditor (editor);
  18774. else lynx::tickNativeEffectEditor (editor);
  18775. };
  18776. offline.renderOffline (o);
  18777. if (facet) lynx::tickFacetEqEditor (editor);
  18778. else lynx::tickNativeEffectEditor (editor);
  18779. };
  18780. // Parametric EQ 2: spectrum + heatmap (Full), flat / band 4 +12 dB / band 4 -12 dB, then the Top position
  18781. auto& display = lynx::peqview::displaySettings();
  18782. const auto kept = display;
  18783. display.spectrum = display.heatmap = true;
  18784. display.position = 0;
  18785. 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" },
  18786. { 0.0, "peq2-heatmap-top.png" } })
  18787. {
  18788. auto eq = lynx::makeEffectSlot (lynx::EffectKind::parametricEq);
  18789. eq.params[(std::size_t) lynx::peq::param (3, 2)] = lynx::peq::gainValue (gain);
  18790. eq.params[(std::size_t) lynx::peq::param (3, 1)] = lynx::peq::hzValue (900.0);
  18791. display.position = juce::String (name).contains ("top") ? 1 : 0;
  18792. offline.setSong (songWith (eq, false));
  18793. offline.dispatchPendingMessages();
  18794. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.25f, 0);
  18795. feed (*editor, false, 120);
  18796. save (*editor, name);
  18797. }
  18798. display = kept;
  18799. // Facet EQ's comparative EQ: listening to the target (insert 2) with its spectrum over the source's
  18800. {
  18801. using namespace lynx::facet;
  18802. auto eq = lynx::makeEffectSlot (lynx::EffectKind::facetEq);
  18803. eq.params[(std::size_t) param (0, 0)] = shapeValue (Shape::bell);
  18804. eq.params[(std::size_t) param (0, 1)] = hzValue (250.0);
  18805. eq.params[(std::size_t) param (0, 2)] = gainValue (-4.0);
  18806. eq.params[(std::size_t) param (1, 0)] = shapeValue (Shape::highShelf);
  18807. eq.params[(std::size_t) param (1, 1)] = hzValue (6000.0);
  18808. eq.params[(std::size_t) param (1, 2)] = gainValue (3.0);
  18809. eq.params[(std::size_t) analyzerParam] = analyzerValue (Analyzer::both);
  18810. eq.sidechain = 2;
  18811. for (const auto& [l, name] : { std::pair { Listen::target, "facet-compare-target.png" }, { Listen::eq, "facet-compare-eq.png" } })
  18812. {
  18813. eq.params[(std::size_t) listenParam] = listenValue (l);
  18814. offline.setSong (songWith (eq, true));
  18815. offline.dispatchPendingMessages();
  18816. auto editor = lynx::makeFacetEqEditor (offline, 1, 0, false);
  18817. feed (*editor, true, 90);
  18818. save (*editor, name);
  18819. }
  18820. }
  18821. }
  18822. void runDesign168rShots (const juce::String& folder)
  18823. {
  18824. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  18825. const juce::File out (folder);
  18826. out.createDirectory();
  18827. lynx::AudioEngine offline (false);
  18828. using K = lynx::EffectKind;
  18829. for (const auto kind : { K::pitchCorrect, K::lovePhilter, K::peakController, K::spreader, K::fruityFastLP, K::flFrequencyShifter,
  18830. K::flLowLifter, K::distructor, K::flBassBoost, K::flDelay1, K::fl7BandEq, K::flCenter, K::flPhaseInverter,
  18831. K::eq, K::delay, K::reverb, K::limiter, K::filter, K::distortion, K::chorus, K::utility, K::lofi,
  18832. K::crossover, K::pitchShift, K::freqShift, K::rhythmGain, K::volumeGate })
  18833. {
  18834. const auto& bank = lynx::presets::factory (kind);
  18835. // Love Philter / Distructor play FL's state: their second picture is FL's default preset (when installed)
  18836. std::optional<lynx::EffectSlot> flPreset;
  18837. if (kind == K::lovePhilter || kind == K::distructor)
  18838. {
  18839. const auto roots = lynx::findFlStudioRoots();
  18840. const auto file = juce::File (juce::String::fromUTF8 (roots.data.c_str()))
  18841. .getChildFile ("Patches/Plugin presets/Effects")
  18842. .getChildFile (kind == K::lovePhilter ? "Fruity Love Philter/Default.fst" : "Distructor/Default.fst");
  18843. juce::MemoryBlock bytes;
  18844. if (file.loadFileAsData (bytes))
  18845. flPreset = lynx::effectFromFlPreset (std::vector<std::uint8_t> ((const std::uint8_t*) bytes.getData(),
  18846. (const std::uint8_t*) bytes.getData() + bytes.getSize()));
  18847. }
  18848. for (int pass = 0; pass < (bank.empty() && ! flPreset ? 1 : 2); ++pass)
  18849. {
  18850. auto fx = lynx::makeEffectSlot (kind);
  18851. if (pass == 1 && flPreset)
  18852. fx = *flPreset;
  18853. else if (pass == 1)
  18854. {
  18855. fx.params = lynx::presets::apply (kind, bank.front(), 120.0);
  18856. fx.presetName = bank.front().name;
  18857. }
  18858. lynx::Song song;
  18859. song.mixer.resize (2);
  18860. song.mixer[0].name = "Master";
  18861. song.mixer[1].name = "Insert 1";
  18862. song.mixer[1].effects.push_back (fx);
  18863. offline.setSong (std::move (song));
  18864. offline.dispatchPendingMessages();
  18865. const auto pages = juce::jmax (1, (int) lynx::plugui::layoutFor (kind).pages.size());
  18866. for (const auto scale : { 1.0f, 2.0f })
  18867. for (int page = 0; page < pages; ++page)
  18868. {
  18869. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, scale, page);
  18870. if (editor == nullptr)
  18871. continue;
  18872. juce::Image image (juce::Image::ARGB, juce::jmax (1, editor->getWidth()), juce::jmax (1, editor->getHeight()), true);
  18873. {
  18874. juce::Graphics g (image);
  18875. g.fillAll (lynx::theme::panel);
  18876. editor->paintEntireComponent (g, false);
  18877. }
  18878. // (FL's "Frequency Shifter" and LYNX's "Frequency shifter" differ only in case: FL editors get "FL ")
  18879. const auto file = out.getChildFile ((lynx::plugui::hasFlLayout (kind) ? "FL " : "")
  18880. + juce::String (lynx::effectInfo (kind).name).replaceCharacters ("/\\:", "---")
  18881. + (pass == 1 ? "-preset" : "") + (page > 0 ? "-p" + juce::String (page + 1) : juce::String())
  18882. + (scale > 1.5f ? "-200" : "-100") + ".png");
  18883. file.deleteFile();
  18884. juce::PNGImageFormat png;
  18885. if (auto stream = file.createOutputStream())
  18886. png.writeImageToStream (image, *stream);
  18887. }
  18888. }
  18889. }
  18890. }
  18891. bool runInstrumentShots (const juce::File& folder, const juce::String& which, const juce::String& source)
  18892. {
  18893. folder.createDirectory();
  18894. auto key = [] (juce::String n) { return n.toLowerCase().removeCharacters (" -!._"); };
  18895. juce::StringArray wanted;
  18896. wanted.addTokens (which, ",", "");
  18897. auto ok = true;
  18898. struct Shot
  18899. {
  18900. juce::String name;
  18901. std::optional<lynx::ChannelDef> channel;
  18902. };
  18903. std::vector<Shot> shots;
  18904. for (const auto& e : lynx::natives::instrumentEngines())
  18905. {
  18906. const auto name = key (e.name);
  18907. const auto banked = which == "banks" && lynx::banks::hasBank (e.kind);
  18908. if (! banked && ! wanted.contains (name))
  18909. continue;
  18910. auto channel = source == "fl" || source == "flm" ? lynx::natives::makeChannel (e.kind, lynx::flStudioAccess())
  18911. : lynx::banks::defaultChannel (e.kind, e.name);
  18912. // (round 190u) source "flm": the channel as the .flm import makes it (Transistor Bass: FL Studio Mobile's build)
  18913. if (source == "flm" && channel && e.kind == lynx::InstrumentKind::transistorbass)
  18914. {
  18915. 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
  18916. channel->modelParams = { 1.0f };
  18917. channel->samplePath.clear();
  18918. }
  18919. if (! channel)
  18920. {
  18921. std::fprintf (stderr, "%s: no %s channel\n", e.name, source.toRawUTF8());
  18922. ok = false;
  18923. continue;
  18924. }
  18925. shots.push_back ({ name, std::move (channel) });
  18926. }
  18927. // Autogun (round 169h): not in the Add menus (no preset files); FL's own render-test channel, either source
  18928. if (wanted.contains ("autogun"))
  18929. {
  18930. if (auto channel = lynx::natives::autogunShotChannel (lynx::flStudioAccess()))
  18931. shots.push_back ({ "autogun", std::move (channel) });
  18932. else
  18933. {
  18934. std::fprintf (stderr, "Autogun: no channel (FL Studio's Render tests\\Autogun.flp)\n");
  18935. ok = false;
  18936. }
  18937. }
  18938. for (auto& shot : shots)
  18939. {
  18940. const auto& name = shot.name;
  18941. auto& channel = shot.channel;
  18942. lynx::AudioEngine offline (false);
  18943. lynx::Song song;
  18944. song.mixer = lynx::Song::defaultMixer (2);
  18945. song.channels.push_back (*channel);
  18946. song.patterns.emplace_back();
  18947. {
  18948. juce::String error; // the project too, so an older build can picture the same channel (--snapshot)
  18949. lynx::ProjectFile::save (song, folder.getChildFile (name + "-" + source + ".lynx"), error);
  18950. }
  18951. offline.setSong (std::move (song));
  18952. offline.dispatchPendingMessages();
  18953. auto frame = lynx::makeChannelFrame (offline, 0, 0);
  18954. if (frame == nullptr || frame->getWidth() <= 0)
  18955. {
  18956. ok = false;
  18957. continue;
  18958. }
  18959. for (const auto scale : { 1.0f, 1.5f, 2.0f })
  18960. {
  18961. const auto file = folder.getChildFile (name + "-" + source + "-" + juce::String (juce::roundToInt (scale * 100)) + ".png");
  18962. savePng (frame->createComponentSnapshot (frame->getLocalBounds(), true, scale), file.getFullPathName());
  18963. std::printf ("%s %dx%d\n", file.getFullPathName().toRawUTF8(), frame->getWidth(), frame->getHeight());
  18964. }
  18965. // round 169h: the layout's other pages (Toxic's MIDI / Seq …), one shot each at 1.5×
  18966. for (int page = 1; page < lynx::showChannelLayoutPage (*frame, -1); ++page)
  18967. {
  18968. lynx::showChannelLayoutPage (*frame, page);
  18969. const auto file = folder.getChildFile (name + "-" + source + "-page" + juce::String (page) + "-150.png");
  18970. savePng (frame->createComponentSnapshot (frame->getLocalBounds(), true, 1.5f), file.getFullPathName());
  18971. std::printf ("%s\n", file.getFullPathName().toRawUTF8());
  18972. }
  18973. }
  18974. return ok;
  18975. }
  18976. // --- round 170j: the pilot editors with their own art -------------------------------------------------
  18977. struct ArtPilot
  18978. {
  18979. std::string file; // the art's name as a file name: "toxic-biohazard"
  18980. bool instrument;
  18981. lynx::InstrumentKind instrumentKind;
  18982. lynx::EffectKind effectKind;
  18983. lynx::skin::Style before; // the automatic style it had before the Themed style
  18984. };
  18985. static juce::StringArray& artOnly() // --artshot / --artgui: only these (file names), all when empty
  18986. {
  18987. static juce::StringArray only;
  18988. return only;
  18989. }
  18990. // every plugin with art of its own (round 170j/170k): generators first, then effects; built from the art
  18991. // registries, so a new theme is shot without touching this list
  18992. static const std::vector<ArtPilot>& artPilots()
  18993. {
  18994. using I = lynx::InstrumentKind;
  18995. using E = lynx::EffectKind;
  18996. static const std::vector<ArtPilot> list = [] {
  18997. std::vector<ArtPilot> all;
  18998. auto slug = [] (lynx::skin::Art a) {
  18999. return juce::String (lynx::skin::artName (a)).toLowerCase().replaceCharacters (" ", "-").removeCharacters ("!.()'").toStdString();
  19000. };
  19001. for (const auto& e : lynx::natives::instrumentEngines()) // (the engines' order first)
  19002. if (const auto a = lynx::skin::artForInstrument (e.kind); a != lynx::skin::Art::none)
  19003. all.push_back ({ slug (a), true, e.kind, E::reverb, lynx::skin::Style::neon });
  19004. for (int k = 0; k <= (int) I::wavetraveller; ++k) // then every other kind with art (DrumSynth, Autogun, Wasp...)
  19005. if (const auto a = lynx::skin::artForInstrument ((I) k); a != lynx::skin::Art::none)
  19006. all.push_back ({ slug (a), true, (I) k, E::reverb, lynx::skin::Style::neon });
  19007. for (int k = 0; k <= (int) lynx::lastEffectKind; ++k)
  19008. if (const auto a = lynx::skin::artForEffect ((E) k); a != lynx::skin::Art::none)
  19009. all.push_back ({ slug (a), false, I::synth, (E) k, lynx::skin::plainStyleFor (k) });
  19010. std::vector<ArtPilot> kept;
  19011. for (auto& p : all)
  19012. if (artOnly().isEmpty() || artOnly().contains (juce::String (p.file)))
  19013. if (std::none_of (kept.begin(), kept.end(), [&] (const ArtPilot& q) { return q.file == p.file; }))
  19014. kept.push_back (p);
  19015. return kept;
  19016. }();
  19017. return list;
  19018. }
  19019. // the song and the editor of a pilot (an instrument: the channel window on its Plugin tab)
  19020. static std::unique_ptr<juce::Component> makeArtPilot (lynx::AudioEngine& engine, const ArtPilot& p)
  19021. {
  19022. lynx::Song song;
  19023. song.mixer = lynx::Song::defaultMixer (2);
  19024. if (p.instrument)
  19025. {
  19026. for (const auto& e : lynx::natives::instrumentEngines())
  19027. if (e.kind == p.instrumentKind)
  19028. {
  19029. auto channel = lynx::natives::makeChannel (e.kind, lynx::flStudioAccess());
  19030. if (! channel) channel = lynx::banks::defaultChannel (e.kind, e.name);
  19031. if (! channel) return nullptr;
  19032. song.channels.push_back (*channel);
  19033. break;
  19034. }
  19035. if (song.channels.empty()) // a kind without an engine entry: its LYNX default, else an empty channel of that kind
  19036. {
  19037. const std::string name = lynx::skin::artName (lynx::skin::artForInstrument (p.instrumentKind));
  19038. auto channel = lynx::banks::defaultChannel (p.instrumentKind, name);
  19039. if (! channel)
  19040. {
  19041. channel = lynx::ChannelDef {};
  19042. channel->instrument = p.instrumentKind;
  19043. channel->name = name;
  19044. }
  19045. song.channels.push_back (*channel);
  19046. }
  19047. song.patterns.emplace_back();
  19048. }
  19049. else
  19050. {
  19051. song.mixer[1].effects.push_back (lynx::makeEffectSlot (p.effectKind));
  19052. }
  19053. engine.setSong (std::move (song));
  19054. engine.dispatchPendingMessages();
  19055. if (p.instrument) return lynx::makeChannelFrame (engine, 0, 0);
  19056. if (p.effectKind == lynx::EffectKind::facetEq) return lynx::makeFacetEqEditor (engine, 1, 0, true);
  19057. if (lynx::ProEditorWindows::handles (p.effectKind)) return lynx::makeProEditor (engine, 1, 0, true); // display-first editors, demo signal
  19058. return lynx::makeNativeEffectEditor (engine, 1, 0, 1.0f, 0);
  19059. }
  19060. // "before": the style each pilot had (forced for its run); "after": automatic (the pilots are Themed)
  19061. static void artPilotStyle (const ArtPilot& p, const juce::String& mode)
  19062. {
  19063. lynx::skin::setForcedStyle (mode == "before" ? (int) p.before : -1);
  19064. lynx::skin::setArtMotion (mode != "still");
  19065. }
  19066. bool runArtShots (const juce::File& folder, bool before)
  19067. {
  19068. folder.createDirectory();
  19069. auto ok = true;
  19070. juce::String titles ("editor\tsize\twidth\tname width at the style's size\tbox\tsize used\tlines\tresult\n");
  19071. for (const auto& p : artPilots())
  19072. {
  19073. artPilotStyle (p, before ? "before" : "after");
  19074. lynx::AudioEngine offline (false);
  19075. auto editor = makeArtPilot (offline, p);
  19076. if (editor == nullptr || editor->getWidth() <= 0)
  19077. {
  19078. std::fprintf (stderr, "%s: no editor\n", p.file.c_str());
  19079. ok = false;
  19080. continue;
  19081. }
  19082. if (p.effectKind == lynx::EffectKind::facetEq) lynx::tickFacetEqEditor (*editor);
  19083. // round 170k2: titles.tsv, how the header's name fitted (its width at the style's size, the box, the size used)
  19084. auto fit = [&] (const juce::String& at) {
  19085. const auto f = lynx::skin::lastTitleFit();
  19086. if (f.have <= 0.0f) return; // no plugin header drawn (a generator's channel window)
  19087. titles << juce::String (p.file) << "\t" << at << "\t" << editor->getWidth() << "\t" << juce::String (f.need, 1) << "\t" << juce::String (f.have, 1)
  19088. << "\t" << juce::String (f.size, 1) << "\t" << f.lines << "\t" << (f.clipped ? "ELLIPSIS" : "full") << "\n";
  19089. };
  19090. for (const auto scale : { 1.0f, 2.0f })
  19091. {
  19092. const auto file = folder.getChildFile (juce::String (p.file) + "-" + (before ? "before" : "after") + "-" + juce::String (juce::roundToInt (scale * 100)) + ".png");
  19093. lynx::skin::resetTitleFit();
  19094. savePng (editor->createComponentSnapshot (editor->getLocalBounds(), true, scale), file.getFullPathName());
  19095. std::printf ("%s %dx%d\n", file.getFullPathName().toRawUTF8(), editor->getWidth(), editor->getHeight());
  19096. if (scale == 1.0f) fit ("100");
  19097. }
  19098. // ... and at the smallest size its window allows (effect panels; the Pro editors scale as a whole)
  19099. if (const auto smallest = lynx::nativeEditorMinimumSize (*editor); smallest.x > 0)
  19100. {
  19101. editor->setSize (smallest.x, smallest.y);
  19102. const auto file = folder.getChildFile (juce::String (p.file) + "-" + (before ? "before" : "after") + "-min.png");
  19103. lynx::skin::resetTitleFit();
  19104. savePng (lynx::shot::snapshot (*editor), file.getFullPathName());
  19105. fit ("min");
  19106. }
  19107. }
  19108. folder.getChildFile (juce::String ("titles-") + (before ? "before" : "after") + ".tsv").replaceWithText (titles);
  19109. lynx::skin::setForcedStyle (-1);
  19110. return ok;
  19111. }
  19112. struct ArtGuiRun final : juce::Timer
  19113. {
  19114. juce::File folder;
  19115. juce::String mode, report;
  19116. std::size_t at = 0;
  19117. int phase = 0;
  19118. double t0 = 0.0, c0 = 0.0;
  19119. std::unique_ptr<lynx::AudioEngine> engine;
  19120. std::unique_ptr<juce::DocumentWindow> window;
  19121. std::function<void()> done;
  19122. void start()
  19123. {
  19124. engine = std::make_unique<lynx::AudioEngine> (false);
  19125. report << "editor\tmode\tcpu % of one core\tart layer animating\n";
  19126. open();
  19127. startTimer (100);
  19128. }
  19129. void open()
  19130. {
  19131. window.reset();
  19132. const auto& pilots = artPilots();
  19133. if (at >= pilots.size())
  19134. {
  19135. folder.getChildFile ("cpu-" + mode + ".txt").replaceWithText (report);
  19136. stopTimer();
  19137. lynx::skin::setForcedStyle (-1);
  19138. lynx::skin::setArtMotion (true);
  19139. if (done) done();
  19140. return;
  19141. }
  19142. const auto& p = pilots[at];
  19143. artPilotStyle (p, mode);
  19144. auto editor = makeArtPilot (*engine, p);
  19145. if (editor == nullptr) { ++at; open(); return; }
  19146. window = std::make_unique<juce::DocumentWindow> (juce::String ("LYNX art - ") + juce::String (p.file), lynx::theme::colour::bg1, 0);
  19147. window->setUsingNativeTitleBar (true);
  19148. window->setContentOwned (editor.release(), true);
  19149. const auto area = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea;
  19150. window->setTopLeftPosition (area.getX() + 24, area.getY() + 24);
  19151. window->setAlwaysOnTop (true);
  19152. window->setVisible (true);
  19153. phase = 0;
  19154. t0 = juce::Time::getMillisecondCounterHiRes();
  19155. }
  19156. bool animating() const
  19157. {
  19158. if (window == nullptr || window->getContentComponent() == nullptr) return false;
  19159. std::function<bool (juce::Component&)> find = [&] (juce::Component& c) {
  19160. if (auto* l = dynamic_cast<lynx::skin::ArtLayer*> (&c); l != nullptr && l->animating()) return true;
  19161. for (auto* child : c.getChildren())
  19162. if (find (*child)) return true;
  19163. return false;
  19164. };
  19165. return find (*window->getContentComponent());
  19166. }
  19167. void timerCallback() override
  19168. {
  19169. const auto now = juce::Time::getMillisecondCounterHiRes();
  19170. const auto& p = artPilots()[at];
  19171. const auto ready = folder.getChildFile (juce::String (p.file) + "-" + mode + ".ready");
  19172. const auto shotDone = folder.getChildFile (juce::String (p.file) + "-" + mode + ".done");
  19173. if (phase == 0 && now - t0 > 1500.0)
  19174. {
  19175. // the window's content on screen, in physical pixels, for the outside screenshot to crop
  19176. auto* c = window->getContentComponent();
  19177. const auto scale = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->scale;
  19178. const auto b = c->getScreenBounds();
  19179. shotDone.deleteFile();
  19180. ready.replaceWithText (juce::String (juce::roundToInt (b.getX() * scale)) + " " + juce::String (juce::roundToInt (b.getY() * scale)) + " "
  19181. + juce::String (juce::roundToInt (b.getWidth() * scale)) + " " + juce::String (juce::roundToInt (b.getHeight() * scale)));
  19182. phase = 1;
  19183. t0 = now;
  19184. return;
  19185. }
  19186. if (phase == 1 && (shotDone.existsAsFile() || now - t0 > 10000.0))
  19187. {
  19188. ready.deleteFile();
  19189. shotDone.deleteFile();
  19190. phase = 2;
  19191. t0 = now;
  19192. c0 = lynx::processCpuSeconds();
  19193. return;
  19194. }
  19195. if (phase == 2 && now - t0 > 6000.0)
  19196. {
  19197. const auto cpu = (lynx::processCpuSeconds() - c0) / ((now - t0) * 0.001) * 100.0;
  19198. report << juce::String (p.file) << "\t" << mode << "\t" << juce::String (cpu, 2) << "\t" << (animating() ? "yes" : "no") << "\n";
  19199. ++at;
  19200. open();
  19201. }
  19202. }
  19203. };
  19204. std::unique_ptr<ArtGuiRun> artGui;
  19205. void runArtGui (const juce::File& folder, const juce::String& mode)
  19206. {
  19207. folder.createDirectory();
  19208. artGui = std::make_unique<ArtGuiRun>();
  19209. artGui->folder = folder;
  19210. artGui->mode = mode;
  19211. artGui->done = [this] { juce::MessageManager::callAsync ([this] { artGui.reset(); quit(); }); };
  19212. artGui->start();
  19213. }
  19214. void runDesign190inShot (const juce::String& prefix, const juce::String& project)
  19215. {
  19216. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  19217. juce::String report;
  19218. {
  19219. lynx::AudioEngine engine (false);
  19220. juce::String error;
  19221. if (const juce::File input (project); input.existsAsFile() && input.hasFileExtension ("flp"))
  19222. report << "import: " << (engine.importFlpFile (input, error) ? "ok" : "failed " + error) << "\n";
  19223. engine.dispatchPendingMessages();
  19224. // a native FL generator with FL's presets (FL's capture: FLEX's "Piano Dark"), on a mixer track of its own
  19225. const auto& fl = lynx::flStudioAccess();
  19226. auto osc = lynx::natives::makeChannel (lynx::InstrumentKind::threeosc, fl);
  19227. int generator = -1, sampler = -1;
  19228. engine.editSong ([&] (lynx::Song& s) {
  19229. if (osc)
  19230. {
  19231. osc->mixerTrack = s.claimFreeInsert();
  19232. s.channels.push_back (*osc);
  19233. generator = (int) s.channels.size() - 1;
  19234. }
  19235. if (const juce::File kick (juce::String::fromUTF8 (fl.roots.data.c_str()) + "/Patches/Packs/Drums/Kicks/808 Kick.wav"); kick.existsAsFile())
  19236. {
  19237. lynx::ChannelDef d; // FL's Sampler with a kick, as FL's default channel (the Sample, Envelope and Misc tabs)
  19238. d.instrument = lynx::InstrumentKind::sampler;
  19239. lynx::audioclips::loadSampleInto (d, kick.getFullPathName().toStdString(), "808 Kick");
  19240. d.mixerTrack = s.claimFreeInsert();
  19241. s.channels.push_back (d);
  19242. sampler = (int) s.channels.size() - 1;
  19243. }
  19244. for (const auto withSample : { true, false }) // (a sampler with its sample first, else any)
  19245. for (int c = 0; c < (int) s.channels.size() && sampler < 0; ++c)
  19246. if (s.channels[(std::size_t) c].instrument == lynx::InstrumentKind::sampler && (! withSample || ! s.channels[(std::size_t) c].samplePath.empty()))
  19247. sampler = c;
  19248. });
  19249. engine.dispatchPendingMessages();
  19250. lynx::MainComponent ui (engine, false); // (sets the Channel rack's wrapper-menu items)
  19251. ui.setSize (1920, 1080);
  19252. report << "generator " << generator << ", sampler " << sampler << "\n";
  19253. auto shoot = [&] (juce::Component& c, const juce::String& name) {
  19254. savePng (lynx::shot::snapshot (c), prefix + name);
  19255. report << name << " " << c.getWidth() << "x" << c.getHeight() << "\n";
  19256. };
  19257. auto window = [&] (int channel, int tab, const juce::String& name) {
  19258. if (channel < 0)
  19259. return;
  19260. if (auto w = lynx::makeChannelWindowForShot (engine, channel, tab))
  19261. shoot (*w, name);
  19262. };
  19263. window (generator, 0, "-cw-plugin.png");
  19264. window (generator, -1, "-cw-plugin-misc.png");
  19265. window (sampler, 0, "-cw-sample.png");
  19266. window (sampler, 1, "-cw-envelope.png");
  19267. window (sampler, -1, "-cw-misc.png");
  19268. // the strip of a window with the system's title bar (docking off): ▸ and the presets stay in it
  19269. if (generator >= 0)
  19270. if (auto frame = lynx::makeChannelFrame (engine, generator, 0))
  19271. {
  19272. shoot (*frame, "-frame-floating.png");
  19273. if (auto menu = lynx::channelWrapperMenu (*frame))
  19274. {
  19275. // FL's two columns: the plugin's items, then the Channel column (split at the column break)
  19276. juce::PopupMenu left, right;
  19277. auto* to = &left;
  19278. for (juce::PopupMenu::MenuItemIterator it (*menu); it.next();)
  19279. {
  19280. to->addItem (it.getItem());
  19281. if (it.getItem().shouldBreakAfter)
  19282. to = &right;
  19283. }
  19284. saveMenus (juce::StringArray { "Plugin", "Channel" }, std::vector<juce::PopupMenu> { left, right }, prefix + "-menu-channel.png");
  19285. report << "menu items " << left.getNumItems() << " + " << right.getNumItems() << "\n";
  19286. }
  19287. }
  19288. }
  19289. {
  19290. // FW-8: LYNX engines standing in for FL plugins of an imported project (the import's flOrigin) are titled
  19291. // with FL's name; LYNX's own Delay (no FL origin) keeps its own
  19292. lynx::AudioEngine offline (false);
  19293. lynx::Song song;
  19294. song.mixer.resize (2);
  19295. song.mixer[0].name = "Master";
  19296. song.mixer[1].name = "Insert 1";
  19297. const std::vector<std::pair<lynx::EffectKind, const char*>> standIns { { lynx::EffectKind::limiter, "Fruity Limiter" },
  19298. { lynx::EffectKind::utility, "Fruity Stereo Shaper" }, { lynx::EffectKind::delay, "Fruity Delay 3" },
  19299. { lynx::EffectKind::reverb, "Fruity Reeverb 2" }, { lynx::EffectKind::delay, "" } };
  19300. for (const auto& [kind, origin] : standIns)
  19301. {
  19302. auto fx = lynx::makeEffectSlot (kind);
  19303. fx.flOrigin.plugin = origin;
  19304. song.mixer[1].effects.push_back (fx);
  19305. }
  19306. offline.setSong (std::move (song));
  19307. offline.dispatchPendingMessages();
  19308. std::vector<juce::Image> strips;
  19309. int width = 0, height = 0;
  19310. for (int k = 0; k < (int) standIns.size(); ++k)
  19311. if (auto editor = lynx::makeNativeEffectEditor (offline, 1, k, 1.0f, 0))
  19312. {
  19313. auto image = lynx::shot::paint (*editor, lynx::theme::panel); // (as --plugui draws the editors)
  19314. const auto h = juce::jmin (image.getHeight(), (int) std::ceil (30.0f * lynx::shot::scale()));
  19315. juce::Image strip (juce::Image::ARGB, image.getWidth(), h, true);
  19316. juce::Graphics (strip).drawImageAt (image, 0, 0);
  19317. strips.push_back (strip);
  19318. width = juce::jmax (width, image.getWidth());
  19319. height += h + 4;
  19320. }
  19321. if (! strips.empty())
  19322. {
  19323. juce::Image all (juce::Image::RGB, width, height, true);
  19324. {
  19325. juce::Graphics g (all); // (flushed when it goes: a native image's context draws on its release)
  19326. g.fillAll (juce::Colours::black);
  19327. int y = 0;
  19328. for (auto& strip : strips)
  19329. {
  19330. g.drawImageAt (strip, 0, y);
  19331. y += strip.getHeight() + 4;
  19332. }
  19333. }
  19334. savePng (all, prefix + "-names.png");
  19335. report << "names " << (int) strips.size() << "\n";
  19336. }
  19337. }
  19338. juce::File (prefix + "-report.txt").replaceWithText (report);
  19339. }
  19340. void runPluginEditorSnapshots (const juce::String& folder)
  19341. {
  19342. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  19343. {
  19344. const juce::File out (folder);
  19345. out.createDirectory();
  19346. lynx::AudioEngine offline (false);
  19347. const auto roots = lynx::findFlStudioRoots();
  19348. const auto presets = juce::File (juce::String::fromUTF8 (roots.data.c_str())).getChildFile ("Patches/Plugin presets/Effects");
  19349. auto kinds = lynx::plugui::flLayoutKinds();
  19350. kinds.push_back (lynx::EffectKind::maximus); // Soundgoodizer (below)
  19351. for (const auto own : lynx::plugui::ownLayoutKinds()) // LYNX's own panels (mixing suite, round 96)
  19352. kinds.push_back (own);
  19353. kinds.push_back (lynx::EffectKind::apexLimiter); // round 114: display-first editor
  19354. kinds.push_back (lynx::EffectKind::ridgeStrip); // round 145: the second pass shows the Vocal strip voicing
  19355. kinds.push_back (lynx::EffectKind::ridgeStrip); // round 165: the third pass shows the E console voicing
  19356. kinds.push_back (lynx::EffectKind::compressor); // round 152: the RComp role's panel (vintage voicing, RComp ranges)
  19357. const auto database = juce::File (juce::String::fromUTF8 (roots.data.c_str())).getChildFile ("Patches/Plugin database/Effects");
  19358. auto maximusPasses = 0; // Maximus has its own page (first pass); the second pass shows Soundgoodizer
  19359. auto ridgePasses = 0;
  19360. // round 173d3: the parity pictures of one editor — LYNX_PLUGUI_ONLY=<effect name>, LYNX_PLUGUI_PRESET=<.fst>,
  19361. // LYNX_PLUGUI_PAGES=<page,page,…> (the page numbers as the editor encodes them)
  19362. const auto only = juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGUI_ONLY", {});
  19363. const auto onlyPreset = juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGUI_PRESET", {});
  19364. const auto onlyPages = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGUI_PAGES", {}), ",", "");
  19365. for (const auto kind : kinds)
  19366. {
  19367. if (only.isNotEmpty() && only != lynx::effectInfo (kind).name)
  19368. continue;
  19369. auto fx = lynx::makeEffectSlot (kind);
  19370. juce::String name (lynx::effectInfo (kind).name);
  19371. for (const auto& plugin : lynx::flPluginsForEffect (kind))
  19372. {
  19373. const auto dir = presets.getChildFile (juce::String::fromUTF8 (plugin.c_str()));
  19374. auto file = dir.getChildFile ("Default.fst");
  19375. if (! file.existsAsFile()) // plugins without presets: their entry of FL's plugin database
  19376. for (const auto& f : database.findChildFiles (juce::File::findFiles, true, juce::String::fromUTF8 (plugin.c_str()) + ".fst"))
  19377. file = f;
  19378. if (only.isNotEmpty() && onlyPreset.isNotEmpty())
  19379. file = juce::File (onlyPreset);
  19380. if (! file.existsAsFile())
  19381. {
  19382. auto files = dir.findChildFiles (juce::File::findFiles, true, "*.fst");
  19383. std::sort (files.begin(), files.end(), [] (const juce::File& a, const juce::File& b) { return a.getFullPathName().compareNatural (b.getFullPathName()) < 0; });
  19384. file = files.isEmpty() ? juce::File() : files[0];
  19385. }
  19386. juce::MemoryBlock data;
  19387. if (file.existsAsFile() && file.loadFileAsData (data))
  19388. {
  19389. const auto* bytes = static_cast<const std::uint8_t*> (data.getData());
  19390. 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)
  19391. {
  19392. fx = *loaded;
  19393. // round 190in (FW-8): a LYNX engine loaded with an FL plugin's preset stands in for that
  19394. // plugin as an imported slot does (its header shows FL's name)
  19395. if (fx.flOrigin.empty() && ! lynx::plugui::hasFlLayout (kind))
  19396. fx.flOrigin.plugin = plugin;
  19397. }
  19398. }
  19399. name = juce::String::fromUTF8 (plugin.c_str());
  19400. break;
  19401. }
  19402. if (kind == lynx::EffectKind::maximus && ++maximusPasses == 2) // Soundgoodizer: preset A of the installation, Amount 60 %
  19403. {
  19404. juce::MemoryBlock data;
  19405. juce::File (juce::String::fromUTF8 (roots.factoryData.c_str())).getChildFile ("Plugins/Fruity/Effects/Soundgoodizer/Data/Presets/a.dat").loadFileAsData (data);
  19406. lynx::maximusfx::Blob blob;
  19407. blob.build = lynx::hlfx::MaximusBuild::soundgoodizer;
  19408. blob.mix = 600;
  19409. const auto* b = static_cast<const std::uint8_t*> (data.getData());
  19410. blob.state.assign (b, b + data.getSize());
  19411. fx = lynx::makeEffectSlot (kind);
  19412. fx.state = lynx::maximusfx::pack (blob);
  19413. name = "Soundgoodizer";
  19414. }
  19415. if (kind == lynx::EffectKind::ridgeStrip && ++ridgePasses == 2) // round 145: her Vocalstrip 2 setting
  19416. {
  19417. for (const auto& [param, value] : { std::pair<const char*, float> { "Vocal strip", 1.0f }, { "Compander", 1.0f },
  19418. { "Compander threshold", 0.3083f }, { "Compander ratio", 0.6929f }, { "Compander attack", 0.2543f },
  19419. { "Compander release", 0.5316f }, { "Make-up", 0.2917f }, { "Soft knee", 1.0f },
  19420. { "Expander threshold", 0.2198f }, { "Vocal input", 0.6792f }, { "Vocal output", 0.3938f },
  19421. { "Process order", 0.4783f }, { "De-esser", 1.0f } })
  19422. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, param)] = value;
  19423. name = "Ridge Strip (Vocal strip)";
  19424. }
  19425. else if (kind == lynx::EffectKind::ridgeStrip && ridgePasses == 3) // round 165: the E console, EQ to the side chain
  19426. {
  19427. for (const auto& [param, value] : { std::pair<const char*, float> { "Voicing", 1.0f }, { "HPF", 0.3f }, { "HF gain", 0.8f },
  19428. { "HF bell", 1.0f }, { "Ratio", 0.5f }, { "Comp. threshold", 0.4f }, { "EQ to SC", 1.0f },
  19429. { "Filter split", 1.0f }, { "Expander", 1.0f } })
  19430. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, param)] = value;
  19431. name = "Ridge Strip (E console)";
  19432. }
  19433. else if (kind == lynx::EffectKind::ridgeStrip) // a vocal setting, so the graphs show something
  19434. for (const auto& [param, value] : { std::pair<const char*, float> { "HPF", 0.3f }, { "LMF gain", 0.35f }, { "HF gain", 0.7f },
  19435. { "Ratio", 0.3f }, { "Comp. threshold", 0.55f } })
  19436. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, param)] = value;
  19437. if (kind == lynx::EffectKind::compressor) // round 152: the vintage voicing with the reference's ranges and meter
  19438. {
  19439. for (const auto& [param, value] : { std::pair<const char*, float> { "Voicing", 1.0f }, { "Ranges", 1.0f }, { "Limiter", 1.0f },
  19440. { "Threshold", 0.6f }, { "RC ratio", 0.4f } })
  19441. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, param)] = value;
  19442. name = "Compressor (RComp role)";
  19443. }
  19444. if (kind == lynx::EffectKind::apexLimiter) // round 114: gain into the ceiling, so the display shows reduction
  19445. fx.params[0] = 0.33f;
  19446. if (kind == lynx::EffectKind::ember)
  19447. {
  19448. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, "Drive")] = 0.5f;
  19449. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, "Bands")] = 1.0f; // round 108: the band rows
  19450. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, "B3 drive")] = 0.6f;
  19451. }
  19452. if (kind == lynx::EffectKind::crestCompressor) // round 108: a curve with a knee and a side-chain low cut
  19453. for (const auto& [param, value] : { std::pair<const char*, float> { "Threshold", 0.55f }, { "Knee", 0.15f },
  19454. { "SC1 shape", 0.5f }, { "SC1 freq.", 0.3f } })
  19455. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, param)] = value;
  19456. lynx::Song song;
  19457. song.mixer.resize (2);
  19458. song.mixer[0].name = "Master";
  19459. song.mixer[1].name = "Insert 1";
  19460. song.mixer[1].effects.push_back (fx);
  19461. offline.setSong (std::move (song));
  19462. offline.dispatchPendingMessages();
  19463. if (lynx::ProEditorWindows::handles (kind)) // round 114: the display-first editors, with a demo signal
  19464. {
  19465. auto editor = lynx::makeProEditor (offline, 1, 0, true);
  19466. auto image = lynx::shot::paint (*editor);
  19467. const auto file = lynx::shot::file (out.getChildFile (name + ".png"));
  19468. file.deleteFile();
  19469. juce::PNGImageFormat png;
  19470. if (auto stream = file.createOutputStream())
  19471. png.writeImageToStream (image, *stream);
  19472. continue;
  19473. }
  19474. const auto pages = name == "Soundgoodizer" ? 1 : juce::jmax (1, (int) lynx::plugui::layoutFor (kind).pages.size());
  19475. std::vector<int> pageList;
  19476. for (int page = 0; page < pages; ++page)
  19477. pageList.push_back (page);
  19478. if (only.isNotEmpty() && ! onlyPages.isEmpty())
  19479. {
  19480. pageList.clear();
  19481. for (const auto& p : onlyPages)
  19482. pageList.push_back (p.getIntValue());
  19483. }
  19484. for (const auto page : pageList)
  19485. {
  19486. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, page);
  19487. auto image = lynx::shot::paint (*editor, lynx::theme::panel);
  19488. const auto file = lynx::shot::file (out.getChildFile (name + (page > 0 ? "-p" + juce::String (page + 1) : juce::String()) + ".png"));
  19489. file.deleteFile();
  19490. juce::PNGImageFormat png;
  19491. if (auto stream = file.createOutputStream())
  19492. png.writeImageToStream (image, *stream);
  19493. }
  19494. }
  19495. // round 137: Echoform in its Rhythm mode (EchoBoy's role) with the Present era
  19496. {
  19497. namespace ef = lynx::echosuite::echoform;
  19498. auto fx = lynx::makeEffectSlot (lynx::EffectKind::echoform);
  19499. fx.params[ef::rhythm] = 1.0f;
  19500. fx.params[ef::rhythmRepeats] = 5.0f / 15.0f;
  19501. fx.params[ef::rhythmDecay] = 0.25f;
  19502. fx.params[ef::rhythmTap1 + 2] = 0.45f;
  19503. fx.params[ef::feedback] = 0.25f;
  19504. fx.params[ef::era] = 0.5f;
  19505. for (const auto& [param, value] : ef::rhythmPresetEdits (0)) // round 144: a pattern in the rhythm editor (Grid)
  19506. fx.params[(std::size_t) param] = value;
  19507. fx.params[ef::rhythmShape] = 0.5f; // swell
  19508. lynx::Song song;
  19509. song.mixer.resize (2);
  19510. song.mixer[0].name = "Master";
  19511. song.mixer[1].name = "Insert 1";
  19512. song.mixer[1].effects.push_back (fx);
  19513. offline.setSong (std::move (song));
  19514. offline.dispatchPendingMessages();
  19515. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
  19516. auto image = lynx::shot::paint (*editor, lynx::theme::panel);
  19517. const auto file = lynx::shot::file (out.getChildFile ("Echoform-rhythm.png"));
  19518. file.deleteFile();
  19519. juce::PNGImageFormat png;
  19520. if (auto stream = file.createOutputStream())
  19521. png.writeImageToStream (image, *stream);
  19522. }
  19523. // round 150: Echoform with a voicing (the Stereo / L/R offset controls on the Rhythm row)
  19524. {
  19525. namespace ef = lynx::echosuite::echoform;
  19526. auto fx = lynx::makeEffectSlot (lynx::EffectKind::echoform);
  19527. fx.params[ef::voicing] = ef::voicingValue (ef::voicingForEchoBoyStyle (19));
  19528. fx.params[ef::style] = ef::styleValue (ef::Style::dual);
  19529. lynx::Song song;
  19530. song.mixer.resize (2);
  19531. song.mixer[0].name = "Master";
  19532. song.mixer[1].name = "Insert 1";
  19533. song.mixer[1].effects.push_back (fx);
  19534. offline.setSong (std::move (song));
  19535. offline.dispatchPendingMessages();
  19536. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
  19537. auto image = lynx::shot::paint (*editor, lynx::theme::panel);
  19538. const auto file = lynx::shot::file (out.getChildFile ("Echoform-voicing.png"));
  19539. file.deleteFile();
  19540. juce::PNGImageFormat png;
  19541. if (auto stream = file.createOutputStream())
  19542. png.writeImageToStream (image, *stream);
  19543. }
  19544. // round 150: Auto-pan's Rhythm voicing with its Tweak row (PanMan's role)
  19545. {
  19546. auto fx = lynx::makeEffectSlot (lynx::EffectKind::autoPan);
  19547. fx.params[lynx::autopan::count] = 1.0f; // the Rhythm voicing
  19548. fx.params[lynx::autopan::count + 13] = 0.75f; // offset mod +90°
  19549. lynx::Song song;
  19550. song.mixer.resize (2);
  19551. song.mixer[0].name = "Master";
  19552. song.mixer[1].name = "Insert 1";
  19553. song.mixer[1].effects.push_back (fx);
  19554. offline.setSong (std::move (song));
  19555. offline.dispatchPendingMessages();
  19556. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
  19557. auto image = lynx::shot::paint (*editor, lynx::theme::panel);
  19558. const auto file = lynx::shot::file (out.getChildFile ("Auto-pan-tweak.png"));
  19559. file.deleteFile();
  19560. juce::PNGImageFormat png;
  19561. if (auto stream = file.createOutputStream())
  19562. png.writeImageToStream (image, *stream);
  19563. }
  19564. // round 165: Ember's Classic voicing (the Decapitator role) in its one-screen panel
  19565. {
  19566. namespace em = lynx::mixsuite::ember;
  19567. auto fx = lynx::makeEffectSlot (lynx::EffectKind::ember);
  19568. fx.params[em::voicing] = 1.0f;
  19569. fx.params[em::classicDrive] = 0.35f;
  19570. lynx::Song song;
  19571. song.mixer.resize (2);
  19572. song.mixer[0].name = "Master";
  19573. song.mixer[1].name = "Insert 1";
  19574. song.mixer[1].effects.push_back (fx);
  19575. offline.setSong (std::move (song));
  19576. offline.dispatchPendingMessages();
  19577. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
  19578. auto image = lynx::shot::paint (*editor, lynx::theme::panel);
  19579. const auto file = lynx::shot::file (out.getChildFile ("Ember Saturator-classic.png"));
  19580. file.deleteFile();
  19581. juce::PNGImageFormat png;
  19582. if (auto stream = file.createOutputStream())
  19583. png.writeImageToStream (image, *stream);
  19584. }
  19585. // round 152: Foil Plate's one-knob Plate view (the Little Plate role)
  19586. {
  19587. auto fx = lynx::makeEffectSlot (lynx::EffectKind::foilPlate);
  19588. fx.params[14] = 1.0f; // the measured plate voicing
  19589. fx.params[15] = 1.0f; // View = Plate
  19590. lynx::Song song;
  19591. song.mixer.resize (2);
  19592. song.mixer[0].name = "Master";
  19593. song.mixer[1].name = "Insert 1";
  19594. song.mixer[1].effects.push_back (fx);
  19595. offline.setSong (std::move (song));
  19596. offline.dispatchPendingMessages();
  19597. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
  19598. auto image = lynx::shot::paint (*editor, lynx::theme::panel);
  19599. const auto file = lynx::shot::file (out.getChildFile ("Foil Plate-plate.png"));
  19600. file.deleteFile();
  19601. juce::PNGImageFormat png;
  19602. if (auto stream = file.createOutputStream())
  19603. png.writeImageToStream (image, *stream);
  19604. }
  19605. // LYNX's own editors with live displays (round 103): Facet EQ (a mixing curve, one dynamic band, demo analyser)
  19606. // and LYNX Tune (demo pitch phrase)
  19607. {
  19608. lynx::setNativeEditorDemo (true);
  19609. using namespace lynx::facet;
  19610. auto eq = lynx::makeEffectSlot (lynx::EffectKind::facetEq);
  19611. const struct { Shape s; double f, g, q; int slope; double range; } bandsDemo[] = {
  19612. { Shape::lowCut, 32, 0, 1, 24, 0 }, { Shape::bell, 110, 3, 1.2, 12, 0 }, { Shape::bell, 380, -3.5, 1.6, 12, 0 },
  19613. { Shape::bell, 3200, 0, 2.5, 12, -6 }, { Shape::highShelf, 9000, 2.5, 0.8, 12, 0 }
  19614. };
  19615. for (int b = 0; b < 5; ++b)
  19616. {
  19617. eq.params[(std::size_t) param (b, 0)] = shapeValue (bandsDemo[b].s);
  19618. eq.params[(std::size_t) param (b, 1)] = hzValue (bandsDemo[b].f);
  19619. eq.params[(std::size_t) param (b, 2)] = gainValue (bandsDemo[b].g);
  19620. eq.params[(std::size_t) param (b, 3)] = qValue (bandsDemo[b].q);
  19621. eq.params[(std::size_t) param (b, 4)] = slopeValue (bandsDemo[b].slope);
  19622. eq.params[(std::size_t) (rangeParam0 + b)] = rangeValue (bandsDemo[b].range);
  19623. }
  19624. eq.params[(std::size_t) phaseParam] = phaseValue (Phase::natural);
  19625. const auto own = [&] (const lynx::EffectSlot& fx, const juce::String& file, bool facetEditor, int page = 0) {
  19626. lynx::Song song;
  19627. song.mixer.resize (2);
  19628. song.mixer[0].name = "Master";
  19629. song.mixer[1].name = "Vocal";
  19630. song.mixer[1].effects.push_back (fx);
  19631. offline.setSong (std::move (song));
  19632. offline.dispatchPendingMessages();
  19633. auto editor = facetEditor ? lynx::makeFacetEqEditor (offline, 1, 0, true) : lynx::makeNativeEffectEditor (offline, 1, 0, 1.25f, page);
  19634. auto image = lynx::shot::paint (*editor, lynx::theme::panel);
  19635. const auto f = lynx::shot::file (out.getChildFile (file));
  19636. f.deleteFile();
  19637. juce::PNGImageFormat png;
  19638. if (auto stream = f.createOutputStream())
  19639. png.writeImageToStream (image, *stream);
  19640. };
  19641. own (eq, "Facet EQ.png", true);
  19642. own (lynx::makeEffectSlot (lynx::EffectKind::lynxTune), "LYNX Tune.png", false);
  19643. {
  19644. // round 128: the ADVANCED page, with E bypassed and A removed on the keyboard and a created vibrato
  19645. auto tune = lynx::makeEffectSlot (lynx::EffectKind::lynxTune);
  19646. tune.params[(std::size_t) (lynx::lynxtune::bypassC + 4)] = 1.0f;
  19647. tune.params[(std::size_t) (lynx::lynxtune::noteC + 9)] = 0.0f;
  19648. tune.params[lynx::lynxtune::vibratoShape] = 1.0f / 3.0f;
  19649. // round 166c: the created vibrato's amplitude / formant / variation, a short throat, In scale +2
  19650. tune.params[lynx::lynxtune::vibratoAmplitude] = 1.0f / 3.0f;
  19651. tune.params[lynx::lynxtune::vibratoFormant] = 0.7f;
  19652. tune.params[lynx::lynxtune::vibratoVariation] = 0.2f;
  19653. tune.params[lynx::lynxtune::throatLength] = lynx::lynxtune::throatValue (80.0);
  19654. tune.params[lynx::lynxtune::transposeInScale] = 1.0f;
  19655. tune.params[lynx::lynxtune::scaleTranspose] = lynx::lynxtune::scaleTransposeValue (2);
  19656. own (tune, "LYNX Tune-p2.png", false, 1);
  19657. }
  19658. own (lynx::makeEffectSlot (lynx::EffectKind::lynxTune), "LYNX Tune-p3.png", false, 2); // round 135w: Real-time
  19659. lynx::setNativeEditorDemo (false);
  19660. }
  19661. // generators in FL's arrangement: the channel's plugin page with the FL preset's settings
  19662. const auto generators = juce::File (juce::String::fromUTF8 (roots.data.c_str())).getChildFile ("Patches/Plugin presets/Generators");
  19663. 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" } })
  19664. {
  19665. juce::MemoryBlock data;
  19666. if (juce::String (folder) == "Harmor") // the first preset whose state the engine reads
  19667. {
  19668. auto files = generators.getChildFile (folder).findChildFiles (juce::File::findFiles, true, "*.fst");
  19669. files.sort();
  19670. for (const auto& f : files)
  19671. {
  19672. juce::MemoryBlock block;
  19673. if (! f.loadFileAsData (block))
  19674. continue;
  19675. const auto* b = static_cast<const std::uint8_t*> (block.getData());
  19676. try
  19677. {
  19678. const auto p = flp::parseProject (std::vector<std::uint8_t> (b, b + block.getSize()), true);
  19679. if (! p.channels.empty() && lynx::harmorStateUsable (p.channels.front().pluginState))
  19680. {
  19681. preset = nullptr;
  19682. data = block;
  19683. break;
  19684. }
  19685. }
  19686. catch (const std::exception&)
  19687. {
  19688. }
  19689. }
  19690. }
  19691. auto file = preset == nullptr ? juce::File() : juce::String (preset).isEmpty() ? database.getSiblingFile ("Generators").getChildFile ("Misc").getChildFile (juce::String (folder) + ".fst")
  19692. : generators.getChildFile (folder).getChildFile (preset);
  19693. if (! file.existsAsFile())
  19694. {
  19695. auto files = generators.getChildFile (folder).findChildFiles (juce::File::findFiles, true, "*.fst");
  19696. files.sort();
  19697. file = files.isEmpty() ? juce::File() : files[0];
  19698. }
  19699. if (data.isEmpty() && ! file.loadFileAsData (data))
  19700. continue;
  19701. try
  19702. {
  19703. const auto* bytes = static_cast<const std::uint8_t*> (data.getData());
  19704. auto project = flp::parseProject (std::vector<std::uint8_t> (bytes, bytes + data.getSize()), true);
  19705. if (project.channels.empty())
  19706. continue;
  19707. project.channels.front().type = flp::ChannelType::native;
  19708. lynx::FlpImportOptions options;
  19709. options.roots = roots;
  19710. options.fileExists = [] (const std::string& path) { return lynx::platform::localFile (path).existsAsFile(); };
  19711. options.readFile = [] (const std::string& path) {
  19712. juce::MemoryBlock block;
  19713. lynx::platform::localFile (path).loadFileAsData (block);
  19714. const auto* b = static_cast<const std::uint8_t*> (block.getData());
  19715. return std::vector<std::uint8_t> (b, b + block.getSize());
  19716. };
  19717. options.saveEmbedded = [out] (const std::vector<std::uint8_t>& wav, const std::string& name) {
  19718. const auto f = out.getChildFile ("samples").getNonexistentChildFile (juce::String::fromUTF8 (name.c_str()), ".wav");
  19719. f.getParentDirectory().createDirectory();
  19720. f.replaceWithData (wav.data(), wav.size());
  19721. return f.getFullPathName().toStdString();
  19722. };
  19723. auto song = lynx::importFlp (project, options);
  19724. // the page only needs the plugin's saved state (FL Keys' sample zones need the installed wavetables)
  19725. if (! song.channels.empty() && project.channels.front().pluginName == "BooBass" && song.channels.front().instrument != lynx::InstrumentKind::boobass)
  19726. {
  19727. song.channels.front().instrument = lynx::InstrumentKind::boobass; // (its sound needs the engine DLL; the page does not)
  19728. song.channels.front().modelParams.assign (3, 32768.0f);
  19729. }
  19730. if (! song.channels.empty() && project.channels.front().pluginName == "FL Keys")
  19731. {
  19732. song.channels.front().instrument = lynx::InstrumentKind::flkeys;
  19733. song.channels.front().pluginState = project.channels.front().pluginState;
  19734. }
  19735. offline.setSong (std::move (song));
  19736. offline.dispatchPendingMessages();
  19737. if (offline.getSong().channels.empty())
  19738. continue;
  19739. auto panel = lynx::makeChannelSettingsPanel (offline, 0);
  19740. auto image = lynx::shot::paint (*panel, lynx::theme::panel);
  19741. const auto out2 = lynx::shot::file (out.getChildFile (juce::String (folder) + ".png"));
  19742. out2.deleteFile();
  19743. juce::PNGImageFormat png;
  19744. if (auto stream = out2.createOutputStream())
  19745. png.writeImageToStream (image, *stream);
  19746. }
  19747. catch (const std::exception&)
  19748. {
  19749. }
  19750. }
  19751. }
  19752. quit();
  19753. }
  19754. void runVideoShot (const juce::String& prefix, const juce::String& videoPath)
  19755. {
  19756. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  19757. // the message loop runs while the frames decode (modal loops are off): a timer takes one snapshot per step
  19758. struct VideoShot final : juce::Timer
  19759. {
  19760. lynx::AudioEngine offline { false };
  19761. std::unique_ptr<juce::Component> editor;
  19762. juce::String prefix, report;
  19763. int step = 0;
  19764. std::function<void()> done;
  19765. void moveTo (double seconds)
  19766. {
  19767. offline.getTransport().positionTicks.store (seconds * offline.getSong().bpm / 60.0 * lynx::ppq);
  19768. }
  19769. void timerCallback() override
  19770. {
  19771. static constexpr double times[] = { 0.0, 1.5, 3.25 };
  19772. constexpr int typeInStep = (int) std::size (times) + 1;
  19773. if (step > 0 && step < typeInStep && editor != nullptr)
  19774. savePng (lynx::shot::snapshot (*editor), prefix + "-" + juce::String (step - 1) + ".png");
  19775. if (editor != nullptr && step == (int) std::size (times))
  19776. {
  19777. // round 174d: FL's in-place type-in of the current time (a right click on it)
  19778. lynx::videoview::openTypeIn (*editor, 2);
  19779. ++step;
  19780. return;
  19781. }
  19782. if (editor != nullptr && step == typeInStep)
  19783. savePng (lynx::shot::snapshot (*editor), prefix + "-typein.png");
  19784. if (editor == nullptr || step >= typeInStep)
  19785. {
  19786. stopTimer();
  19787. juce::File (prefix + "-report.txt").replaceWithText (report);
  19788. if (done)
  19789. done();
  19790. return;
  19791. }
  19792. moveTo (times[step++]);
  19793. }
  19794. };
  19795. static std::unique_ptr<VideoShot> shot;
  19796. shot = std::make_unique<VideoShot>();
  19797. shot->prefix = prefix;
  19798. auto& offline = shot->offline;
  19799. lynx::videoview::install (offline);
  19800. lynx::Song song;
  19801. song.mixer = lynx::Song::defaultMixer (2);
  19802. lynx::ChannelDef c;
  19803. c.name = "Fruity Video Player";
  19804. c.instrument = lynx::InstrumentKind::videoplayer;
  19805. lynx::video::Settings vs;
  19806. vs.path = juce::File (videoPath).getFullPathName().toStdString();
  19807. vs.delay = lynx::video::unitsPerSecond / 2; // the video starts at 0.5 s
  19808. c.pluginState = lynx::video::write (vs);
  19809. song.channels.push_back (c);
  19810. song.patterns.emplace_back();
  19811. {
  19812. // round 174d (A3): the same Video Player in a song whose tempo drops from 120 to 60 BPM at bar 5, for FL
  19813. // (LYNX.exe --export-flp <prefix>-tempo.lynx <prefix>-tempo.flp), to compare FL's video clock with LYNX's
  19814. auto fl = song;
  19815. fl.bpm = 120.0;
  19816. fl.mode = lynx::PlayMode::song;
  19817. auto settings = vs;
  19818. settings.delay = 0;
  19819. settings.timeDisplay = lynx::video::Settings {}.timeDisplay;
  19820. fl.channels[0].pluginState = lynx::video::write (settings);
  19821. fl.patterns[0].name = "Pattern 1";
  19822. lynx::Automation tempo;
  19823. tempo.name = "Tempo";
  19824. tempo.target = { lynx::AutomationTargetKind::tempo, 0, 0, 0 };
  19825. const auto bar = (std::int64_t) lynx::ppq * 4;
  19826. tempo.points = { { 0, lynx::valueFromTempo (120.0), 0.0f }, { bar * 4 - 1, lynx::valueFromTempo (120.0), 0.0f },
  19827. { bar * 4, lynx::valueFromTempo (60.0), 0.0f }, { bar * 8, lynx::valueFromTempo (60.0), 0.0f } };
  19828. fl.automations.push_back (tempo);
  19829. lynx::Clip at;
  19830. at.kind = lynx::ClipKind::automation;
  19831. at.automation = 0;
  19832. at.track = 1;
  19833. at.start = 0;
  19834. at.length = bar * 8;
  19835. fl.playlist.push_back (at);
  19836. lynx::Clip pc;
  19837. pc.pattern = 0;
  19838. pc.track = 0;
  19839. pc.start = 0;
  19840. pc.length = bar * 8;
  19841. fl.playlist.push_back (pc);
  19842. juce::String error;
  19843. lynx::ProjectFile::save (fl, juce::File (prefix + "-tempo.lynx"), error);
  19844. }
  19845. offline.setSong (std::move (song));
  19846. offline.dispatchPendingMessages();
  19847. auto& report = shot->report;
  19848. report << "ffmpeg: " << lynx::findFfmpeg().getFullPathName() << "\n";
  19849. report << lynx::videoview::report (vs.path).fromFirstOccurrenceOf ("Input #0", true, false).upToFirstOccurrenceOf ("At least", false, false) << "\n";
  19850. shot->editor = lynx::makeChannelSettingsPanel (offline, 0);
  19851. if (shot->editor != nullptr)
  19852. shot->editor->setVisible (true);
  19853. shot->done = [this] { juce::MessageManager::callAsync ([this] { shot.reset(); quit(); }); };
  19854. shot->startTimer (1500);
  19855. }
  19856. void runVideoTrackShot (const juce::String& prefix, const juce::String& videoPath, const juce::String& secondPath)
  19857. {
  19858. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  19859. struct TrackShot final : juce::Timer
  19860. {
  19861. lynx::AudioEngine offline { false };
  19862. std::unique_ptr<lynx::PlaylistComponent> playlist;
  19863. std::unique_ptr<lynx::media::FrameDecoder> decoder;
  19864. juce::String prefix, report, path;
  19865. double fps = 25.0;
  19866. int step = 0, waits = 0, adrStep = 0;
  19867. std::unique_ptr<juce::Component> adrPanel;
  19868. std::function<void()> done;
  19869. // song times (s): before, inside the first clip (on and between frame edges), across the second clip
  19870. std::vector<double> times { 0.0, 1.0, 2.0 + 1.0 / 25.0, 2.5, 4.0, 7.3 };
  19871. void timerCallback() override
  19872. {
  19873. if (step > 0 && adrStep == 0)
  19874. {
  19875. // the frame the decoder shows for the wanted file time (the clip starts at song 1.0 s, offset 0)
  19876. const auto want = times[(std::size_t) step - 1] - 1.0;
  19877. double ft = -1.0;
  19878. const auto img = decoder->frame (ft);
  19879. const auto expected = std::floor (want * fps + 1e-6) / fps;
  19880. if (want >= 0.0 && ft < expected - 1e-3 && ++waits < 20)
  19881. return; // (still decoding)
  19882. waits = 0;
  19883. report << "song " << juce::String (times[(std::size_t) step - 1], 3) << " s: wanted file time " << juce::String (want, 4)
  19884. << ", frame shown at " << juce::String (ft, 4) << " (expected " << juce::String (expected, 4) << ")"
  19885. << (want < 0.0 ? " [before the clip]" : std::abs (ft - expected) < 1e-3 ? " OK" : " MISMATCH") << "\n";
  19886. savePng (lynx::shot::snapshot (*playlist), prefix + "-playlist-" + juce::String (step - 1) + ".png");
  19887. if (img.isValid())
  19888. savePng (img, prefix + "-frame-" + juce::String (step - 1) + ".png");
  19889. for (int w = 0; w < juce::Desktop::getInstance().getNumComponents(); ++w)
  19890. if (auto* c = juce::Desktop::getInstance().getComponent (w); c != nullptr && c->getName().startsWith ("Picture"))
  19891. savePng (lynx::shot::snapshot (*c), prefix + "-window-" + juce::String (step - 1) + ".png");
  19892. }
  19893. if (step >= (int) times.size() && adrStep == 0)
  19894. {
  19895. // the ADR window: two cues, takes on the first; the play position inside the streamer before the in
  19896. // point (4.0 s), so the video window shows the streamer and the line
  19897. adrStep = 1;
  19898. offline.editSong ([] (lynx::Song& s) {
  19899. lynx::AdrCue a, b;
  19900. a.id = "SC1-01";
  19901. a.in = 4.0;
  19902. a.out = 6.4;
  19903. a.character = "Dr. Silva";
  19904. a.line = "We have to leave before the storm reaches the coast.";
  19905. a.notes = "softer, out of breath";
  19906. a.status = lynx::AdrCue::Status::recorded;
  19907. for (int n = 1; n <= 3; ++n)
  19908. {
  19909. lynx::AdrTake t;
  19910. t.number = n;
  19911. t.name = lynx::adr::takeName (a, n);
  19912. t.rating = n == 2 ? 4 : n;
  19913. t.circled = n == 2;
  19914. a.takes.push_back (t);
  19915. }
  19916. a.selected = 2;
  19917. lynx::adr::setCompRange (a, 4.0, 5.1, 2);
  19918. lynx::adr::setCompRange (a, 5.1, 6.4, 3);
  19919. b.id = "SC1-02";
  19920. b.in = 8.0;
  19921. b.out = 9.5;
  19922. b.character = "Marta";
  19923. b.line = "Then we go now.";
  19924. s.adr.cues = { a, b };
  19925. s.adr.current = 0;
  19926. });
  19927. adrPanel = lynx::adrwindow::makePanel (offline);
  19928. adrPanel->setSize (1200, 640);
  19929. adrPanel->setVisible (true);
  19930. offline.getTransport().positionTicks.store (3.0 * offline.getSong().bpm / 60.0 * lynx::ppq);
  19931. decoder->request (2.0, false);
  19932. return;
  19933. }
  19934. if (adrStep == 1)
  19935. {
  19936. adrStep = 2;
  19937. savePng (lynx::shot::snapshot (*adrPanel), prefix + "-adr.png");
  19938. for (int w = 0; w < juce::Desktop::getInstance().getNumComponents(); ++w)
  19939. if (auto* c = juce::Desktop::getInstance().getComponent (w); c != nullptr && c->getName().startsWith ("Picture"))
  19940. savePng (lynx::shot::snapshot (*c), prefix + "-adr-window.png");
  19941. offline.getTransport().positionTicks.store (4.5 * offline.getSong().bpm / 60.0 * lynx::ppq);
  19942. decoder->request (3.5, false);
  19943. return;
  19944. }
  19945. if (adrStep == 2)
  19946. {
  19947. for (int w = 0; w < juce::Desktop::getInstance().getNumComponents(); ++w)
  19948. if (auto* c = juce::Desktop::getInstance().getComponent (w); c != nullptr && c->getName().startsWith ("Picture"))
  19949. savePng (lynx::shot::snapshot (*c), prefix + "-adr-window-line.png");
  19950. adrPanel.reset();
  19951. // export with video: a 3 s mix under the picture, re-encoded (the clip starts at 1 s) and copied (from 1 s)
  19952. {
  19953. const juce::File wav (prefix + "-mix.wav");
  19954. wav.deleteFile();
  19955. juce::WavAudioFormat format;
  19956. if (std::unique_ptr<juce::OutputStream> os (wav.createOutputStream().release()); os != nullptr)
  19957. if (std::unique_ptr<juce::AudioFormatWriter> w (format.createWriterFor (os.get(), 48000.0, 2, 16, {}, 0)); w != nullptr)
  19958. {
  19959. os.release();
  19960. juce::AudioBuffer<float> b (2, 48000 * 3);
  19961. for (int k = 0; k < b.getNumSamples(); ++k)
  19962. 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));
  19963. w->writeFromAudioSampleBuffer (b, 0, b.getNumSamples());
  19964. }
  19965. for (const auto origin : { 0.0, 1.0 })
  19966. {
  19967. const juce::File out (prefix + "-mux-" + juce::String ((int) origin) + ".mp4");
  19968. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  19969. const auto error = lynx::videotracks::muxWithVideo (offline.getSong(), origin, wav, out);
  19970. report << "export with video from " << origin << " s: " << (error.isEmpty() ? "OK " + juce::String (out.getSize()) + " bytes" : "FAILED " + error)
  19971. << " (" << juce::String ((juce::Time::getMillisecondCounterHiRes() - t0) / 1000.0, 2) << " s)\n";
  19972. }
  19973. }
  19974. stopTimer();
  19975. report << "frames decoded " << decoder->frameCount() << ", dropped " << decoder->droppedCount() << "\n";
  19976. juce::File (prefix + "-report.txt").replaceWithText (report);
  19977. if (done)
  19978. done();
  19979. return;
  19980. }
  19981. const auto t = times[(std::size_t) step++];
  19982. offline.getTransport().positionTicks.store (t * offline.getSong().bpm / 60.0 * lynx::ppq);
  19983. decoder->request (std::max (0.0, t - 1.0), false);
  19984. }
  19985. };
  19986. static std::unique_ptr<TrackShot> shot;
  19987. shot = std::make_unique<TrackShot>();
  19988. shot->prefix = prefix;
  19989. auto& offline = shot->offline;
  19990. lynx::Song song;
  19991. song.mixer = lynx::Song::defaultMixer (2);
  19992. song.patterns.emplace_back();
  19993. song.mode = lynx::PlayMode::song;
  19994. song.bpm = 120.0;
  19995. offline.setSong (std::move (song));
  19996. offline.dispatchPendingMessages();
  19997. const juce::File video (videoPath);
  19998. const auto pr = lynx::media::probe (video.getFullPathName());
  19999. auto& report = shot->report;
  20000. report << "decoder: " << (pr.backend.isEmpty() ? juce::String ("none") : pr.backend) << " (system: " << lynx::media::nativeBackendName()
  20001. << ", ffmpeg: " << lynx::findFfmpeg().getFullPathName() << ")\n";
  20002. report << "video: " << pr.info.width << "x" << pr.info.height << " " << juce::String (pr.info.fps, 3) << " fps " << juce::String (pr.info.duration, 3)
  20003. << " s, sound " << (pr.info.hasAudio ? "yes" : "no") << "\n";
  20004. shot->fps = pr.info.fps > 1.0 ? pr.info.fps : 25.0;
  20005. shot->times[2] = 2.0 + 1.0 / shot->fps; // (exactly on a frame edge)
  20006. lynx::videotracks::importVideo (offline, video, 1.0, -1);
  20007. if (secondPath.isNotEmpty())
  20008. lynx::videotracks::importVideo (offline, juce::File (secondPath), 3.0, 1);
  20009. offline.editSong ([] (lynx::Song& s) {
  20010. s.video.startTimecode = 3600.0;
  20011. s.video.burnIn = true;
  20012. if (s.videoTracks.size() < 2)
  20013. s.videoTracks.push_back ({});
  20014. s.videoTracks[0].name = "Picture";
  20015. s.videoTracks[1].name = "Reference";
  20016. });
  20017. report << "project rate: " << lynx::vtime::rateName (offline.getSong().video.rate) << ", clip 1: "
  20018. << juce::String (offline.getSong().videoTracks[0].clips.empty() ? -1.0 : offline.getSong().videoTracks[0].clips[0].length, 3) << " s\n";
  20019. // the project round trip
  20020. {
  20021. const juce::File file (prefix + "-project.lynx");
  20022. juce::String error;
  20023. lynx::ProjectFile::save (offline.getSong(), file, error);
  20024. const auto back = lynx::ProjectFile::load (file, error);
  20025. report << "project file round trip: " << (back && back->videoTracks == offline.getSong().videoTracks && back->video == offline.getSong().video ? "OK" : "MISMATCH " + error) << "\n";
  20026. }
  20027. shot->playlist = std::make_unique<lynx::PlaylistComponent> (offline);
  20028. shot->playlist->setSize (1400, 640);
  20029. shot->playlist->setVisible (true);
  20030. shot->decoder = std::make_unique<lynx::media::FrameDecoder>();
  20031. shot->decoder->setSource (video.getFullPathName(), pr.info);
  20032. shot->decoder->setSize (pr.info.width, pr.info.height);
  20033. shot->decoder->startThread (juce::Thread::Priority::low);
  20034. lynx::videotracks::showWindow (offline, 0);
  20035. shot->done = [this] { juce::MessageManager::callAsync ([this] { shot.reset(); quit(); }); };
  20036. shot->startTimer (700);
  20037. }
  20038. void runDanceShot (const juce::String& prefix)
  20039. {
  20040. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  20041. // the moves: one row each, eight moments of a cycle (both facings for Spinning; Pose ends the sheet)
  20042. {
  20043. constexpr int cell = 120, cols = 8;
  20044. auto sheet = lynx::shot::canvas (130 + cols * cell, lynx::dance::moveCount * cell + 10);
  20045. {
  20046. // (the picture is complete when its Graphics is gone: round 190ba, the file was blank on Windows)
  20047. juce::Graphics g (sheet);
  20048. lynx::shot::logical (g);
  20049. g.fillAll (lynx::theme::colour::bg0);
  20050. for (int m = 0; m < lynx::dance::moveCount; ++m)
  20051. {
  20052. g.setColour (lynx::theme::colour::textSecondary);
  20053. g.setFont (14.0f);
  20054. g.drawText (lynx::dance::moveName (m), 8, m * cell + 5, 118, cell, juce::Justification::centredLeft);
  20055. for (int k = 0; k < cols; ++k)
  20056. {
  20057. const auto pose = lynx::dance::pose (m, k / (double) cols + (m == lynx::dance::freestyle ? k * 2 : 0), 1);
  20058. lynx::dancer::draw (g, { 130.0f + (k + 0.5f) * cell, (float) (m + 1) * cell - 6.0f }, 92.0f, pose, false, juce::Colour (0xffff3048));
  20059. }
  20060. }
  20061. }
  20062. savePng (sheet, prefix + "-moves.png");
  20063. }
  20064. lynx::AudioEngine offline (false);
  20065. lynx::Song song;
  20066. song.mixer = lynx::Song::defaultMixer (2);
  20067. for (int d = 0; d < 2; ++d)
  20068. {
  20069. lynx::ChannelDef c;
  20070. c.name = d == 0 ? "Fruity Dance" : "Fruity Dance #2";
  20071. c.instrument = lynx::InstrumentKind::fruitydance;
  20072. lynx::dance::Settings s;
  20073. s.move = d == 0 ? lynx::dance::stepping : lynx::dance::waving;
  20074. s.x = d == 0 ? 520 : 760;
  20075. s.y = 560;
  20076. s.colour = d == 0 ? 0xffff3048 : 0xff30a8ff;
  20077. s.mirrored = d == 1;
  20078. c.pluginState = lynx::dance::toState (s);
  20079. song.channels.push_back (c);
  20080. }
  20081. // Issue #121 (round 190ba): a sprite sheet in FL's Fruity Dance format (8 frames across, a row per move, a names
  20082. // file beside it), made here from LYNX's own poses, loaded back as a user's sheet would be
  20083. juce::String sheetReport;
  20084. {
  20085. constexpr int fw = 120, fh = 150;
  20086. const std::vector<std::pair<const char*, int>> rows { { "Idle", lynx::dance::waiting }, { "Step", lynx::dance::stepping },
  20087. { "Jump", lynx::dance::jumping }, { "Wave", lynx::dance::waving },
  20088. { "Windmill", lynx::dance::windmill }, { "Held", lynx::dance::held } };
  20089. juce::Image sheet (juce::Image::ARGB, fw * lynx::dance::sheetColumns, fh * (int) rows.size(), true);
  20090. {
  20091. juce::Graphics g (sheet);
  20092. for (int r = 0; r < (int) rows.size(); ++r)
  20093. for (int k = 0; k < lynx::dance::sheetColumns; ++k)
  20094. {
  20095. juce::Graphics::ScopedSaveState save (g);
  20096. g.reduceClipRegion (k * fw, r * fh, fw, fh);
  20097. lynx::dancer::draw (g, { (k + 0.5f) * fw, (float) (r + 1) * fh - 8.0f }, 96.0f,
  20098. lynx::dance::pose (rows[(std::size_t) r].second, k / (double) lynx::dance::sheetColumns, 1), false, juce::Colour (0xff35c46a));
  20099. }
  20100. }
  20101. const juce::File picture (prefix + "-sheet.png");
  20102. savePng (sheet, picture.getFullPathName());
  20103. juce::String names;
  20104. for (const auto& [name, move] : rows)
  20105. names << (names.isEmpty() ? "" : "\r\n") << name;
  20106. picture.withFileExtension ("txt").replaceWithText (names, false, false, nullptr);
  20107. // a picture that is not a whole number of frames: FL's "Bitmap size is incorrect."
  20108. const juce::File wrong (prefix + "-sheet-wrong.png");
  20109. savePng (sheet.getClippedImage ({ 0, 0, sheet.getWidth() - 3, sheet.getHeight() }), wrong.getFullPathName());
  20110. wrong.withFileExtension ("txt").replaceWithText (names, false, false, nullptr);
  20111. auto error = lynx::dancer::SheetError::none;
  20112. const auto loaded = lynx::dancer::sheetFor (picture.getFullPathName().toStdString(), &error);
  20113. auto wrongError = lynx::dancer::SheetError::none;
  20114. const auto refused = lynx::dancer::sheetFor (wrong.getFullPathName().toStdString(), &wrongError);
  20115. auto missingError = lynx::dancer::SheetError::none;
  20116. const auto missing = lynx::dancer::sheetFor (juce::File (prefix + "-sheet-none.png").getFullPathName().toStdString(), &missingError);
  20117. sheetReport << "sheet_loaded=" << (loaded != nullptr ? 1 : 0) << "\n"
  20118. << "sheet_wrong_size_refused=" << (refused == nullptr && wrongError == lynx::dancer::SheetError::size ? 1 : 0) << "\n"
  20119. << "sheet_missing_refused=" << (missing == nullptr && missingError == lynx::dancer::SheetError::missing ? 1 : 0) << "\n";
  20120. bool ok = loaded != nullptr && refused == nullptr && missing == nullptr;
  20121. if (loaded != nullptr)
  20122. {
  20123. sheetReport << "sheet_rows=" << loaded->layout.rows << "\nsheet_frame=" << loaded->layout.frameWidth << "x" << loaded->layout.frameHeight
  20124. << "\nsheet_moves=" << loaded->moves() << "\nsheet_names=";
  20125. for (const auto& n : loaded->names)
  20126. sheetReport << juce::String::fromUTF8 (n.c_str()) << ";";
  20127. sheetReport << "\n";
  20128. ok = ok && loaded->layout.rows == (int) rows.size() && loaded->layout.frameWidth == fw && loaded->layout.frameHeight == fh;
  20129. // the animation as the stage draws it: a row of moments of the move "Wave" (blending on), then mirrored,
  20130. // then the row shown while the dancer is held
  20131. auto strip = lynx::shot::canvas (fw * 12, fh * 3 + 20);
  20132. int solid = 0;
  20133. {
  20134. juce::Graphics g (strip);
  20135. lynx::shot::logical (g);
  20136. g.fillAll (lynx::theme::colour::bg0);
  20137. for (int line = 0; line < 3; ++line)
  20138. {
  20139. lynx::dance::SheetAnimator animator (3);
  20140. for (int k = 0; k < 12; ++k)
  20141. {
  20142. const auto frame = animator.advance (k / 12.0 + 0.001, loaded->layout.rows, 4, line == 1, true, 0.5f, line == 2);
  20143. const juce::Point<float> feet ((k + 0.5f) * fw, (float) (line + 1) * fh + 5.0f);
  20144. lynx::dancer::drawSheet (g, *loaded, feet, 1.0f, frame);
  20145. solid += lynx::dancer::sheetSolidAt (*loaded, feet, 1.0f, frame, feet.translated (0.0f, -70.0f)) ? 1 : 0;
  20146. ok = ok && ! lynx::dancer::sheetSolidAt (*loaded, feet, 1.0f, frame, feet.translated (-(float) fw * 0.5f + 1.0f, -(float) fh + 1.0f));
  20147. }
  20148. }
  20149. }
  20150. // mirrored = the same frame flipped left-right, on whatever renderer this build draws with
  20151. {
  20152. lynx::dance::SheetFrame plain;
  20153. plain.row = 3;
  20154. plain.column = 2;
  20155. auto turned = plain;
  20156. turned.mirrored = true;
  20157. juce::Image a (juce::Image::ARGB, fw, fh, true), b (juce::Image::ARGB, fw, fh, true);
  20158. {
  20159. juce::Graphics ga (a);
  20160. lynx::dancer::drawSheet (ga, *loaded, { fw * 0.5f, (float) fh }, 1.0f, plain);
  20161. }
  20162. {
  20163. juce::Graphics gb (b);
  20164. lynx::dancer::drawSheet (gb, *loaded, { fw * 0.5f, (float) fh }, 1.0f, turned);
  20165. }
  20166. int same = 0, flippedSame = 0, solidPixels = 0;
  20167. for (int y = 0; y < fh; ++y)
  20168. for (int x = 0; x < fw; ++x)
  20169. {
  20170. const auto pa = a.getPixelAt (x, y);
  20171. if (pa.getAlpha() < 200)
  20172. continue;
  20173. ++solidPixels;
  20174. auto alike = [pa] (juce::Colour c) {
  20175. return std::abs ((int) c.getRed() - (int) pa.getRed()) + std::abs ((int) c.getGreen() - (int) pa.getGreen())
  20176. + std::abs ((int) c.getBlue() - (int) pa.getBlue()) + std::abs ((int) c.getAlpha() - (int) pa.getAlpha()) < 12;
  20177. };
  20178. same += alike (b.getPixelAt (x, y)) ? 1 : 0;
  20179. flippedSame += alike (b.getPixelAt (fw - 1 - x, y)) ? 1 : 0;
  20180. }
  20181. const auto flips = solidPixels > 500 && flippedSame >= solidPixels * 98 / 100 && same < solidPixels * 95 / 100;
  20182. sheetReport << "sheet_mirror_flips=" << (flips ? 1 : 0) << " (" << flippedSame << " of " << solidPixels << " solid pixels match flipped, " << same
  20183. << " unflipped)\n";
  20184. ok = ok && flips;
  20185. }
  20186. sheetReport << "sheet_body_solid=" << solid << "/36\n";
  20187. ok = ok && solid >= 18;
  20188. savePng (strip, prefix + "-sheet-frames.png");
  20189. }
  20190. sheetReport << "sheet_result=" << (ok ? "OK" : "ERROR") << "\n";
  20191. lynx::ChannelDef c;
  20192. c.name = "Fruity Dance #3";
  20193. c.instrument = lynx::InstrumentKind::fruitydance;
  20194. lynx::dance::Settings s;
  20195. s.move = 2; // (the sheet's second row: "Step")
  20196. s.x = 1000;
  20197. s.y = 560;
  20198. s.sheet = picture.getFullPathName().toStdString();
  20199. c.pluginState = lynx::dance::toState (s);
  20200. song.channels.push_back (c);
  20201. }
  20202. song.patterns.emplace_back();
  20203. {
  20204. const juce::File demo (prefix + "-demo.lynx");
  20205. juce::String error;
  20206. lynx::ProjectFile::save (song, demo, error);
  20207. }
  20208. offline.setSong (std::move (song));
  20209. offline.dispatchPendingMessages();
  20210. if (auto editor = lynx::makeChannelSettingsPanel (offline, 0))
  20211. savePng (lynx::shot::snapshot (*editor), prefix + "-editor.png");
  20212. if (auto frame = lynx::makeChannelFrame (offline, 1, 0))
  20213. savePng (lynx::shot::snapshot (*frame), prefix + "-frame.png");
  20214. if (auto editor = lynx::makeChannelSettingsPanel (offline, 2))
  20215. savePng (lynx::shot::snapshot (*editor), prefix + "-sheet-editor.png");
  20216. {
  20217. // the stage with the three dancers (the third from the sheet)
  20218. lynx::DanceStage stage (offline);
  20219. stage.setSize (1280, 640);
  20220. stage.update();
  20221. sheetReport << "stage_dancers=" << stage.dancerCount() << "\n";
  20222. auto picture = lynx::shot::canvas (1280, 640);
  20223. {
  20224. juce::Graphics g (picture);
  20225. lynx::shot::logical (g);
  20226. g.fillAll (lynx::theme::colour::bg0);
  20227. stage.paintEntireComponent (g, true);
  20228. }
  20229. savePng (picture, prefix + "-sheet-stage.png");
  20230. }
  20231. juce::File (prefix + "-sheetreport.txt").replaceWithText (sheetReport);
  20232. }
  20233. void runControllerShot (const juce::String& prefix)
  20234. {
  20235. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  20236. lynx::AudioEngine offline (false);
  20237. lynx::Song song;
  20238. song.mixer = lynx::Song::defaultMixer (2);
  20239. song.mixer[1].name = "Insert 1";
  20240. auto fx = lynx::makeEffectSlot (lynx::EffectKind::formulaController);
  20241. lynx::formula::State formula;
  20242. formula.formula = "a*Sin(SongTime*Pi*b*4)+c";
  20243. fx.state = lynx::formula::writeState (formula);
  20244. fx.params[0] = 0.5f;
  20245. fx.params[1] = 0.25f;
  20246. fx.params[2] = 0.5f;
  20247. song.mixer[1].effects.push_back (fx);
  20248. // round 164: X-Y (slot 2), X-Y-Z (slot 3) and a Control Surface (slot 4)
  20249. {
  20250. auto xyFx = lynx::makeEffectSlot (lynx::EffectKind::xyController);
  20251. xyFx.params[(std::size_t) lynx::xy::level (0)] = 0.3f;
  20252. xyFx.params[(std::size_t) lynx::xy::level (1)] = 0.7f;
  20253. xyFx.params[(std::size_t) lynx::xy::tension (0)] = 0.8f;
  20254. song.mixer[1].effects.push_back (xyFx);
  20255. auto xyzFx = lynx::makeEffectSlot (lynx::EffectKind::xyzController);
  20256. xyzFx.params[(std::size_t) lynx::xy::level (2)] = 0.8f;
  20257. song.mixer[1].effects.push_back (xyzFx);
  20258. // round 165: an X-Y-Z whose X curve is FL's "Stairs" (tension +40 %) and Y a bent single curve
  20259. xyzFx.params[(std::size_t) lynx::xy::curveMode (0)] = lynx::xy::curveModeValue (lynx::flcurve::stairs);
  20260. xyzFx.params[(std::size_t) lynx::xy::tension (0)] = 0.7f;
  20261. xyzFx.params[(std::size_t) lynx::xy::level (0)] = 0.62f;
  20262. xyzFx.params[(std::size_t) lynx::xy::tension (1)] = 0.825f;
  20263. song.mixer[1].effects.push_back (xyzFx);
  20264. auto panel = lynx::makeEffectSlot (lynx::EffectKind::controlSurface);
  20265. lynx::SurfaceControl c;
  20266. for (const auto& [kind, name, v, x, y] : std::vector<std::tuple<lynx::SurfaceControl::Kind, const char*, float, float, float>> {
  20267. { lynx::SurfaceControl::Kind::knob, "Cutoff", 0.65f, 20.0f, 20.0f },
  20268. { lynx::SurfaceControl::Kind::knob, "Reso", 0.3f, 90.0f, 20.0f },
  20269. { lynx::SurfaceControl::Kind::slider, "Mix", 0.8f, 170.0f, 20.0f },
  20270. { lynx::SurfaceControl::Kind::xy, "Space", 0.4f, 230.0f, 20.0f },
  20271. { lynx::SurfaceControl::Kind::button, "Drop", 0.0f, 20.0f, 110.0f },
  20272. { lynx::SurfaceControl::Kind::checkBox, "Bypass", 1.0f, 20.0f, 160.0f } })
  20273. {
  20274. c.kind = kind;
  20275. c.name = name;
  20276. c.value = v;
  20277. c.valueY = 0.6f;
  20278. c.x = x;
  20279. c.y = y;
  20280. lynx::surface::add (panel, c);
  20281. }
  20282. song.mixer[1].effects.push_back (panel);
  20283. }
  20284. lynx::ChannelDef env;
  20285. env.name = "Envelope Controller";
  20286. env.instrument = lynx::InstrumentKind::controller;
  20287. auto ecData = lynx::defaultEnvelopeController();
  20288. ecData[0].lfoOn = true;
  20289. ecData[0].lfoTempo = true;
  20290. ecData[0].lfoSpeed = 40898;
  20291. ecData[0].maps[lynx::mapKeyboard].count = 2;
  20292. ecData[0].maps[lynx::mapKeyboard].time = { 0.2f, 0.8f };
  20293. ecData[0].maps[lynx::mapKeyboard].level = { 0.0f, 1.0f };
  20294. ecData[0].maps[lynx::mapModX] = ecData[0].maps[lynx::mapKeyboard];
  20295. env.controllerState = lynx::writeEnvelopeController (ecData);
  20296. song.channels.push_back (env);
  20297. lynx::ChannelDef out;
  20298. out.name = "MIDI Out";
  20299. out.instrument = lynx::InstrumentKind::midiOut;
  20300. lynx::midictl::MidiOutSettings settings;
  20301. settings.port = 1;
  20302. lynx::midictl::writeMidiOut (out.pluginState, settings);
  20303. song.channels.push_back (out);
  20304. // a Layer (round 164) over three synths split across the keyboard, crossfading
  20305. for (const auto* name : { "Bass", "Pad", "Lead" })
  20306. {
  20307. lynx::ChannelDef c;
  20308. c.name = name;
  20309. c.instrument = lynx::InstrumentKind::synth;
  20310. song.channels.push_back (c);
  20311. }
  20312. {
  20313. lynx::ChannelDef layer;
  20314. layer.name = "Layer";
  20315. layer.instrument = lynx::InstrumentKind::layer;
  20316. song.channels.push_back (layer);
  20317. const auto self = (int) song.channels.size() - 1;
  20318. lynx::layer::setChildren (song, self, { 2, 3, 4 });
  20319. song.channels[2].keyLow = 0, song.channels[2].keyHigh = 47;
  20320. song.channels[3].keyLow = 36, song.channels[3].keyHigh = 83;
  20321. song.channels[4].keyLow = 72, song.channels[4].keyHigh = 127;
  20322. song.channels[(std::size_t) self].layer.crossfade = true;
  20323. song.channels[(std::size_t) self].layer.fade = 0.35f;
  20324. }
  20325. {
  20326. lynx::ChannelDef dash; // channel 6
  20327. dash.name = "Dashboard";
  20328. dash.instrument = lynx::InstrumentKind::dashboard;
  20329. dash.patcher.surface = lynx::surface::starterControls();
  20330. song.channels.push_back (dash);
  20331. }
  20332. {
  20333. lynx::ChannelDef volt; // channel 7: FL's render-test settings (main L pitch, R gate × 0.5) with Out 2 on insert 3
  20334. volt.name = "Voltage Controller";
  20335. volt.instrument = lynx::InstrumentKind::voltage;
  20336. lynx::voltage::Settings v;
  20337. v.enabled = true;
  20338. v.params[9] = 49152;
  20339. v.unipolar[2] = true;
  20340. v.tracks = { 3, 0, 0 };
  20341. v.source[6] = lynx::voltage::Source::clock;
  20342. volt.pluginState = lynx::voltage::write (v);
  20343. song.channels.push_back (volt);
  20344. }
  20345. song.patterns.emplace_back();
  20346. offline.setSong (std::move (song));
  20347. offline.dispatchPendingMessages();
  20348. auto shoot = [&] (std::unique_ptr<juce::Component> c, const juce::String& name) {
  20349. if (c == nullptr)
  20350. return;
  20351. savePng (lynx::shot::snapshot (*c), prefix + name);
  20352. };
  20353. shoot (lynx::makeChannelSettingsPanel (offline, 0), "-envelope-controller.png");
  20354. shoot (lynx::makeChannelSettingsPanel (offline, 1), "-midi-out.png");
  20355. shoot (lynx::makeChannelSettingsPanel (offline, 5), "-layer.png");
  20356. shoot (lynx::makeChannelFrame (offline, 3, -1), "-layer-child-misc.png"); // (the key-region ruler over the root keyboard)
  20357. {
  20358. const auto slotOf = [] (int k) -> lynx::SlotLocator {
  20359. return [k] (lynx::Song& s) { return &s.mixer[1].effects[(std::size_t) k]; };
  20360. };
  20361. const lynx::AutomationTarget target { lynx::AutomationTargetKind::effectParam, 1, 1, 0 };
  20362. shoot (lynx::makeXyControllerEditor (offline, slotOf (1), nullptr, target), "-xy-controller.png");
  20363. shoot (lynx::makeXyControllerEditor (offline, slotOf (2), nullptr, target), "-xyz-controller.png");
  20364. shoot (lynx::makeXyControllerEditor (offline, slotOf (3), nullptr, target), "-xyz-controller-stairs.png");
  20365. shoot (lynx::makeControlSurfaceEditor (offline, slotOf (4), target), "-control-surface.png");
  20366. shoot (lynx::makeChannelSettingsPanel (offline, 6), "-dashboard.png");
  20367. shoot (lynx::makeChannelSettingsPanel (offline, 7), "-voltage-controller.png");
  20368. }
  20369. // FL's Dashboard presets of this PC's FL Studio, imported (round 164f): one PNG each
  20370. if (const auto fl = lynx::findFlStudio(); fl.installDir.isDirectory())
  20371. for (const auto& file : fl.installDir.getChildFile ("Data/Patches/Plugin presets/Generators/Dashboard").findChildFiles (juce::File::findFiles, false, "*.fst"))
  20372. {
  20373. juce::MemoryBlock bytes;
  20374. if (! file.loadFileAsData (bytes))
  20375. continue;
  20376. const auto preset = flp::parseProject ({ (const std::uint8_t*) bytes.getData(), bytes.getSize() }, true);
  20377. const auto dash = preset.channels.empty() ? std::nullopt : lynx::surface::parseFlDashboard (preset.channels[0].pluginState);
  20378. if (! dash || dash->controls.empty())
  20379. continue;
  20380. offline.editSong ([&] (lynx::Song& s) {
  20381. s.channels[6].name = file.getFileNameWithoutExtension().toStdString();
  20382. s.channels[6].patcher.surface = dash->controls;
  20383. s.channels[6].pluginState = preset.channels[0].pluginState; // (its MIDI port, channel, program)
  20384. });
  20385. offline.dispatchPendingMessages();
  20386. const auto name = file.getFileNameWithoutExtension().replaceCharacter (' ', '-');
  20387. shoot (lynx::makeChannelSettingsPanel (offline, 6), "-dashboard-fl-" + name + ".png");
  20388. // edit mode (round 165): each control's output number and the MIDI it sends ("1 CC74")
  20389. if (auto panel = lynx::makeChannelSettingsPanel (offline, 6))
  20390. {
  20391. std::function<void (juce::Component&)> pressEdit = [&] (juce::Component& c) {
  20392. for (auto* child : c.getChildren())
  20393. {
  20394. if (auto* b = dynamic_cast<juce::TextButton*> (child); b != nullptr && b->getButtonText() == lynx::tr ("Edit"))
  20395. b->setToggleState (true, juce::sendNotificationSync);
  20396. pressEdit (*child);
  20397. }
  20398. };
  20399. pressEdit (*panel);
  20400. shoot (std::move (panel), "-dashboard-fl-" + name + "-edit.png");
  20401. }
  20402. }
  20403. // the Envelope Controller's pages (issue #7): one PNG per part of the dropdown
  20404. if (auto ec = lynx::makeEnvelopeControllerEditor (offline, 0))
  20405. for (int part = 0; part < 7; ++part)
  20406. {
  20407. for (auto* child : ec->getChildren())
  20408. if (auto* box = dynamic_cast<juce::ComboBox*> (child))
  20409. box->setSelectedItemIndex (part, juce::sendNotificationSync);
  20410. savePng (lynx::shot::snapshot (*ec), prefix + "-ec-part" + juce::String (part) + ".png");
  20411. }
  20412. lynx::FormulaControllerWindows::open (offline, 1, 0);
  20413. for (int k = 0; k < juce::TopLevelWindow::getNumTopLevelWindows(); ++k)
  20414. if (auto* w = dynamic_cast<juce::DocumentWindow*> (juce::TopLevelWindow::getTopLevelWindow (k)))
  20415. if (w->getName().startsWith ("Formula") && w->getContentComponent() != nullptr)
  20416. savePng (lynx::shot::snapshot (*w->getContentComponent()), prefix + "-formula-controller.png");
  20417. lynx::FormulaControllerWindows::closeAll();
  20418. }
  20419. bool runEdisonSlotTest (const juce::String& folderPath, const juce::String& flp)
  20420. {
  20421. namespace ae = lynx::audioedit;
  20422. namespace ef = lynx::edisonfx;
  20423. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  20424. const juce::File folder (folderPath);
  20425. folder.createDirectory();
  20426. juce::String report;
  20427. bool all = true;
  20428. auto check = [&] (const juce::String& name, bool ok, const juce::String& note = {}) {
  20429. report << name << "=" << (ok ? "ok" : "FAIL") << (note.isNotEmpty() ? " (" + note + ")" : juce::String()) << "\n";
  20430. all = all && ok;
  20431. };
  20432. auto shot = [&folder] (juce::Component& c, const juce::String& name) {
  20433. savePng (lynx::shot::paint (c, lynx::theme::panel), folder.getChildFile (name).getFullPathName());
  20434. };
  20435. auto findSlot = [] (const lynx::Song& song, int& track, int& slot) {
  20436. for (track = 0; track < (int) song.mixer.size(); ++track)
  20437. for (slot = 0; slot < (int) song.mixer[(std::size_t) track].effects.size(); ++slot)
  20438. if (song.mixer[(std::size_t) track].effects[(std::size_t) slot].kind == lynx::EffectKind::edison)
  20439. return true;
  20440. return false;
  20441. };
  20442. {
  20443. lynx::AudioEngine engine (false);
  20444. engine.setRecordingTarget (folder.getChildFile ("Audio").getChildFile ("Recorded"), "Test");
  20445. // a project without the plugin is written as before: nothing of it in the file, and it reads back the same
  20446. const auto before = lynx::ProjectFile::toJson (engine.getSong(), false);
  20447. juce::String error;
  20448. const auto same = lynx::ProjectFile::fromJson (before, error);
  20449. check ("old_project_text_has_no_trace", ! before.containsIgnoreCase ("edison"));
  20450. check ("old_project_round_trip_stable", same.has_value() && lynx::ProjectFile::toJson (*same, false) == before);
  20451. const auto at = lynx::addEdisonSlot (engine, 1);
  20452. engine.dispatchPendingMessages();
  20453. check ("slot_added_to_first_empty_slot", at == 0 && engine.getSong().mixer[1].effects.size() == 1
  20454. && engine.getSong().mixer[1].effects[0].kind == lynx::EffectKind::edison);
  20455. if (at < 0)
  20456. {
  20457. folder.getChildFile ("report.txt").replaceWithText (report);
  20458. return false;
  20459. }
  20460. const auto second = lynx::addEdisonSlot (engine, 1); // several instances on a track
  20461. engine.dispatchPendingMessages();
  20462. check ("second_instance_on_the_same_track", second == 1);
  20463. engine.editSong ([at] (lynx::Song& s) {
  20464. s.mixer[1].effects[(std::size_t) at].params[ef::recordMode] = ef::modeValue (ef::Mode::now);
  20465. });
  20466. engine.dispatchPendingMessages();
  20467. const auto slotOf = [&engine, at] { return engine.getSong().mixer[1].effects[(std::size_t) at]; };
  20468. const auto fx = engine.getEffect (1, at);
  20469. const auto p = std::dynamic_pointer_cast<ef::Processor> (fx);
  20470. const auto session = ef::findSession (slotOf().instance.id);
  20471. check ("engine_built_the_effect_with_its_session", p != nullptr && session != nullptr);
  20472. const auto other = ef::findSession (engine.getSong().mixer[1].effects[1].instance.id);
  20473. check ("instances_have_their_own_audio", other != nullptr && other != session);
  20474. if (p == nullptr || session == nullptr)
  20475. {
  20476. folder.getChildFile ("report.txt").replaceWithText (report);
  20477. return false;
  20478. }
  20479. // idle: the audio passes through bit for bit
  20480. const auto rate = p->sampleRate();
  20481. std::vector<float> l (512), r (512);
  20482. auto fill = [&] (int block) {
  20483. for (int k = 0; k < 512; ++k)
  20484. {
  20485. const auto t = (double) (block * 512 + k) / rate;
  20486. l[(std::size_t) k] = 0.6f * (float) std::sin (2.0 * 3.141592653589793 * 220.0 * t);
  20487. r[(std::size_t) k] = 0.4f * (float) std::sin (2.0 * 3.141592653589793 * 330.0 * t);
  20488. }
  20489. };
  20490. fill (0);
  20491. auto inL = l, inR = r;
  20492. p->process (l.data(), r.data(), 512, slotOf().params, 120.0);
  20493. check ("idle_pass_through_bit_exact", l == inL && r == inR);
  20494. // a take through the slot (Now), then the flush that makes it a file of the project
  20495. std::vector<float> wantL, wantR;
  20496. check ("record_starts", session->start (p, true));
  20497. for (int block = 0; block < 60; ++block)
  20498. {
  20499. fill (block);
  20500. wantL.insert (wantL.end(), l.begin(), l.end());
  20501. wantR.insert (wantR.end(), r.begin(), r.end());
  20502. p->process (l.data(), r.data(), 512, slotOf().params, 120.0);
  20503. }
  20504. session->stop();
  20505. check ("take_is_the_input", session->document().audio.numChannels() == 2 && session->document().audio.channels[0] == wantL
  20506. && session->document().audio.channels[1] == wantR);
  20507. ae::Document withMarkers = session->document();
  20508. ae::addMarker (withMarkers, 4000, "Verse");
  20509. ae::addMarker (withMarkers, 12000);
  20510. ae::setLoop (withMarkers, { 2000, 20000 });
  20511. session->setDocument (withMarkers);
  20512. engine.flushEdisonAudio();
  20513. engine.dispatchPendingMessages();
  20514. const juce::File file (juce::String::fromUTF8 (slotOf().samplePath.c_str()));
  20515. check ("audio_written_to_the_project_folder", file.existsAsFile() && file.isAChildOf (folder.getChildFile ("Audio").getChildFile ("Recorded")),
  20516. file.getFullPathName());
  20517. check ("file_listed_with_the_session_recordings", std::find (engine.getSessionRecordings().begin(), engine.getSessionRecordings().end(), file)
  20518. != engine.getSessionRecordings().end());
  20519. check ("effect_kept_running_through_the_flush", engine.getEffect (1, at) == fx);
  20520. check ("nothing_unsaved_after_the_flush", ! session->dirty());
  20521. engine.flushEdisonAudio(); // (a second flush writes nothing new)
  20522. check ("second_flush_keeps_the_file", juce::File (juce::String::fromUTF8 (slotOf().samplePath.c_str())) == file);
  20523. // the project file: saved, loaded, the same slot with the same audio
  20524. engine.editSong ([at] (lynx::Song& s) {
  20525. auto& params = s.mixer[1].effects[(std::size_t) at].params;
  20526. params[ef::recordMode] = ef::modeValue (ef::Mode::onPlay);
  20527. params[ef::append] = 0.0f;
  20528. params[ef::muteInput] = 1.0f;
  20529. params[ef::slave] = 1.0f;
  20530. params[ef::maxTime] = 5.0f / 6.0f;
  20531. });
  20532. engine.capturePluginStates();
  20533. const auto project = folder.getChildFile ("edison-slot.lynx");
  20534. check ("project_saved", lynx::ProjectFile::save (engine.getSong(), project, error), error);
  20535. auto loaded = lynx::ProjectFile::load (project, error);
  20536. check ("project_loaded", loaded.has_value(), error);
  20537. if (loaded)
  20538. {
  20539. const auto& a = slotOf();
  20540. const auto& b = loaded->mixer[1].effects[(std::size_t) at];
  20541. check ("slot_kind_kept", b.kind == lynx::EffectKind::edison && loaded->mixer[1].effects.size() == 2);
  20542. check ("slot_settings_kept", ef::modeOf (b.params) == ef::Mode::onPlay && b.params[ef::append] < 0.5f && b.params[ef::muteInput] >= 0.5f
  20543. && b.params[ef::slave] >= 0.5f && ef::maxTimeIndexOf (b.params) == 5
  20544. && std::abs (b.params[ef::noiseThreshold] - a.params[ef::noiseThreshold]) < 1.0e-6f);
  20545. check ("slot_audio_path_kept", b.samplePath == a.samplePath);
  20546. check ("project_text_round_trip_stable", lynx::ProjectFile::toJson (*loaded, false) == lynx::ProjectFile::toJson (engine.getSong(), false));
  20547. lynx::AudioEngine second (false);
  20548. second.setSong (std::move (*loaded));
  20549. second.dispatchPendingMessages();
  20550. const auto reopened = ef::findSession (second.getSong().mixer[1].effects[(std::size_t) at].instance.id);
  20551. check ("reopened_project_has_the_audio", reopened != nullptr && reopened != session
  20552. && reopened->document().audio.channels == withMarkers.audio.channels
  20553. && reopened->document().audio.sampleRate == withMarkers.audio.sampleRate);
  20554. check ("reopened_project_has_markers_and_loop", reopened != nullptr && reopened->document().markers.size() == 2
  20555. && reopened->document().markers[0].name == "Verse"
  20556. && reopened->document().loopStart == 2000 && reopened->document().loopEnd == 20000);
  20557. check ("reopened_empty_instance_is_empty", ef::findSession (second.getSong().mixer[1].effects[1].instance.id) != nullptr
  20558. && ef::findSession (second.getSong().mixer[1].effects[1].instance.id)->document().audio.empty());
  20559. if (auto editor = lynx::makeEdisonSlotEditor (second, 1, at))
  20560. {
  20561. editor->setSize (1120, 600);
  20562. second.dispatchPendingMessages();
  20563. shot (*editor, "slot-editor-reopened.png");
  20564. }
  20565. }
  20566. // the plugin's window: the audio editor on the slot (empty instance, then the one with the take)
  20567. if (auto editor = lynx::makeEdisonSlotEditor (engine, 1, 1))
  20568. {
  20569. editor->setSize (1120, 600);
  20570. engine.dispatchPendingMessages();
  20571. shot (*editor, "slot-editor-empty.png");
  20572. }
  20573. auto editor = lynx::makeEdisonSlotEditor (engine, 1, at);
  20574. check ("slot_window_is_the_audio_editor", editor != nullptr);
  20575. if (editor != nullptr)
  20576. {
  20577. editor->setSize (1120, 600);
  20578. engine.dispatchPendingMessages();
  20579. shot (*editor, "slot-editor.png");
  20580. juce::File (folder.getChildFile ("slot-menu.txt")).replaceWithText (lynx::audioEditorMenuForSnapshot (*editor).joinIntoString ("\n") + "\n");
  20581. }
  20582. check ("no_editor_for_other_slots", lynx::makeEdisonSlotEditor (engine, 0, 0) == nullptr);
  20583. editor.reset();
  20584. // deleting the slot leaves the song without it (the file stays for the unused-recordings prompt)
  20585. engine.editSong ([at] (lynx::Song& s) { s.mixer[1].effects.erase (s.mixer[1].effects.begin() + at); });
  20586. engine.dispatchPendingMessages();
  20587. check ("deleted_slot_is_gone", engine.getSong().mixer[1].effects.size() == 1 && file.existsAsFile());
  20588. }
  20589. if (flp.isNotEmpty())
  20590. {
  20591. lynx::AudioEngine engine (false);
  20592. juce::String error;
  20593. const auto imported = engine.importFlpFile (juce::File (flp), error);
  20594. engine.dispatchPendingMessages();
  20595. check ("flp_imported", imported, error);
  20596. int count = 0, withAudio = 0;
  20597. const auto& song = engine.getSong();
  20598. for (int t = 0; t < (int) song.mixer.size(); ++t)
  20599. for (int s = 0; s < (int) song.mixer[(std::size_t) t].effects.size(); ++s)
  20600. {
  20601. const auto& fx = song.mixer[(std::size_t) t].effects[(std::size_t) s];
  20602. if (fx.kind != lynx::EffectKind::edison)
  20603. continue;
  20604. ++count;
  20605. const auto session = ef::findSession (fx.instance.id);
  20606. const auto frames = session != nullptr ? session->document().audio.frames() : -1;
  20607. withAudio += frames > 0 ? 1 : 0;
  20608. report << "flp_slot track " << t << " slot " << s << ": mode " << ef::modeName (ef::modeOf (fx.params))
  20609. << ", append " << (fx.params[ef::append] >= 0.5f ? "on" : "off") << ", mute input " << (fx.params[ef::muteInput] >= 0.5f ? "on" : "off")
  20610. << ", slave " << (fx.params[ef::slave] >= 0.5f ? "on" : "off") << ", loop " << (fx.params[ef::loopPlay] >= 0.5f ? "on" : "off")
  20611. << ", max time index " << ef::maxTimeIndexOf (fx.params) << ", threshold " << juce::String (fx.params[ef::noiseThreshold], 4)
  20612. << ", state " << (int) fx.state.size() << " bytes, audio " << (juce::int64) frames << " frames"
  20613. << (session != nullptr && frames > 0 ? " at " + juce::String (session->document().audio.sampleRate, 0) + " Hz, "
  20614. + juce::String (session->document().audio.numChannels()) + " ch, "
  20615. + juce::String ((int) session->document().markers.size()) + " markers"
  20616. : juce::String())
  20617. << "\n";
  20618. if (count == 1 || (frames > 0 && withAudio == 1))
  20619. if (auto editor = lynx::makeEdisonSlotEditor (engine, t, s))
  20620. {
  20621. editor->setSize (1120, 600);
  20622. engine.dispatchPendingMessages();
  20623. shot (*editor, frames > 0 ? "slot-editor-flp-audio.png" : "slot-editor-flp.png");
  20624. }
  20625. }
  20626. check ("flp_edison_slots_kept_as_the_plugin", count > 0, juce::String (count) + " slots, " + juce::String (withAudio) + " with audio");
  20627. // saved as .lynx and read again: still the plugin, FL's state (the audio) with it
  20628. int t = 0, s = 0;
  20629. if (findSlot (song, t, s))
  20630. {
  20631. const auto project = folder.getChildFile ("edison-flp.lynx");
  20632. const auto saved = lynx::ProjectFile::save (song, project, error);
  20633. std::optional<lynx::Song> loaded;
  20634. if (saved)
  20635. loaded = lynx::ProjectFile::load (project, error);
  20636. check ("flp_slot_survives_the_project_file", loaded.has_value() && t < (int) loaded->mixer.size()
  20637. && s < (int) loaded->mixer[(std::size_t) t].effects.size()
  20638. && loaded->mixer[(std::size_t) t].effects[(std::size_t) s].kind == lynx::EffectKind::edison
  20639. && loaded->mixer[(std::size_t) t].effects[(std::size_t) s].state == song.mixer[(std::size_t) t].effects[(std::size_t) s].state
  20640. && loaded->mixer[(std::size_t) t].effects[(std::size_t) s].params == song.mixer[(std::size_t) t].effects[(std::size_t) s].params,
  20641. error);
  20642. }
  20643. }
  20644. // round 190ct (live FL check 190cq): the open-and-record preset, the fresh defaults and the question before
  20645. // "Remove all Edison instances", in the app
  20646. {
  20647. lynx::AudioEngine engine (false);
  20648. lynx::MainComponent ui (engine, false);
  20649. ui.setSize (1600, 900);
  20650. engine.dispatchPendingMessages();
  20651. const auto toolsMenu = [&ui] {
  20652. const auto names = ui.getMenuNamesForSnapshot();
  20653. for (int m = 0; m < names.size(); ++m)
  20654. if (names[m] == lynx::tr ("Tools"))
  20655. return ui.getMenuForSnapshot (m);
  20656. return juce::PopupMenu();
  20657. };
  20658. const auto removeItem = [&toolsMenu] (bool& found, bool& enabled) {
  20659. found = enabled = false;
  20660. const auto menu = toolsMenu(); // (the iterator keeps a reference)
  20661. for (juce::PopupMenu::MenuItemIterator it (menu, true); it.next();)
  20662. if (it.getItem().text == lynx::tr ("Remove all Edison instances"))
  20663. {
  20664. found = true;
  20665. enabled = it.getItem().isEnabled;
  20666. if (enabled && it.getItem().action)
  20667. it.getItem().action(); // asks: nothing may go before the answer
  20668. return;
  20669. }
  20670. };
  20671. const auto count = [&engine] {
  20672. int n = 0;
  20673. for (const auto& track : engine.getSong().mixer)
  20674. for (const auto& fx : track.effects)
  20675. n += fx.kind == lynx::EffectKind::edison ? 1 : 0;
  20676. return n;
  20677. };
  20678. bool found = false, enabled = false;
  20679. removeItem (found, enabled);
  20680. check ("remove_all_edison_enabled_with_none", found && enabled && count() == 0);
  20681. const auto plain = lynx::addEdisonSlot (engine, 1);
  20682. const auto armed = lynx::addEdisonSlot (engine, 2, true);
  20683. engine.dispatchPendingMessages();
  20684. if (plain >= 0 && armed >= 0)
  20685. {
  20686. const auto& a = engine.getSong().mixer[1].effects[(std::size_t) plain].params;
  20687. const auto& b = engine.getSong().mixer[2].effects[(std::size_t) armed].params;
  20688. check ("open_audio_editor_fresh_defaults", ef::modeOf (a) == ef::Mode::onInput && ef::maxTimeIndexOf (a) == 5 && a[ef::append] >= 0.5f
  20689. && a[ef::slave] < 0.5f);
  20690. check ("open_audio_editor_and_record_preset", ef::modeOf (b) == ef::Mode::onPlay && ef::maxTimeIndexOf (b) == 3 && b[ef::append] < 0.5f
  20691. && b[ef::slave] >= 0.5f);
  20692. }
  20693. else
  20694. check ("open_audio_editor_slots_added", false);
  20695. removeItem (found, enabled);
  20696. engine.dispatchPendingMessages();
  20697. check ("remove_all_edison_asks_first", found && enabled && count() == 2);
  20698. const auto question = lynx::removeAllEdisonInstancesQuestion();
  20699. check ("remove_all_edison_question_is_fls", question.getTitle() == lynx::tr ("Remove Edison instances")
  20700. && question.getMessage() == lynx::tr ("Are you sure you want to remove all Edison instances from the project ?")
  20701. && question.getNumButtons() == 2 && question.getButtonText (0) == lynx::tr ("Yes")
  20702. && question.getButtonText (1) == lynx::tr ("No"));
  20703. // LYNX keeps an undo for the removal (rollup 190cv), so the question may not promise "(No undo)" in any
  20704. // language, and the Yes action must come back with one undo
  20705. {
  20706. bool noUndoLine = false;
  20707. for (const auto& line : juce::StringArray::fromLines (question.getMessage()))
  20708. noUndoLine = noUndoLine || line.trim().startsWithChar ('(');
  20709. check ("remove_all_edison_question_has_no_no_undo_line", ! noUndoLine && ! question.getMessage().contains ("No undo"));
  20710. const int before = count();
  20711. lynx::removeAllEdisonInstances (engine);
  20712. engine.dispatchPendingMessages();
  20713. const int removed = count();
  20714. engine.undo();
  20715. engine.dispatchPendingMessages();
  20716. check ("remove_all_edison_yes_removes_and_undo_restores", before == 2 && removed == 0 && count() == 2);
  20717. }
  20718. {
  20719. juce::AlertWindow box (question.getTitle(), question.getMessage(), question.getIconType());
  20720. box.addButton (question.getButtonText (0), 1);
  20721. box.addButton (question.getButtonText (1), 0);
  20722. box.setSize (box.getWidth(), box.getHeight());
  20723. savePng (lynx::shot::paint (box, lynx::theme::panel), folder.getChildFile ("remove-all-edison-question.png").getFullPathName());
  20724. }
  20725. {
  20726. lynx::EffectSlot slot = lynx::makeEffectSlot (lynx::EffectKind::edison);
  20727. lynx::edisonfx::setOpenAndRecord (slot.params);
  20728. engine.editSong ([&slot] (lynx::Song& s) { s.mixer[3].effects.push_back (slot); });
  20729. engine.dispatchPendingMessages();
  20730. if (const auto editor = lynx::makeEdisonSlotEditor (engine, 3, 0))
  20731. {
  20732. editor->setSize (1120, 600);
  20733. engine.dispatchPendingMessages();
  20734. shot (*editor, "slot-editor-open-and-record.png");
  20735. }
  20736. if (const auto editor = lynx::makeEdisonSlotEditor (engine, 1, plain))
  20737. {
  20738. editor->setSize (1120, 600);
  20739. engine.dispatchPendingMessages();
  20740. shot (*editor, "slot-editor-fresh-defaults.png");
  20741. }
  20742. }
  20743. }
  20744. report << (all ? "ALL OK\n" : "FAILURES\n");
  20745. folder.getChildFile ("report.txt").replaceWithText (report);
  20746. return all;
  20747. }
  20748. void runNewtoneShot (const juce::String& prefix, const juce::String& file)
  20749. {
  20750. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  20751. lynx::AudioEngine offline (false);
  20752. const auto sample = offline.getSampleLibrary().load (file);
  20753. if (sample == nullptr)
  20754. {
  20755. std::fprintf (stderr, "newtoneshot: cannot read %s\n", file.toRawUTF8());
  20756. return;
  20757. }
  20758. int at = 0;
  20759. offline.editSong ([&] (lynx::Song& song) {
  20760. if (song.mixer.size() < 2)
  20761. song.mixer.resize (2);
  20762. auto tone = lynx::makeEffectSlot (lynx::EffectKind::newtone);
  20763. tone.samplePath = file.toStdString();
  20764. tone.state = lynx::newtonefx::writeNative (lynx::newtonefx::analyseNotes (*sample));
  20765. at = (int) song.mixer[1].effects.size();
  20766. song.mixer[1].effects.push_back (tone);
  20767. }, false);
  20768. auto shot = [&] (const juce::String& name, const juce::StringArray& states) {
  20769. auto editor = lynx::makeNewtoneEditor (offline, 1, at);
  20770. for (const auto& st : states)
  20771. lynx::setNewtoneShotState (*editor, st);
  20772. saveSnapshot (*editor, prefix + "-" + name + ".png");
  20773. };
  20774. shot ("plain", {});
  20775. shot ("cursor", { "cursor:30000" });
  20776. shot ("selected", { "select:2" });
  20777. shot ("advanced", { "select:3", "advanced" });
  20778. shot ("vibrato", { "select:3", "vibrato" });
  20779. shot ("cut", { "cut" });
  20780. shot ("timesel", { "timesel:20000,60000" });
  20781. shot ("moved", { "shift:2,2", "select:2" });
  20782. // paint cost: 40 full paints of each layout
  20783. juce::String report;
  20784. {
  20785. auto fl = lynx::makeNewtoneEditor (offline, 1, at);
  20786. lynx::newtonePaintMs (*fl, 3);
  20787. report << "fl-look " << fl->getWidth() << "x" << fl->getHeight() << " ms/paint " << juce::String (lynx::newtonePaintMs (*fl, 40), 3) << "\n";
  20788. auto old = lynx::makeNewtoneEditor (offline, 1, at);
  20789. lynx::setNewtoneShotState (*old, "lynxlook");
  20790. lynx::newtonePaintMs (*old, 3);
  20791. report << "lynx-165g-look " << old->getWidth() << "x" << old->getHeight() << " ms/paint " << juce::String (lynx::newtonePaintMs (*old, 40), 3) << "\n";
  20792. saveSnapshot (*old, prefix + "-lynxlook.png");
  20793. }
  20794. lynx::shot::file (juce::File (prefix + "-paint.txt")).replaceWithText (report);
  20795. std::printf ("%s", report.toRawUTF8());
  20796. }
  20797. void runEdisonShot (const juce::String& prefix, const juce::String& file)
  20798. {
  20799. namespace ae = lynx::audioedit;
  20800. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  20801. lynx::AudioEngine offline (false);
  20802. ae::Document d;
  20803. if (file.isNotEmpty())
  20804. {
  20805. juce::MemoryBlock bytes;
  20806. if (! juce::File (file).loadFileAsData (bytes) || ! ae::decodeWav (static_cast<const std::uint8_t*> (bytes.getData()), bytes.getSize(), d))
  20807. {
  20808. std::fprintf (stderr, "edisonshot: cannot read %s\n", file.toRawUTF8());
  20809. return;
  20810. }
  20811. }
  20812. else
  20813. {
  20814. // a drum loop with a hum and hiss under it (something for the denoiser and the EQ to show)
  20815. d.title = "Drum loop";
  20816. d.audio.sampleRate = 44100.0;
  20817. const auto frames = (std::size_t) (44100 * 2);
  20818. d.audio.channels.assign (2, std::vector<float> (frames, 0.0f));
  20819. std::uint32_t seed = 7;
  20820. for (std::size_t i = 0; i < frames; ++i)
  20821. {
  20822. seed = seed * 1664525u + 1013904223u;
  20823. const auto hiss = ((float) (seed >> 8) / 16777216.0f - 0.5f) * 0.02f;
  20824. const auto hum = 0.01f * (float) std::sin (2.0 * 3.141592653589793 * 50.0 * (double) i / 44100.0);
  20825. d.audio.channels[0][i] = hiss + hum;
  20826. d.audio.channels[1][i] = hiss * 0.9f + hum;
  20827. }
  20828. for (int hit = 0; hit < 8; ++hit)
  20829. {
  20830. const auto at = (std::size_t) hit * frames / 8;
  20831. const auto kick = hit % 2 == 0;
  20832. double phase = 0.0;
  20833. for (std::size_t i = 0; i < 12000 && at + i < frames; ++i)
  20834. {
  20835. seed = seed * 1664525u + 1013904223u;
  20836. const auto noise = (float) (seed >> 8) / 16777216.0f - 0.5f;
  20837. const auto t = (double) i / 44100.0;
  20838. phase += 2.0 * 3.141592653589793 * (kick ? 45.0 + 160.0 * std::exp (-t * 30.0) : 190.0) / 44100.0;
  20839. const auto body = (float) std::sin (phase) * (float) std::exp (-t * (kick ? 9.0 : 22.0));
  20840. const auto v = kick ? 0.85f * body : 0.35f * body + 0.6f * noise * (float) std::exp (-t * 18.0);
  20841. d.audio.channels[0][at + i] += v;
  20842. d.audio.channels[1][at + i] += kick ? v : v * 0.8f;
  20843. }
  20844. }
  20845. for (int hit = 1; hit < 8; ++hit)
  20846. ae::addMarker (d, (std::int64_t) (hit * frames / 8));
  20847. ae::setLoop (d, { 0, (std::int64_t) frames });
  20848. }
  20849. // a volume envelope (a fade-in and a dip) to show the envelope mode and the envelope tools
  20850. 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 } };
  20851. auto editor = lynx::makeAudioEditorForSnapshot (offline, d, false);
  20852. auto shot = [&prefix] (juce::Component& c, const juce::String& name) {
  20853. auto image = lynx::shot::paint (c, lynx::theme::panel);
  20854. savePng (image, prefix + name);
  20855. };
  20856. editor->setSize (1120, 600);
  20857. lynx::setAudioEditorEnvelopeModeForSnapshot (*editor, 1);
  20858. shot (*editor, "-editor-volume-envelope.png");
  20859. lynx::setAudioEditorEnvelopeModeForSnapshot (*editor, 0);
  20860. juce::File (prefix + "-menu.txt").replaceWithText (lynx::audioEditorMenuForSnapshot (*editor).joinIntoString ("\n") + "\n");
  20861. // round 190ee: the first marker's menu (Trigger note) and FL's four snap modes on a probe frame
  20862. if (! d.markers.empty())
  20863. juce::File (prefix + "-marker-menu.txt").replaceWithText (lynx::audioEditorMarkerMenuForSnapshot (*editor, 0).joinIntoString ("\n") + "\n");
  20864. {
  20865. juce::StringArray snaps;
  20866. const auto probe = (std::int64_t) (d.audio.frames() * 3 / 8) + 777;
  20867. for (int mode = 0; mode < 5; ++mode) // (round natives190kj: 5 = Snap to pitch period)
  20868. snaps.add (lynx::setAudioEditorSnapForSnapshot (*editor, mode, probe));
  20869. juce::File (prefix + "-snap.txt").replaceWithText (snaps.joinIntoString ("\n") + "\n");
  20870. lynx::setAudioEditorSnapForSnapshot (*editor, 0, probe);
  20871. shot (*editor, "-editor-snap-on.png");
  20872. }
  20873. // round natives190kj: FL's Dual view, the time grid at a few zooms, grid-slicing, Detect pitch regions, the Scrub
  20874. // button's player (prefix-natives190kj.txt: one "name=ok|FAIL" or a report line per check)
  20875. {
  20876. juce::StringArray report;
  20877. const auto frames = d.audio.frames();
  20878. lynx::setAudioEditorViewForSnapshot (*editor, false, false, 0, frames);
  20879. shot (*editor, "-editor-wave.png");
  20880. lynx::setAudioEditorViewForSnapshot (*editor, false, true, 0, frames);
  20881. shot (*editor, "-editor-dual-wave.png");
  20882. lynx::setAudioEditorViewForSnapshot (*editor, true, false, 0, frames);
  20883. shot (*editor, "-editor-spectrum.png");
  20884. lynx::setAudioEditorViewForSnapshot (*editor, true, true, 0, frames);
  20885. shot (*editor, "-editor-dual-spectrum.png");
  20886. lynx::setAudioEditorViewForSnapshot (*editor, true, true, frames / 4, frames / 4 + 8 * 1080); // (8 samples per pixel)
  20887. shot (*editor, "-editor-dual-spectrum-zoom8.png");
  20888. lynx::setAudioEditorViewForSnapshot (*editor, false, false, 0, frames);
  20889. for (const auto& [from, to] : { std::pair<std::int64_t, std::int64_t> { 0, frames }, { 0, frames / 4 }, { 0, frames / 40 }, { 0, frames / 400 } })
  20890. {
  20891. lynx::setAudioEditorViewForSnapshot (*editor, false, false, from, to);
  20892. report.add ("grid seconds, view " + juce::String (from) + ".." + juce::String (to) + ": " + lynx::audioEditorCommandForSnapshot (*editor, "grid"));
  20893. }
  20894. lynx::setAudioEditorViewForSnapshot (*editor, false, false, 0, frames);
  20895. shot (*editor, "-editor-grid-seconds.png");
  20896. auto synced = d.props;
  20897. synced.tempo = 120.0;
  20898. synced.tempoSync = true;
  20899. lynx::setAudioEditorSamplePropsForSnapshot (*editor, synced);
  20900. report.add ("grid beats (tempo-sync 120 BPM): " + lynx::audioEditorCommandForSnapshot (*editor, "grid"));
  20901. shot (*editor, "-editor-grid-beats.png");
  20902. lynx::setAudioEditorSamplePropsForSnapshot (*editor, d.props);
  20903. {
  20904. auto plainDoc = d; // (a copy: the editor above keeps its markers for the tool shots)
  20905. plainDoc.markers.clear();
  20906. auto slicer = lynx::makeAudioEditorForSnapshot (offline, plainDoc, false);
  20907. slicer->setSize (1120, 600);
  20908. report.add (lynx::audioEditorCommandForSnapshot (*slicer, "grid-medium-all"));
  20909. shot (*slicer, "-editor-grid-slicing-medium.png");
  20910. report.add (lynx::audioEditorCommandForSnapshot (*slicer, "grid-small-all"));
  20911. shot (*slicer, "-editor-grid-slicing-small.png");
  20912. }
  20913. // Detect pitch regions on three sung-like notes (A3, C4, E4)
  20914. {
  20915. ae::Document m;
  20916. m.title = "Three notes";
  20917. m.audio.sampleRate = 44100.0;
  20918. const auto len = (std::size_t) (44100 * 3);
  20919. m.audio.channels.assign (1, std::vector<float> (len));
  20920. double phase = 0.0;
  20921. for (std::size_t i = 0; i < len; ++i)
  20922. {
  20923. const auto hz = i < len / 3 ? 220.0 : i < 2 * len / 3 ? 261.6256 : 329.6276;
  20924. phase += 2.0 * 3.141592653589793 * hz / 44100.0;
  20925. m.audio.channels[0][i] = (float) (0.4 * std::sin (phase) + 0.2 * std::sin (2.0 * phase) + 0.1 * std::sin (3.0 * phase));
  20926. }
  20927. auto melody = lynx::makeAudioEditorForSnapshot (offline, m, false);
  20928. melody->setSize (1120, 600);
  20929. report.add (lynx::audioEditorCommandForSnapshot (*melody, "pitch-regions"));
  20930. shot (*melody, "-editor-pitch-regions.png");
  20931. }
  20932. // the Scrub button's player: paused (silent, held), 2x forward, 1x backward, held at the start
  20933. {
  20934. lynx::PreviewPlayer player;
  20935. player.prepareToPlay (44100.0, 512);
  20936. auto ramp = std::make_shared<lynx::SampleData>();
  20937. ramp->sampleRate = 44100.0;
  20938. ramp->left.resize (44100);
  20939. for (std::size_t i = 0; i < ramp->left.size(); ++i)
  20940. ramp->left[i] = (float) i / 44100.0f;
  20941. ramp->right = ramp->left;
  20942. juce::AudioBuffer<float> block (2, 512);
  20943. juce::MidiBuffer midi;
  20944. player.playScrub (ramp, 22050, 1.0f);
  20945. player.processBlock (block, midi);
  20946. report.add (juce::String ("scrub paused holds=") + (player.getPlayPosition() == 22050.0 && block.getMagnitude (0, 512) == 0.0f ? "ok" : "FAIL"));
  20947. player.setScrubSpeed (2.0);
  20948. player.processBlock (block, midi);
  20949. report.add (juce::String ("scrub 2x forward=") + (std::abs (player.getPlayPosition() - (22050.0 + 1024.0)) < 1e-6 && std::abs (block.getSample (0, 511) - (22050.0f + 1022.0f) / 44100.0f) < 1e-3f ? "ok" : "FAIL")
  20950. + " (pos " + juce::String (player.getPlayPosition()) + ", last " + juce::String (block.getSample (0, 511), 5) + ")");
  20951. player.setScrubSpeed (-1.0);
  20952. player.processBlock (block, midi);
  20953. report.add (juce::String ("scrub 1x backward=") + (std::abs (player.getPlayPosition() - (22050.0 + 512.0)) < 1e-6 && block.getSample (0, 0) > block.getSample (0, 511) ? "ok" : "FAIL"));
  20954. player.setScrubSpeed (-16.0);
  20955. for (int b = 0; b < 20; ++b)
  20956. player.processBlock (block, midi);
  20957. report.add (juce::String ("scrub held at the start=") + (player.getPlayPosition() == 0.0 ? "ok" : "FAIL"));
  20958. // CPU of a 16x block (the widest kernel)
  20959. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  20960. player.setScrubSpeed (16.0);
  20961. for (int b = 0; b < 200; ++b)
  20962. player.processBlock (block, midi);
  20963. report.add ("scrub 16x: " + juce::String ((juce::Time::getMillisecondCounterHiRes() - t0) / 200.0, 4) + " ms per 512-frame block");
  20964. }
  20965. // paint cost: full paints of the editor, waveform / Dual view / spectrogram
  20966. for (const auto& [spectrum, dual, name] : { std::tuple<bool, bool, const char*> { false, false, "wave" }, { false, true, "dual-wave" }, { true, true, "dual-spectrum" }, { true, false, "spectrum" } })
  20967. {
  20968. lynx::setAudioEditorViewForSnapshot (*editor, spectrum, dual, 0, frames);
  20969. juce::Image img (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
  20970. {
  20971. juce::Graphics g (img);
  20972. editor->paintEntireComponent (g, true); // (the spectrogram images are made once)
  20973. }
  20974. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  20975. for (int k = 0; k < 40; ++k)
  20976. {
  20977. juce::Graphics g (img);
  20978. editor->paintEntireComponent (g, true);
  20979. }
  20980. report.add ("paint " + juce::String (name) + ": " + juce::String ((juce::Time::getMillisecondCounterHiRes() - t0) / 40.0, 3) + " ms per full paint");
  20981. }
  20982. lynx::setAudioEditorViewForSnapshot (*editor, false, false, 0, frames);
  20983. juce::File (prefix + "-natives190kj.txt").replaceWithText (report.joinIntoString ("\n") + "\n");
  20984. }
  20985. // round gaps190kf: FL's Sample properties window (Format › Edit properties..., F2) for this audio, with a few
  20986. // properties set, and the WAV chunks it writes (smpl / inst / acid / LIST INFO) listed
  20987. {
  20988. auto withProps = d;
  20989. withProps.props.name = "Drum loop";
  20990. withProps.props.comments = "LYNX SHARE test loop";
  20991. withProps.props.tempo = 120.0;
  20992. withProps.props.tempoSync = true;
  20993. withProps.props.fineTune = 12.0;
  20994. lynx::SamplePropertiesHost host;
  20995. host.projectTempo = 120.0;
  20996. auto props = lynx::makeSamplePropertiesPanel (withProps, d.title.empty() ? std::string ("Drum loop") : d.title, host);
  20997. shot (*props, "-sample-properties.png");
  20998. // the file's own properties (a WAV without them: FL's defaults — the FL | LYNX pair of the form as it opens)
  20999. auto plain = lynx::makeSamplePropertiesPanel (d, file.isNotEmpty() ? juce::File (file).getFileNameWithoutExtension().toStdString() : std::string ("Drum loop"), host);
  21000. shot (*plain, "-sample-properties-file.png");
  21001. juce::StringArray chunks;
  21002. const auto wav = ae::encodeWav (withProps, ae::WavFormat::int16);
  21003. for (std::size_t p = 12; p + 8 <= wav.size();)
  21004. {
  21005. const auto len = (std::size_t) wav[p + 4] | (std::size_t) wav[p + 5] << 8 | (std::size_t) wav[p + 6] << 16 | (std::size_t) wav[p + 7] << 24;
  21006. chunks.add (juce::String (reinterpret_cast<const char*> (wav.data() + p), 4) + " " + juce::String ((int) len));
  21007. p += 8 + len + (len & 1);
  21008. }
  21009. juce::File (prefix + "-sample-properties-chunks.txt").replaceWithText (chunks.joinIntoString ("\n") + "\n");
  21010. }
  21011. for (int t = 0; lynx::audioToolNameForSnapshot (t) != nullptr; ++t)
  21012. {
  21013. const auto envelopeTool = t >= 10 && t <= 14; // Scale levels .. Create sequence work on the volume envelope
  21014. if (auto panel = lynx::makeAudioToolPanelForSnapshot (*editor, t, envelopeTool ? 1 : 0))
  21015. {
  21016. offline.dispatchPendingMessages();
  21017. const auto name = juce::String (lynx::audioToolNameForSnapshot (t)).toLowerCase().retainCharacters ("abcdefghijklmnopqrstuvwxyz ").trim().replaceCharacter (' ', '-');
  21018. shot (*panel, "-tool-" + juce::String (t).paddedLeft ('0', 2) + "-" + name + ".png");
  21019. if (envelopeTool)
  21020. shot (*editor, "-tool-" + juce::String (t).paddedLeft ('0', 2) + "-" + name + "-editor.png");
  21021. panel.reset(); // (puts the envelope back)
  21022. }
  21023. }
  21024. }
  21025. static juce::TextButton* findButton (juce::Component& root, const juce::String& text)
  21026. {
  21027. if (auto* b = dynamic_cast<juce::TextButton*> (&root); b != nullptr && b->getButtonText() == text)
  21028. return b;
  21029. for (auto* child : root.getChildren())
  21030. if (auto* b = findButton (*child, text))
  21031. return b;
  21032. return nullptr;
  21033. }
  21034. // a VFX Script editor's Script / Log / API reference tabs, then the Script tab of a script with an error
  21035. void shootScriptTabs (juce::Component& panel, lynx::AudioEngine& engine, int index, const juce::String& name)
  21036. {
  21037. const std::pair<const char*, const char*> tabs[] = { { "Script", "script" }, { "Log", "log" }, { "API reference", "api" } };
  21038. for (const auto& [tab, file] : tabs)
  21039. if (auto* b = findButton (panel, lynx::tr (tab)); b != nullptr && b->onClick)
  21040. {
  21041. b->onClick();
  21042. savePng (lynx::shot::snapshot (panel), name + "-tab-" + file + ".png");
  21043. }
  21044. engine.editSong ([&] (lynx::Song& s) {
  21045. auto st = *lynx::vfx::readState (s.channels[(std::size_t) index].pluginState);
  21046. auto settings = lynx::vfx::parseScript (st.fl).value_or (lynx::vfx::defaultScript());
  21047. settings.setSource ("import flvfx as vfx\n\ndef onTriggerVoice(incomingVoice):\n v = vfx.Voice(incomingVoice)\n"
  21048. " v.note += 7\n v.trigger(\n\ndef onReleaseVoice(incomingVoice):\n pass\n");
  21049. st.fl = lynx::vfx::writeScript (settings);
  21050. s.channels[(std::size_t) index].pluginState = lynx::vfx::writeState (st);
  21051. });
  21052. engine.dispatchPendingMessages();
  21053. if (auto broken = lynx::makeChannelSettingsPanel (engine, index))
  21054. {
  21055. engine.dispatchPendingMessages();
  21056. if (auto* b = findButton (*broken, lynx::tr ("Script")); b != nullptr && b->onClick)
  21057. b->onClick();
  21058. savePng (lynx::shot::snapshot (*broken), name + "-error.png");
  21059. }
  21060. }
  21061. void runVfxShot (const juce::String& prefix)
  21062. {
  21063. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  21064. lynx::AudioEngine offline (false);
  21065. lynx::MainComponent ui (offline, false);
  21066. ui.setSize (1280, 720);
  21067. auto song = lynx::Song::makeDefault();
  21068. song.channels.clear();
  21069. for (const auto kind : lynx::vfx::allKinds)
  21070. {
  21071. lynx::ChannelDef c;
  21072. lynx::vfx::makeChannel (c, kind);
  21073. if (kind == lynx::vfx::Kind::keyMapper) // a chord on every key: something to see in the grid
  21074. for (const auto& p : lynx::vfx::builtInPresets (kind))
  21075. if (p.name == "Major triad")
  21076. {
  21077. auto st = *lynx::vfx::readState (c.pluginState);
  21078. st.fl = p.fl;
  21079. c.pluginState = lynx::vfx::writeState (st);
  21080. }
  21081. song.channels.push_back (c);
  21082. }
  21083. // a Patcher: its notes through a Color Mapper to three synths
  21084. lynx::ChannelDef patcher;
  21085. patcher.name = "Patcher";
  21086. patcher.instrument = lynx::InstrumentKind::patcher;
  21087. lynx::PatchNode mapper;
  21088. mapper.generator = true;
  21089. lynx::vfx::makeChannel (mapper.channel, lynx::vfx::Kind::colorMapper);
  21090. mapper.x = 260.0f;
  21091. patcher.patcher.nodes.push_back (mapper);
  21092. lynx::PatchWire notes;
  21093. notes.kind = lynx::PatchWire::Kind::midi, notes.to = 0;
  21094. patcher.patcher.wires.push_back (notes);
  21095. for (int k = 0; k < 3; ++k)
  21096. {
  21097. lynx::PatchNode synth;
  21098. synth.generator = true;
  21099. synth.channel.instrument = lynx::InstrumentKind::synth;
  21100. synth.channel.name = "Synth " + std::to_string (k + 1);
  21101. synth.x = 520.0f, synth.y = (float) k * 90.0f;
  21102. patcher.patcher.nodes.push_back (synth);
  21103. lynx::PatchWire in, out;
  21104. in.kind = lynx::PatchWire::Kind::midi, in.from = 0, in.fromPort = k, in.to = 1 + k;
  21105. out.from = 1 + k, out.to = lynx::patchToHost;
  21106. patcher.patcher.wires.push_back (in);
  21107. patcher.patcher.wires.push_back (out);
  21108. }
  21109. patcher.patcher.outputX = 760.0f;
  21110. song.channels.push_back (patcher);
  21111. offline.setSong (std::move (song));
  21112. offline.dispatchPendingMessages();
  21113. for (int c = 0; c < lynx::vfx::kindCount; ++c)
  21114. if (auto panel = lynx::makeChannelSettingsPanel (offline, c))
  21115. {
  21116. offline.dispatchPendingMessages();
  21117. savePng (lynx::shot::snapshot (*panel),
  21118. prefix + "-" + juce::String (lynx::vfx::flName (*lynx::vfx::kindOf (offline.getSong().channels[(std::size_t) c]))).replaceCharacter (' ', '-').toLowerCase() + ".png");
  21119. }
  21120. // with FL Studio installed: the Sequencer with FL's factory bank (to compare with FL's own editor) and
  21121. // a Script with FL's "Snap To Scale"
  21122. if (const auto roots = lynx::findFlStudioRoots(); ! roots.data.empty())
  21123. {
  21124. const auto data = juce::File (juce::String::fromUTF8 (roots.data.c_str()));
  21125. const std::pair<lynx::vfx::Kind, juce::String> extra[] = {
  21126. { lynx::vfx::Kind::sequencer, "Patches/Plugin database/Effects/Patcher/VFX Sequencer.fst" },
  21127. { lynx::vfx::Kind::script, "Patches/Plugin presets/Effects/VFX Script/Snap To Scale.fst" },
  21128. };
  21129. for (const auto& [kind, path] : extra)
  21130. {
  21131. juce::MemoryBlock bytes;
  21132. if (! data.getChildFile (path).loadFileAsData (bytes))
  21133. continue;
  21134. const auto* b = static_cast<const std::uint8_t*> (bytes.getData());
  21135. const auto fl = lynx::vfx::stateFromFlPreset (std::vector<std::uint8_t> (b, b + bytes.getSize()), kind);
  21136. int index = -1;
  21137. for (int c = 0; c < lynx::vfx::kindCount; ++c)
  21138. if (lynx::vfx::kindOf (offline.getSong().channels[(std::size_t) c]) == kind)
  21139. index = c;
  21140. if (! fl || index < 0)
  21141. continue;
  21142. offline.editSong ([&] (lynx::Song& s) {
  21143. auto st = *lynx::vfx::readState (s.channels[(std::size_t) index].pluginState);
  21144. st.fl = *fl;
  21145. s.channels[(std::size_t) index].pluginState = lynx::vfx::writeState (st);
  21146. });
  21147. offline.dispatchPendingMessages();
  21148. if (auto panel = lynx::makeChannelSettingsPanel (offline, index))
  21149. {
  21150. offline.dispatchPendingMessages();
  21151. const auto name = prefix + "-" + juce::String (lynx::vfx::flName (kind)).replaceCharacter (' ', '-').toLowerCase();
  21152. savePng (lynx::shot::snapshot (*panel), name + "-fl.png");
  21153. if (kind == lynx::vfx::Kind::script) // the editor's other tabs (round 165d)
  21154. shootScriptTabs (*panel, offline, index, name);
  21155. }
  21156. }
  21157. }
  21158. lynx::PatcherWindows::openChannel (offline, lynx::vfx::kindCount);
  21159. for (int k = 0; k < juce::TopLevelWindow::getNumTopLevelWindows(); ++k)
  21160. if (auto* w = dynamic_cast<juce::DocumentWindow*> (juce::TopLevelWindow::getTopLevelWindow (k)))
  21161. if (w->getName().startsWith (lynx::tr ("Patcher")) && w->getContentComponent() != nullptr)
  21162. {
  21163. auto* content = w->getContentComponent();
  21164. savePng (lynx::shot::snapshot (*content), prefix + "-patcher.png");
  21165. delete w;
  21166. break;
  21167. }
  21168. lynx::PatcherWindows::shootMenus (offline, true, lynx::vfx::kindCount, 0, [&] (const juce::Image& image, const juce::String& name) {
  21169. savePng (image, prefix + "-patcher-menu-" + name + ".png");
  21170. });
  21171. // a plugin renamed in the Plugin database ("1_EQ", FL): the Quick-add palette and the mixer slot show the new name
  21172. if (juce::SystemStats::getEnvironmentVariable ("LYNX_TEST_MODE", {}).isNotEmpty())
  21173. {
  21174. const auto key = std::string ("lynx:fx:") + lynx::effectInfo (lynx::EffectKind::parametricEq).name;
  21175. offline.getPluginHost().setPluginName (key, "1_EQ");
  21176. offline.editSong ([] (lynx::Song& s) {
  21177. if (s.mixer.size() > 1)
  21178. {
  21179. lynx::EffectSlot slot;
  21180. slot.kind = lynx::EffectKind::parametricEq;
  21181. s.mixer[1].effects.push_back (slot);
  21182. }
  21183. });
  21184. offline.dispatchPendingMessages();
  21185. {
  21186. lynx::QuickAddTargets targets;
  21187. targets.addInstrument = [] (lynx::ChannelDef) {};
  21188. targets.addEffect = [] (lynx::EffectSlot) {};
  21189. auto palette = lynx::makeQuickAddPalette (offline, std::move (targets));
  21190. savePng (lynx::shot::snapshot (*palette), prefix + "-quickadd-renamed.png");
  21191. }
  21192. ui.selectTabForSnapshot (3);
  21193. ui.getMixerForSnapshot().selectTrack (1);
  21194. offline.dispatchPendingMessages();
  21195. savePng (lynx::shot::snapshot (ui), prefix + "-mixer-renamed.png");
  21196. offline.getPluginHost().setPluginName (key, "");
  21197. }
  21198. }
  21199. void runAudioXShot (const juce::String& prefix)
  21200. {
  21201. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  21202. lynx::AudioEngine offline (false);
  21203. {
  21204. lynx::MainComponent ui (offline, false);
  21205. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  21206. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  21207. offline.dispatchPendingMessages();
  21208. // 1. sends: insert 1 feeds insert 3 pre-fader and insert 4 post-fader (FL's way)
  21209. offline.editSong ([] (lynx::Song& s) {
  21210. if (s.mixer.size() < 5)
  21211. return;
  21212. s.mixer[1].name = "Vocal";
  21213. s.mixer[3].name = "Reverb";
  21214. s.mixer[4].name = "Delay";
  21215. s.setRoute (1, 3, true);
  21216. s.setRoute (1, 4, true);
  21217. s.setRouteLevel (1, 3, 0.6f);
  21218. s.setRouteLevel (1, 4, 0.4f);
  21219. s.setSendPre (1, 3, true);
  21220. });
  21221. offline.dispatchPendingMessages();
  21222. ui.selectTabForSnapshot (3);
  21223. ui.getMixerForSnapshot().selectTrack (1);
  21224. offline.dispatchPendingMessages();
  21225. saveSnapshot (ui, prefix + "-send-pre.png");
  21226. auto& strips = ui.getMixerForSnapshot().getStripsForSnapshot();
  21227. saveMenus (juce::StringArray { "Send to Reverb (pre-fader)", "Send to Delay (post-fader)" },
  21228. std::vector<juce::PopupMenu> { strips.buildSendMenu (3), strips.buildSendMenu (4) }, prefix + "-send-menu.png");
  21229. // 2. low latency while recording: the monitored track's look-ahead limiter is bypassed, the EQ stays
  21230. offline.editSong ([] (lynx::Song& s) {
  21231. s.mixer[1].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::parametricEq));
  21232. s.mixer[1].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::limiter));
  21233. s.mixer[1].inputChannel = 0;
  21234. s.mixer[1].monitor = lynx::InputMonitor::on;
  21235. });
  21236. offline.dispatchPendingMessages();
  21237. saveSnapshot (ui, prefix + "-lowlat-off.png");
  21238. auto options = offline.getRecordOptions();
  21239. options.lowLatencyRecording = true;
  21240. offline.setRecordOptions (options);
  21241. offline.dispatchPendingMessages();
  21242. ui.getMixerForSnapshot().selectTrack (1);
  21243. offline.dispatchPendingMessages();
  21244. saveSnapshot (ui, prefix + "-lowlat-on.png");
  21245. saveMenus (juce::StringArray { "Record" }, std::vector<juce::PopupMenu> { ui.getFullRecordMenuForSnapshot() }, prefix + "-lowlat-menu.png");
  21246. juce::String report;
  21247. report << "latency_with_option=" << offline.getLatencySamples() << " bypassed_slots=" << offline.lowLatencyBypassedCount() << "\n";
  21248. options.lowLatencyRecording = false;
  21249. offline.setRecordOptions (options);
  21250. offline.dispatchPendingMessages();
  21251. report << "latency_without_option=" << offline.getLatencySamples() << "\n";
  21252. // 3. the Browser's "Preview in time": a 120 BPM loop previewed in a 140 BPM project
  21253. const auto dir = juce::File (prefix).getParentDirectory().getChildFile ("audiox-preview");
  21254. dir.createDirectory();
  21255. const auto wav = dir.getChildFile ("Drum loop 120 bpm.wav");
  21256. {
  21257. const int frames = 44100 * 4;
  21258. juce::AudioBuffer<float> audio (1, frames);
  21259. for (int i = 0; i < frames; ++i)
  21260. {
  21261. const auto t = (double) (i % 22050) / 44100.0;
  21262. 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)));
  21263. }
  21264. wav.deleteFile();
  21265. juce::WavAudioFormat format;
  21266. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  21267. if (auto* w = format.createWriterFor (out.get(), 44100.0, 1, 16, {}, 0))
  21268. {
  21269. out.release();
  21270. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  21271. writer->writeFromAudioSampleBuffer (audio, 0, frames);
  21272. }
  21273. }
  21274. offline.getTransport().bpm.store (140.0);
  21275. offline.setPreviewInTime (true);
  21276. ui.showDesktopForSnapshot (false);
  21277. offline.previewFile (wav);
  21278. offline.finishPreviewJobs();
  21279. ui.getBrowserForSnapshot().showPreviewForSnapshot (wav);
  21280. offline.dispatchPendingMessages();
  21281. saveSnapshot (ui, prefix + "-preview-in-time.png");
  21282. saveMenus (juce::StringArray { "Browser options" }, std::vector<juce::PopupMenu> { ui.getBrowserForSnapshot().buildViewMenu() }, prefix + "-preview-menu.png");
  21283. const auto& timing = offline.getPreviewTiming();
  21284. report << "preview file_bpm=" << timing.fileBpm << " project_bpm=" << timing.projectBpm << " ratio=" << timing.ratio
  21285. << " prepare_ms=" << juce::String (offline.getLastPreviewPrepareMs(), 1) << "\n";
  21286. offline.previewFile ({});
  21287. offline.setPreviewInTime (false);
  21288. juce::File (prefix + "-report.txt").replaceWithText (report);
  21289. }
  21290. }
  21291. void runComp177Shot (const juce::String& prefix, const juce::String& projectPath)
  21292. {
  21293. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  21294. lynx::AudioEngine offline (false);
  21295. {
  21296. lynx::MainComponent ui (offline, false);
  21297. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  21298. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  21299. ui.openFile (juce::File (projectPath));
  21300. offline.dispatchPendingMessages();
  21301. ui.selectTabForSnapshot (2);
  21302. offline.dispatchPendingMessages();
  21303. auto& playlist = ui.getPlaylistForSnapshot();
  21304. std::int64_t last = 0;
  21305. for (const auto& c : offline.getSong().playlist)
  21306. last = std::max (last, c.end());
  21307. const auto bars = juce::jmax (1, (int) (last / (4 * lynx::ppq)) + 1);
  21308. playlist.setViewForSnapshot (juce::jmax (60.0, (ui.getWidth() - 300.0) / bars), 0, 0);
  21309. // (the first paint asks for the clips' waveforms, a worker thread loads them)
  21310. saveSnapshot (ui, prefix + "-opened.png");
  21311. juce::Thread::sleep (3000);
  21312. offline.dispatchPendingMessages();
  21313. saveSnapshot (ui, prefix + "-opened.png");
  21314. // a muted clip selected
  21315. for (int c = 0; c < (int) offline.getSong().playlist.size(); ++c)
  21316. if (offline.getSong().playlist[(std::size_t) c].muted)
  21317. {
  21318. playlist.selectClipsForSnapshot ({ c });
  21319. offline.dispatchPendingMessages();
  21320. saveSnapshot (ui, prefix + "-selected.png");
  21321. playlist.selectClipsForSnapshot ({});
  21322. break;
  21323. }
  21324. juce::String report;
  21325. const auto listTracks = [&offline, &report] (const juce::String& title) {
  21326. const auto& s = offline.getSong();
  21327. report << title << "\n";
  21328. for (int t = 0; t < (int) s.playlistTracks.size(); ++t)
  21329. {
  21330. int clips = 0, muted = 0;
  21331. for (const auto& c : s.playlist)
  21332. if (c.track == t)
  21333. ++clips, muted += c.muted ? 1 : 0;
  21334. const auto& pt = s.playlistTracks[(std::size_t) t];
  21335. if (clips > 0 || pt.grouped || ! pt.name.empty())
  21336. report << "track " << (t + 1) << " '" << juce::String::fromUTF8 (pt.name.c_str()) << "' grouped=" << (pt.grouped ? 1 : 0) << " collapsed=" << (pt.collapsed ? 1 : 0)
  21337. << " comp=" << (pt.compTrack ? 1 : 0) << " clips=" << clips << " muted=" << muted << "\n";
  21338. }
  21339. };
  21340. listTracks ("opened");
  21341. // the first group's header (a member's menu holds "Comp these takes" too)
  21342. int firstGroup = -1;
  21343. for (int t = 0; t < (int) offline.getSong().playlistTracks.size() && firstGroup < 0; ++t)
  21344. if (lynx::comp::canComp (offline.getSong(), t))
  21345. firstGroup = t;
  21346. report << "first group with takes: track " << (firstGroup + 1) << "\n";
  21347. if (firstGroup >= 0)
  21348. {
  21349. saveMenus (juce::StringArray { "Playlist track" }, std::vector<juce::PopupMenu> { playlist.getTrackMenuForSnapshot (firstGroup) }, prefix + "-trackmenu.png");
  21350. int comp = -1;
  21351. offline.editSong ([firstGroup, &comp] (lynx::Song& s) { comp = lynx::comp::compTakes (s, firstGroup); });
  21352. offline.dispatchPendingMessages();
  21353. saveSnapshot (ui, prefix + "-comped.png");
  21354. listTracks ("after Comp these takes");
  21355. const auto g = lynx::comp::groupOf (offline.getSong(), comp);
  21356. std::int64_t from = -1, to = 0;
  21357. for (const auto& c : offline.getSong().playlist)
  21358. if (c.track == g.first)
  21359. from = from < 0 ? c.start : std::min (from, c.start), to = std::max (to, c.end());
  21360. if (g.valid() && to > from)
  21361. {
  21362. offline.editSong ([&g, from, to] (lynx::Song& s) { lynx::comp::swipe (s, g.first, from + (to - from) / 4, from + (to - from) / 2); });
  21363. offline.dispatchPendingMessages();
  21364. saveSnapshot (ui, prefix + "-swiped.png");
  21365. listTracks ("after a swipe of the middle of the first lane");
  21366. // a lane auditioned; the crossfade close up; the comp flattened
  21367. offline.editSong ([&g] (lynx::Song& s) { lynx::comp::setAudition (s, g.first); }, false);
  21368. offline.dispatchPendingMessages();
  21369. saveSnapshot (ui, prefix + "-audition.png");
  21370. offline.editSong ([] (lynx::Song& s) { lynx::comp::setAudition (s, -1); }, false);
  21371. const auto switchAt = from + (to - from) / 4;
  21372. playlist.setViewForSnapshot (4.0 * 4.0 * lynx::ppq, 0, 0);
  21373. playlist.setScrollTickForSnapshot ((double) (switchAt - 100));
  21374. juce::Thread::sleep (1500);
  21375. offline.dispatchPendingMessages();
  21376. saveSnapshot (ui, prefix + "-crossfade.png");
  21377. playlist.setViewForSnapshot (juce::jmax (60.0, (ui.getWidth() - 300.0) / bars), 0, 0);
  21378. offline.editSong ([comp] (lynx::Song& s) { lynx::comp::flatten (s, comp); });
  21379. offline.dispatchPendingMessages();
  21380. saveSnapshot (ui, prefix + "-flattened.png");
  21381. listTracks ("after Flatten comp");
  21382. }
  21383. }
  21384. saveMenus (juce::StringArray { "Record" }, std::vector<juce::PopupMenu> { ui.getRecordMenuForSnapshot() }, prefix + "-recordmenu.png");
  21385. juce::File (prefix + "-tracks.txt").replaceWithText (report);
  21386. }
  21387. }
  21388. // Round 190bx: the Settings pages alone (the full --snapshot takes minutes). prefix-settings-<page>.png at the
  21389. // window's size, -small.png at 390 x 390 (rows must scroll, never be cut off or squeezed) and -whole.png tall
  21390. // enough to show every row of the page.
  21391. void runSettingsShot (const juce::String& prefix)
  21392. {
  21393. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  21394. {
  21395. lynx::AudioEngine offline (false);
  21396. offline.editSong ([] (lynx::Song& s) {
  21397. s.info = { "Night Drive", "LYNX SHARE demo", "Synthwave", "https://lynx-share.com",
  21398. "Made with LYNX SHARE.\nDrums and bass from the Channel Rack, pads from the Browser.", false };
  21399. }, false);
  21400. auto shoot = [&] (lynx::SettingsPage page, const juce::String& name, int width, int height) {
  21401. auto panel = lynx::makeSettingsPanel (offline, page);
  21402. if (width > 0)
  21403. panel->setSize (width, height);
  21404. juce::Component frame;
  21405. frame.setSize (panel->getWidth(), panel->getHeight());
  21406. frame.addAndMakeVisible (*panel);
  21407. panel->setTopLeftPosition (0, 0);
  21408. juce::Image image (juce::Image::ARGB, frame.getWidth(), frame.getHeight(), true);
  21409. {
  21410. juce::Graphics g (image);
  21411. g.fillAll (lynx::theme::panel);
  21412. frame.paintEntireComponent (g, false);
  21413. }
  21414. savePng (image, prefix + "-settings-" + name + ".png");
  21415. };
  21416. const std::pair<lynx::SettingsPage, const char*> pages[] = { { lynx::SettingsPage::audio, "audio" }, { lynx::SettingsPage::midi, "midi" },
  21417. { lynx::SettingsPage::general, "general" }, { lynx::SettingsPage::theme, "theme" },
  21418. { lynx::SettingsPage::files, "files" }, { lynx::SettingsPage::extras, "extras" },
  21419. { lynx::SettingsPage::project, "project" }, { lynx::SettingsPage::info, "info" } };
  21420. for (const auto& [page, name] : pages)
  21421. {
  21422. shoot (page, name, 0, 0);
  21423. shoot (page, juce::String (name) + "-small", 390, 390);
  21424. }
  21425. shoot (lynx::SettingsPage::audio, "audio-whole", 680, 1500);
  21426. shoot (lynx::SettingsPage::general, "general-whole", 680, 2400); // (round 190gh: + the Updates section's previous-version row)
  21427. // round 190jp (design190ia FW-20): the whole Theme page (thumbnails, Adjustments, dots, A | B), then with
  21428. // Adjustments and two dots set, in that theme
  21429. shoot (lynx::SettingsPage::theme, "theme-whole", 680, 1900);
  21430. {
  21431. const auto before = lynx::themeui::current();
  21432. auto adjusted = before;
  21433. adjusted.hue = 40.0f;
  21434. adjusted.saturation = 0.45f;
  21435. adjusted.contrast = 0.3f;
  21436. adjusted.text = 0.4f;
  21437. adjusted.dots[(std::size_t) lynx::themes::Dot::steps] = 0xffffa040;
  21438. adjusted.dots[(std::size_t) lynx::themes::Dot::highlight] = 0xff30a5ff;
  21439. lynx::themeui::apply (adjusted, false);
  21440. shoot (lynx::SettingsPage::theme, "theme-adjusted", 680, 1900);
  21441. lynx::themeui::apply (before, false);
  21442. }
  21443. }
  21444. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  21445. }
  21446. // round 190bw: FL's 13 curve modes of an automation clip's points (see --curveshot)
  21447. bool runPickerDropShot (const juce::String& prefix)
  21448. {
  21449. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  21450. lynx::AudioEngine offline (false);
  21451. juce::StringArray checks;
  21452. bool all = true;
  21453. const auto check = [&checks, &all] (bool ok, const juce::String& what) {
  21454. checks.add ((ok ? "OK " : "FAIL ") + what);
  21455. all = all && ok;
  21456. };
  21457. {
  21458. lynx::MainComponent ui (offline, false);
  21459. ui.setSize (1600, 900);
  21460. offline.dispatchPendingMessages();
  21461. const auto bar = (std::int64_t) lynx::ppq * 4;
  21462. offline.editSong ([bar] (lynx::Song& s) {
  21463. s.patterns.resize (3);
  21464. const char* names[] = { "Pattern 1", "Pattern 2", "Pattern 3" };
  21465. for (int p = 0; p < 3; ++p)
  21466. {
  21467. auto& pattern = s.patterns[(std::size_t) p];
  21468. pattern.name = names[p];
  21469. pattern.notes.clear();
  21470. for (int n = 0; n < 4 * (p + 1); ++n)
  21471. {
  21472. lynx::Note note;
  21473. note.start = (std::int64_t) n * lynx::ppq / 2;
  21474. note.length = lynx::ppq / 4;
  21475. note.key = 60 + (n * 5 + p * 3) % 12;
  21476. pattern.notes.push_back (note);
  21477. }
  21478. }
  21479. s.patterns[1].lengthTicks = bar * 2; // (Pattern 2 is two bars long)
  21480. s.currentPattern = 0;
  21481. s.playlist.clear();
  21482. }, false);
  21483. offline.dispatchPendingMessages();
  21484. ui.selectTabForSnapshot (2);
  21485. offline.dispatchPendingMessages();
  21486. auto& playlist = ui.getPlaylistForSnapshot();
  21487. playlist.setViewForSnapshot (120.0, 0, 0);
  21488. offline.dispatchPendingMessages();
  21489. // the drag's description survives the trip
  21490. {
  21491. auto kind = lynx::ClipKind::audio;
  21492. std::vector<int> entries;
  21493. const auto text = lynx::PlaylistComponent::pickerDragDescription (lynx::ClipKind::pattern, { 2, 0 });
  21494. check (lynx::PlaylistComponent::pickerDrag (text, kind, entries) && kind == lynx::ClipKind::pattern && entries == std::vector<int> ({ 2, 0 }),
  21495. "drag description " + text);
  21496. }
  21497. const auto at = [&playlist] (int track, double ticks) {
  21498. return juce::Point<int> (juce::roundToInt (playlist.xOfTickForSnapshot (ticks)), playlist.trackRowForSnapshot (track).getCentreY());
  21499. };
  21500. const auto find = [&offline] (int track, int pattern) -> const lynx::Clip* {
  21501. for (const auto& c : offline.getSong().playlist)
  21502. if (c.track == track && c.kind == lynx::ClipKind::pattern && c.pattern == pattern)
  21503. return &c;
  21504. return nullptr;
  21505. };
  21506. // 1. Pattern 1 dropped on track 1 a little after bar 2's line: it starts on that line
  21507. playlist.dropFromPicker (lynx::ClipKind::pattern, { 0 }, at (0, (double) bar + lynx::ppq * 0.2), false);
  21508. offline.dispatchPendingMessages();
  21509. const auto* one = find (0, 0);
  21510. check (one != nullptr && one->start == bar && one->length == bar, "plain drop: Pattern 1 on track 1 at bar 2");
  21511. // 2. Pattern 2 + Pattern 3 (picked together) dropped on track 3 at bar 3: tracks 3 and 4, same time
  21512. playlist.dropFromPicker (lynx::ClipKind::pattern, { 1, 2 }, at (2, (double) bar * 2), false);
  21513. offline.dispatchPendingMessages();
  21514. const auto* two = find (2, 1);
  21515. const auto* three = find (3, 2);
  21516. check (two != nullptr && three != nullptr && two->start == bar * 2 && three->start == bar * 2,
  21517. "two picked patterns: Pattern 2 on track 3, Pattern 3 on track 4, both at bar 3");
  21518. check (offline.getSong().currentPattern == 2, "the current pattern is the last dropped one (Pattern 3)");
  21519. const auto selectedAre = [&playlist, &offline] (int track, std::size_t count) {
  21520. const auto& sel = playlist.getSelectedClips();
  21521. if (sel.size() != count)
  21522. return false;
  21523. for (const auto i : sel)
  21524. 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)
  21525. || (track >= 0 && offline.getSong().playlist[(std::size_t) i].track != track))
  21526. return false;
  21527. return true;
  21528. };
  21529. check (selectedAre (-1, 2), "the two dropped clips are the selection (FL), Pattern 1's clip is not");
  21530. saveSnapshot (ui, prefix + "-plain.png");
  21531. // 3. Shift: all three on track 6 from bar 1, one after the other
  21532. playlist.dropFromPicker (lynx::ClipKind::pattern, { 0, 1, 2 }, at (5, 0.0), true);
  21533. offline.dispatchPendingMessages();
  21534. const auto* a = find (5, 0);
  21535. const auto* b = find (5, 1);
  21536. const auto* c = find (5, 2);
  21537. check (a != nullptr && b != nullptr && c != nullptr && a->start == 0 && b->start == a->end() && c->start == b->end(),
  21538. "Shift drop: Pattern 1, 2, 3 one after the other on track 6");
  21539. check (offline.getSong().currentPattern == 2, "Shift keeps the current pattern");
  21540. check (selectedAre (5, 3), "the three chained clips are the selection");
  21541. saveSnapshot (ui, prefix + "-shift.png");
  21542. }
  21543. checks.add (all ? "ALL OK" : "FAILURES");
  21544. juce::File (prefix + "-checks.txt").replaceWithText (checks.joinIntoString ("\n") + "\n");
  21545. return all;
  21546. }
  21547. bool runTrackModeShot (const juce::String& prefix)
  21548. {
  21549. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  21550. lynx::AudioEngine offline (false);
  21551. bool all = true;
  21552. juce::String report;
  21553. {
  21554. lynx::MainComponent ui (offline, false);
  21555. ui.setSize (1600, 900);
  21556. offline.dispatchPendingMessages();
  21557. auto& playlist = ui.getPlaylistForSnapshot();
  21558. // the track's menu, Track mode and Audio track side by side; the Audio track entries as FL writes them
  21559. // ("-" in front = greyed, "v" = ticked)
  21560. const auto shoot = [&] (int track, const juce::String& name, const juce::StringArray& fl) {
  21561. const auto menu = playlist.getTrackMenuForSnapshot (track);
  21562. juce::StringArray names { "Track " + juce::String (track + 1) };
  21563. std::vector<juce::PopupMenu> menus { menu };
  21564. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  21565. if (it.getItem().subMenu != nullptr && it.getItem().text == lynx::theme::mnemonic (lynx::tr ("Track mode"), 'T'))
  21566. {
  21567. names.add (lynx::tr ("Track mode"));
  21568. menus.push_back (*it.getItem().subMenu);
  21569. }
  21570. if (menus.size() == 2)
  21571. for (juce::PopupMenu::MenuItemIterator it (menus[1]); it.next();)
  21572. if (it.getItem().subMenu != nullptr && it.getItem().text == lynx::theme::mnemonic (lynx::tr ("Audio track"), 'A'))
  21573. {
  21574. names.add (lynx::tr ("Audio track"));
  21575. menus.push_back (*it.getItem().subMenu);
  21576. }
  21577. juce::StringArray lynxList;
  21578. if (menus.size() == 3)
  21579. for (juce::PopupMenu::MenuItemIterator it (menus[2]); it.next();)
  21580. lynxList.add (it.getItem().isSeparator ? juce::String ("|")
  21581. : (it.getItem().isTicked ? "v " : "") + juce::String (it.getItem().isEnabled ? "" : "- ") + it.getItem().text);
  21582. saveMenus (names, menus, prefix + "-" + name + ".png");
  21583. const auto same = menus.size() == 3 && lynxList == fl;
  21584. all = all && same;
  21585. report << name << ": " << (same ? "SAME AS FL" : "DIFFERENT") << "\n LYNX: " << lynxList.joinIntoString (" / ")
  21586. << "\n FL: " << fl.joinIntoString (" / ") << "\n";
  21587. };
  21588. const auto flList = [] (int inserts, std::map<int, juce::String> named, std::set<int> greyed) {
  21589. juce::StringArray l { "New mixer track(s)", "|" };
  21590. for (int i = 1; i <= inserts; ++i)
  21591. l.add ((greyed.count (i) ? "- " : "") + juce::String (i) + ". " + (named.count (i) ? named[i] : "Insert " + juce::String (i)));
  21592. return l;
  21593. };
  21594. // q1-01: a fresh project, Track 1 unassigned
  21595. shoot (0, "fresh", flList (16, {}, {}));
  21596. // q1-02: Track 1 linked to insert 6, insert 7 renamed "Vox chain"; Track 2's menu
  21597. offline.editSong ([] (lynx::Song& s) {
  21598. lynx::trackmodes::assignAudioTracks (s, { 0 }, 6);
  21599. s.mixer[7].name = "Vox chain";
  21600. });
  21601. offline.dispatchPendingMessages();
  21602. shoot (1, "linked-renamed", flList (16, { { 7, "Vox chain" } }, { 6 }));
  21603. // q1-07: the rest of FL's session (live 190cu Q2): Track 3 → 7; Track 4 → New mixer track (17), insert 9
  21604. // renamed "Vox chain", Track 4 → 9; Track 5 "Lead" → 11, insert 12 "Vox chain", Track 5 → 12; Track 6 "Lead"
  21605. // (unassigned), insert 13 "Vox chain", Track 6 → 13. Track 7's menu
  21606. offline.editSong ([] (lynx::Song& s) {
  21607. namespace tm = lynx::trackmodes;
  21608. if (s.playlistTracks.size() < 8)
  21609. s.playlistTracks.resize (8);
  21610. tm::assignAudioTracks (s, { 2 }, 7);
  21611. tm::assignAudioTracks (s, { 3 }, tm::newMixerTrack);
  21612. s.mixer[9].name = "Vox chain";
  21613. tm::assignAudioTracks (s, { 3 }, 9);
  21614. s.playlistTracks[4].name = "Lead";
  21615. tm::assignAudioTracks (s, { 4 }, 11);
  21616. s.mixer[12].name = "Vox chain";
  21617. tm::assignAudioTracks (s, { 4 }, 12);
  21618. s.playlistTracks[5].name = "Lead";
  21619. s.mixer[13].name = "Vox chain";
  21620. tm::assignAudioTracks (s, { 5 }, 13);
  21621. });
  21622. offline.dispatchPendingMessages();
  21623. shoot (6, "full-state", flList (17, { { 7, "Vox chain" }, { 9, "Insert 17" }, { 12, "Lead" }, { 13, "Vox chain" } }, { 6, 7, 9, 12, 13 }));
  21624. }
  21625. report << (all ? "ALL SAME AS FL\n" : "FAILURES\n");
  21626. juce::File (prefix + "-report.txt").replaceWithText (report);
  21627. return all;
  21628. }
  21629. void runCurveShot (const juce::String& prefix)
  21630. {
  21631. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  21632. lynx::AudioEngine offline (false);
  21633. {
  21634. lynx::MainComponent ui (offline, false);
  21635. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  21636. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  21637. offline.dispatchPendingMessages();
  21638. // FL's menu order, one bar per mode, the levels going up and down; a tension where the mode needs one to show
  21639. static const int order[] = { lynx::flcurve::smooth, lynx::flcurve::hold, lynx::flcurve::singleCurve, lynx::flcurve::singleCurve2,
  21640. lynx::flcurve::singleCurve3, lynx::flcurve::doubleCurve, lynx::flcurve::doubleCurve2, lynx::flcurve::doubleCurve3,
  21641. lynx::flcurve::halfSine, lynx::flcurve::stairs, lynx::flcurve::smoothStairs, lynx::flcurve::pulse, lynx::flcurve::wave };
  21642. const auto bar = (std::int64_t) lynx::ppq * 4;
  21643. offline.editSong ([bar] (lynx::Song& song) {
  21644. song.mode = lynx::PlayMode::song;
  21645. lynx::Automation a;
  21646. a.name = "Curve modes";
  21647. a.target = { lynx::AutomationTargetKind::mixerVolume, 1 };
  21648. a.points.push_back ({ 0, 0.15f, 0.0f });
  21649. int k = 0;
  21650. for (const auto mode : order)
  21651. {
  21652. const auto stepped = mode == lynx::flcurve::stairs || mode == lynx::flcurve::smoothStairs || mode == lynx::flcurve::pulse || mode == lynx::flcurve::wave;
  21653. a.points.back().mode = (std::uint8_t) mode;
  21654. a.points.back().tension = mode == lynx::flcurve::smooth || mode == lynx::flcurve::hold ? 0.0f : stepped ? -0.72f : (k % 2 == 0 ? 0.55f : -0.55f);
  21655. ++k;
  21656. a.points.push_back ({ bar * k, k % 2 == 1 ? 0.85f : 0.15f, 0.0f });
  21657. }
  21658. song.automations.insert (song.automations.begin(), a);
  21659. for (auto& c : song.playlist)
  21660. if (c.kind == lynx::ClipKind::automation)
  21661. ++c.automation;
  21662. lynx::Clip clip;
  21663. clip.kind = lynx::ClipKind::automation;
  21664. clip.automation = 0;
  21665. clip.track = 3;
  21666. clip.length = bar * 13;
  21667. song.playlist.push_back (clip);
  21668. if (song.playlistTracks.size() < 4)
  21669. song.playlistTracks.resize (4);
  21670. song.playlistTracks[3].height = 150;
  21671. }, false);
  21672. offline.dispatchPendingMessages();
  21673. ui.selectTabForSnapshot (2);
  21674. offline.dispatchPendingMessages();
  21675. auto& playlist = ui.getPlaylistForSnapshot();
  21676. saveSnapshot (ui, prefix + "-playlist.png");
  21677. const auto clipIndex = (int) offline.getSong().playlist.size() - 1;
  21678. // the point menu of the point that ends the "Stairs" segment (point 10), and of the first point
  21679. saveMenus (juce::StringArray { "Automation point (ends a Stairs segment)", "First point" },
  21680. std::vector<juce::PopupMenu> { playlist.getAutomationPointMenuForSnapshot (clipIndex, 10), playlist.getAutomationPointMenuForSnapshot (clipIndex, 0) },
  21681. prefix + "-point-menu.png");
  21682. auto editor = lynx::makeAutomationEditor (offline, 0);
  21683. editor->setSize (1500, 420);
  21684. savePng (editor->createComponentSnapshot (editor->getLocalBounds()), prefix + "-editor.png");
  21685. editor.reset();
  21686. // the project itself, for --export-flp and a look at the same clip in FL
  21687. {
  21688. juce::String saveError;
  21689. lynx::ProjectFile::save (offline.getSong(), juce::File (prefix + "-modes.lynx"), saveError);
  21690. }
  21691. // part 2: the Piano roll tools that gained FL's options (they preview on the pattern and put the notes back)
  21692. ui.selectTabForSnapshot (1);
  21693. offline.dispatchPendingMessages();
  21694. auto& roll = ui.getPianoRollForSnapshot();
  21695. const std::pair<lynx::NoteTool, const char*> tools[] = { { lynx::NoteTool::flip, "-tool-flip.png" },
  21696. { lynx::NoteTool::limit, "-tool-limit.png" },
  21697. { lynx::NoteTool::scaleLevels, "-tool-scalelevels.png" },
  21698. { lynx::NoteTool::randomise, "-tool-randomise.png" },
  21699. { lynx::NoteTool::lfo, "-tool-lfo.png" } };
  21700. // round 190ct: checks of the FL-live fixes, one line each in <prefix>-checks.txt (OK / FAIL)
  21701. juce::StringArray checks;
  21702. const auto check = [&checks] (bool ok, const juce::String& what) { checks.add ((ok ? "OK " : "FAIL ") + what); };
  21703. {
  21704. juce::String header;
  21705. const auto pointMenu = playlist.getAutomationPointMenuForSnapshot (clipIndex, 10); // (the iterator keeps a reference)
  21706. for (juce::PopupMenu::MenuItemIterator it (pointMenu); it.next();)
  21707. {
  21708. header = it.getItem().text;
  21709. break;
  21710. }
  21711. check (header == "Point 11/14", "point menu header \"" + header + "\" (FL: \"Point n/N\")");
  21712. }
  21713. for (const auto& [tool, name] : tools)
  21714. {
  21715. auto panel = lynx::makeNoteToolPanel (offline, tool, roll.noteIndicesForSnapshot(), roll.gridForSnapshot());
  21716. offline.dispatchPendingMessages();
  21717. savePng (panel->createComponentSnapshot (panel->getLocalBounds()), prefix + name);
  21718. if (tool == lynx::NoteTool::flip)
  21719. {
  21720. std::vector<juce::ToggleButton*> toggles;
  21721. for (auto* child : panel->getChildren())
  21722. if (auto* t = dynamic_cast<juce::ToggleButton*> (child))
  21723. toggles.push_back (t);
  21724. check (toggles.size() == 3 && toggles[0]->getToggleState() && toggles[1]->getToggleState() && ! toggles[2]->getToggleState(),
  21725. "flip opens with Flip horizontally on, Preserve start times on, Flip vertically off");
  21726. if (toggles.size() == 3)
  21727. {
  21728. toggles[2]->setToggleState (true, juce::sendNotificationSync);
  21729. check (! toggles[0]->getToggleState() && toggles[2]->getToggleState(), "flip: vertically turns horizontally off (radios)");
  21730. toggles[0]->setToggleState (true, juce::sendNotificationSync);
  21731. check (toggles[0]->getToggleState() && ! toggles[2]->getToggleState(), "flip: horizontally turns vertically off (radios)");
  21732. }
  21733. }
  21734. if (tool == lynx::NoteTool::limit)
  21735. {
  21736. auto* list = lynx::noteToolLongestChoiceForSnapshot (*panel);
  21737. juce::ComboBox* key = nullptr;
  21738. for (auto* child : panel->getChildren())
  21739. if (auto* box = dynamic_cast<juce::ComboBox*> (child); box != nullptr && box->getNumItems() == 12)
  21740. key = box;
  21741. check (list != nullptr && list->getNumItems() == 89, "limit list has (none) + 66 chords + 22 scales: "
  21742. + juce::String (list != nullptr ? list->getNumItems() : 0));
  21743. check (list != nullptr && key != nullptr && list->getY() == key->getY() && list->getX() > key->getRight(),
  21744. "limit: Key and the chord / scale list share one row");
  21745. if (list != nullptr)
  21746. saveMenus (juce::StringArray { "Limit: Key / scale list" }, std::vector<juce::PopupMenu> { *list->getRootMenu() },
  21747. prefix + "-tool-limit-list.png");
  21748. }
  21749. if (tool == lynx::NoteTool::lfo)
  21750. saveMenus (juce::StringArray { "LFO tool: right-click on a Period slider" },
  21751. std::vector<juce::PopupMenu> { lynx::noteToolPresetMenuForSnapshot (*panel) }, prefix + "-tool-lfo-steps.png");
  21752. }
  21753. juce::File (prefix + "-checks.txt").replaceWithText (checks.joinIntoString ("\n") + "\n");
  21754. }
  21755. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  21756. }
  21757. bool runEvPaneShot (const juce::String& prefix, const juce::String& projectPath)
  21758. {
  21759. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  21760. lynx::AudioEngine offline (false);
  21761. juce::StringArray report;
  21762. bool ok = true;
  21763. {
  21764. lynx::MainComponent ui (offline, false);
  21765. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  21766. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  21767. if (projectPath.isNotEmpty())
  21768. ui.openFile (juce::File (projectPath));
  21769. offline.dispatchPendingMessages();
  21770. ui.selectTabForSnapshot (1); // the Piano Roll
  21771. offline.dispatchPendingMessages();
  21772. auto& roll = ui.getPianoRollForSnapshot();
  21773. roll.scrollToNotes();
  21774. const auto area = ui.getLocalArea (&roll, roll.getLocalBounds());
  21775. const auto file = lynx::platform::settingsFile ("piano-roll-event-pane.txt");
  21776. auto source = juce::Desktop::getInstance().getMainMouseSource();
  21777. const auto now = juce::Time::getCurrentTime();
  21778. auto event = [&] (juce::Point<int> p, juce::Point<int> down, juce::ModifierKeys mods, int clicks, bool dragged) {
  21779. 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);
  21780. };
  21781. auto barCentre = [&roll] { return roll.eventPaneBarArea().getCentre(); };
  21782. const juce::ModifierKeys left (juce::ModifierKeys::leftButtonModifier), right (juce::ModifierKeys::rightButtonModifier),
  21783. middle (juce::ModifierKeys::middleButtonModifier);
  21784. auto click = [&] (juce::ModifierKeys button, int clicks) {
  21785. const auto at = barCentre();
  21786. roll.mouseDown (event (at, at, button, clicks, false));
  21787. roll.mouseUp (event (at, at, {}, clicks, false));
  21788. offline.dispatchPendingMessages();
  21789. };
  21790. auto dragTo = [&] (int y) {
  21791. const auto at = barCentre();
  21792. roll.mouseDown (event (at, at, left, 1, false));
  21793. for (int step = 1; step <= 8; ++step) // (a few moves, as a hand does)
  21794. roll.mouseDrag (event ({ at.x, at.y + (y - at.y) * step / 8 }, at, left, 1, true));
  21795. roll.mouseUp (event ({ at.x, y }, at, {}, 1, true));
  21796. offline.dispatchPendingMessages();
  21797. };
  21798. auto state = [&] (const juce::String& name) {
  21799. const auto grid = roll.getHeight() - lynx::PianoRollComponent::headerHeight - roll.velocityHeight - lynx::evpane::barThickness;
  21800. const auto& st = lynx::PianoRollComponent::eventPaneState();
  21801. report.add (name + ": roll " + juce::String (roll.getHeight()) + " px, grid " + juce::String (juce::jmax (0, grid)) + " px, bar top "
  21802. + juce::String (roll.eventPaneBarTopForTests()) + ", event editor " + juce::String (roll.velocityHeight) + " px, aspect "
  21803. + juce::String (st.aspect, 4) + ", spare " + juce::String (st.spare, 4) + ", file \"" + file.loadFileAsString().trim().replace ("\n", " ") + "\"");
  21804. saveArea (ui, area, prefix + "-" + name + ".png");
  21805. };
  21806. auto expect = [&] (bool condition, const juce::String& what) {
  21807. report.add ((condition ? "PASS " : "FAIL ") + what);
  21808. ok = ok && condition;
  21809. };
  21810. state ("1-default");
  21811. const auto defaultLane = roll.velocityHeight;
  21812. expect (std::abs (lynx::PianoRollComponent::eventPaneState().aspect - 0.8f) < 1e-6f, "default place is FL's 0.8");
  21813. ui.setHintForSnapshot (roll.hintAt (barCentre()));
  21814. saveSnapshot (ui, prefix + "-2-hover-hint.png");
  21815. ui.setHintForSnapshot ({});
  21816. const auto travelTop = lynx::PianoRollComponent::headerHeight, travelBottom = roll.getHeight() - lynx::evpane::barThickness;
  21817. dragTo (travelTop + (travelBottom - travelTop) * 45 / 100);
  21818. state ("3-dragged-larger");
  21819. const auto largeLane = roll.velocityHeight;
  21820. expect (largeLane > defaultLane * 2, "drag up makes the event editor taller");
  21821. expect (lynx::evpane::fromText (file.loadFileAsString().toStdString()) == lynx::PianoRollComponent::eventPaneState(),
  21822. "the place is written to the settings file on release");
  21823. click (right, 1);
  21824. state ("4-right-click-alternate");
  21825. expect (roll.velocityHeight == 0, "right-click: the alternate size (FL's spare 1.0) folds the event editor away");
  21826. click (right, 1);
  21827. state ("5-right-click-back");
  21828. expect (roll.velocityHeight == largeLane, "right-click again: back to the dragged size");
  21829. roll.runAction ("pianoRoll.eventPaneAlternate");
  21830. offline.dispatchPendingMessages();
  21831. expect (roll.velocityHeight == 0, "Shift+Enter (pianoRoll.eventPaneAlternate) swaps too");
  21832. roll.runAction ("pianoRoll.eventPaneAlternate");
  21833. offline.dispatchPendingMessages();
  21834. dragTo (travelTop + 10);
  21835. state ("6-grid-folded");
  21836. expect (roll.eventPaneBarTopForTests() == travelTop, "a drag within 23 px of the top folds the note grid away");
  21837. click (middle, 1);
  21838. state ("7-middle-click-default");
  21839. expect (roll.velocityHeight == defaultLane, "middle-click: back to the default place");
  21840. // a taller window keeps the proportion (the place is a fraction of the travel)
  21841. dragTo (travelTop + (travelBottom - travelTop) * 60 / 100);
  21842. const auto before = lynx::PianoRollComponent::eventPaneState().aspect;
  21843. roll.setSize (roll.getWidth(), roll.getHeight() + 200);
  21844. offline.dispatchPendingMessages();
  21845. const auto newTravel = roll.getHeight() - lynx::evpane::barThickness - travelTop;
  21846. expect (std::abs (roll.eventPaneBarTopForTests() - (travelTop + juce::roundToInt (before * (float) newTravel))) <= 1,
  21847. "a taller window keeps the proportion");
  21848. roll.setSize (roll.getWidth(), roll.getHeight() - 200);
  21849. offline.dispatchPendingMessages();
  21850. click (middle, 1); // leave FL's default behind
  21851. }
  21852. report.add (ok ? "RESULT OK" : "RESULT FAIL");
  21853. juce::File (prefix + "-report.txt").replaceWithText (report.joinIntoString ("\n") + "\n");
  21854. return ok;
  21855. }
  21856. void runFeat166Shot (const juce::String& prefix, const juce::String& projectPath)
  21857. {
  21858. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  21859. lynx::AudioEngine offline (false);
  21860. {
  21861. lynx::MainComponent ui (offline, false);
  21862. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  21863. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  21864. if (projectPath.isNotEmpty())
  21865. ui.openFile (juce::File (projectPath));
  21866. offline.dispatchPendingMessages();
  21867. ui.selectTabForSnapshot (1); // the Piano Roll, on the channel with the most notes
  21868. offline.dispatchPendingMessages();
  21869. // the scale the pattern's notes fit best (major / minor, any root)
  21870. const auto& song = offline.getSong();
  21871. const auto& notes = song.patterns[(std::size_t) song.currentPattern].notes;
  21872. int bestRoot = 0, bestScale = 1, bestHits = -1;
  21873. for (int sc = 1; sc < (int) lynx::notetools::scales().size(); ++sc)
  21874. {
  21875. const juce::String name (lynx::notetools::scales()[(std::size_t) sc].name);
  21876. if (name != "Major" && name != "Minor")
  21877. continue;
  21878. for (int root = 0; root < 12; ++root)
  21879. {
  21880. int hits = 0;
  21881. for (const auto& n : notes)
  21882. hits += lynx::notetools::inScale (n.key, root, sc) ? 1 : 0;
  21883. if (hits > bestHits)
  21884. bestHits = hits, bestRoot = root, bestScale = sc;
  21885. }
  21886. }
  21887. auto& roll = ui.getPianoRollForSnapshot();
  21888. roll.setScaleForSnapshot (bestRoot, bestScale);
  21889. roll.scrollToNotes();
  21890. offline.dispatchPendingMessages();
  21891. saveSnapshot (ui, prefix + "-pr-scale.png");
  21892. roll.setFoldToScale (true);
  21893. offline.dispatchPendingMessages();
  21894. saveSnapshot (ui, prefix + "-pr-folded.png");
  21895. roll.setFoldToScale (false);
  21896. // ghost channels: only the first other channel with notes stays a ghost
  21897. const auto selected = offline.getSelectedChannel();
  21898. int keep = -1;
  21899. for (const auto& n : notes)
  21900. if (n.channel != selected && keep < 0)
  21901. keep = n.channel;
  21902. offline.editSong ([keep] (lynx::Song& s) {
  21903. for (int c = 0; c < (int) s.channels.size(); ++c)
  21904. s.channels[(std::size_t) c].ghostHidden = c != keep;
  21905. }, false);
  21906. offline.dispatchPendingMessages();
  21907. saveSnapshot (ui, prefix + "-pr-ghost-one.png");
  21908. saveMenus (juce::StringArray { "Ghost channels" }, { roll.ghostChannelsMenu() }, prefix + "-ghostmenu.png");
  21909. offline.editSong ([] (lynx::Song& s) {
  21910. for (auto& c : s.channels)
  21911. c.ghostHidden = false;
  21912. }, false);
  21913. // the Mixer at 500 inserts
  21914. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  21915. offline.editSong ([] (lynx::Song& s) { lynx::mixerops::insertTracks (s, (int) s.mixer.size(), lynx::mixerops::roomForInserts (s)); }, false);
  21916. const auto t1 = juce::Time::getMillisecondCounterHiRes();
  21917. offline.dispatchPendingMessages();
  21918. ui.selectTabForSnapshot (3);
  21919. offline.dispatchPendingMessages();
  21920. auto& mixer = ui.getMixerForSnapshot();
  21921. const auto t2 = juce::Time::getMillisecondCounterHiRes();
  21922. saveSnapshot (ui, prefix + "-mixer500-start.png");
  21923. const auto t3 = juce::Time::getMillisecondCounterHiRes();
  21924. mixer.selectTrack ((int) offline.getSong().mixer.size() - 1);
  21925. offline.dispatchPendingMessages();
  21926. saveSnapshot (ui, prefix + "-mixer500-end.png");
  21927. juce::File (prefix + "-mixer500.txt")
  21928. .replaceWithText ("inserts=" + juce::String ((int) offline.getSong().mixer.size() - 1) + "\nfill_ms=" + juce::String (t1 - t0, 2)
  21929. + "\nsnapshot_ms=" + juce::String (t3 - t2, 2) + "\n");
  21930. }
  21931. }
  21932. // Round 190ay, Freeze, end to end with the real engine, files and export (LYNX.exe --freezetest prefix [project]).
  21933. // The project (.lynx / .flp / .als; without one, a small demo song) is rendered live, every channel that can be
  21934. // frozen is frozen, and the same render is made again: the two mixes must null. Written to prefix-report.txt: the
  21935. // null residual, the process memory and the render time before / frozen / unfrozen, what a save holds, whether
  21936. // Unfreeze gives the channels back as they were, the out-of-date and missing-audio states. Shots: the Channel Rack
  21937. // (live, frozen, out of date), the channel menus, the Piano roll of a frozen channel. The frozen audio goes to
  21938. // prefix-data (never next to the project). True = every check passed.
  21939. bool runFreezeTest (const juce::String& prefix, const juce::String& projectPath, const juce::String& mode = {})
  21940. {
  21941. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  21942. lynx::AudioEngine offline (false);
  21943. lynx::MainComponent ui (offline, false);
  21944. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  21945. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  21946. const auto write = [&prefix, &ui] (const char* name) {
  21947. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  21948. file.deleteFile();
  21949. juce::FileOutputStream out (file);
  21950. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (ui), out);
  21951. };
  21952. juce::String report;
  21953. int failures = 0;
  21954. const auto check = [&] (bool ok, const juce::String& what) {
  21955. report << (ok ? "ok " : "FAIL ") << what << "\n";
  21956. failures += ok ? 0 : 1;
  21957. };
  21958. const auto flush = [&] { juce::File (prefix + "-report.txt").replaceWithText (report + "failures=" + juce::String (failures) + "\n"); };
  21959. if (projectPath.isNotEmpty())
  21960. {
  21961. ui.openFile (juce::File (projectPath));
  21962. offline.dispatchPendingMessages();
  21963. }
  21964. else
  21965. offline.editSong ([] (lynx::Song& s) {
  21966. s.channels.clear();
  21967. s.patterns.clear();
  21968. s.playlist.clear();
  21969. s.bpm = 120.0;
  21970. const char* names[] = { "Lead", "Bass", "Pad", "Kick" };
  21971. for (int c = 0; c < 4; ++c)
  21972. {
  21973. lynx::ChannelDef d;
  21974. d.name = names[c];
  21975. d.instrument = c == 3 ? lynx::InstrumentKind::kick : lynx::InstrumentKind::synth;
  21976. d.synth.release = 0.3f + 0.3f * (float) c;
  21977. d.synth.cutoff = 1500.0f + 900.0f * (float) c;
  21978. d.mixerTrack = c + 1;
  21979. s.channels.push_back (d);
  21980. }
  21981. for (int p = 0; p < 2; ++p)
  21982. {
  21983. auto& pattern = s.patterns.emplace_back();
  21984. pattern.name = p == 0 ? "Verse" : "Break";
  21985. pattern.lengthTicks = 4 * lynx::ppq * 4;
  21986. for (int c = 0; c < 4; ++c)
  21987. for (int step = 0; step < (p == 0 ? 8 : 2); ++step)
  21988. {
  21989. lynx::Note n;
  21990. n.channel = c;
  21991. n.start = (std::int64_t) step * lynx::ppq * (p == 0 ? 2 : 1) + (c == 2 ? lynx::ppq / 2 : 0);
  21992. n.length = c == 3 ? lynx::ppq / 4 : lynx::ppq;
  21993. n.key = c == 3 ? 36 : 48 + c * 7 + (step * 5) % 12;
  21994. pattern.notes.push_back (n);
  21995. }
  21996. pattern.sortNotes();
  21997. }
  21998. const int order[] = { 0, 0, 1, 0 };
  21999. for (int i = 0; i < 4; ++i)
  22000. {
  22001. lynx::Clip clip;
  22002. clip.pattern = order[i];
  22003. clip.start = (std::int64_t) i * 16 * lynx::ppq;
  22004. clip.length = 16 * lynx::ppq;
  22005. s.playlist.push_back (clip);
  22006. }
  22007. s.mode = lynx::PlayMode::song;
  22008. });
  22009. offline.dispatchPendingMessages();
  22010. // the case Freeze exists for, a heavy hosted plugin: LYNX_FREEZETEST_PLUGIN = a plugin file whose first
  22011. // instrument plays the demo song's Lead (tools/testplugin/lynx_test_heavy_vst3.cpp: memory, CPU, latency, a
  22012. // state, and with LYNX_TEST_HEAVY_LOG the instances alive)
  22013. int hostedChannel = -1;
  22014. const auto hostedLog = juce::SystemStats::getEnvironmentVariable ("LYNX_TEST_HEAVY_LOG", {});
  22015. const auto hostedAlive = [&hostedLog] {
  22016. int alive = 0;
  22017. juce::StringArray lines;
  22018. juce::File (hostedLog).readLines (lines);
  22019. for (const auto& l : lines)
  22020. alive += l.startsWith ("create") ? 1 : l.startsWith ("destroy") ? -1 : 0;
  22021. return alive;
  22022. };
  22023. if (const auto pluginPath = juce::SystemStats::getEnvironmentVariable ("LYNX_FREEZETEST_PLUGIN", {}); pluginPath.isNotEmpty() && projectPath.isEmpty())
  22024. {
  22025. auto& host = offline.getPluginHost();
  22026. const auto added = host.addPluginFile (juce::File (pluginPath));
  22027. report << "hosted plugin file: " << pluginPath << " (" << added << " plugins)\n";
  22028. for (const auto& type : host.getKnownPlugins().getTypes())
  22029. if (type.isInstrument && juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginPath).getFileName())
  22030. {
  22031. offline.editSong ([&type] (lynx::Song& s) {
  22032. auto& c = s.channels[0];
  22033. c.instrument = lynx::InstrumentKind::plugin;
  22034. c.plugin.id = type.createIdentifierString().toStdString();
  22035. c.plugin.name = type.name.toStdString();
  22036. });
  22037. hostedChannel = 0;
  22038. break;
  22039. }
  22040. offline.dispatchPendingMessages();
  22041. auto* instance = dynamic_cast<lynx::PluginInstrument*> (offline.getChannelInstrument (0).get());
  22042. check (hostedChannel == 0 && instance != nullptr, "the hosted plugin is loaded on channel 1");
  22043. report << "hosted plugin: " << juce::String::fromUTF8 (offline.getSong().channels[0].plugin.name.c_str())
  22044. << ", engine latency " << offline.getLatencySamples() << " frames, instances alive " << hostedAlive() << "\n";
  22045. }
  22046. const auto hostedLine = [&] (const char* stage) {
  22047. if (hostedChannel < 0)
  22048. return;
  22049. offline.freeRetiredRacks();
  22050. report << "hosted, " << stage << ": instance on the channel "
  22051. << (dynamic_cast<lynx::PluginInstrument*> (offline.getChannelInstrument (hostedChannel).get()) != nullptr ? "yes" : "no")
  22052. << ", plugin instances alive in the process " << (hostedLog.isNotEmpty() ? juce::String (hostedAlive()) : juce::String ("(no log)")) << "\n";
  22053. };
  22054. const juce::File data (prefix + "-data");
  22055. data.deleteRecursively();
  22056. offline.setRecordingTarget (data.getChildFile ("Audio").getChildFile ("Recorded"), "freezetest");
  22057. report << "project=" << (projectPath.isNotEmpty() ? projectPath : juce::String ("(demo song)")) << "\n"
  22058. << "frozen_audio_folder=" << offline.getFreezeFolder().getFullPathName() << "\n";
  22059. const auto megabytes = [] (std::int64_t bytes) { return juce::String ((double) bytes / 1048576.0, 1); };
  22060. struct Mix
  22061. {
  22062. juce::AudioBuffer<float> audio;
  22063. double renderSeconds = 0.0, audioSeconds = 0.0;
  22064. std::int64_t workingSet = 0, privateBytes = 0;
  22065. };
  22066. // the song as it stands, rendered by an export (its own engine: frozen channels play their audio there too)
  22067. const auto renderMix = [&] (const char* name, const lynx::Song* other = nullptr, std::vector<int>* renderedLive = nullptr, int range = 0) {
  22068. Mix m;
  22069. offline.dispatchPendingMessages();
  22070. offline.freeRetiredRacks(); // (what the message loop does in the app: this mode runs without one)
  22071. m.workingSet = lynx::toolbar::PerformanceMeter::processMemoryBytes();
  22072. m.privateBytes = lynx::toolbar::PerformanceMeter::processPrivateBytes();
  22073. const juce::File file (prefix + "-" + name + ".wav");
  22074. lynx::ExportSettings settings;
  22075. settings.format = lynx::ExportSettings::Format::wav32Float;
  22076. settings.sampleRate = offline.getTransport().sampleRate.load();
  22077. settings.tailSeconds = 2.0;
  22078. juce::String error;
  22079. {
  22080. auto options = settings.toOptions();
  22081. options.hqAllPlugins = false; // the quality heard while playing: what a frozen channel's audio is made at
  22082. options.disableMaxPolyphony = false; // (and each channel's Max polyphony, as while playing)
  22083. if (range == 1)
  22084. options.range = lynx::exportopts::Range::selection;
  22085. if (range == 2)
  22086. {
  22087. options.range = lynx::exportopts::Range::pattern;
  22088. options.loops = 2;
  22089. }
  22090. lynx::ExportJob job (other != nullptr ? *other : offline.getSong(), options, file);
  22091. if (renderedLive != nullptr)
  22092. *renderedLive = job.channelsRenderedLive();
  22093. const auto started = juce::Time::getMillisecondCounterHiRes();
  22094. const auto ok = job.run ([] (double) { return true; }, error);
  22095. m.renderSeconds = (juce::Time::getMillisecondCounterHiRes() - started) / 1000.0;
  22096. check (ok, juce::String ("render ") + name + (ok ? juce::String() : ": " + error));
  22097. }
  22098. juce::WavAudioFormat wav;
  22099. if (std::unique_ptr<juce::AudioFormatReader> reader { wav.createReaderFor (file.createInputStream().release(), true) })
  22100. {
  22101. m.audio.setSize (2, (int) reader->lengthInSamples);
  22102. reader->read (&m.audio, 0, (int) reader->lengthInSamples, 0, true, true);
  22103. m.audioSeconds = (double) reader->lengthInSamples / reader->sampleRate;
  22104. }
  22105. file.deleteFile();
  22106. return m;
  22107. };
  22108. // the worst sample difference, in dB below the first mix's peak
  22109. const auto residual = [] (const Mix& a, const Mix& b, float& peak) {
  22110. float worst = 0.0f;
  22111. peak = 0.0f;
  22112. const auto n = juce::jmin (a.audio.getNumSamples(), b.audio.getNumSamples());
  22113. for (int ch = 0; ch < 2; ++ch)
  22114. for (int i = 0; i < n; ++i)
  22115. {
  22116. worst = juce::jmax (worst, std::abs (a.audio.getSample (ch, i) - b.audio.getSample (ch, i)));
  22117. peak = juce::jmax (peak, std::abs (a.audio.getSample (ch, i)));
  22118. }
  22119. return worst <= 0.0f ? -200.0 : 20.0 * std::log10 ((double) worst / (double) juce::jmax (peak, 1.0e-12f));
  22120. };
  22121. const auto line = [&] (const char* name, const Mix& m) {
  22122. report << name << ": working set " << megabytes (m.workingSet) << " MB, private " << megabytes (m.privateBytes) << " MB, render "
  22123. << juce::String (m.renderSeconds, 2) << " s for " << juce::String (m.audioSeconds, 2) << " s of audio ("
  22124. << juce::String (m.audioSeconds > 0.0 ? 100.0 * m.renderSeconds / m.audioSeconds : 0.0, 1) << " % of real time)\n";
  22125. };
  22126. if (mode == "measure")
  22127. {
  22128. // a process that only loaded this project and renders it: its memory with the project loaded, and after
  22129. int frozenCount = 0, hosted = 0;
  22130. for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
  22131. {
  22132. frozenCount += offline.getSong().channels[(std::size_t) c].freeze.on();
  22133. hosted += dynamic_cast<lynx::PluginInstrument*> (offline.getChannelInstrument (c).get()) != nullptr;
  22134. }
  22135. report << "channels " << (int) offline.getSong().channels.size() << ", frozen " << frozenCount << ", hosted plugin instances " << hosted << "\n";
  22136. const auto m = renderMix ("measure");
  22137. line ("loaded ", m);
  22138. report << "after the render: working set " << megabytes (lynx::toolbar::PerformanceMeter::processMemoryBytes()) << " MB, private "
  22139. << megabytes (lynx::toolbar::PerformanceMeter::processPrivateBytes()) << " MB\n";
  22140. flush();
  22141. return failures == 0;
  22142. }
  22143. // --- live ---
  22144. offline.capturePluginStates();
  22145. offline.editSong ([] (lynx::Song&) {}, false); // (whatever any edit settles — ids of new objects... — settled first)
  22146. const auto before = offline.getSong();
  22147. // (the project's working-time counter runs on while the test does: not part of what is compared)
  22148. const auto savedJson = [] (lynx::Song song) {
  22149. song.info.workSeconds = 0.0;
  22150. return lynx::ProjectFile::toJson (song, false);
  22151. };
  22152. const auto jsonBefore = savedJson (before);
  22153. std::vector<int> targets;
  22154. for (int c = 0; c < (int) before.channels.size(); ++c)
  22155. {
  22156. const auto* why = lynx::freeze::whyNot (before, c);
  22157. const auto plays = std::any_of (before.patterns.begin(), before.patterns.end(), [c] (const lynx::Pattern& p) {
  22158. return std::any_of (p.notes.begin(), p.notes.end(), [c] (const lynx::Note& n) { return n.channel == c; });
  22159. });
  22160. report << "channel " << (c + 1) << " '" << juce::String::fromUTF8 (before.channels[(std::size_t) c].name.c_str()) << "': "
  22161. << (why != nullptr ? juce::String ("not frozen (") + why + ")" : plays ? juce::String ("freeze") : juce::String ("no notes, left alone")) << "\n";
  22162. if (why == nullptr && plays)
  22163. {
  22164. targets.push_back (c);
  22165. // what could make a stem differ from the live channel, for the record
  22166. const auto& def = before.channels[(std::size_t) c];
  22167. int volPan = 0, params = 0, live = 0, lanes = 0, routes = 0;
  22168. for (const auto& a : before.automations)
  22169. if (a.target.index == c)
  22170. {
  22171. volPan += a.target.kind == lynx::AutomationTargetKind::channelVolume || a.target.kind == lynx::AutomationTargetKind::channelPan;
  22172. params += a.target.kind == lynx::AutomationTargetKind::channelParam;
  22173. live += a.isLive() && (a.target.kind == lynx::AutomationTargetKind::channelVolume || a.target.kind == lynx::AutomationTargetKind::channelPan
  22174. || a.target.kind == lynx::AutomationTargetKind::channelParam);
  22175. }
  22176. for (const auto& p : before.patterns)
  22177. for (const auto& lane : p.events)
  22178. lanes += lane.target.index == c && (lane.target.kind == lynx::AutomationTargetKind::channelVolume
  22179. || lane.target.kind == lynx::AutomationTargetKind::channelPan
  22180. || lane.target.kind == lynx::AutomationTargetKind::channelParam);
  22181. for (const auto& m : before.modulators)
  22182. for (const auto& r : m.routes)
  22183. routes += r.target.index == c && (r.target.kind == lynx::AutomationTargetKind::channelVolume
  22184. || r.target.kind == lynx::AutomationTargetKind::channelPan
  22185. || r.target.kind == lynx::AutomationTargetKind::channelParam);
  22186. report << " instrument kind " << (int) def.instrument << ", insert " << def.mixerTrack << ", automation: volume/pan " << volPan
  22187. << ", parameters " << params << ", live links " << live << ", event lanes " << lanes << ", modulator routes " << routes << "\n";
  22188. }
  22189. }
  22190. check (! targets.empty(), "the project has channels to freeze (" + juce::String ((int) targets.size()) + ")");
  22191. if (targets.empty())
  22192. {
  22193. flush();
  22194. return false;
  22195. }
  22196. const auto first = targets.front();
  22197. offline.setSelectedChannel (first);
  22198. ui.selectTabForSnapshot (0);
  22199. write ("rack-live");
  22200. saveMenus (juce::StringArray { "Channel (live)" }, std::vector<juce::PopupMenu> { ui.getRackForSnapshot().getChannelMenuForSnapshot (first) }, prefix + "-menu-live.png");
  22201. const auto live = renderMix ("live");
  22202. line ("live ", live);
  22203. hostedLine ("live");
  22204. const auto hostedState = hostedChannel >= 0 ? before.channels[(std::size_t) hostedChannel].plugin.state : std::string();
  22205. if (hostedChannel >= 0)
  22206. check (! hostedState.empty(), "the hosted plugin's state is in the project (" + juce::String ((int) hostedState.size()) + " characters)");
  22207. flush();
  22208. // --- frozen ---
  22209. const auto freezeStarted = juce::Time::getMillisecondCounterHiRes();
  22210. for (const auto c : targets)
  22211. {
  22212. const auto error = lynx::freezeChannelNow (offline, c);
  22213. check (error.isEmpty(), "freeze channel " + juce::String (c + 1) + (error.isEmpty() ? juce::String() : ": " + error));
  22214. }
  22215. const auto freezeSeconds = (juce::Time::getMillisecondCounterHiRes() - freezeStarted) / 1000.0;
  22216. offline.dispatchPendingMessages();
  22217. std::int64_t stemBytes = 0;
  22218. int stemFiles = 0;
  22219. bool pluginsGone = true, allFrozen = true;
  22220. for (const auto c : targets)
  22221. {
  22222. const auto& ch = offline.getSong().channels[(std::size_t) c];
  22223. allFrozen = allFrozen && ch.freeze.on() && ! offline.frozenAudioMissing (c) && ! offline.freezeOutOfDate (c);
  22224. for (const auto& stem : ch.freeze.stems)
  22225. {
  22226. stemBytes += juce::File (juce::String::fromUTF8 (stem.path.c_str())).getSize();
  22227. ++stemFiles;
  22228. }
  22229. pluginsGone = pluginsGone && dynamic_cast<lynx::PluginInstrument*> (offline.getChannelInstrument (c).get()) == nullptr;
  22230. auto thawed = ch;
  22231. thawed.freeze = {};
  22232. check (thawed == before.channels[(std::size_t) c], "channel " + juce::String (c + 1) + " keeps its instrument and settings as they were while frozen");
  22233. }
  22234. check (allFrozen, "every target is frozen, its audio on disk and up to date");
  22235. check (pluginsGone, "no hosted plugin instance is left on a frozen channel");
  22236. report << "freeze: " << juce::String (freezeSeconds, 2) << " s for " << (int) targets.size() << " channels, " << stemFiles << " files, "
  22237. << megabytes (stemBytes) << " MB on disk\n";
  22238. if (mode == "keep")
  22239. {
  22240. juce::String error;
  22241. check (lynx::ProjectFile::save (offline.getSong(), juce::File (prefix + "-frozen.lynx"), error), "the frozen project is saved" + (error.isEmpty() ? juce::String() : ": " + error));
  22242. flush();
  22243. return failures == 0;
  22244. }
  22245. const auto frozen = renderMix ("frozen");
  22246. line ("frozen ", frozen);
  22247. hostedLine ("frozen");
  22248. if (hostedChannel >= 0 && hostedLog.isNotEmpty())
  22249. check (hostedAlive() == 0, "while frozen no instance of the hosted plugin is alive in the process");
  22250. float peak = 0.0f;
  22251. const auto nullFrozen = residual (live, frozen, peak);
  22252. report << "null frozen vs live: " << juce::String (nullFrozen, 1) << " dB (peak " << juce::String (peak, 4) << ", "
  22253. << live.audio.getNumSamples() << " / " << frozen.audio.getNumSamples() << " samples)\n";
  22254. check (peak > 0.001f && nullFrozen < -90.0 && live.audio.getNumSamples() == frozen.audio.getNumSamples(), "the frozen mix nulls against the live mix (below -90 dB)");
  22255. ui.selectTabForSnapshot (0);
  22256. ui.setHintForSnapshot (ui.getRackForSnapshot().getChannelHintForSnapshot (first));
  22257. write ("rack-frozen");
  22258. saveMenus (juce::StringArray { "Channel (frozen)" }, std::vector<juce::PopupMenu> { ui.getRackForSnapshot().getChannelMenuForSnapshot (first) }, prefix + "-menu-frozen.png");
  22259. report << "hint frozen: " << ui.getRackForSnapshot().getChannelHintForSnapshot (first).text << "\n";
  22260. offline.setSelectedChannel (first);
  22261. ui.selectTabForSnapshot (1);
  22262. offline.setSelectedChannel (first);
  22263. offline.dispatchPendingMessages();
  22264. ui.setHintForSnapshot ({ lynx::tr ("{0} is frozen: Unfreeze to edit ([RMB] on the channel, Unfreeze)",
  22265. { juce::String::fromUTF8 (offline.getSong().channels[(std::size_t) first].name.c_str()) }), {} });
  22266. write ("pianoroll-frozen");
  22267. // --- exports that do not play the song's timeline once: a selection, one pattern twice ---
  22268. // (the frozen audio is the whole song from its start: those renders play the instruments, never a wrong part of it)
  22269. if (projectPath.isEmpty())
  22270. {
  22271. auto part = offline.getSong();
  22272. part.loopStart = 16 * lynx::ppq;
  22273. part.loopEnd = 40 * lynx::ppq;
  22274. const auto partLive = lynx::freeze::thawed (part);
  22275. for (int range = 1; range <= 2; ++range)
  22276. {
  22277. std::vector<int> renderedLive;
  22278. const auto a = renderMix (range == 1 ? "selection-live" : "pattern-live", &partLive, nullptr, range);
  22279. const auto b = renderMix (range == 1 ? "selection-frozen" : "pattern-frozen", &part, &renderedLive, range);
  22280. float partPeak = 0.0f;
  22281. const auto null = residual (a, b, partPeak);
  22282. report << (range == 1 ? "export of a selection (bars 5-10)" : "export of the current pattern, twice") << ", frozen vs live: " << juce::String (null, 1)
  22283. << " dB (peak " << juce::String (partPeak, 4) << ", " << juce::String (b.audioSeconds, 2) << " s), channels rendered live: " << (int) renderedLive.size() << "\n";
  22284. check (partPeak > 0.001f && null < -90.0 && a.audio.getNumSamples() == b.audio.getNumSamples(),
  22285. 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");
  22286. }
  22287. }
  22288. // --- what a save holds ---
  22289. {
  22290. const auto json = lynx::ProjectFile::toJson (offline.getSong(), false);
  22291. juce::String error;
  22292. const auto loaded = lynx::ProjectFile::fromJson (json, error);
  22293. check (json.contains ("\"freeze\""), "the saved project holds the frozen state");
  22294. check (loaded.has_value() && loaded->channels.size() == offline.getSong().channels.size()
  22295. && loaded->channels[(std::size_t) first].freeze == offline.getSong().channels[(std::size_t) first].freeze,
  22296. "a frozen project loads frozen, with the same audio files");
  22297. check (savedJson (lynx::freeze::thawed (offline.getSong())) == jsonBefore,
  22298. "without the frozen state the saved project is byte for byte what it was before the freeze");
  22299. check (! jsonBefore.contains ("\"freeze\""), "a project with nothing frozen has no freeze field");
  22300. }
  22301. // --- out of date: the tempo, a note of the frozen channel; not another channel's notes ---
  22302. {
  22303. offline.editSong ([] (lynx::Song& s) { s.bpm += 4.0; });
  22304. check (offline.freezeOutOfDate (first), "a tempo change marks the freeze out of date");
  22305. ui.selectTabForSnapshot (0);
  22306. ui.setHintForSnapshot (ui.getRackForSnapshot().getChannelHintForSnapshot (first));
  22307. write ("rack-out-of-date");
  22308. report << "hint out of date: " << ui.getRackForSnapshot().getChannelHintForSnapshot (first).text << "\n";
  22309. offline.editSong ([] (lynx::Song& s) { s.bpm -= 4.0; });
  22310. check (! offline.freezeOutOfDate (first), "the tempo back: up to date again");
  22311. int pattern = -1;
  22312. for (int p = 0; p < (int) before.patterns.size() && pattern < 0; ++p)
  22313. for (const auto& n : before.patterns[(std::size_t) p].notes)
  22314. if (n.channel == first)
  22315. {
  22316. pattern = p;
  22317. break;
  22318. }
  22319. if (pattern >= 0)
  22320. {
  22321. offline.editSong ([pattern, first] (lynx::Song& s) {
  22322. lynx::Note n;
  22323. n.channel = first;
  22324. n.start = 0;
  22325. n.key = 71;
  22326. s.patterns[(std::size_t) pattern].notes.push_back (n);
  22327. s.patterns[(std::size_t) pattern].sortNotes();
  22328. });
  22329. check (offline.freezeOutOfDate (first), "a note edit on the frozen channel marks it out of date");
  22330. bool othersFresh = true;
  22331. for (const auto c : targets)
  22332. othersFresh = othersFresh && (c == first || ! offline.freezeOutOfDate (c));
  22333. check (othersFresh, "the other frozen channels stay up to date");
  22334. // an export of the project in that state: the out-of-date channel renders live (never the old audio),
  22335. // the others keep their frozen audio — the same mix as the edited project with nothing frozen
  22336. {
  22337. std::vector<int> renderedLive;
  22338. const auto stale = renderMix ("stale", nullptr, &renderedLive);
  22339. const auto edited = lynx::freeze::thawed (offline.getSong());
  22340. const auto reference = renderMix ("stale-reference", &edited);
  22341. float stalePeak = 0.0f;
  22342. const auto nullStale = residual (reference, stale, stalePeak);
  22343. const auto nullOld = residual (frozen, stale, stalePeak);
  22344. report << "export with channel " << (first + 1) << " out of date: " << juce::String (nullStale, 1) << " dB vs the edited project live, "
  22345. << juce::String (nullOld, 1) << " dB vs the old frozen mix; channels rendered live: " << (int) renderedLive.size() << "\n";
  22346. check (renderedLive == std::vector<int> { first }, "an export renders the out-of-date frozen channel live, and only that one");
  22347. check (nullStale < -90.0 && nullOld > -60.0, "an export of an out-of-date freeze holds the edited notes, not the old audio");
  22348. }
  22349. offline.editSong ([&before] (lynx::Song& s) { s.patterns = before.patterns; });
  22350. check (! offline.freezeOutOfDate (first), "the notes back: up to date again");
  22351. }
  22352. }
  22353. // --- the audio gone: the instrument plays, never silence ---
  22354. {
  22355. const auto stems = offline.getSong().channels[(std::size_t) first].freeze.stems;
  22356. std::vector<std::pair<juce::File, juce::File>> moved;
  22357. for (const auto& stem : stems)
  22358. {
  22359. const juce::File file (juce::String::fromUTF8 (stem.path.c_str()));
  22360. const auto away = file.getSiblingFile (file.getFileName() + ".away");
  22361. if (file.moveFileTo (away))
  22362. moved.emplace_back (file, away);
  22363. }
  22364. offline.editSong ([] (lynx::Song&) {}, false);
  22365. check (offline.frozenAudioMissing (first), "frozen audio that is not on disk is noticed");
  22366. report << "hint audio missing: " << ui.getRackForSnapshot().getChannelHintForSnapshot (first).text << "\n";
  22367. const auto fallback = renderMix ("missing");
  22368. const auto nullMissing = residual (live, fallback, peak);
  22369. report << "null with the first channel's audio missing vs live: " << juce::String (nullMissing, 1) << " dB\n";
  22370. check (nullMissing < -90.0, "with its audio missing the channel plays its instrument");
  22371. for (const auto& [file, away] : moved)
  22372. away.moveFileTo (file);
  22373. offline.editSong ([] (lynx::Song&) {}, false);
  22374. check (! offline.frozenAudioMissing (first), "the audio back: frozen again");
  22375. // the frozen mix did not null and the first channel is not (alone) why: which one is, each thawed in turn
  22376. if (nullFrozen >= -90.0 && nullMissing >= -90.0)
  22377. for (const auto c : targets)
  22378. {
  22379. if (c == first)
  22380. continue;
  22381. std::vector<std::pair<juce::File, juce::File>> aside;
  22382. for (const auto& stem : offline.getSong().channels[(std::size_t) c].freeze.stems)
  22383. {
  22384. const juce::File file (juce::String::fromUTF8 (stem.path.c_str()));
  22385. const auto away = file.getSiblingFile (file.getFileName() + ".away");
  22386. if (file.moveFileTo (away))
  22387. aside.emplace_back (file, away);
  22388. }
  22389. offline.editSong ([] (lynx::Song&) {}, false);
  22390. const auto one = renderMix ("thawed");
  22391. report << "null with channel " << (c + 1) << " thawed vs live: " << juce::String (residual (live, one, peak), 1) << " dB\n";
  22392. for (const auto& [file, away] : aside)
  22393. away.moveFileTo (file);
  22394. offline.editSong ([] (lynx::Song&) {}, false);
  22395. }
  22396. }
  22397. // --- unfrozen ---
  22398. std::vector<juce::File> stemPaths;
  22399. for (const auto c : targets)
  22400. for (const auto& stem : offline.getSong().channels[(std::size_t) c].freeze.stems)
  22401. stemPaths.emplace_back (juce::String::fromUTF8 (stem.path.c_str()));
  22402. for (const auto c : targets)
  22403. lynx::unfreezeChannel (offline, c);
  22404. offline.dispatchPendingMessages();
  22405. check (offline.getSong().channels == before.channels, "Unfreeze gives every channel back exactly as it was (instrument, plugin state, settings)");
  22406. {
  22407. const auto jsonAfter = savedJson (offline.getSong());
  22408. check (jsonAfter == jsonBefore, "the unfrozen project saves byte for byte as before the freeze");
  22409. if (jsonAfter != jsonBefore)
  22410. {
  22411. juce::File (prefix + "-before.json").replaceWithText (jsonBefore);
  22412. juce::File (prefix + "-after.json").replaceWithText (jsonAfter);
  22413. }
  22414. }
  22415. int left = 0;
  22416. for (const auto& f : stemPaths)
  22417. left += f.existsAsFile() ? 1 : 0;
  22418. check (left == 0, "Unfreeze deletes the frozen audio (" + juce::String (left) + " of " + juce::String ((int) stemPaths.size()) + " files left)");
  22419. if (hostedChannel >= 0)
  22420. {
  22421. // the new instance (it starts with another tuning than the first one had) took the saved state
  22422. offline.capturePluginStates();
  22423. check (dynamic_cast<lynx::PluginInstrument*> (offline.getChannelInstrument (hostedChannel).get()) != nullptr, "Unfreeze loads the hosted plugin again");
  22424. check (offline.getSong().channels[(std::size_t) hostedChannel].plugin.state == hostedState,
  22425. "the hosted plugin's state, read back from the new instance, is the state it had before the freeze");
  22426. }
  22427. const auto unfrozen = renderMix ("unfrozen");
  22428. line ("unfrozen ", unfrozen);
  22429. hostedLine ("unfrozen");
  22430. const auto nullUnfrozen = residual (live, unfrozen, peak);
  22431. report << "null unfrozen vs live: " << juce::String (nullUnfrozen, 1) << " dB\n";
  22432. check (nullUnfrozen < -90.0, "the unfrozen mix nulls against the live mix");
  22433. ui.selectTabForSnapshot (0);
  22434. flush();
  22435. data.deleteRecursively();
  22436. return failures == 0;
  22437. }
  22438. // Round 190ff, the Clip-launch workflow's track commands end to end with the real engine, files and export
  22439. // (LYNX --trackfreezetest prefix). A demo song of three tracks (Lead through a delay and a reverb whose mix is
  22440. // automated, Bass through a delay, Drums on a bare insert; each insert's fader, pan and EQ set) is rendered live; then
  22441. // Freeze Track on every track (the instrument with its volume and pan through its insert's effects), the same render
  22442. // again (must null), the effects and instruments unloaded, the render time (the CPU while frozen), what a save holds;
  22443. // Flatten (Bounce Track in Place on a frozen track) with its undo; Bounce Track in Place of a live track; Bounce to New
  22444. // Track of a track's clips against that track's device output; Consolidate of pattern clips; Unfreeze. Written to
  22445. // prefix-report.txt; shots of the grid, the column menus, the Detail View's frozen devices and the Playlist's clip
  22446. // menu. True = every check passed.
  22447. bool runTrackFreezeTest (const juce::String& prefix)
  22448. {
  22449. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  22450. lynx::AudioEngine offline (false);
  22451. lynx::MainComponent ui (offline, false);
  22452. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  22453. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  22454. const auto write = [&prefix, &ui] (const char* name) {
  22455. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  22456. file.deleteFile();
  22457. juce::FileOutputStream out (file);
  22458. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (ui), out);
  22459. };
  22460. juce::String report;
  22461. int failures = 0;
  22462. const auto check = [&] (bool ok, const juce::String& what) {
  22463. report << (ok ? "ok " : "FAIL ") << what << "\n";
  22464. failures += ok ? 0 : 1;
  22465. };
  22466. const auto flush = [&] { juce::File (prefix + "-report.txt").replaceWithText (report + "failures=" + juce::String (failures) + "\n"); };
  22467. const juce::File data (prefix + "-data");
  22468. data.deleteRecursively();
  22469. offline.setRecordingTarget (data.getChildFile ("Audio").getChildFile ("Recorded"), "trackfreezetest");
  22470. ui.setVisible (true);
  22471. lynx::DetailView::shownSetting = lynx::DetailView::devicesPage = true;
  22472. ui.setClipLaunchWorkflow (true);
  22473. offline.editSong ([] (lynx::Song& s) {
  22474. s.channels.clear();
  22475. s.patterns.clear();
  22476. s.playlist.clear();
  22477. s.automations.clear();
  22478. s.bpm = 120.0;
  22479. s.mode = lynx::PlayMode::song;
  22480. const char* names[] = { "Lead", "Bass", "Drums" };
  22481. for (int c = 0; c < 3; ++c)
  22482. {
  22483. lynx::ChannelDef d;
  22484. d.name = names[c];
  22485. d.instrument = c == 2 ? lynx::InstrumentKind::kick : lynx::InstrumentKind::synth;
  22486. d.synth.release = c == 0 ? 0.6f : 0.2f;
  22487. d.synth.cutoff = c == 0 ? 2400.0f : 900.0f;
  22488. d.volume = c == 0 ? 0.65f : 0.78f;
  22489. d.pan = c == 0 ? 0.25f : 0.0f;
  22490. d.mixerTrack = c + 1;
  22491. s.channels.push_back (d);
  22492. }
  22493. if (s.mixer.size() < 5)
  22494. s.mixer.resize (5);
  22495. s.mixer[1].effects = { lynx::makeEffectSlot (lynx::EffectKind::delay), lynx::makeEffectSlot (lynx::EffectKind::reverb) };
  22496. s.mixer[2].effects = { lynx::makeEffectSlot (lynx::EffectKind::delay) };
  22497. s.mixer[3].effects.clear();
  22498. for (int t = 1; t <= 3; ++t)
  22499. {
  22500. s.mixer[(std::size_t) t].name = names[t - 1];
  22501. s.mixer[(std::size_t) t].volume = 0.7f;
  22502. s.mixer[(std::size_t) t].pan = t == 1 ? -0.3f : 0.1f;
  22503. s.mixer[(std::size_t) t].eq.gainDb[1] = 3.0f;
  22504. }
  22505. for (int p = 0; p < 3; ++p)
  22506. {
  22507. auto& pattern = s.patterns.emplace_back();
  22508. pattern.name = names[p];
  22509. pattern.lengthTicks = 4 * lynx::ppq * 2;
  22510. for (int step = 0; step < 8; ++step)
  22511. {
  22512. lynx::Note n;
  22513. n.channel = p;
  22514. n.start = (std::int64_t) step * lynx::ppq;
  22515. n.length = p == 2 ? lynx::ppq / 4 : lynx::ppq / 2;
  22516. n.key = p == 2 ? 36 : (p == 0 ? 60 : 36) + (step * 5) % 12;
  22517. pattern.notes.push_back (n);
  22518. }
  22519. }
  22520. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 4));
  22521. for (int t = 0; t < 3; ++t)
  22522. {
  22523. s.playlistTracks[(std::size_t) t].name = names[t];
  22524. for (int k = 0; k < 3; ++k)
  22525. {
  22526. if (t == 0 && k == 1)
  22527. continue; // (a gap in the Lead: its tail rings into it)
  22528. lynx::Clip clip;
  22529. clip.pattern = t;
  22530. clip.track = t;
  22531. clip.start = (std::int64_t) k * 8 * lynx::ppq;
  22532. clip.length = 8 * lynx::ppq;
  22533. s.playlist.push_back (clip);
  22534. }
  22535. }
  22536. // the Lead's reverb mix rises over the song (automation the freeze takes into its audio)
  22537. lynx::Automation a;
  22538. a.name = "Lead reverb mix";
  22539. a.target = { lynx::AutomationTargetKind::effectMix, 1, 1, 0 };
  22540. a.points = { { 0, 0.2f }, { 24 * lynx::ppq, 0.9f } };
  22541. s.automations.push_back (a);
  22542. lynx::Clip lane;
  22543. lane.kind = lynx::ClipKind::automation;
  22544. lane.automation = 0;
  22545. lane.track = 3;
  22546. lane.length = 24 * lynx::ppq;
  22547. s.playlist.push_back (lane);
  22548. std::stable_sort (s.playlist.begin(), s.playlist.end(), [] (const lynx::Clip& x, const lynx::Clip& y) { return x.start < y.start; });
  22549. });
  22550. offline.dispatchPendingMessages();
  22551. const auto megabytes = [] (std::int64_t bytes) { return juce::String ((double) bytes / 1048576.0, 1); };
  22552. struct Mix
  22553. {
  22554. juce::AudioBuffer<float> audio;
  22555. double renderSeconds = 0.0, audioSeconds = 0.0;
  22556. };
  22557. const auto renderMix = [&] (const char* name, const lynx::Song* other = nullptr) {
  22558. Mix m;
  22559. offline.dispatchPendingMessages();
  22560. offline.freeRetiredRacks();
  22561. const juce::File file (prefix + "-" + name + ".wav");
  22562. lynx::ExportSettings settings;
  22563. settings.format = lynx::ExportSettings::Format::wav32Float;
  22564. settings.sampleRate = offline.getTransport().sampleRate.load();
  22565. settings.tailSeconds = 2.0;
  22566. juce::String error;
  22567. auto options = settings.toOptions();
  22568. options.hqAllPlugins = false;
  22569. options.disableMaxPolyphony = false;
  22570. {
  22571. lynx::ExportJob job (other != nullptr ? *other : offline.getSong(), options, file);
  22572. const auto started = juce::Time::getMillisecondCounterHiRes();
  22573. const auto ok = job.run ([] (double) { return true; }, error);
  22574. m.renderSeconds = (juce::Time::getMillisecondCounterHiRes() - started) / 1000.0;
  22575. check (ok, juce::String ("render ") + name + (ok ? juce::String() : ": " + error));
  22576. }
  22577. juce::WavAudioFormat wav;
  22578. if (std::unique_ptr<juce::AudioFormatReader> reader { wav.createReaderFor (file.createInputStream().release(), true) })
  22579. {
  22580. m.audio.setSize (2, (int) reader->lengthInSamples);
  22581. reader->read (&m.audio, 0, (int) reader->lengthInSamples, 0, true, true);
  22582. m.audioSeconds = (double) reader->lengthInSamples / reader->sampleRate;
  22583. }
  22584. if (juce::SystemStats::getEnvironmentVariable ("LYNX_TRACKFREEZE_KEEP", {}).isEmpty()) // (kept: to look at a residual)
  22585. file.deleteFile();
  22586. return m;
  22587. };
  22588. const auto residual = [] (const Mix& a, const Mix& b, float& peak) {
  22589. float worst = 0.0f;
  22590. peak = 0.0f;
  22591. const auto n = juce::jmin (a.audio.getNumSamples(), b.audio.getNumSamples());
  22592. for (int ch = 0; ch < 2; ++ch)
  22593. for (int i = 0; i < n; ++i)
  22594. {
  22595. worst = juce::jmax (worst, std::abs (a.audio.getSample (ch, i) - b.audio.getSample (ch, i)));
  22596. peak = juce::jmax (peak, std::abs (a.audio.getSample (ch, i)));
  22597. }
  22598. return worst <= 0.0f ? -200.0 : 20.0 * std::log10 ((double) worst / (double) juce::jmax (peak, 1.0e-12f));
  22599. };
  22600. const auto nullLine = [&] (const char* what, const Mix& a, const Mix& b, double limit) {
  22601. float peak = 0.0f;
  22602. const auto r = residual (a, b, peak);
  22603. report << what << ": " << juce::String (r, 1) << " dB (peak " << juce::String (peak, 4) << ", " << a.audio.getNumSamples() << " / "
  22604. << b.audio.getNumSamples() << " samples)\n";
  22605. check (peak > 0.001f && r < limit && a.audio.getNumSamples() == b.audio.getNumSamples(), juce::String (what) + " below " + juce::String (limit, 0) + " dB");
  22606. return r;
  22607. };
  22608. const auto savedJson = [] (lynx::Song song) {
  22609. song.info.workSeconds = 0.0;
  22610. return lynx::ProjectFile::toJson (song, false);
  22611. };
  22612. // --- live ---
  22613. offline.capturePluginStates();
  22614. offline.editSong ([] (lynx::Song&) {}, false);
  22615. const auto before = offline.getSong();
  22616. const auto jsonBefore = savedJson (before);
  22617. auto* grid = ui.getClipGridForSnapshot();
  22618. check (grid != nullptr, "the Clip-launch workflow's grid is there");
  22619. if (grid == nullptr)
  22620. {
  22621. flush();
  22622. return false;
  22623. }
  22624. ui.setClipGridView (lynx::PlaylistArea::GridView::beside);
  22625. write ("live");
  22626. saveMenus (juce::StringArray { "Track title (live)" }, std::vector<juce::PopupMenu> { lynx::clipGridHeaderMenu (*grid, 0) }, prefix + "-menu-track-live.png");
  22627. int leadClip = -1;
  22628. for (int i = 0; i < (int) before.playlist.size() && leadClip < 0; ++i)
  22629. if (before.playlist[(std::size_t) i].track == 0 && before.playlist[(std::size_t) i].kind == lynx::ClipKind::pattern)
  22630. leadClip = i;
  22631. ui.getPlaylistForSnapshot().selectForSnapshot ({ leadClip });
  22632. saveMenus (juce::StringArray { "Playlist clip (Clip-launch workflow)" }, std::vector<juce::PopupMenu> { ui.getPlaylistForSnapshot().getClipMenuForSnapshot (leadClip) },
  22633. prefix + "-menu-clip.png");
  22634. const auto live = renderMix ("live");
  22635. report << "live: render " << juce::String (live.renderSeconds, 2) << " s for " << juce::String (live.audioSeconds, 2) << " s of audio\n";
  22636. // --- Freeze Track on every track ---
  22637. std::vector<int> channels;
  22638. for (int t = 0; t < 3; ++t)
  22639. {
  22640. const auto c = lynx::detailchain::forTrack (before, t).channel;
  22641. check (c == t, "track " + juce::String (t + 1) + " shows channel " + juce::String (t + 1));
  22642. const auto* why = lynx::freeze::whyNotTrack (before, c);
  22643. check (why == nullptr, "track " + juce::String (t + 1) + " can be frozen" + (why != nullptr ? juce::String (": ") + why : juce::String()));
  22644. const auto error = lynx::freezeTrackNow (offline, c);
  22645. check (error.isEmpty(), "Freeze Track " + juce::String (t + 1) + (error.isEmpty() ? juce::String() : ": " + error));
  22646. channels.push_back (c);
  22647. }
  22648. offline.dispatchPendingMessages();
  22649. offline.freeRetiredRacks();
  22650. int loadedEffects = 0;
  22651. for (int t = 1; t <= 3; ++t)
  22652. for (int slot = 0; slot < (int) offline.getSong().mixer[(std::size_t) t].effects.size(); ++slot)
  22653. loadedEffects += offline.getEffect (t, slot) != nullptr ? 1 : 0;
  22654. check (loadedEffects == 0, "no effect of a frozen track is loaded (" + juce::String (loadedEffects) + " left)");
  22655. bool fresh = true;
  22656. for (const auto c : channels)
  22657. {
  22658. const auto& f = offline.getSong().channels[(std::size_t) c].freeze;
  22659. fresh = fresh && f.on() && f.insert == c + 1 && lynx::freeze::trackFreezeHolds (offline.getSong(), c) && ! offline.freezeOutOfDate (c)
  22660. && ! offline.frozenAudioMissing (c);
  22661. }
  22662. check (fresh, "every track is frozen with its insert, its audio on disk and up to date");
  22663. check (offline.getSong().mixer == before.mixer, "the project keeps every effect as it was (Unfreeze brings them back)");
  22664. const auto frozenSong = offline.getSong();
  22665. const auto frozen = renderMix ("frozen");
  22666. report << "frozen: render " << juce::String (frozen.renderSeconds, 2) << " s (" << juce::String (100.0 * frozen.renderSeconds / juce::jmax (0.001, live.renderSeconds), 0)
  22667. << " % of the live render's time)\n";
  22668. nullLine ("frozen vs live", live, frozen, -90.0);
  22669. write ("frozen");
  22670. saveMenus (juce::StringArray { "Track title (frozen)" }, std::vector<juce::PopupMenu> { lynx::clipGridHeaderMenu (*grid, 0) }, prefix + "-menu-track-frozen.png");
  22671. if (auto* detail = ui.getDetailViewForSnapshot())
  22672. {
  22673. detail->showSelection (0, 0);
  22674. detail->setPage (lynx::DetailView::Page::devices);
  22675. write ("detail-frozen");
  22676. }
  22677. // the insert's fader is live: moved, the frozen and the live song change alike
  22678. {
  22679. auto liveLouder = before, frozenLouder = frozenSong;
  22680. liveLouder.mixer[1].volume = frozenLouder.mixer[1].volume = 0.8f;
  22681. nullLine ("frozen vs live, the Lead's fader moved afterwards", renderMix ("live-louder", &liveLouder), renderMix ("frozen-louder", &frozenLouder), -90.0);
  22682. }
  22683. // --- what a save holds ---
  22684. {
  22685. const auto json = lynx::ProjectFile::toJson (offline.getSong(), false);
  22686. juce::String error;
  22687. const auto loaded = lynx::ProjectFile::fromJson (json, error);
  22688. check (json.contains ("\"trackFreeze\"") && ! json.contains ("\"freeze\""), "a track freeze is saved under its own key (older versions play it live)");
  22689. check (loaded.has_value() && loaded->channels.size() == frozenSong.channels.size() && loaded->channels[0].freeze == frozenSong.channels[0].freeze,
  22690. "a track-frozen project loads frozen, with its insert and audio files");
  22691. check (savedJson (lynx::freeze::thawed (offline.getSong())) == jsonBefore, "without the frozen state the project saves as before the freeze");
  22692. }
  22693. // --- an edit of a frozen device's insert routing: the freeze stops holding, the track plays live ---
  22694. {
  22695. offline.editSong ([] (lynx::Song& s) { s.channels[1].mixerTrack = 1; }); // (the Bass into the Lead's insert)
  22696. check (! lynx::freeze::trackFreezeHolds (offline.getSong(), 0) && offline.freezeOutOfDate (0), "another channel routed into a frozen insert: out of date, plays live");
  22697. offline.undo();
  22698. offline.dispatchPendingMessages();
  22699. check (lynx::freeze::trackFreezeHolds (offline.getSong(), 0) && ! offline.freezeOutOfDate (0), "undo: frozen again");
  22700. }
  22701. // --- Flatten: Bounce Track in Place on the frozen Lead, and its undo ---
  22702. {
  22703. const auto error = lynx::flattenChannelNow (offline, 0);
  22704. check (error.isEmpty(), "Bounce Track in Place of the frozen Lead (Flatten)" + (error.isEmpty() ? juce::String() : ": " + error));
  22705. const auto& song = offline.getSong();
  22706. check (song.channels[0].instrument == lynx::InstrumentKind::audioClip && song.mixer[1].effects.empty() && song.mixer[1].volume == before.mixer[1].volume
  22707. && song.channels[0].name == "Lead (Bounce)",
  22708. "the Lead is audio now (\"Lead (Bounce)\"), its insert's effects removed, its fader kept");
  22709. int audioClips = 0;
  22710. for (const auto& c : song.playlist)
  22711. audioClips += c.kind == lynx::ClipKind::audio && c.channel == 0;
  22712. report << "flattened Lead: " << audioClips << " audio clips\n";
  22713. write ("flattened");
  22714. // over the song (the flattened clips end where the arrangement ends, as a frozen track plays; an export's
  22715. // ring-out after the song's end is not in them)
  22716. const auto span = (int) std::llround (before.secondsForTicks (24 * lynx::ppq) * offline.getTransport().sampleRate.load());
  22717. auto flatMix = renderMix ("flattened");
  22718. auto reference = live;
  22719. reference.audio.setSize (2, juce::jmin (span, reference.audio.getNumSamples()), true);
  22720. flatMix.audio.setSize (2, reference.audio.getNumSamples(), true);
  22721. nullLine ("flattened (Lead) + frozen (others) vs live, over the song", reference, flatMix, -90.0);
  22722. offline.undo();
  22723. offline.dispatchPendingMessages();
  22724. check (savedJson (offline.getSong()) == savedJson (frozenSong), "undo of the Flatten: the frozen project exactly as before");
  22725. }
  22726. // --- Unfreeze every track ---
  22727. for (const auto c : channels)
  22728. lynx::unfreezeChannel (offline, c);
  22729. offline.dispatchPendingMessages();
  22730. check (savedJson (offline.getSong()) == jsonBefore, "Unfreeze: the project saves byte for byte as before the freeze");
  22731. nullLine ("unfrozen vs live", live, renderMix ("unfrozen"), -90.0);
  22732. // --- Bounce Track in Place of a live track (render and flatten in one step, one undo) ---
  22733. {
  22734. const auto error = lynx::freezeTrackNow (offline, 1, true);
  22735. check (error.isEmpty(), "Bounce Track in Place of the live Bass" + (error.isEmpty() ? juce::String() : ": " + error));
  22736. check (offline.getSong().channels[1].instrument == lynx::InstrumentKind::audioClip && ! offline.getSong().channels[1].freeze.on(),
  22737. "the Bass is audio, not frozen");
  22738. auto bouncedMix = renderMix ("bounced");
  22739. auto reference = live;
  22740. const auto span = (int) std::llround (before.secondsForTicks (24 * lynx::ppq) * offline.getTransport().sampleRate.load());
  22741. reference.audio.setSize (2, juce::jmin (span, reference.audio.getNumSamples()), true);
  22742. bouncedMix.audio.setSize (2, reference.audio.getNumSamples(), true);
  22743. nullLine ("Bass bounced in place vs live, over the song", reference, bouncedMix, -90.0);
  22744. offline.undo();
  22745. offline.dispatchPendingMessages();
  22746. check (savedJson (offline.getSong()) == jsonBefore, "undo of Bounce Track in Place: the project as before");
  22747. }
  22748. // --- Bounce to New Track: the Lead's clips onto a new track (the clips muted, the new track with the Lead's mixer) ---
  22749. {
  22750. std::vector<int> leadClips;
  22751. for (int i = 0; i < (int) offline.getSong().playlist.size(); ++i)
  22752. if (offline.getSong().playlist[(std::size_t) i].track == 0 && offline.getSong().playlist[(std::size_t) i].kind == lynx::ClipKind::pattern)
  22753. leadClips.push_back (i);
  22754. const auto channelsBefore = offline.getSong().channels.size();
  22755. const auto error = lynx::bounceToNewTrack (offline, leadClips, true);
  22756. check (error.isEmpty(), "Bounce to New Track of the Lead's clips" + (error.isEmpty() ? juce::String() : ": " + error));
  22757. const auto& song = offline.getSong();
  22758. check (song.channels.size() == channelsBefore + 1 && song.channels.back().instrument == lynx::InstrumentKind::audioClip
  22759. && song.channels.back().mixerTrack > 3 && song.mixer[(std::size_t) song.channels.back().mixerTrack].volume == before.mixer[1].volume,
  22760. "a new audio channel holds the bounce, on an insert with the Lead's mixer");
  22761. // the song's span (the bounce stops at the last clip's end, the live render rings on after it)
  22762. auto bounced = renderMix ("bounced-new-track");
  22763. auto reference = live;
  22764. const auto span = (int) std::llround (before.secondsForTicks (24 * lynx::ppq) * offline.getTransport().sampleRate.load());
  22765. reference.audio.setSize (2, juce::jmin (span, reference.audio.getNumSamples()), true);
  22766. bounced.audio.setSize (2, reference.audio.getNumSamples(), true);
  22767. nullLine ("Bounce to New Track (Lead's clips muted) vs live, over the song", reference, bounced, -90.0);
  22768. write ("bounced-new-track");
  22769. offline.undo();
  22770. offline.dispatchPendingMessages();
  22771. check (savedJson (offline.getSong()) == jsonBefore, "undo of Bounce to New Track: the project as before");
  22772. }
  22773. // --- Consolidate: the Bass's three pattern clips become one ---
  22774. {
  22775. std::vector<int> bassClips;
  22776. for (int i = 0; i < (int) offline.getSong().playlist.size(); ++i)
  22777. if (offline.getSong().playlist[(std::size_t) i].track == 1 && offline.getSong().playlist[(std::size_t) i].kind == lynx::ClipKind::pattern)
  22778. bassClips.push_back (i);
  22779. const auto error = lynx::consolidateClips (offline, bassClips, true);
  22780. check (error.isEmpty(), "Consolidate of the Bass's clips" + (error.isEmpty() ? juce::String() : ": " + error));
  22781. int left = 0;
  22782. for (const auto& c : offline.getSong().playlist)
  22783. left += c.track == 1 && c.kind == lynx::ClipKind::pattern;
  22784. check (left == 1, "one clip on the Bass track (" + juce::String (left) + ")");
  22785. nullLine ("consolidated vs live", live, renderMix ("consolidated"), -90.0);
  22786. offline.undo();
  22787. offline.dispatchPendingMessages();
  22788. check (savedJson (offline.getSong()) == jsonBefore, "undo of Consolidate: the project as before");
  22789. }
  22790. report << "frozen audio folder: " << offline.getFreezeFolder().getFullPathName() << "\n";
  22791. flush();
  22792. data.deleteRecursively();
  22793. (void) megabytes;
  22794. return failures == 0;
  22795. }
  22796. // --paintbench (round 190ge): the paint cost of every main view, off screen. Each view is shown maximised in a
  22797. // LYNX_SNAPSHOT_SIZE window (default 1920x1080) and drawn whole into a picture `frames` times (after a repaint of
  22798. // all of it, so no cached picture is reused: the cost of a frame after an edit), then `frames` times without the
  22799. // repaint (what a view's own caches leave of a frame). The report gives the median and the 90th percentile of
  22800. // the message thread's CPU per frame.
  22801. void runPaintBench (const juce::File& project, const juce::File& report)
  22802. {
  22803. // LYNX_PROFILE_MAIN=<file> (round 190gr): the message thread sampled while it paints (Windows; one view at a time
  22804. // with LYNX_PAINTBENCH_VIEWS)
  22805. const auto profile = juce::SystemStats::getEnvironmentVariable ("LYNX_PROFILE_MAIN", {});
  22806. if (profile.isNotEmpty())
  22807. lynx::crashguard::startMainProfiler (profile.toStdString(), 1000, 2);
  22808. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  22809. lynx::AudioEngine offline (false);
  22810. lynx::MainComponent ui (offline, false);
  22811. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1920x1080"), "x", "");
  22812. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  22813. juce::String text;
  22814. text << "project: " << project.getFullPathName() << "\nLYNX " << getApplicationVersion() << ", " << juce::SystemStats::getCpuModel()
  22815. << ", window " << ui.getWidth() << "x" << ui.getHeight() << "\n";
  22816. if (project.existsAsFile())
  22817. {
  22818. // (round perfgate190id) the time to open it headless, and the memory after
  22819. const auto open0 = juce::Time::getMillisecondCounterHiRes();
  22820. const auto cpu0 = lynx::threadCpuSeconds();
  22821. ui.openFile (project);
  22822. offline.dispatchPendingMessages();
  22823. text << "open: " << juce::String (juce::Time::getMillisecondCounterHiRes() - open0, 1) << " ms wall, "
  22824. << juce::String (1000.0 * (lynx::threadCpuSeconds() - cpu0), 1) << " ms message thread CPU, working set "
  22825. << juce::String ((double) lynx::toolbar::PerformanceMeter::processMemoryBytes() / 1048576.0, 0) << " MB\n";
  22826. }
  22827. const auto& song = offline.getSong();
  22828. text << "channels " << (int) song.channels.size() << ", patterns " << (int) song.patterns.size() << ", playlist clips " << (int) song.playlist.size()
  22829. << ", inserts " << (int) song.mixer.size() << "\n";
  22830. // the playhead a third into the song (song mode) so the views draw it as when playing
  22831. offline.getTransport().songMode = true;
  22832. offline.getTransport().positionTicks.store ((double) song.songLength() / 3.0);
  22833. const auto frames = juce::jlimit (3, 500, juce::SystemStats::getEnvironmentVariable ("LYNX_PAINTBENCH_FRAMES", "40").getIntValue());
  22834. juce::Image image (juce::Image::ARGB, ui.getWidth(), ui.getHeight(), true);
  22835. {
  22836. // (round 190gr) which renderer draws the frames: the software one (Linux), Direct2D (Windows), Core Graphics
  22837. juce::Graphics g (image);
  22838. auto& context = g.getInternalContext();
  22839. text << "renderer: " << (dynamic_cast<juce::LowLevelGraphicsSoftwareRenderer*> (&context) != nullptr ? "software" : typeid (context).name())
  22840. << ", paint caches " << (lynx::ui::paintCache() ? "on" : "off (LYNX_PAINT_CACHE=0)") << ", paint savings "
  22841. << (lynx::ui::paintSavings() ? "on" : "off (LYNX_PAINT_SAVINGS=0)") << "\n";
  22842. }
  22843. // LYNX_PAINTBENCH_VIEWS="mixer,channel rack" (round 190gr): only those views
  22844. const auto onlyViews = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_PAINTBENCH_VIEWS", {}), ",", "");
  22845. const auto wanted = [&onlyViews] (const juce::String& name) { return onlyViews.isEmpty() || onlyViews.contains (name); };
  22846. // the picture's pixels as one number: the same before and after a change = the same drawing
  22847. auto pixelHash = [&image] {
  22848. const juce::Image::BitmapData data (image, juce::Image::BitmapData::readOnly);
  22849. std::uint64_t h = 1469598103934665603ull;
  22850. for (int y = 0; y < data.height; ++y)
  22851. for (int x = 0; x < data.width; ++x)
  22852. h = (h ^ data.getPixelColour (x, y).getARGB()) * 1099511628211ull;
  22853. return juce::String::toHexString ((juce::int64) h);
  22854. };
  22855. // mode 0: whole frames after a repaint of everything; 1: whole frames, the views' own caches kept; 2: a 14-pixel
  22856. // column of the whole height at 40 places (what a moving playhead repaints each frame)
  22857. auto measure = [&] (const juce::String& name, int mode) {
  22858. offline.dispatchPendingMessages();
  22859. std::vector<double> ms, wall;
  22860. juce::String hash;
  22861. for (int f = -3; f < frames; ++f) // (3 frames to warm the caches up)
  22862. {
  22863. if (mode == 0)
  22864. ui.repaint();
  22865. const auto column = juce::Rectangle<int> ((juce::jmax (0, f) * 97) % juce::jmax (1, ui.getWidth() - 14), 0, 14, ui.getHeight());
  22866. const auto t0 = lynx::threadCpuSeconds();
  22867. const auto w0 = juce::Time::getMillisecondCounterHiRes();
  22868. {
  22869. juce::Graphics g (image);
  22870. if (mode == 2)
  22871. g.reduceClipRegion (column);
  22872. ui.paintEntireComponent (g, true);
  22873. }
  22874. if (f >= 0)
  22875. {
  22876. ms.push_back (1000.0 * (lynx::threadCpuSeconds() - t0));
  22877. wall.push_back (juce::Time::getMillisecondCounterHiRes() - w0); // (round 190gr: Direct2D's work ends with the frame)
  22878. }
  22879. if (f == 0 && mode == 0)
  22880. {
  22881. hash = pixelHash();
  22882. // LYNX_PAINTBENCH_PNG=<prefix> (round 190gr): the whole frame as <prefix>-<view>.png, to compare pixels
  22883. if (const auto png = juce::SystemStats::getEnvironmentVariable ("LYNX_PAINTBENCH_PNG", {}); png.isNotEmpty())
  22884. {
  22885. const juce::File file (png + "-" + name.replaceCharacter (' ', '-') + ".png");
  22886. file.deleteFile();
  22887. juce::FileOutputStream out (file);
  22888. juce::PNGImageFormat().writeImageToStream (image, out);
  22889. }
  22890. }
  22891. }
  22892. std::sort (ms.begin(), ms.end());
  22893. std::sort (wall.begin(), wall.end());
  22894. text << name << (mode == 0 ? ", whole frame" : mode == 1 ? ", cached frame" : ", playhead column") << ": median "
  22895. << juce::String (ms[ms.size() / 2], 3) << " ms, p90 " << juce::String (ms[(ms.size() * 9) / 10], 3) << " ms, wall median "
  22896. << juce::String (wall[wall.size() / 2], 3) << " ms"
  22897. << (hash.isNotEmpty() ? ", pixels " + hash : juce::String()) << "\n";
  22898. report.replaceWithText (text);
  22899. };
  22900. auto measureAll = [&] (const juce::String& name) {
  22901. if (! wanted (name))
  22902. return;
  22903. measure (name, 0);
  22904. measure (name, 1);
  22905. measure (name, 2);
  22906. // the columns' pixels too (painted over the whole frame: culling must not change a pixel)
  22907. ui.repaint();
  22908. {
  22909. juce::Graphics g (image);
  22910. ui.paintEntireComponent (g, true);
  22911. for (int x = 3; x < ui.getWidth() - 14; x += 211)
  22912. {
  22913. juce::Graphics::ScopedSaveState state (g);
  22914. g.reduceClipRegion (x, 0, 14, ui.getHeight());
  22915. ui.paintEntireComponent (g, true);
  22916. }
  22917. }
  22918. text << name << ", columns over the whole frame: pixels " << pixelHash() << "\n";
  22919. };
  22920. const char* views[] { "channel rack", "piano roll", "playlist", "mixer" };
  22921. for (int v = 0; v < 4; ++v)
  22922. {
  22923. ui.selectTabForSnapshot (v);
  22924. measureAll (views[v]);
  22925. }
  22926. ui.showDesktopForSnapshot (false);
  22927. measureAll ("desktop");
  22928. ui.selectTabForSnapshot (2);
  22929. ui.setClipLaunchWorkflow (true);
  22930. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  22931. measureAll ("clip grid");
  22932. ui.setClipGridView (lynx::PlaylistArea::GridView::song); // (round 190jn: the Clip-launch layout's Arrangement)
  22933. measureAll ("clip arrangement");
  22934. // (and with View > Tall Arrangement lanes: LYNX's 38 px rows in Live's look, the classic look's row height)
  22935. lynx::playlistTallLiveLanes() = true;
  22936. ui.getPlaylistForSnapshot().liveLanesChanged();
  22937. measureAll ("clip arrangement, tall lanes");
  22938. lynx::playlistTallLiveLanes() = false;
  22939. ui.getPlaylistForSnapshot().liveLanesChanged();
  22940. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  22941. ui.setClipLaunchWorkflow (false);
  22942. // LYNX_PAINTBENCH_SIMPLE=1 (round 190jc): the same project's Playlist in the Simple layout too
  22943. if (juce::SystemStats::getEnvironmentVariable ("LYNX_PAINTBENCH_SIMPLE", {}) == "1")
  22944. {
  22945. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  22946. offline.dispatchPendingMessages();
  22947. if (auto* simple = ui.getSimpleWorkflowForSnapshot())
  22948. simple->hideChooser();
  22949. ui.selectTabForSnapshot (2);
  22950. measureAll ("simple playlist");
  22951. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
  22952. }
  22953. text << "result=OK\n";
  22954. report.replaceWithText (text);
  22955. if (profile.isNotEmpty())
  22956. lynx::crashguard::stopMainProfiler();
  22957. }
  22958. // Round 190iv: the toolbar per layout style (see --toolbarshot190iv above)
  22959. void runToolbarShot190iv (const juce::String& prefix, const juce::String& projectPath)
  22960. {
  22961. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  22962. lynx::ui::motion::enabled() = false; // (hover states drawn at once, no fade)
  22963. lynx::AudioEngine offline (false);
  22964. lynx::MainComponent ui (offline, false);
  22965. ui.setSize (1920, 1080);
  22966. juce::String report;
  22967. const auto write = [&prefix] (const juce::Image& image, const juce::String& name) {
  22968. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  22969. file.deleteFile();
  22970. juce::FileOutputStream out (file);
  22971. juce::PNGImageFormat().writeImageToStream (image, out);
  22972. };
  22973. const auto bar = [&ui] { return ui.getLocalBounds().withHeight (juce::jmin (ui.getHeight(), 90)); };
  22974. const auto describe = [&ui, &report] (const juce::String& title) {
  22975. report << "== " << title << " (" << ui.getWidth() << "x" << ui.getHeight() << ")\n";
  22976. for (const auto* name : { "play", "stop", "record", "metronome", "tap", "tempo", "signature", "quantisation", "key", "link", "browser",
  22977. "backToArrangement", "position", "overdub", "capture", "sessionRecord", "punch", "draw", "computerKeys",
  22978. "keyMap", "midiMap", "cpu", "more", "sessionView", "arrangementView", "status", "finish" })
  22979. if (auto* c = ui.toolbarPartForSnapshot (name); c != nullptr && c->isVisible() && c->getParentComponent() == &ui)
  22980. report << " " << name << " " << c->getBounds().toString() << "\n";
  22981. };
  22982. const std::pair<int, int> sizes[] { { 1920, 1080 }, { 1366, 768 }, { 1280, 800 } };
  22983. // a song with a few tracks for the Simple layout (voice, instrument, drums), as --simpleshot makes them
  22984. offline.editSong ([] (lynx::Song& s) {
  22985. namespace st = lynx::simpletracks;
  22986. st::Request q;
  22987. q.kind = st::Kind::voice;
  22988. q.name = "Lead vocal";
  22989. st::addTrack (s, q);
  22990. q = {};
  22991. q.kind = st::Kind::instrument;
  22992. q.name = "Keys";
  22993. lynx::ChannelDef keys;
  22994. keys.instrument = lynx::InstrumentKind::synth;
  22995. q.channel = keys;
  22996. st::addTrack (s, q);
  22997. q = {};
  22998. q.kind = st::Kind::drums;
  22999. q.name = "Drums";
  23000. st::addTrack (s, q);
  23001. s.bpm = 120.0;
  23002. }, false);
  23003. offline.dispatchPendingMessages();
  23004. // 1. Pattern: FL's toolbar (it must stay as it was: compare with the base build's)
  23005. ui.selectTabForSnapshot (2);
  23006. for (const auto& [w, h] : sizes)
  23007. {
  23008. ui.setSize (w, h);
  23009. write (lynx::shot::snapshot (ui, bar()), "pattern-bar-" + juce::String (w));
  23010. }
  23011. ui.setSize (1920, 1080);
  23012. // 2. Simple
  23013. ui.setLayoutStyle (lynx::layoutstyle::Style::simple, false);
  23014. offline.dispatchPendingMessages();
  23015. for (const auto& [w, h] : sizes)
  23016. {
  23017. ui.setSize (w, h);
  23018. offline.dispatchPendingMessages();
  23019. write (lynx::shot::snapshot (ui), "simple-" + juce::String (w));
  23020. write (lynx::shot::snapshot (ui, bar()), "simple-bar-" + juce::String (w));
  23021. describe ("simple " + juce::String (w));
  23022. }
  23023. ui.setSize (1920, 1080);
  23024. auto* play = dynamic_cast<juce::Button*> (ui.toolbarPartForSnapshot ("play"));
  23025. auto* stop = dynamic_cast<juce::Button*> (ui.toolbarPartForSnapshot ("stop"));
  23026. auto* rec = dynamic_cast<juce::Button*> (ui.toolbarPartForSnapshot ("record"));
  23027. const auto capsuleArea = [&] {
  23028. juce::Rectangle<int> r;
  23029. for (const auto* name : { "play", "stop", "record", "position", "metronome", "tempo", "signature", "key" })
  23030. if (auto* c = ui.toolbarPartForSnapshot (name); c != nullptr && c->isVisible())
  23031. r = r.isEmpty() ? c->getBounds() : r.getUnion (c->getBounds());
  23032. return r.expanded (8, 10);
  23033. };
  23034. if (play != nullptr && stop != nullptr && rec != nullptr)
  23035. {
  23036. write (lynx::shot::snapshot (ui, capsuleArea()), "simple-transport-idle");
  23037. play->setState (juce::Button::buttonOver);
  23038. write (lynx::shot::snapshot (ui, capsuleArea()), "simple-transport-hover");
  23039. play->setState (juce::Button::buttonDown);
  23040. write (lynx::shot::snapshot (ui, capsuleArea()), "simple-transport-pressed");
  23041. play->setState (juce::Button::buttonNormal);
  23042. play->setToggleState (true, juce::dontSendNotification);
  23043. write (lynx::shot::snapshot (ui, capsuleArea()), "simple-transport-playing");
  23044. rec->setToggleState (true, juce::dontSendNotification);
  23045. write (lynx::shot::snapshot (ui, capsuleArea()), "simple-transport-recording");
  23046. play->setToggleState (false, juce::dontSendNotification);
  23047. rec->setToggleState (false, juce::dontSendNotification);
  23048. }
  23049. if (auto* status = ui.toolbarPartForSnapshot ("status"))
  23050. {
  23051. using S = lynx::toolbarlayout::SaveState;
  23052. int n = 0;
  23053. for (const auto state : { S::fresh, S::unsaved, S::backedUp, S::saved })
  23054. {
  23055. ui.setSaveStatusForSnapshot (state);
  23056. auto r = status->getBounds();
  23057. if (auto* finish = ui.toolbarPartForSnapshot ("finish"); finish != nullptr && finish->isVisible())
  23058. r = r.getUnion (finish->getBounds());
  23059. write (lynx::shot::snapshot (ui, r.expanded (8, 10)), "simple-status-" + juce::String (n++));
  23060. }
  23061. }
  23062. {
  23063. auto more = ui.makeToolbarMoreMenuForSnapshot();
  23064. saveMenus (juce::StringArray { "More" }, std::vector<juce::PopupMenu> { more }, prefix + "-simple-more-menu.png");
  23065. }
  23066. // 3. Clip-launch: Live's control bar (the Live demo set when given, else an empty grid)
  23067. if (projectPath.isNotEmpty())
  23068. {
  23069. ui.openFile (juce::File (projectPath));
  23070. offline.dispatchPendingMessages();
  23071. }
  23072. ui.setLayoutStyle (lynx::layoutstyle::Style::clipLaunch, false);
  23073. offline.dispatchPendingMessages();
  23074. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  23075. for (const auto& [w, h] : sizes)
  23076. {
  23077. ui.setSize (w, h);
  23078. offline.dispatchPendingMessages();
  23079. write (lynx::shot::snapshot (ui), "live-" + juce::String (w));
  23080. write (lynx::shot::snapshot (ui, bar()), "live-bar-" + juce::String (w));
  23081. describe ("clip-launch " + juce::String (w));
  23082. }
  23083. ui.setSize (1920, 1080);
  23084. ui.setClipGridView (lynx::PlaylistArea::GridView::song);
  23085. write (lynx::shot::snapshot (ui), "live-arrangement-1920");
  23086. ui.setClipGridView (lynx::PlaylistArea::GridView::beside);
  23087. write (lynx::shot::snapshot (ui), "live-both-1920");
  23088. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  23089. // every control-bar button idle / hover / pressed / lit, all at once per picture
  23090. std::vector<juce::Button*> buttons;
  23091. for (const auto* name : { "play", "stop", "record", "metronome", "tap", "browser", "backToArrangement", "overdub", "capture", "sessionRecord", "punch",
  23092. "draw", "computerKeys", "keyMap", "midiMap", "more", "sessionView", "arrangementView" })
  23093. if (auto* b = dynamic_cast<juce::Button*> (ui.toolbarPartForSnapshot (name)); b != nullptr && b->isVisible())
  23094. buttons.push_back (b);
  23095. std::vector<bool> lit;
  23096. for (auto* b : buttons)
  23097. lit.push_back (b->getToggleState());
  23098. const auto controlBar = ui.getLocalBounds().withTrimmedTop (lynx::toolbarlayout::livebar::menuRow).withHeight (lynx::toolbarlayout::livebar::band);
  23099. write (lynx::shot::snapshot (ui, controlBar), "live-states-idle");
  23100. for (const auto& [state, name] : { std::pair<juce::Button::ButtonState, const char*> { juce::Button::buttonOver, "hover" }, { juce::Button::buttonDown, "pressed" } })
  23101. {
  23102. for (auto* b : buttons)
  23103. b->setState (state);
  23104. write (lynx::shot::snapshot (ui, controlBar), juce::String ("live-states-") + name);
  23105. }
  23106. for (auto* b : buttons)
  23107. {
  23108. b->setState (juce::Button::buttonNormal);
  23109. b->setToggleState (true, juce::dontSendNotification);
  23110. }
  23111. write (lynx::shot::snapshot (ui, controlBar), "live-states-lit");
  23112. for (std::size_t k = 0; k < buttons.size(); ++k)
  23113. buttons[k]->setToggleState (lit[k], juce::dontSendNotification);
  23114. {
  23115. auto more = ui.makeToolbarMoreMenuForSnapshot();
  23116. saveMenus (juce::StringArray { "More" }, std::vector<juce::PopupMenu> { more }, prefix + "-live-more-menu.png");
  23117. }
  23118. // the Session button row kept as an option
  23119. ui.setSessionButtonRowShown (true);
  23120. write (lynx::shot::snapshot (ui), "live-buttonrow-1920");
  23121. ui.setSessionButtonRowShown (false);
  23122. // 4. back to Pattern: FL's toolbar again, as it was
  23123. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern, false);
  23124. offline.dispatchPendingMessages();
  23125. for (const auto& [w, h] : sizes)
  23126. {
  23127. ui.setSize (w, h);
  23128. write (lynx::shot::snapshot (ui, bar()), "pattern-after-bar-" + juce::String (w));
  23129. }
  23130. juce::File (prefix + "-report.txt").replaceWithText (report);
  23131. lynx::ui::motion::enabled() = true;
  23132. }
  23133. void runGridShot (const juce::String& prefix, const juce::String& projectPath = {})
  23134. {
  23135. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  23136. lynx::AudioEngine offline (false);
  23137. lynx::MainComponent ui (offline, false);
  23138. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  23139. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  23140. const auto write = [&prefix, &ui] (const char* name) {
  23141. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  23142. file.deleteFile();
  23143. juce::FileOutputStream out (file);
  23144. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (ui), out);
  23145. };
  23146. ui.selectTabForSnapshot (2); // the Playlist panel, maximized
  23147. if (projectPath.isNotEmpty())
  23148. {
  23149. ui.openFile (juce::File (projectPath));
  23150. offline.dispatchPendingMessages();
  23151. ui.setClipLaunchWorkflow (true);
  23152. offline.dispatchPendingMessages();
  23153. write ("file-both");
  23154. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  23155. write ("file-grid");
  23156. const auto& song = offline.getSong();
  23157. juce::String info;
  23158. info << "grid " << (song.clipGrid ? "yes" : "no") << ", clips " << (song.clipGrid ? (int) song.clipGrid->clips.size() : 0)
  23159. << ", scenes " << (song.clipGrid ? (int) song.clipGrid->scenes.size() : 0) << ", playlist clips " << (int) song.playlist.size() << "\n";
  23160. juce::File (prefix + "-file.txt").replaceWithText (info);
  23161. ui.setClipLaunchWorkflow (false);
  23162. return;
  23163. }
  23164. write ("pattern"); // Pattern workflow: nothing of the grid exists yet
  23165. const auto madeBefore = lynx::launcher::Runtime::instances.load();
  23166. offline.editSong ([] (lynx::Song& s) {
  23167. while (s.patterns.size() < 6)
  23168. s.patterns.emplace_back();
  23169. for (int p = 0; p < 6; ++p)
  23170. {
  23171. auto& pattern = s.patterns[(std::size_t) p];
  23172. const char* names[] { "Drums A", "Drums B", "Bass", "Chords", "Lead", "Pad" };
  23173. pattern.name = names[p];
  23174. pattern.lengthTicks = 4 * lynx::ppq;
  23175. }
  23176. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 6));
  23177. const char* tracks[] { "Drums", "Bass", "Chords", "Lead", "Vocals", "FX" };
  23178. for (int t = 0; t < 6; ++t)
  23179. s.playlistTracks[(std::size_t) t].name = tracks[t];
  23180. 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 } };
  23181. for (const auto& c : placed)
  23182. {
  23183. lynx::Clip clip;
  23184. clip.pattern = c[2];
  23185. clip.length = 4 * lynx::ppq;
  23186. lynx::launcher::setClip (s, c[0], c[1], clip);
  23187. }
  23188. auto& grid = lynx::launcher::ensureGrid (s);
  23189. const char* scenes[] { "Intro", "Verse", "Drop", "Break" };
  23190. grid.scenes.resize (6);
  23191. for (int r = 0; r < 4; ++r)
  23192. grid.scenes[(std::size_t) r].name = scenes[r];
  23193. }, false);
  23194. offline.dispatchPendingMessages();
  23195. write ("pattern-edited"); // the same song as -pattern-after: the workflow must leave no trace
  23196. ui.setClipLaunchWorkflow (true);
  23197. offline.dispatchPendingMessages();
  23198. if (auto* runtime = offline.launcherStateForSnapshot())
  23199. {
  23200. runtime->tracks[0].playing.store (2);
  23201. runtime->tracks[0].progress.store (0.4f);
  23202. runtime->tracks[0].taken.store (true);
  23203. runtime->tracks[1].playing.store (2);
  23204. runtime->tracks[1].progress.store (0.4f);
  23205. runtime->tracks[1].taken.store (true);
  23206. runtime->tracks[2].pending.store (2);
  23207. runtime->tracks[3].taken.store (true);
  23208. }
  23209. write ("both");
  23210. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  23211. write ("grid");
  23212. // round 190bv: recording into slots and the Groove Pool. Two tracks armed (round record buttons in their empty
  23213. // slots, their arm buttons lit), one of them recording and one waiting for its start; then a clip through a
  23214. // groove with the pool shown, and the slot menus
  23215. if (auto* gridView = ui.getClipGridForSnapshot())
  23216. {
  23217. offline.setGridTrackArmed (4, true);
  23218. offline.setGridTrackArmed (5, true, false);
  23219. offline.dispatchPendingMessages();
  23220. write ("rec-armed");
  23221. if (auto* runtime = offline.launcherStateForSnapshot())
  23222. {
  23223. runtime->tracks[4].recording.store (1);
  23224. runtime->tracks[4].recordFrom.store (0.0); // (round 190cy: one beat recorded, the counter reads 0.1.0)
  23225. runtime->clockNow.store ((double) lynx::ppq);
  23226. runtime->tracks[5].recordPending.store (1);
  23227. }
  23228. write ("rec-recording");
  23229. if (auto* runtime = offline.launcherStateForSnapshot())
  23230. {
  23231. runtime->tracks[4].recording.store (-1);
  23232. runtime->tracks[5].recordPending.store (-1);
  23233. }
  23234. offline.editSong ([] (lynx::Song& s) {
  23235. const auto& bank = lynx::groove::factoryBank();
  23236. std::uint32_t first = 0;
  23237. for (const auto index : { std::size_t (9), std::size_t (20), std::size_t (27) })
  23238. if (index < bank.size())
  23239. {
  23240. const auto id = lynx::groove::add (s.grooves, bank[index].groove);
  23241. first = first == 0 ? id : first;
  23242. }
  23243. lynx::groove::setClipGroove (s, 0, 0, first);
  23244. }, false);
  23245. offline.dispatchPendingMessages();
  23246. lynx::setClipGridGroovePoolShown (*gridView, true);
  23247. write ("groove-pool");
  23248. saveMenus ({ "Clip slot", "Groove", "Empty slot" },
  23249. { lynx::clipGridSlotMenu (*gridView, 0, 0), [&] {
  23250. juce::PopupMenu found;
  23251. const auto menu = lynx::clipGridSlotMenu (*gridView, 0, 0);
  23252. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  23253. if (it.getItem().subMenu != nullptr && it.getItem().text == lynx::tr ("Groove"))
  23254. found = *it.getItem().subMenu;
  23255. return found;
  23256. }(), lynx::clipGridSlotMenu (*gridView, 4, 1) },
  23257. prefix + "-rec-menus.png");
  23258. lynx::setClipGridGroovePoolShown (*gridView, false);
  23259. // round 190cy: a second record button pressed while recording: the first take ("Vocals 1") plays on, the
  23260. // clicked slot records "Vocals 2" with its counter at 2.0.2 (as Live 12.4.16, live check 190cw shot 03b)
  23261. {
  23262. const auto name = offline.slotRecordingName (4);
  23263. offline.editSong ([&name] (lynx::Song& s) { lynx::session::placeRecordedPattern (s, 4, 0, {}, 8 * lynx::ppq, name); }, false);
  23264. offline.dispatchPendingMessages();
  23265. if (auto* runtime = offline.launcherStateForSnapshot())
  23266. {
  23267. runtime->tracks[4].playing.store (0);
  23268. runtime->tracks[4].progress.store (0.3f);
  23269. runtime->tracks[4].recording.store (1);
  23270. runtime->tracks[4].recordFrom.store (0.0);
  23271. runtime->clockNow.store (8.0 * lynx::ppq + 2.0 * lynx::ppq / 4.0);
  23272. }
  23273. write ("rec-second");
  23274. if (auto* runtime = offline.launcherStateForSnapshot())
  23275. {
  23276. runtime->tracks[4].playing.store (-1);
  23277. runtime->tracks[4].recording.store (-1);
  23278. }
  23279. offline.editSong ([] (lynx::Song& s) {
  23280. if (lynx::session::cut (s, 4, 0) && ! s.patterns.empty())
  23281. s.patterns.pop_back();
  23282. }, false);
  23283. offline.dispatchPendingMessages();
  23284. }
  23285. offline.setGridTrackArmed (4, false);
  23286. offline.setGridTrackArmed (5, false);
  23287. offline.dispatchPendingMessages();
  23288. }
  23289. ui.setClipGridView (lynx::PlaylistArea::GridView::song);
  23290. write ("song");
  23291. ui.setClipLaunchWorkflow (false);
  23292. write ("pattern-after");
  23293. juce::File (prefix + "-counts.txt").replaceWithText ("runtimes before " + juce::String (madeBefore) + ", after " + juce::String (lynx::launcher::Runtime::instances.load()) + "\n");
  23294. }
  23295. // Round 190bu: the Simple workflow's track dock (ui/SimpleDock.h), off-screen
  23296. void runSimpleFxShot (const juce::String& prefix)
  23297. {
  23298. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  23299. lynx::AudioEngine offline (false);
  23300. lynx::MainComponent ui (offline, false);
  23301. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  23302. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  23303. const auto writeImage = [&prefix] (const juce::Image& image, const juce::String& name) {
  23304. const auto file = juce::File (prefix + "-" + name + ".png");
  23305. file.deleteFile();
  23306. juce::FileOutputStream out (file);
  23307. juce::PNGImageFormat().writeImageToStream (image, out);
  23308. };
  23309. juce::String report;
  23310. const auto line = [&report] (const juce::String& text) { report << text << "\n"; };
  23311. const auto check = [&report] (const juce::String& what, bool ok) { report << (ok ? "OK " : "ERROR ") << what << "\n"; };
  23312. const auto madeBefore = lynx::SimpleWorkflow::instances.load();
  23313. ui.selectTabForSnapshot (2);
  23314. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  23315. offline.dispatchPendingMessages();
  23316. auto* simple = ui.getSimpleWorkflowForSnapshot();
  23317. if (simple == nullptr)
  23318. {
  23319. juce::File (prefix + "-report.txt").replaceWithText ("ERROR no Simple workflow\n");
  23320. return;
  23321. }
  23322. simple->hideChooser();
  23323. // three tracks: a voice, keys with a few chords, a drum kit
  23324. int keysInsert = -1;
  23325. offline.editSong ([&keysInsert] (lynx::Song& s) {
  23326. namespace st = lynx::simpletracks;
  23327. st::Request q;
  23328. q.kind = st::Kind::voice;
  23329. q.name = "Lead vocal";
  23330. st::addTrack (s, q);
  23331. q = {};
  23332. q.kind = st::Kind::instrument;
  23333. q.name = "Keys";
  23334. lynx::ChannelDef keys;
  23335. keys.instrument = lynx::InstrumentKind::synth;
  23336. q.channel = keys;
  23337. lynx::Pattern chords;
  23338. for (int i = 0; i < 4; ++i)
  23339. for (int k : { 60, 64, 67 })
  23340. chords.notes.push_back (lynx::Note { (std::int64_t) i * 4 * lynx::ppq, 4 * lynx::ppq - lynx::ppq / 4, 0, k });
  23341. q.pattern = chords;
  23342. keysInsert = st::addTrack (s, q).insert;
  23343. q = {};
  23344. q.kind = st::Kind::drums;
  23345. for (auto kind : { lynx::InstrumentKind::kick, lynx::InstrumentKind::snare, lynx::InstrumentKind::hat })
  23346. {
  23347. lynx::ChannelDef c;
  23348. c.instrument = kind;
  23349. c.name = kind == lynx::InstrumentKind::kick ? "Kick" : kind == lynx::InstrumentKind::snare ? "Snare" : "Hat";
  23350. q.kit.push_back (c);
  23351. }
  23352. lynx::Pattern beat;
  23353. for (int step = 0; step < 16; step += 2)
  23354. beat.notes.push_back (lynx::Note { (std::int64_t) step * lynx::ticksPerStep, lynx::ticksPerStep, 2, 60 });
  23355. q.pattern = beat;
  23356. st::addTrack (s, q);
  23357. });
  23358. offline.dispatchPendingMessages();
  23359. simple->hideChooser();
  23360. auto& playlist = ui.getPlaylistForSnapshot();
  23361. // the tracks' places in the Playlist
  23362. int voiceTrack = -1, keysTrack = -1, drumsTrack = -1;
  23363. {
  23364. const auto& song = offline.getSong();
  23365. for (int t = 0; t < (int) song.playlistTracks.size(); ++t)
  23366. if (const auto kind = lynx::simpletracks::kindOf (song, t))
  23367. {
  23368. if (*kind == lynx::simpletracks::Kind::audio && voiceTrack < 0)
  23369. voiceTrack = t;
  23370. else if (*kind == lynx::simpletracks::Kind::instrument && keysTrack < 0)
  23371. keysTrack = t;
  23372. else if (*kind == lynx::simpletracks::Kind::drums && drumsTrack < 0)
  23373. drumsTrack = t;
  23374. }
  23375. }
  23376. check ("three Simple tracks (voice, keys, drums)", voiceTrack >= 0 && keysTrack >= 0 && drumsTrack >= 0);
  23377. playlist.selectTrack (keysTrack);
  23378. offline.dispatchPendingMessages();
  23379. auto* dock = simple->dockForSnapshot();
  23380. if (dock == nullptr)
  23381. {
  23382. juce::File (prefix + "-report.txt").replaceWithText (report + "ERROR no dock\n");
  23383. return;
  23384. }
  23385. // the whole window and the dock alone, at 1x and 2x
  23386. const auto shots = [&] (const juce::String& name) {
  23387. offline.dispatchPendingMessages();
  23388. for (float scale : { 1.0f, 2.0f })
  23389. {
  23390. const auto suffix = scale > 1.0f ? juce::String ("@2x") : juce::String();
  23391. writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, scale), name + suffix);
  23392. writeImage (dock->createComponentSnapshot (dock->getLocalBounds(), true, scale), "dock-" + name + suffix);
  23393. }
  23394. };
  23395. const auto menuShot = [&] (const juce::PopupMenu& menu, const juce::String& title, const juce::String& subTitle, const juce::String& name) {
  23396. juce::StringArray names { title };
  23397. std::vector<juce::PopupMenu> menus { menu };
  23398. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  23399. if (it.getItem().subMenu != nullptr && it.getItem().text == subTitle)
  23400. {
  23401. names.add (subTitle);
  23402. menus.push_back (*it.getItem().subMenu);
  23403. }
  23404. saveMenus (names, menus, prefix + "-" + name + ".png");
  23405. };
  23406. // --- the Instrument tab ---------------------------------------------------------------------------------------
  23407. check ("the dock shows the selected track", dock->shownTrack() == keysTrack && dock->isVisible() && dock->getParentComponent() != nullptr);
  23408. check ("an instrument track opens on its sound", dock->hasInstrumentTabForCheck() && dock->getTab() == lynx::SimpleDock::Tab::instrument);
  23409. const auto channel = dock->channelForCheck();
  23410. line ("sound at first: " + dock->soundNameForCheck() + ", rows in its category: " + juce::String (dock->soundRowsForCheck()));
  23411. shots ("instrument");
  23412. // a click on a row of another category: the track plays that sound, its own settings stay
  23413. const auto before = offline.getSong().channels[(std::size_t) channel];
  23414. dock->showCategoryForSnapshot ((int) lynx::soundlib::Category::pad);
  23415. offline.dispatchPendingMessages();
  23416. const auto padRows = dock->soundRowsForCheck();
  23417. dock->clickSoundForCheck (juce::jmin (2, padRows - 1));
  23418. offline.dispatchPendingMessages();
  23419. {
  23420. const auto& now = offline.getSong().channels[(std::size_t) channel];
  23421. const auto found = lynx::soundlib::find (lynx::soundlib::builtIn(), now);
  23422. check ("a click on a sound puts it on the track's channel (" + dock->soundNameForCheck() + ")",
  23423. padRows > 0 && found >= 0 && lynx::soundlib::builtIn()[(std::size_t) found].category == lynx::soundlib::Category::pad
  23424. && ! lynx::soundlib::sameSound (before, now));
  23425. check ("the channel keeps its name, level and insert", now.name == before.name && now.volume == before.volume && now.mixerTrack == before.mixerTrack);
  23426. double seconds = 0.0;
  23427. const auto heard = offline.auditionSound (now, { 60, 64, 67 }, &seconds);
  23428. check ("the sound's audition renders (" + juce::String (seconds, 2) + " s)", heard && seconds > 1.0);
  23429. }
  23430. shots ("instrument-pad");
  23431. const auto picked = dock->soundNameForCheck();
  23432. dock->stepSoundForCheck (1);
  23433. offline.dispatchPendingMessages();
  23434. const auto stepped = dock->soundNameForCheck();
  23435. dock->stepSoundForCheck (-1);
  23436. offline.dispatchPendingMessages();
  23437. check ("the arrows step through the category (" + picked + " -> " + stepped + " -> back)", stepped != picked && dock->soundNameForCheck() == picked);
  23438. check ("one undo step per sound", offline.canUndo());
  23439. // the user's SoundFont files (an index made here: no file is read)
  23440. {
  23441. std::vector<lynx::sf::IndexedFont> fonts (2);
  23442. fonts[0].path = "/home/me/SoundFonts/Concert Band.sf2";
  23443. fonts[0].name = "Concert Band";
  23444. int program = 0;
  23445. for (const char* name : { "Grand Piano", "Bright Piano", "Electric Piano", "Harpsichord", "Clavinet", "Celesta", "Music Box", "Vibraphone" })
  23446. fonts[0].presets.push_back ({ name, 0, program++ });
  23447. 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 } })
  23448. fonts[0].presets.push_back ({ name, 0, p });
  23449. fonts[0].presets.push_back ({ "Standard Kit", 128, 0 });
  23450. fonts[1].path = "/home/me/SoundFonts/Old Upright.sf2";
  23451. fonts[1].name = "Old Upright";
  23452. fonts[1].presets.push_back ({ "Old Upright", 0, 0 });
  23453. fonts[1].presets.push_back ({ "Old Upright Soft", 0, 1 });
  23454. dock->setFontsForSnapshot (fonts);
  23455. dock->showCategoryForSnapshot ((int) lynx::soundlib::Category::keys);
  23456. offline.dispatchPendingMessages();
  23457. check ("My SoundFonts lists the presets of the user's files by category (Keys: " + juce::String (dock->soundRowsForCheck()) + " of 17)", dock->soundRowsForCheck() == 7);
  23458. dock->clickSoundForCheck (0);
  23459. offline.dispatchPendingMessages();
  23460. const auto& now = offline.getSong().channels[(std::size_t) channel];
  23461. check ("a SoundFont preset becomes the track's sound (" + dock->soundNameForCheck() + ")",
  23462. now.instrument == lynx::InstrumentKind::soundfont && juce::String (now.samplePath).endsWith (".sf2"));
  23463. shots ("instrument-soundfonts");
  23464. }
  23465. // --- the Effects tab ------------------------------------------------------------------------------------------
  23466. playlist.selectTrack (voiceTrack);
  23467. offline.dispatchPendingMessages();
  23468. const auto insert = dock->insertForCheck();
  23469. check ("an audio track has no Instrument tab and opens on its effects",
  23470. dock->shownTrack() == voiceTrack && ! dock->hasInstrumentTabForCheck() && dock->getTab() == lynx::SimpleDock::Tab::effects && insert > 0);
  23471. check ("no effects yet: no cards", dock->cardCountForCheck() == 0);
  23472. shots ("effects-empty");
  23473. menuShot (dock->addMenuForSnapshot(), lynx::tr ("Add an effect"), {}, "menu-add");
  23474. // + adds one-knob effects at the end of the chain
  23475. dock->addOneKnobForCheck (lynx::goals::brighter);
  23476. dock->addOneKnobForCheck (lynx::goals::room);
  23477. dock->addOneKnobForCheck (lynx::goals::level);
  23478. offline.dispatchPendingMessages();
  23479. const auto slotsText = [&offline] (int t) {
  23480. juce::String text;
  23481. const auto rows = lynx::mixerops::effectRows (offline.getSong().mixer[(std::size_t) t].effects); // (the Mixer's slot of each)
  23482. std::size_t at = 0;
  23483. for (const auto& fx : offline.getSong().mixer[(std::size_t) t].effects)
  23484. text << "[slot " << rows[at++] + 1 << " " << lynx::effectInfo (fx.kind).name
  23485. << (lynx::goals::active (fx) ? " = " + juce::String (lynx::goals::name (fx.goal)) + " " + juce::String (juce::roundToInt (fx.goalAmount * 100.0f)) + "%" : juce::String())
  23486. << (fx.enabled ? "" : " off") << "] ";
  23487. return text.trimEnd();
  23488. };
  23489. line ("after + x3: " + slotsText (insert));
  23490. check ("three cards, three one-knob effects", dock->cardCountForCheck() == 3 && dock->oneKnobCardsForCheck() == 3);
  23491. // the knob writes the effect's own parameters
  23492. const auto roomBefore = offline.getSong().mixer[(std::size_t) insert].effects[1];
  23493. dock->turnKnobForCheck (1, 0.8f);
  23494. offline.dispatchPendingMessages();
  23495. {
  23496. const auto& room = offline.getSong().mixer[(std::size_t) insert].effects[1];
  23497. 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));
  23498. }
  23499. // ‹ › reorder, × removes
  23500. dock->moveCardForCheck (2, -1);
  23501. offline.dispatchPendingMessages();
  23502. line ("Level moved left: " + slotsText (insert));
  23503. {
  23504. const auto& fx = offline.getSong().mixer[(std::size_t) insert].effects;
  23505. check ("the card moved one place earlier", fx.size() == 3 && fx[1].goal == lynx::goals::level && fx[2].goal == lynx::goals::room);
  23506. }
  23507. dock->removeCardForCheck (0);
  23508. offline.dispatchPendingMessages();
  23509. line ("Brighter removed: " + slotsText (insert));
  23510. check ("the card is gone", dock->cardCountForCheck() == 2 && offline.getSong().mixer[(std::size_t) insert].effects.size() == 2);
  23511. // a hand edit in the full editor: the slot is an ordinary effect again (its card shows Mix)
  23512. offline.editSong ([insert] (lynx::Song& s) {
  23513. auto& slot = s.mixer[(std::size_t) insert].effects[0];
  23514. const auto moved = (std::size_t) lynx::goals::mapping (slot.goal, slot.goalAmount).back().param;
  23515. slot.params[moved] = slot.params[moved] > 0.5f ? 0.2f : 0.9f;
  23516. });
  23517. offline.dispatchPendingMessages();
  23518. check ("a parameter moved by hand makes the card an ordinary effect", dock->cardCountForCheck() == 2 && dock->oneKnobCardsForCheck() == 1);
  23519. dock->turnKnobForCheck (0, 0.5f); // (its knob is the slot's Mix now)
  23520. offline.dispatchPendingMessages();
  23521. 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);
  23522. // a preset replaces the chain; Blend is the chain's dry/wet
  23523. if (const auto* preset = lynx::chains::find ("Clear Voice"))
  23524. offline.editSongStructural ([insert, preset] (lynx::Song& s) { lynx::chains::apply (s, insert, *preset); });
  23525. offline.dispatchPendingMessages();
  23526. line ("preset Clear Voice: " + slotsText (insert));
  23527. 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)
  23528. && dock->cardCountForCheck() == (int) offline.getSong().mixer[(std::size_t) insert].effects.size());
  23529. shots ("effects-preset");
  23530. menuShot (dock->presetMenuForSnapshot(), lynx::tr ("Preset"), lynx::tr ("Voice"), "menu-preset");
  23531. dock->setBlendForCheck (0.7f);
  23532. dock->addOneKnobForCheck (lynx::goals::echo);
  23533. offline.dispatchPendingMessages();
  23534. check ("Blend 70 % is the insert's chain blend; the preset shows as edited",
  23535. std::abs (offline.getSong().mixer[(std::size_t) insert].chainBlend - 0.7f) < 1.0e-6f && ! lynx::chains::unchanged (offline.getSong(), insert));
  23536. shots ("effects-edited");
  23537. // a user preset: saved to a file, loaded on another track (its slots and Blend; that track's level stays)
  23538. const auto mine = offline.getSong().mixer[(std::size_t) insert];
  23539. const auto saved = lynx::SimpleDock::saveUserPreset (offline, insert, "My voice");
  23540. const auto file = lynx::SimpleDock::userPresetFolder().getChildFile ("My voice.lynxtrack");
  23541. check ("the preset is saved as " + file.getFileName(), saved && file.existsAsFile() && offline.getSong().mixer[(std::size_t) insert].chainPreset == "My voice");
  23542. offline.editSong ([keysInsert] (lynx::Song& s) { s.mixer[(std::size_t) keysInsert].volume = 0.42f; });
  23543. const auto loaded = keysInsert > 0 && lynx::SimpleDock::loadUserPreset (offline, keysInsert, file);
  23544. offline.dispatchPendingMessages();
  23545. {
  23546. const auto& other = offline.getSong().mixer[(std::size_t) keysInsert];
  23547. auto same = loaded && other.effects.size() == mine.effects.size() && std::abs (other.chainBlend - mine.chainBlend) < 1.0e-6f && other.chainPreset == "My voice";
  23548. for (std::size_t i = 0; same && i < mine.effects.size(); ++i)
  23549. same = other.effects[i].kind == mine.effects[i].kind && other.effects[i].goal == mine.effects[i].goal
  23550. && 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]);
  23551. check ("loaded on the Keys track: the same slots and Blend", same);
  23552. check ("the Keys track keeps its level", std::abs (other.volume - 0.42f) < 1.0e-6f);
  23553. line ("Keys after load: " + slotsText (keysInsert));
  23554. }
  23555. menuShot (dock->presetMenuForSnapshot(), lynx::tr ("Preset"), lynx::tr ("My presets"), "menu-preset-mine");
  23556. file.deleteFile();
  23557. // the drums: effects only (a kit has no single sound to pick)
  23558. playlist.selectTrack (drumsTrack);
  23559. offline.dispatchPendingMessages();
  23560. check ("the Drums track shows its insert's effects, no Instrument tab", dock->shownTrack() == drumsTrack && ! dock->hasInstrumentTabForCheck() && dock->insertForCheck() > 0);
  23561. if (const auto* preset = lynx::chains::find ("Smash Room"))
  23562. offline.editSongStructural ([t = dock->insertForCheck(), preset] (lynx::Song& s) { lynx::chains::apply (s, t, *preset); });
  23563. shots ("effects-drums");
  23564. // the project file keeps all of it
  23565. {
  23566. juce::String error;
  23567. const auto json = lynx::ProjectFile::toJson (offline.getSong());
  23568. const auto back = lynx::ProjectFile::fromJson (json, error);
  23569. auto same = back && back->mixer.size() == offline.getSong().mixer.size();
  23570. for (std::size_t t = 0; same && t < back->mixer.size(); ++t)
  23571. {
  23572. const auto& a = offline.getSong().mixer[t];
  23573. const auto& b = back->mixer[t];
  23574. same = a.effects.size() == b.effects.size() && std::abs (a.chainBlend - b.chainBlend) < 1.0e-6f && a.chainPreset == b.chainPreset;
  23575. for (std::size_t i = 0; same && i < a.effects.size(); ++i)
  23576. 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
  23577. && std::abs (a.effects[i].goalAmount - b.effects[i].goalAmount) < 1.0e-6f;
  23578. }
  23579. check ("saved and loaded as a project: the same chains, knobs, Blend and preset names", same);
  23580. }
  23581. // --- the same plugins in the same slots in FL's layout --------------------------------------------------------
  23582. const auto simpleSong = offline.getSong();
  23583. const auto inSimple = slotsText (insert);
  23584. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
  23585. offline.dispatchPendingMessages();
  23586. check ("Pattern workflow: the dock is gone", dock->getParentComponent() == nullptr);
  23587. ui.selectTabForSnapshot (3);
  23588. ui.getMixerForSnapshot().selectTrack (insert);
  23589. offline.dispatchPendingMessages();
  23590. for (float scale : { 1.0f, 2.0f })
  23591. writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, scale), juce::String ("pattern-mixer") + (scale > 1.0f ? "@2x" : ""));
  23592. line ("Simple layout: " + inSimple);
  23593. line ("Pattern layout: " + slotsText (insert));
  23594. check ("the same effects in the same Mixer slots in the Pattern workflow", offline.getSong().mixer == simpleSong.mixer && offline.getSong().channels == simpleSong.channels);
  23595. // an effect added in the Mixer's way shows as a card when the Simple workflow comes back
  23596. offline.editSongStructural ([insert] (lynx::Song& s) { lynx::mixerops::insertEffectAtRow (s, insert, lynx::makeEffectSlot (lynx::EffectKind::chorus), 7); });
  23597. ui.selectTabForSnapshot (2);
  23598. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  23599. offline.dispatchPendingMessages();
  23600. simple->hideChooser();
  23601. playlist.selectTrack (voiceTrack);
  23602. offline.dispatchPendingMessages();
  23603. check ("back in Simple: the dock shows the insert as it is now, the Mixer's new effect too",
  23604. dock->getParentComponent() != nullptr && dock->cardCountForCheck() == (int) offline.getSong().mixer[(std::size_t) insert].effects.size()
  23605. && lynx::mixerops::effectRows (offline.getSong().mixer[(std::size_t) insert].effects).back() == 7);
  23606. line ("Simple again: " + slotsText (insert));
  23607. shots ("effects-back");
  23608. // hidden with its key, shown again by "+FX"
  23609. simple->toggleDock();
  23610. offline.dispatchPendingMessages();
  23611. check ("Ctrl+Alt+L hides the dock", ! simple->isDockShowing() && ! lynx::SimpleDock::shownSetting);
  23612. writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, 1.0f), "dock-hidden");
  23613. simple->showEffectsOfInsert (keysInsert);
  23614. offline.dispatchPendingMessages();
  23615. check ("+FX on a track header shows the dock on that track's effects",
  23616. simple->isDockShowing() && dock->shownTrack() == keysTrack && dock->getTab() == lynx::SimpleDock::Tab::effects && dock->insertForCheck() == keysInsert);
  23617. simple->cycleDockTab();
  23618. check ("Shift+Tab goes to the Instrument tab", dock->getTab() == lynx::SimpleDock::Tab::instrument);
  23619. line ("Simple workflow objects: " + juce::String (madeBefore) + " before, " + juce::String (lynx::SimpleWorkflow::instances.load()) + " after");
  23620. line (report.contains ("ERROR ") ? "RESULT ERROR" : "RESULT OK");
  23621. juce::File (prefix + "-report.txt").replaceWithText (report);
  23622. }
  23623. // --simpleclosetest (round 190fc, 0.1.27 RC blocker B1): every close in the Simple layout crashed (the Simple workflow
  23624. // was destroyed after the Workspace and its destructor called into it). Off-screen, no window: the main window in the
  23625. // Simple layout with everything of it open — Welcome, the first-song tour's card, Start from, a demo song, each dock
  23626. // tab (the Editor tab docks the Piano roll), Finish, Lyrics, the chooser — then destroyed as the app's shutdown does.
  23627. // A second main window goes Simple -> Pattern -> Simple and closes too. Checks: no Simple workflow outlives its main
  23628. // window's destructor body, none is left at all. (Under ASan on Linux the old order is a heap-use-after-free.)
  23629. bool runDonateShot (const juce::String& prefix)
  23630. {
  23631. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  23632. juce::String report;
  23633. bool ok = true;
  23634. const auto line = [&report, &prefix] (const juce::String& text) {
  23635. report << text << "\n";
  23636. juce::File (prefix + "-report.txt").replaceWithText (report); // (written as it goes)
  23637. };
  23638. const auto check = [&line, &ok] (const juce::String& what, bool good) {
  23639. line ((good ? "ok " : "FAIL ") + what);
  23640. ok = ok && good;
  23641. };
  23642. const auto writeImage = [&prefix] (const juce::Image& image, const juce::String& name) {
  23643. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  23644. file.deleteFile();
  23645. juce::FileOutputStream out (file);
  23646. juce::PNGImageFormat().writeImageToStream (image, out);
  23647. };
  23648. // a window as the --snapshot route saves one (off the desktop, on the theme's panel colour), at 1x and 2x
  23649. const auto saveAlert = [&] (juce::AlertWindow& w, const juce::String& name) {
  23650. if (w.isOnDesktop())
  23651. w.removeFromDesktop();
  23652. w.setOpaque (true);
  23653. juce::Component frame;
  23654. frame.setSize (w.getWidth(), w.getHeight());
  23655. frame.setOpaque (true);
  23656. frame.addAndMakeVisible (w);
  23657. w.setTopLeftPosition (0, 0);
  23658. writeImage (lynx::shot::paint (frame, lynx::theme::panel), name);
  23659. writeImage (frame.createComponentSnapshot (frame.getLocalBounds(), true, 2.0f), name + "@2x");
  23660. frame.removeChildComponent (&w);
  23661. };
  23662. const auto buttonTexts = [] (juce::AlertWindow& w) {
  23663. if (auto* d = dynamic_cast<lynx::ui::dialog::Dialog*> (&w)) // (round 190jp: LYNX's dialog, its own buttons)
  23664. return d->dialogButtonTexts();
  23665. juce::StringArray texts;
  23666. for (int b = 0; b < w.getNumButtons(); ++b)
  23667. if (auto* button = w.getButton (b))
  23668. texts.add (button->getButtonText());
  23669. return texts;
  23670. };
  23671. check ("the donation page is one constant, on Ko-fi", juce::String (lynx::links::donate).startsWith ("https://ko-fi"));
  23672. line ("donate URL: " + juce::String (lynx::links::donate));
  23673. const auto stateFile = lynx::PluginHost::settingsFolder().getChildFile ("support-note.txt");
  23674. const auto hadState = stateFile.existsAsFile();
  23675. const auto oldState = stateFile.loadFileAsString();
  23676. line ("state file: " + stateFile.getFullPathName() + (hadState ? " (exists; put back at the end)" : ""));
  23677. {
  23678. lynx::AudioEngine offline (false);
  23679. lynx::MainComponent ui (offline, false);
  23680. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  23681. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  23682. ui.setVisible (true);
  23683. const auto settle = [&] {
  23684. for (int k = 0; k < 3; ++k)
  23685. offline.dispatchPendingMessages();
  23686. };
  23687. // --- Help › Support LYNX SHARE..., right above About, in the three layouts ----------------------------------
  23688. for (auto [style, name] : { std::pair { lynx::layoutstyle::Style::pattern, "pattern" }, { lynx::layoutstyle::Style::clipLaunch, "cliplaunch" },
  23689. { lynx::layoutstyle::Style::simple, "simple" } })
  23690. {
  23691. ui.setLayoutStyle (style);
  23692. settle();
  23693. const auto help = ui.getMenuForSnapshot (ui.getMenuNamesForSnapshot().indexOf (lynx::tr ("Help")));
  23694. juce::StringArray items;
  23695. for (juce::PopupMenu::MenuItemIterator it (help); it.next();)
  23696. if (! it.getItem().isSeparator)
  23697. items.add (it.getItem().text);
  23698. const auto support = items.indexOf (lynx::tr ("Support LYNX SHARE..."));
  23699. const auto about = items.indexOf (lynx::tr ("About LYNX SHARE"));
  23700. check (juce::String ("Help has Support LYNX SHARE... right above About LYNX SHARE (") + name + " layout)",
  23701. support >= 0 && about == support + 1);
  23702. saveMenus ({ lynx::tr ("Help") }, { help }, prefix + "-menu-help-" + name + ".png");
  23703. }
  23704. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
  23705. settle();
  23706. // --- the Support window -------------------------------------------------------------------------------------
  23707. {
  23708. auto w = lynx::support::makeSupportWindow();
  23709. const auto texts = buttonTexts (*w);
  23710. check ("Support window: Donate on Ko-fi, Close", texts == juce::StringArray { lynx::tr ("Donate on Ko-fi"), lynx::tr ("Close") });
  23711. check ("Support window: Donate on Ko-fi points at the constant",
  23712. dynamic_cast<lynx::ui::dialog::Dialog*> (w.get()) != nullptr
  23713. && static_cast<lynx::ui::dialog::Dialog*> (w.get())->dialogButton (0)->getTooltip() == juce::String (lynx::links::donate));
  23714. check ("Support window title", w->getName() == lynx::tr ("Support LYNX SHARE"));
  23715. saveAlert (*w, "support");
  23716. }
  23717. // --- the About window ---------------------------------------------------------------------------------------
  23718. {
  23719. auto w = lynx::MainComponent::makeAboutWindow();
  23720. const auto texts = buttonTexts (*w);
  23721. check ("About window: Support LYNX SHARE (result 2) and OK", texts == juce::StringArray { lynx::tr ("Support LYNX SHARE"), lynx::tr ("OK") });
  23722. saveAlert (*w, "about");
  23723. }
  23724. // --- Settings › General › Show the support note -------------------------------------------------------------
  23725. {
  23726. auto page = lynx::makeGeneralPage (offline, {}, false);
  23727. bool found = false;
  23728. std::function<void (juce::Component&)> walk = [&] (juce::Component& c) {
  23729. if (auto* t = dynamic_cast<juce::ToggleButton*> (&c); t != nullptr && t->getButtonText() == lynx::tr ("Show the support note"))
  23730. found = t->getToggleState();
  23731. for (auto* child : c.getChildren())
  23732. walk (*child);
  23733. };
  23734. walk (*page);
  23735. check ("Settings > General: \"Show the support note\", ticked by default", found);
  23736. }
  23737. // --- the start-up note's rules, end to end on the saved state ----------------------------------------------
  23738. lynx::supportnote::Moment moment; // (the main window here is off-screen: the moment is set by hand)
  23739. lynx::support::StartupNote note (ui, [&moment] { return moment; }, [] { return 0; });
  23740. const auto state = [] { return lynx::support::loadState(); };
  23741. const auto setState = [] (int launches, int next, bool show) { lynx::support::saveState ({ launches, next, show }); };
  23742. stateFile.deleteFile();
  23743. for (int k = 0; k < 15; ++k)
  23744. note.begin (true);
  23745. note.pollForSnapshot();
  23746. check ("test mode / CI runs: 15 starts, nothing counted, no file, no card", ! stateFile.existsAsFile() && ! note.isCardShowing());
  23747. check ("a first start's defaults: next at start 10, shown", state() == lynx::supportnote::State { 0, 10, true });
  23748. for (int k = 1; k <= 9; ++k)
  23749. {
  23750. note.begin (false);
  23751. note.pollForSnapshot();
  23752. }
  23753. check ("starts 1 to 9: counted, no card", state().launches == 9 && ! note.isCardShowing());
  23754. moment.playing = true;
  23755. note.begin (false); // the 10th start
  23756. note.pollForSnapshot();
  23757. check ("10th start while playing: the card waits", state().launches == 10 && ! note.isCardShowing());
  23758. moment = {};
  23759. moment.dialogOpen = true;
  23760. note.pollForSnapshot();
  23761. check ("... and while a dialog is open", ! note.isCardShowing());
  23762. moment = {};
  23763. note.pollForSnapshot();
  23764. check ("10th start, a quiet moment: the card shows", note.isCardShowing());
  23765. check ("shown: left without an answer it comes back 30 starts later", state().nextAt == 40);
  23766. if (auto* card = note.cardForSnapshot())
  23767. {
  23768. const auto b = card->getBounds();
  23769. check ("the card sits in the bottom-right corner", b.getRight() <= ui.getWidth() - 8 && b.getRight() >= ui.getWidth() - 40
  23770. && b.getBottom() <= ui.getHeight() - 4 && b.getBottom() >= ui.getHeight() - 40);
  23771. writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, 1.0f), "note-in-window");
  23772. writeImage (card->createComponentSnapshot (card->getLocalBounds(), true, 2.0f), "note@2x");
  23773. // the corner of the window around the card, at 2x
  23774. writeImage (ui.createComponentSnapshot (b.expanded (220, 120).getIntersection (ui.getLocalBounds()), true, 2.0f), "note-corner@2x");
  23775. }
  23776. moment.playing = true;
  23777. note.pollForSnapshot();
  23778. check ("playback starts: the card steps aside", ! note.isCardShowing());
  23779. moment = {};
  23780. // Not now: again after 30 more starts
  23781. setState (10, 10, true);
  23782. note.begin (false); // start 11
  23783. note.pollForSnapshot();
  23784. if (auto* card = note.cardForSnapshot(); card != nullptr && card->buttonForSnapshot (lynx::supportnote::Choice::notNow) != nullptr)
  23785. card->buttonForSnapshot (lynx::supportnote::Choice::notNow)->onClick();
  23786. note.closeCard(); // (the click closes it on the next message turn)
  23787. check ("Not now: next at start 41", state() == lynx::supportnote::State { 11, 41, true });
  23788. for (int k = 12; k <= 40; ++k)
  23789. {
  23790. note.begin (false);
  23791. note.pollForSnapshot();
  23792. if (note.isCardShowing())
  23793. break;
  23794. }
  23795. check ("Not now: starts 12 to 40 without the card", ! note.isCardShowing() && state().launches == 40);
  23796. note.begin (false);
  23797. note.pollForSnapshot();
  23798. check ("Not now: the card again at start 41", note.isCardShowing());
  23799. // Don't show again: never, and Settings shows the box unticked
  23800. if (auto* card = note.cardForSnapshot())
  23801. card->buttonForSnapshot (lynx::supportnote::Choice::never)->onClick();
  23802. note.closeCard();
  23803. check ("Don't show again: off", ! state().show && ! lynx::support::noteEnabled());
  23804. for (int k = 0; k < 200; ++k)
  23805. {
  23806. note.begin (false);
  23807. note.pollForSnapshot();
  23808. }
  23809. check ("Don't show again: 200 more starts, never", ! note.isCardShowing());
  23810. // Support: opens the Support window (on the next message turn) and the note doesn't come back
  23811. setState (20, 10, true);
  23812. note.begin (false);
  23813. note.pollForSnapshot();
  23814. if (auto* card = note.cardForSnapshot())
  23815. card->buttonForSnapshot (lynx::supportnote::Choice::support)->onClick();
  23816. note.closeCard();
  23817. check ("Support: the note has done its job", ! state().show);
  23818. // Settings off: never; on again: counts from now
  23819. setState (5, 10, true);
  23820. lynx::support::setNoteEnabled (false);
  23821. for (int k = 0; k < 100; ++k)
  23822. {
  23823. note.begin (false);
  23824. note.pollForSnapshot();
  23825. }
  23826. check ("Settings off: 100 starts, never", ! note.isCardShowing() && state().launches == 105);
  23827. lynx::support::setNoteEnabled (true);
  23828. check ("Settings on again: next 30 starts later", state() == lynx::supportnote::State { 105, 135, true });
  23829. note.closeCard();
  23830. }
  23831. stateFile.deleteFile();
  23832. if (hadState)
  23833. stateFile.replaceWithText (oldState);
  23834. line (ok ? "result=OK" : "result=FAILED");
  23835. return ok;
  23836. }
  23837. bool runSimpleCloseTest (const juce::String& reportPath)
  23838. {
  23839. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  23840. juce::String report;
  23841. bool ok = true;
  23842. const auto line = [&report, &reportPath] (const juce::String& text) {
  23843. report << text << "\n";
  23844. juce::File (reportPath).replaceWithText (report); // (written as it goes: a crash still leaves the last step)
  23845. };
  23846. const auto check = [&line, &ok] (const juce::String& what, bool good) {
  23847. line ((good ? "ok " : "FAIL ") + what);
  23848. ok = ok && good;
  23849. };
  23850. const auto aliveBefore = lynx::SimpleWorkflow::alive.load();
  23851. {
  23852. lynx::AudioEngine offline (false);
  23853. {
  23854. lynx::MainComponent ui (offline, false);
  23855. ui.setSize (1600, 900);
  23856. ui.setVisible (true); // (no window: the docked editor and the tour only need their parents visible)
  23857. const auto settle = [&] {
  23858. for (int k = 0; k < 3; ++k)
  23859. offline.dispatchPendingMessages();
  23860. };
  23861. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  23862. settle();
  23863. auto* simple = ui.getSimpleWorkflowForSnapshot();
  23864. check ("the Simple workflow is up", simple != nullptr);
  23865. if (simple != nullptr)
  23866. {
  23867. const auto empty = lynx::builtInTemplateIndex ("Empty");
  23868. offline.setSong (empty >= 0 ? lynx::makeNewProject (empty) : lynx::makeNewProject());
  23869. settle();
  23870. simple->showWelcome();
  23871. settle();
  23872. auto* tour = simple->tourForSnapshot();
  23873. check ("Welcome screen shown", tour != nullptr && tour->isWelcomeShowing());
  23874. simple->startOrContinueTour();
  23875. settle();
  23876. simple->doTourStep (lynx::tour::beat);
  23877. settle();
  23878. check ("the tour runs with its card up", simple->tourRunning() && tour != nullptr && tour->cardForSnapshot() != nullptr);
  23879. // a demo song from Start from (the panel stays up over the Playlist)
  23880. if (auto* start = simple->startFromForSnapshot(); start != nullptr && lynx::demos::count > 1)
  23881. {
  23882. offline.setSong (lynx::demos::make (1));
  23883. settle();
  23884. check ("a demo song opened, Start from up", simple->isStartFromShowing() && ! offline.getSong().playlist.empty());
  23885. }
  23886. // the dock on a track, every tab (the Editor tab docks the Piano roll)
  23887. if (auto* dock = simple->dockForSnapshot())
  23888. {
  23889. simple->trackSelected ([] (const lynx::Song& song) { // the first Instrument track (the dock's Keyboard and Editor tabs are for it)
  23890. for (int t = 0; t < (int) song.playlistTracks.size(); ++t)
  23891. if (lynx::simpletracks::kindOf (song, t) == lynx::simpletracks::Kind::instrument)
  23892. return t;
  23893. return 0;
  23894. } (offline.getSong()));
  23895. for (auto tab : { lynx::SimpleDock::Tab::instrument, lynx::SimpleDock::Tab::keyboard, lynx::SimpleDock::Tab::editor,
  23896. lynx::SimpleDock::Tab::effects, lynx::SimpleDock::Tab::editor })
  23897. {
  23898. dock->setTab (tab);
  23899. settle();
  23900. }
  23901. check ("the dock shows", simple->isDockShowing());
  23902. line ("dock tab at the close: " + juce::String ((int) dock->getTab()) + " (2 = Editor, the docked Piano roll)");
  23903. }
  23904. ui.toggleLyrics(); // (Lyrics, then Finish: they share the dock on the right)
  23905. settle();
  23906. simple->showFinish();
  23907. settle();
  23908. check ("Finish open", simple->isFinishShowing());
  23909. simple->showChooser();
  23910. settle();
  23911. line ("Simple workflow objects alive before the close: " + juce::String (lynx::SimpleWorkflow::alive.load() - aliveBefore));
  23912. }
  23913. } // (the main window goes as at shutdown)
  23914. check ("no Simple workflow outlived its main window's destructor body (it reaches the Workspace)",
  23915. lynx::MainComponent::simpleWorkflowAliveAfterTeardown == aliveBefore);
  23916. check ("none left after the close", lynx::SimpleWorkflow::alive.load() == aliveBefore);
  23917. // Simple, then Pattern, then Simple again, and closed
  23918. {
  23919. lynx::MainComponent ui (offline, false);
  23920. ui.setSize (1600, 900);
  23921. ui.setVisible (true);
  23922. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  23923. offline.dispatchPendingMessages();
  23924. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
  23925. offline.dispatchPendingMessages();
  23926. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  23927. offline.dispatchPendingMessages();
  23928. if (auto* simple = ui.getSimpleWorkflowForSnapshot())
  23929. simple->showWelcome();
  23930. offline.dispatchPendingMessages();
  23931. }
  23932. check ("Simple -> Pattern -> Simple, closed: none outlived the destructor body", lynx::MainComponent::simpleWorkflowAliveAfterTeardown == aliveBefore
  23933. && lynx::SimpleWorkflow::alive.load() == aliveBefore);
  23934. }
  23935. line (ok ? "result=OK" : "result=FAILED");
  23936. return ok;
  23937. }
  23938. void runTour190dvShot (const juce::String& prefix)
  23939. {
  23940. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  23941. lynx::AudioEngine offline (false);
  23942. lynx::MainComponent ui (offline, false);
  23943. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  23944. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  23945. ui.setVisible (true); // (no window: the docked editor and the ring's targets only need their parents visible)
  23946. const auto writeImage = [&prefix] (const juce::Image& image, const juce::String& name) {
  23947. const auto file = juce::File (prefix + "-" + name + ".png");
  23948. file.deleteFile();
  23949. juce::FileOutputStream out (file);
  23950. juce::PNGImageFormat().writeImageToStream (image, out);
  23951. };
  23952. juce::String report;
  23953. // (written as it goes: a run that stops halfway still leaves its checks)
  23954. const auto line = [&report, &prefix] (const juce::String& text) {
  23955. report << text << "\n";
  23956. juce::File (prefix + "-report.txt").replaceWithText (report);
  23957. };
  23958. const auto check = [&line] (const juce::String& what, bool ok) { line ((ok ? "OK " : "ERROR ") + what); };
  23959. ui.selectTabForSnapshot (2);
  23960. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  23961. offline.dispatchPendingMessages();
  23962. auto* simple = ui.getSimpleWorkflowForSnapshot();
  23963. auto* tour = simple != nullptr ? simple->tourForSnapshot() : nullptr;
  23964. if (tour == nullptr)
  23965. {
  23966. juce::File (prefix + "-report.txt").replaceWithText ("ERROR no Simple workflow / tour\n");
  23967. return;
  23968. }
  23969. check ("no Welcome screen by itself in a --snapshot route (not a real first start)", ! tour->isWelcomeShowing());
  23970. const auto settle = [&] {
  23971. for (int k = 0; k < 3; ++k)
  23972. offline.dispatchPendingMessages();
  23973. };
  23974. const auto window = [&] (const juce::String& name, bool twoX = false) {
  23975. settle();
  23976. tour->ringForSnapshot(); // (the ring follows the layout: resolved now, as its timer would)
  23977. writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, 1.0f), name);
  23978. if (twoX)
  23979. if (auto* card = tour->cardForSnapshot(); card != nullptr && card->getParentComponent() != nullptr)
  23980. writeImage (card->createComponentSnapshot (card->getLocalBounds(), true, 2.0f), name + "-card@2x");
  23981. };
  23982. const auto stepIs = [&] (int step, const juce::String& target) {
  23983. settle();
  23984. const auto ring = tour->ringForSnapshot();
  23985. const auto id = tour->targetIdForSnapshot();
  23986. line ("step " + juce::String (tour->step() + 1) + " (" + lynx::tour::stepId (tour->step()) + "): ring on " + (id.isEmpty() ? juce::String ("-") : id) + " "
  23987. + ring.toString());
  23988. check (juce::String ("the card shows step ") + lynx::tour::stepId (step), tour->isRunning() && tour->step() == step);
  23989. if (target.isNotEmpty())
  23990. check ("the ring is on " + target, id == target && ! ring.isEmpty());
  23991. };
  23992. // --- the Welcome screen (on a new, empty project: the built-in "Empty" template, as File › New can give) -------------
  23993. const auto emptyProject = [] {
  23994. const auto index = lynx::builtInTemplateIndex ("Empty");
  23995. return index >= 0 ? lynx::makeNewProject (index) : lynx::makeNewProject();
  23996. };
  23997. offline.setSong (emptyProject());
  23998. settle();
  23999. check ("the new project is empty for the Simple workflow (it opens on the chooser)", lynx::simpletracks::isEmptySong (offline.getSong()));
  24000. simple->showWelcome();
  24001. settle();
  24002. check ("Help › Welcome screen shows it", tour->isWelcomeShowing());
  24003. window ("welcome");
  24004. if (auto* w = tour->welcomeForSnapshot())
  24005. writeImage (w->createComponentSnapshot (w->getLocalBounds(), true, 2.0f), "welcome@2x");
  24006. tour->clickForSnapshot ("welcome.tour");
  24007. settle();
  24008. check ("Make my first song: the Welcome screen closes, the tour starts, the chooser comes up for the beat",
  24009. ! tour->isWelcomeShowing() && tour->isRunning() && simple->isChooserShowing());
  24010. // --- step 1: the beat ---------------------------------------------------------------------------------------------
  24011. stepIs (lynx::tour::beat, "simple.tile.drums");
  24012. window ("step1-beat", true);
  24013. simple->showStarterPageForSnapshot();
  24014. stepIs (lynx::tour::beat, "simple.starters");
  24015. window ("step1-beat-starters");
  24016. tour->clickForSnapshot ("do");
  24017. settle();
  24018. check ("Do it for me added a starter beat", lynx::tour::hasBeat (offline.getSong()));
  24019. // --- step 2: the key ----------------------------------------------------------------------------------------------
  24020. stepIs (lynx::tour::key, "toolbar.key");
  24021. window ("step2-key", true);
  24022. tour->clickForSnapshot ("do");
  24023. settle();
  24024. check ("Do it for me set A minor", lynx::projectkey::get (offline.getSong()).has_value());
  24025. // --- step 3: an instrument (Add track opens the chooser: the ring moves to its tile) ------------------------------
  24026. stepIs (lynx::tour::instrument, "simple.addTrack");
  24027. window ("step3-instrument", true);
  24028. simple->showChooser();
  24029. stepIs (lynx::tour::instrument, "simple.tile.instrument");
  24030. window ("step3-instrument-chooser");
  24031. tour->clickForSnapshot ("do");
  24032. settle();
  24033. check ("Do it for me added an Instrument track (the chooser closed)", lynx::tour::firstInstrumentTrack (offline.getSong()) >= 0 && ! simple->isChooserShowing());
  24034. // --- step 4: chords -----------------------------------------------------------------------------------------------
  24035. stepIs (lynx::tour::chords, "keyboard.chordPad");
  24036. window ("step4-chords", true);
  24037. tour->clickForSnapshot ("do");
  24038. settle();
  24039. check ("Do it for me wrote four chords (12 notes) on the instrument's pattern", [&] {
  24040. const auto& song = offline.getSong();
  24041. const auto p = lynx::simpletracks::patternOf (song, lynx::tour::firstInstrumentTrack (song));
  24042. return p >= 0 && song.patterns[(std::size_t) p].notes.size() == 12;
  24043. }());
  24044. // --- step 5: a voice or a loop (no "Do it for me": a loop is dropped as a user would) ------------------------------
  24045. stepIs (lynx::tour::loop, "simple.dropLane"); // (round 190jc, SG-18: it rang "+ Add track")
  24046. window ("step5-loop", true);
  24047. {
  24048. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-190dv-loops");
  24049. dir.deleteRecursively();
  24050. dir.createDirectory();
  24051. const auto wav = dir.getChildFile ("Warm Keys 120 Am.wav");
  24052. const int frames = 192000;
  24053. juce::AudioBuffer<float> audio (1, frames);
  24054. for (int i = 0; i < frames; ++i)
  24055. {
  24056. const auto t = (double) i / 48000.0;
  24057. double v = 0.0;
  24058. for (const auto key : { 57, 60, 64 })
  24059. v += std::sin (2.0 * juce::MathConstants<double>::pi * 440.0 * std::pow (2.0, (key - 69) / 12.0) * t);
  24060. audio.setSample (0, i, (float) (0.1 * v * (1.0 - std::exp (-std::fmod (t, 0.5) * 60.0))));
  24061. }
  24062. {
  24063. juce::WavAudioFormat format;
  24064. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  24065. if (auto* w = format.createWriterFor (out.get(), 48000.0, 1, 16, {}, 0))
  24066. {
  24067. out.release();
  24068. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  24069. writer->writeFromAudioSampleBuffer (audio, 0, frames);
  24070. }
  24071. }
  24072. simple->dropFiles ({ wav.getFullPathName() }, 0);
  24073. settle();
  24074. check ("a dropped loop (A minor in its name) follows the key", [&] {
  24075. for (const auto& c : offline.getSong().playlist)
  24076. if (c.kind == lynx::ClipKind::audio)
  24077. return c.followKey;
  24078. return false;
  24079. }());
  24080. }
  24081. // --- step 6: a one-knob effect --------------------------------------------------------------------------------------
  24082. stepIs (lynx::tour::effect, "simple.dock.addEffect");
  24083. window ("step6-effect", true);
  24084. tour->clickForSnapshot ("do");
  24085. settle();
  24086. check ("Do it for me put Room on the instrument track", lynx::tour::hasOneKnob (offline.getSong()));
  24087. // --- step 7: Finish -----------------------------------------------------------------------------------------------
  24088. stepIs (lynx::tour::finish, "simple.finish");
  24089. window ("step7-finish", true);
  24090. tour->clickForSnapshot ("do");
  24091. settle();
  24092. check ("Do it for me opened Finish and chose Balanced", simple->isFinishShowing() && lynx::looks::present (offline.getSong()));
  24093. // --- the end card, Back / Next, close -------------------------------------------------------------------------------
  24094. settle();
  24095. check ("the end card", tour->isRunning() && tour->step() == lynx::tour::stepCount);
  24096. window ("end", true);
  24097. tour->clickForSnapshot ("back");
  24098. settle();
  24099. check ("Back: the Finish step again, shown done (the tour waits for Next)", tour->step() == lynx::tour::finish
  24100. && tour->machineForCheck().shownDone (offline.getSong()));
  24101. window ("back-done", true);
  24102. tour->clickForSnapshot ("next");
  24103. settle();
  24104. check ("Next: the end card again", tour->step() == lynx::tour::stepCount);
  24105. check ("all seven steps done by the song", tour->machineForCheck().state().completed == 0x7fu);
  24106. tour->clickForSnapshot ("close");
  24107. settle();
  24108. check ("closing the end card ends the tour (not continued from Help)", ! tour->isRunning() && ! tour->canContinue()
  24109. && tour->machineForCheck().state().done);
  24110. line ("-- paused tour");
  24111. // --- a paused tour, the Help menu and the chooser's button ---------------------------------------------------------
  24112. offline.setSong (emptyProject());
  24113. settle();
  24114. tour->machineForCheck() = lynx::tour::Machine {};
  24115. simple->startOrContinueTour();
  24116. settle();
  24117. line ("-- do beat");
  24118. simple->doTourStep (lynx::tour::beat);
  24119. settle();
  24120. check ("a new tour on an empty project: the beat done moves it to the key", tour->step() == lynx::tour::key);
  24121. tour->clickForSnapshot ("close");
  24122. settle();
  24123. check ("closing the card pauses the tour (Help continues it)", ! tour->isRunning() && tour->canContinue());
  24124. line ("-- help menu");
  24125. {
  24126. const auto help = ui.getMenuForSnapshot (ui.getMenuNamesForSnapshot().indexOf (lynx::tr ("Help")));
  24127. bool continueItem = false, welcomeItem = false;
  24128. for (juce::PopupMenu::MenuItemIterator it (help); it.next();)
  24129. {
  24130. continueItem = continueItem || it.getItem().text.startsWith (lynx::tr ("Continue the first-song tour (step {0} of {1})", { "2", "7" }));
  24131. welcomeItem = welcomeItem || it.getItem().text == lynx::tr ("Welcome screen...");
  24132. }
  24133. check ("Help: Continue the first-song tour (step 2 of 7) and Welcome screen...", continueItem && welcomeItem);
  24134. saveMenus ({ lynx::tr ("Help") }, { help }, prefix + "-menu-help.png");
  24135. }
  24136. simple->startOrContinueTour();
  24137. settle();
  24138. check ("Help › Continue: back on the key step", tour->isRunning() && tour->step() == lynx::tour::key);
  24139. tour->clickForSnapshot ("skip");
  24140. settle();
  24141. check ("Skip tour ends it", ! tour->isRunning() && ! tour->canContinue());
  24142. offline.setSong (emptyProject());
  24143. settle();
  24144. simple->showChooser();
  24145. window ("chooser");
  24146. line ("-- start from");
  24147. // --- Start from: the three demo songs; a demo opened in Simple -------------------------------------------------------
  24148. if (auto* start = simple->startFromForSnapshot())
  24149. {
  24150. settle();
  24151. writeImage (start->createComponentSnapshot (start->getLocalBounds(), true, 1.0f), "startfrom");
  24152. const auto list = lynx::startfrom::entries();
  24153. int demos = 0;
  24154. for (const auto& e : list)
  24155. demos += e.kind == lynx::startfrom::Entry::Kind::demo && e.playable ? 1 : 0;
  24156. check ("Start from lists three playable demo songs first", demos == 3 && list.size() >= 3 && list[1].demo == 1 && list[2].demo == 2);
  24157. for (int d = 1; d < 3 && d < (int) list.size(); ++d)
  24158. 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");
  24159. simple->hideStartFrom();
  24160. }
  24161. line ("-- demos");
  24162. for (int d = 1; d < lynx::demos::count; ++d)
  24163. {
  24164. offline.setSong (lynx::demos::make (d));
  24165. settle();
  24166. simple->hideChooser();
  24167. window (juce::String ("demo-") + (d == 1 ? "hiphop" : "pop"));
  24168. // the committed file is the generated song
  24169. const auto file = juce::File::getCurrentWorkingDirectory().getChildFile ("resources/demos").getChildFile (lynx::demos::fileName (d));
  24170. juce::String error;
  24171. const auto loaded = lynx::ProjectFile::load (file, error);
  24172. check ("resources/demos/" + juce::String (lynx::demos::fileName (d)) + " loads and is the generated song",
  24173. loaded.has_value() && lynx::ProjectFile::toJson (*loaded, false) == lynx::ProjectFile::toJson (lynx::demos::make (d), false));
  24174. }
  24175. line (report.contains ("ERROR ") ? "RESULT ERROR" : "RESULT OK");
  24176. juce::File (prefix + "-report.txt").replaceWithText (report);
  24177. }
  24178. // --patterns190ea (round 190ea): FL keeps at least one pattern; the engine now does too (AudioEngine::publishSong,
  24179. // Song::keepOnePattern). Before, a Song without a pattern crashed the docked Piano roll's listener.
  24180. bool runPatterns190ea (const juce::String& reportPath)
  24181. {
  24182. namespace st = lynx::simpletracks;
  24183. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  24184. lynx::AudioEngine offline (false);
  24185. lynx::MainComponent ui (offline, false);
  24186. ui.setSize (1600, 900);
  24187. ui.setVisible (true); // (no window: the docked editor only needs its parents visible)
  24188. juce::String report;
  24189. bool ok = true;
  24190. const auto check = [&report, &ok] (const juce::String& what, bool good) {
  24191. report << (good ? "OK " : "ERROR ") << what << "\n";
  24192. ok = ok && good;
  24193. };
  24194. const auto save = [&report, &reportPath] { juce::File (reportPath).replaceWithText (report); };
  24195. const auto settle = [&] { offline.dispatchPendingMessages(); ui.getPianoRollForSnapshot().repaint(); };
  24196. const auto onePattern = [&offline] {
  24197. const auto& s = offline.getSong();
  24198. return s.patterns.size() >= 1 && s.currentPattern >= 0 && s.currentPattern < (int) s.patterns.size();
  24199. };
  24200. // the hand-built songs the engine can be given: none of them has a pattern
  24201. const auto bare = [] {
  24202. lynx::Song s;
  24203. s.mixer = lynx::Song::defaultMixer();
  24204. return s;
  24205. };
  24206. // every way to reach "no pattern" in the current layout
  24207. const auto paths = [&] (const juce::String& where) {
  24208. offline.setSong (bare());
  24209. settle();
  24210. check (where + ": a song without a pattern opens with one empty \"Pattern 1\"",
  24211. onePattern() && offline.getSong().patterns.size() == 1 && offline.getSong().patterns[0].name == "Pattern 1"
  24212. && offline.getSong().patterns[0].notes.empty());
  24213. offline.editSong ([] (lynx::Song& s) { s.patterns.clear(); });
  24214. settle();
  24215. check (where + ": an edit that clears every pattern leaves one", onePattern());
  24216. offline.editSong ([] (lynx::Song& s) {
  24217. s.patterns.resize (2);
  24218. s.patterns[1].notes.push_back ({});
  24219. s.currentPattern = 1;
  24220. });
  24221. settle();
  24222. offline.editSong ([] (lynx::Song& s) { s.removePattern (s.currentPattern); });
  24223. offline.editSong ([] (lynx::Song& s) { s.removePattern (s.currentPattern); });
  24224. settle();
  24225. check (where + ": deleting the last pattern leaves an empty \"Pattern 1\" (FL's invariant)",
  24226. onePattern() && offline.getSong().patterns.size() == 1 && offline.getSong().patterns[0].notes.empty());
  24227. for (int k = 0; k < 6; ++k)
  24228. {
  24229. offline.undo();
  24230. settle();
  24231. }
  24232. check (where + ": undo back over those steps keeps a pattern", onePattern());
  24233. for (int k = 0; k < 6; ++k)
  24234. {
  24235. offline.redo();
  24236. settle();
  24237. }
  24238. check (where + ": redo keeps a pattern", onePattern());
  24239. offline.applyRemote (bare());
  24240. settle();
  24241. check (where + ": a live session's remote song without a pattern gets one", onePattern());
  24242. offline.editSong ([] (lynx::Song& s) { s.currentPattern = 99; });
  24243. settle();
  24244. check (where + ": a current pattern out of range is put back in range", onePattern() && offline.getSong().currentPattern == 0);
  24245. };
  24246. // the Simple layout with the Piano roll docked in the Editor tab (round 190dv's crash)
  24247. ui.selectTabForSnapshot (2);
  24248. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  24249. settle();
  24250. auto* simple = ui.getSimpleWorkflowForSnapshot();
  24251. check ("the Simple workflow is up", simple != nullptr);
  24252. if (simple == nullptr)
  24253. {
  24254. save();
  24255. return false;
  24256. }
  24257. simple->hideChooser();
  24258. st::Request q;
  24259. q.kind = st::Kind::instrument;
  24260. q.name = "Keys";
  24261. lynx::ChannelDef synth;
  24262. synth.instrument = lynx::InstrumentKind::synth;
  24263. q.channel = synth;
  24264. q.emptyBars = 4;
  24265. st::Result r;
  24266. offline.editSong ([&] (lynx::Song& s) { r = st::addTrack (s, q); });
  24267. settle();
  24268. ui.getPlaylistForSnapshot().selectTrack (r.track);
  24269. simple->trackSelected (r.track);
  24270. settle();
  24271. auto* dock = simple->dockForSnapshot();
  24272. check ("the instrument track's dock has the Editor tab", dock != nullptr && dock->hasPlayTabsForCheck());
  24273. if (dock != nullptr)
  24274. dock->setTab (lynx::SimpleDock::Tab::editor);
  24275. settle();
  24276. check ("the Piano roll is docked in the Editor tab", dock != nullptr && dock->isEditorDocked() && dock->isParentOf (&ui.getPianoRollForSnapshot()));
  24277. paths ("Simple, Editor tab");
  24278. // the Pattern layout with the Piano roll panel, then the Clip-launch layout
  24279. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
  24280. settle();
  24281. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::pianoRoll });
  24282. settle();
  24283. paths ("Pattern layout, Piano roll");
  24284. ui.setLayoutStyle (lynx::layoutstyle::Style::clipLaunch);
  24285. settle();
  24286. paths ("Clip-launch layout");
  24287. report << (ok ? "RESULT OK\n" : "RESULT FAILED\n");
  24288. save();
  24289. return ok;
  24290. }
  24291. // round 190fo: the Simple layout's Sampler track (16 pads) and a folder of stems and MIDI files, off-screen at 1x and
  24292. // 2x, with a text report of the checks (.lynx round trip, kits, typing keys, the folder import)
  24293. void runReabl190foShot (const juce::String& prefix)
  24294. {
  24295. namespace st = lynx::simpletracks;
  24296. namespace sp = lynx::simplepads;
  24297. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  24298. lynx::AudioEngine offline (false);
  24299. lynx::MainComponent ui (offline, false);
  24300. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  24301. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  24302. ui.setVisible (true);
  24303. const auto writeImage = [&prefix] (const juce::Image& image, const juce::String& name) {
  24304. const auto file = juce::File (prefix + "-" + name + ".png");
  24305. file.deleteFile();
  24306. juce::FileOutputStream out (file);
  24307. juce::PNGImageFormat().writeImageToStream (image, out);
  24308. };
  24309. juce::String report;
  24310. const auto line = [&report] (const juce::String& text) { report << text << "\n"; };
  24311. const auto check = [&report] (const juce::String& what, bool ok) { report << (ok ? "OK " : "ERROR ") << what << "\n"; };
  24312. ui.selectTabForSnapshot (2);
  24313. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  24314. offline.dispatchPendingMessages();
  24315. auto* simple = ui.getSimpleWorkflowForSnapshot();
  24316. if (simple == nullptr)
  24317. {
  24318. juce::File (prefix + "-report.txt").replaceWithText ("ERROR no Simple workflow\n");
  24319. return;
  24320. }
  24321. const auto whole = [&] (const juce::String& name) {
  24322. offline.dispatchPendingMessages();
  24323. for (float scale : { 1.0f, 2.0f })
  24324. writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, scale), name + (scale > 1.0f ? "@2x" : ""));
  24325. };
  24326. // the chooser: the Sampler tile (16 pads, "On keys..." for one sample over the keys) and Import's "Folder..."
  24327. simple->showChooser();
  24328. whole ("chooser");
  24329. simple->hideChooser();
  24330. // --- test sounds -------------------------------------------------------------------------------------------------
  24331. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-190fo");
  24332. dir.deleteRecursively();
  24333. dir.createDirectory();
  24334. const auto writeWav = [] (const juce::File& wav, int frames, const std::function<float (int)>& f) {
  24335. juce::AudioBuffer<float> audio (1, frames);
  24336. for (int i = 0; i < frames; ++i)
  24337. audio.setSample (0, i, f (i));
  24338. wav.getParentDirectory().createDirectory();
  24339. juce::WavAudioFormat format;
  24340. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  24341. if (auto* w = format.createWriterFor (out.get(), 48000.0, 1, 16, {}, 0))
  24342. {
  24343. out.release();
  24344. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  24345. writer->writeFromAudioSampleBuffer (audio, 0, frames);
  24346. }
  24347. return wav;
  24348. };
  24349. juce::Random rnd (190);
  24350. const auto pi = juce::MathConstants<double>::pi;
  24351. const auto kick = writeWav (dir.getChildFile ("pads/Kick.wav"), 24000, [pi] (int i) {
  24352. const auto t = i / 48000.0;
  24353. 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));
  24354. });
  24355. 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)); });
  24356. 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)); });
  24357. const auto chord = writeWav (dir.getChildFile ("pads/Chord stab.wav"), 48000, [pi] (int i) {
  24358. const auto t = i / 48000.0;
  24359. double v = 0.0;
  24360. for (int k : { 57, 60, 64 })
  24361. v += std::sin (2.0 * pi * 440.0 * std::pow (2.0, (k - 69) / 12.0) * t);
  24362. return (float) (0.2 * v * std::exp (-t * 2.5));
  24363. });
  24364. const auto vox = writeWav (dir.getChildFile ("pads/Vox hey.wav"), 30000, [pi] (int i) {
  24365. const auto t = i / 48000.0;
  24366. 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));
  24367. });
  24368. // --- the Sampler track ---------------------------------------------------------------------------------------------
  24369. check ("the Sampler tile's track was added", simple->addPads());
  24370. offline.dispatchPendingMessages();
  24371. const auto& song0 = offline.getSong();
  24372. int track = -1;
  24373. for (int t = 0; t < (int) song0.playlistTracks.size() && track < 0; ++t)
  24374. if (st::kindOf (song0, t) == st::Kind::pads)
  24375. track = t;
  24376. check ("a Sampler track with 16 pads", track >= 0 && [&] {
  24377. const auto c = sp::padChannels (song0, track);
  24378. return std::all_of (c.begin(), c.end(), [] (int i) { return i >= 0; });
  24379. }());
  24380. auto* dock = simple->dockForSnapshot();
  24381. if (dock == nullptr || track < 0)
  24382. {
  24383. juce::File (prefix + "-report.txt").replaceWithText (report + "ERROR no dock / track\n");
  24384. return;
  24385. }
  24386. simple->trackSelected (track);
  24387. offline.dispatchPendingMessages();
  24388. check ("the dock opens on the Pads tab", dock->hasPadsTabForCheck() && dock->getTab() == lynx::SimpleDock::Tab::pads);
  24389. const auto shots = [&] (const juce::String& name) {
  24390. offline.dispatchPendingMessages();
  24391. for (float scale : { 1.0f, 2.0f })
  24392. {
  24393. const auto suffix = scale > 1.0f ? juce::String ("@2x") : juce::String();
  24394. writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, scale), name + suffix);
  24395. writeImage (dock->createComponentSnapshot (dock->getLocalBounds(), true, scale), "dock-" + name + suffix);
  24396. }
  24397. };
  24398. shots ("pads-empty");
  24399. const juce::File files[] { kick, snare, hat, hat, chord, vox };
  24400. for (int p = 0; p < 6; ++p)
  24401. dock->padsLoadForCheck (p, files[p]);
  24402. offline.dispatchPendingMessages();
  24403. check ("six pads hold a sound", [&] {
  24404. int n = 0;
  24405. for (int p = 0; p < sp::padCount; ++p)
  24406. n += sp::hasSample (offline.getSong(), track, p) ? 1 : 0;
  24407. return n == 6;
  24408. }());
  24409. // pad 3 = the open hat: one-shot, group 1 with pad 2 (closed hat), a colour; pad 4 = the chord, looped and darker
  24410. dock->padsSelectForCheck (2);
  24411. dock->padsModeForCheck (1);
  24412. dock->padsSelectForCheck (3);
  24413. dock->padsModeForCheck (1);
  24414. offline.editSong ([track] (lynx::Song& s) {
  24415. for (int p : { 2, 3 })
  24416. if (const auto c = sp::padChannel (s, track, p); c >= 0)
  24417. {
  24418. s.channels[(std::size_t) c].simplePad.group = 1;
  24419. s.channels[(std::size_t) c].simplePad.colour = 2;
  24420. sp::apply (s.channels[(std::size_t) c], 4800);
  24421. }
  24422. });
  24423. dock->padsSelectForCheck (4);
  24424. dock->padsModeForCheck (2);
  24425. dock->padsKnobForCheck (2, 0.3f); // tone: a low-pass
  24426. dock->padsKnobForCheck (1, 0.35f); // release
  24427. dock->padsRegionForCheck (0.05f, 0.7f);
  24428. dock->padsNormalizeForCheck();
  24429. dock->padsUpdateForCheck();
  24430. {
  24431. const auto& s = offline.getSong();
  24432. const auto& c = s.channels[(std::size_t) sp::padChannel (s, track, 4)];
  24433. line ("pad 5: mode " + juce::String ((int) c.simplePad.mode) + " tone " + juce::String (c.simplePad.tone, 2) + " cutoff " + juce::String (c.sampler.cutoff, 0)
  24434. + " release " + juce::String (c.sampler.release, 3) + " region " + juce::String (c.sampler.regionStart, 2) + "-" + juce::String (c.sampler.regionEnd, 2)
  24435. + " gain " + juce::String (c.sampler.gainDb, 2) + " dB zones " + juce::String ((int) c.zones.size()));
  24436. 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
  24437. && c.sampler.filterType == 0 && c.sampler.cutoff < 5000.0f && c.sampler.gainDb > 0.5f);
  24438. const auto& h = s.channels[(std::size_t) sp::padChannel (s, track, 3)];
  24439. 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);
  24440. }
  24441. shots ("pads");
  24442. dock->padsHitForCheck (0);
  24443. dock->lightPad (2);
  24444. shots ("pads-hit");
  24445. // the typing keys: V plays pad 1, M pad 4, 7 pad 16; Z is not a pad key
  24446. check ("typing keys reach the pads", simple->padChannelForKey ('V') == sp::padChannel (offline.getSong(), track, 0)
  24447. && simple->padChannelForKey ('m') == sp::padChannel (offline.getSong(), track, 3)
  24448. && simple->padChannelForKey ('7') == sp::padChannel (offline.getSong(), track, 15)
  24449. && simple->padChannelForKey ('Z') == -1);
  24450. // drag pad 6 (vox) onto the empty pad 9: it moves; Alt-drag pad 1 onto pad 10: a copy
  24451. dock->padsDragForCheck (5, 8, false);
  24452. dock->padsDragForCheck (0, 9, true);
  24453. check ("a pad moved and a pad copied", ! sp::hasSample (offline.getSong(), track, 5) && sp::hasSample (offline.getSong(), track, 8)
  24454. && sp::hasSample (offline.getSong(), track, 9) && sp::hasSample (offline.getSong(), track, 0));
  24455. dock->padsSelectForCheck (4);
  24456. shots ("pads-moved");
  24457. saveMenus ({ "Pad menu", "Colour", "Copy a value to every pad" }, [&] {
  24458. const auto top = dock->padMenuForSnapshot (4);
  24459. std::vector<juce::PopupMenu> menus { top };
  24460. for (juce::PopupMenu::MenuItemIterator it (top); it.next();)
  24461. if (it.getItem().subMenu != nullptr)
  24462. menus.push_back (*it.getItem().subMenu);
  24463. return menus;
  24464. }(), prefix + "-menu-pad.png");
  24465. // kits: saved, the pads cleared, opened again
  24466. const auto kitFile = lynx::platform::documentsFolder().getChildFile ("LYNX/Sampler kits/Test kit 190fo.lynxkit");
  24467. kitFile.deleteFile();
  24468. check ("the pads saved as a kit", dock->saveKitForCheck ("Test kit 190fo") && kitFile.existsAsFile());
  24469. saveMenus ({ "Kit", "My kits" }, [&] {
  24470. const auto top = dock->kitMenuForSnapshot();
  24471. std::vector<juce::PopupMenu> menus { top };
  24472. for (juce::PopupMenu::MenuItemIterator it (top); it.next();)
  24473. if (it.getItem().subMenu != nullptr && it.getItem().text == lynx::tr ("My kits"))
  24474. menus.push_back (*it.getItem().subMenu);
  24475. return menus;
  24476. }(), prefix + "-menu-kit.png");
  24477. const auto before = offline.getSong().channels;
  24478. offline.editSong ([track] (lynx::Song& s) {
  24479. for (int p = 0; p < sp::padCount; ++p)
  24480. sp::clearPad (s, track, p);
  24481. });
  24482. check ("the kit opens the same pads again", dock->openKitForCheck (kitFile) && [&] {
  24483. const auto& now = offline.getSong().channels;
  24484. for (int p = 0; p < sp::padCount; ++p)
  24485. {
  24486. const auto c = sp::padChannel (offline.getSong(), track, p);
  24487. 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
  24488. || 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)
  24489. return false;
  24490. }
  24491. return true;
  24492. }());
  24493. {
  24494. const auto renamed = kitFile.getSiblingFile ("Renamed kit 190fo.lynxkit");
  24495. renamed.deleteFile();
  24496. check ("a kit renamed (and a one-letter name refused)", ! lynx::SimpleDock::renameKitForCheck (kitFile, "x")
  24497. && lynx::SimpleDock::renameKitForCheck (kitFile, "Renamed kit 190fo") && renamed.existsAsFile()
  24498. && ! kitFile.exists());
  24499. renamed.deleteFile();
  24500. }
  24501. kitFile.deleteFile();
  24502. // a beat on the pads (the track's pattern) and the .lynx round trip
  24503. offline.editSong ([track] (lynx::Song& s) {
  24504. const auto pattern = [&] {
  24505. for (const auto& c : s.playlist)
  24506. if (c.track == track && c.kind == lynx::ClipKind::pattern)
  24507. return c.pattern;
  24508. return -1;
  24509. }();
  24510. if (pattern < 0)
  24511. return;
  24512. for (int step = 0; step < 16; ++step)
  24513. {
  24514. const int pad = step % 4 == 0 ? 0 : step % 8 == 4 ? 1 : 2;
  24515. lynx::Note n;
  24516. n.channel = sp::padChannel (s, track, pad);
  24517. n.key = sp::padKey;
  24518. n.start = (std::int64_t) step * lynx::ticksPerStep;
  24519. n.length = lynx::ticksPerStep;
  24520. s.patterns[(std::size_t) pattern].notes.push_back (n);
  24521. }
  24522. });
  24523. {
  24524. const auto json = lynx::ProjectFile::toJson (offline.getSong());
  24525. juce::String error;
  24526. const auto back = lynx::ProjectFile::fromJson (json, error);
  24527. bool same = back.has_value() && back->channels.size() == offline.getSong().channels.size() && st::kindOf (*back, track) == st::Kind::pads;
  24528. for (std::size_t c = 0; same && c < back->channels.size(); ++c)
  24529. {
  24530. const auto& a = back->channels[c];
  24531. const auto& b = offline.getSong().channels[c];
  24532. same = a.simplePad == b.simplePad && a.zones == b.zones && a.cutGroup == b.cutGroup && a.cutBy == b.cutBy && a.samplePath == b.samplePath
  24533. && a.sampler.regionStart == b.sampler.regionStart && a.sampler.release == b.sampler.release && a.sampler.cutoff == b.sampler.cutoff;
  24534. }
  24535. check ("pads, their modes, groups and loops survive .lynx", same);
  24536. lynx::Song plain = lynx::Song::makeDefault();
  24537. check ("a project without pads writes no pad field", ! lynx::ProjectFile::toJson (plain).contains ("simplePad"));
  24538. }
  24539. ui.getPlaylistForSnapshot().selectTrack (track);
  24540. // --- a folder of stems and MIDI files (the other app's "download stems" naming) --------------------------------------
  24541. const auto stems = dir.getChildFile ("My song stems");
  24542. writeWav (stems.getChildFile ("01_Drums.wav"), 96000, [&rnd] (int i) { return (i % 24000) < 2000 ? (rnd.nextFloat() - 0.5f) * 0.8f : 0.0f; });
  24543. writeWav (stems.getChildFile ("02_Bass.wav"), 96000, [pi] (int i) { return (float) (0.3 * std::sin (2.0 * pi * 55.0 * i / 48000.0)); });
  24544. 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)); });
  24545. {
  24546. juce::MidiMessageSequence seq;
  24547. for (int k = 0; k < 8; ++k)
  24548. {
  24549. seq.addEvent (juce::MidiMessage::noteOn (1, 36 + (k % 4) * 3, (juce::uint8) 100), k * 480.0);
  24550. seq.addEvent (juce::MidiMessage::noteOff (1, 36 + (k % 4) * 3), k * 480.0 + 400.0);
  24551. }
  24552. seq.updateMatchedPairs();
  24553. juce::MidiFile midi;
  24554. midi.setTicksPerQuarterNote (960);
  24555. midi.addTrack (seq);
  24556. for (const auto& name : { "02_Bass.mid", "03_Keys.mid" })
  24557. {
  24558. juce::FileOutputStream out (stems.getChildFile (name));
  24559. midi.writeTo (out);
  24560. }
  24561. }
  24562. const auto tracksBefore = [&] {
  24563. int n = 0;
  24564. for (int t = 0; t < (int) offline.getSong().playlistTracks.size(); ++t)
  24565. n += st::kindOf (offline.getSong(), t).has_value() ? 1 : 0;
  24566. return n;
  24567. }();
  24568. simple->addFilesForCheck ({ stems });
  24569. offline.dispatchPendingMessages();
  24570. {
  24571. const auto& s = offline.getSong();
  24572. juce::StringArray names;
  24573. int muted = 0, count = 0;
  24574. for (int t = 0; t < (int) s.playlistTracks.size(); ++t)
  24575. if (st::kindOf (s, t).has_value())
  24576. {
  24577. ++count;
  24578. if (count > tracksBefore)
  24579. {
  24580. names.add (juce::String::fromUTF8 (s.playlistTracks[(std::size_t) t].name.c_str()) + (s.playlistTracks[(std::size_t) t].muted ? " (muted)" : ""));
  24581. muted += s.playlistTracks[(std::size_t) t].muted ? 1 : 0;
  24582. }
  24583. }
  24584. line ("folder tracks: " + names.joinIntoString (", "));
  24585. check ("the folder gave 5 tracks in number order, named without numbers, the Bass notes muted (its stem plays)",
  24586. names == juce::StringArray { "Drums", "Bass", "Lead Vox", "Bass 2 (muted)", "Keys" } && muted == 1);
  24587. bool atZero = true;
  24588. for (const auto& c : s.playlist)
  24589. if (c.track >= 0 && st::kindOf (s, c.track) == st::Kind::audio)
  24590. atZero = atZero && c.start == 0;
  24591. check ("every stem starts at the song's start", atZero);
  24592. }
  24593. simple->hideChooser();
  24594. whole ("folder-import");
  24595. dir.deleteRecursively();
  24596. line (report.contains ("ERROR ") ? "RESULT ERROR" : "RESULT OK");
  24597. juce::File (prefix + "-report.txt").replaceWithText (report);
  24598. }
  24599. void runSimple190dsShot (const juce::String& prefix)
  24600. {
  24601. namespace st = lynx::simpletracks;
  24602. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  24603. lynx::AudioEngine offline (false);
  24604. lynx::MainComponent ui (offline, false);
  24605. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  24606. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  24607. ui.setVisible (true); // (no window: the docked editor only needs its parents visible)
  24608. const auto writeImage = [&prefix] (const juce::Image& image, const juce::String& name) {
  24609. const auto file = juce::File (prefix + "-" + name + ".png");
  24610. file.deleteFile();
  24611. juce::FileOutputStream out (file);
  24612. juce::PNGImageFormat().writeImageToStream (image, out);
  24613. };
  24614. juce::String report;
  24615. const auto line = [&report] (const juce::String& text) { report << text << "\n"; };
  24616. const auto check = [&report] (const juce::String& what, bool ok) { report << (ok ? "OK " : "ERROR ") << what << "\n"; };
  24617. ui.selectTabForSnapshot (2);
  24618. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  24619. offline.dispatchPendingMessages();
  24620. auto* simple = ui.getSimpleWorkflowForSnapshot();
  24621. if (simple == nullptr)
  24622. {
  24623. juce::File (prefix + "-report.txt").replaceWithText ("ERROR no Simple workflow\n");
  24624. return;
  24625. }
  24626. simple->hideChooser();
  24627. auto& playlist = ui.getPlaylistForSnapshot();
  24628. // --- three loops: two with their key in the name, one only in its sound ---------------------------------------
  24629. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-190ds-loops");
  24630. dir.deleteRecursively();
  24631. dir.createDirectory();
  24632. // a chord loop (two bars at 120 BPM, 48 kHz): each chord's notes with six harmonics, a soft attack per beat
  24633. const auto writeLoop = [&dir] (const juce::String& name, std::vector<std::vector<int>> chords) {
  24634. const int frames = 192000;
  24635. juce::AudioBuffer<float> audio (1, frames);
  24636. audio.clear();
  24637. for (int i = 0; i < frames; ++i)
  24638. {
  24639. const auto& chord = chords[(std::size_t) (i / (frames / (int) chords.size()))];
  24640. const auto t = (double) i / 48000.0;
  24641. const auto beat = std::fmod (t, 0.5);
  24642. double v = 0.0;
  24643. for (const auto key : chord)
  24644. {
  24645. const auto f = 440.0 * std::pow (2.0, (key - 69) / 12.0);
  24646. for (int h = 1; h <= 6; ++h)
  24647. v += std::sin (2.0 * juce::MathConstants<double>::pi * f * h * t) / (h * h);
  24648. }
  24649. audio.setSample (0, i, (float) (0.08 * v * (1.0 - std::exp (-beat * 60.0)) * (0.6 + 0.4 * std::exp (-beat * 3.0))));
  24650. }
  24651. const auto wav = dir.getChildFile (name);
  24652. juce::WavAudioFormat format;
  24653. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  24654. if (auto* w = format.createWriterFor (out.get(), 48000.0, 1, 16, {}, 0))
  24655. {
  24656. out.release();
  24657. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  24658. writer->writeFromAudioSampleBuffer (audio, 0, frames);
  24659. }
  24660. return wav.getFullPathName();
  24661. };
  24662. const auto gMinor = writeLoop ("Night Pad 120 Gm.wav", { { 55, 58, 62 }, { 51, 55, 58 }, { 53, 57, 60 }, { 55, 58, 62 } });
  24663. const auto dMinor = writeLoop ("Pluck_120_D_minor.wav", { { 50, 53, 57 }, { 46, 50, 53 }, { 48, 52, 55 }, { 50, 53, 57 } });
  24664. 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 } });
  24665. lynx::SimpleWorkflow::answerForSnapshot = 1; // "Set the project key to G minor?" — yes
  24666. simple->dropFiles ({ gMinor, dMinor, eMinor }, 0);
  24667. lynx::SimpleWorkflow::answerForSnapshot = -1;
  24668. offline.dispatchPendingMessages();
  24669. simple->hideChooser();
  24670. line ("question: " + simple->lastKeyQuestionForCheck());
  24671. check ("the first keyed loop offered its key (G minor)", simple->lastKeyQuestionForCheck().contains ("G minor"));
  24672. {
  24673. const auto& song = offline.getSong();
  24674. const auto key = lynx::projectkey::get (song);
  24675. check ("the project key is G minor", key && key->root == 7 && lynx::projectkey::isMinor (*key));
  24676. std::vector<int> clips;
  24677. for (int i = 0; i < (int) song.playlist.size(); ++i)
  24678. if (song.playlist[(std::size_t) i].kind == lynx::ClipKind::audio)
  24679. clips.push_back (i);
  24680. check ("three loop clips", clips.size() == 3);
  24681. const int expect[] { 0, 5, 3 }; // G minor, D minor (F -> Bb: +5), E minor detected (G -> Bb: +3)
  24682. const int roots[] { 7, 2, 4 };
  24683. const int sources[] { 1, 1, 2 };
  24684. for (std::size_t k = 0; k < clips.size() && k < 3; ++k)
  24685. {
  24686. const auto& c = song.playlist[(std::size_t) clips[k]];
  24687. const auto& sampler = song.channels[(std::size_t) c.channel].sampler;
  24688. line ("loop " + juce::String ((int) k + 1) + ": key " + juce::String (sampler.loopKeyRoot) + (sampler.loopKeyMinor ? "m" : "") + " source "
  24689. + juce::String ((int) sampler.loopKeySource) + " follow " + juce::String (c.followKey ? 1 : 0) + " shift " + juce::String ((int) c.keyShift)
  24690. + " pitch " + juce::String (c.pitch));
  24691. check ("loop " + juce::String ((int) k + 1) + " key, source and move", sampler.loopKeyRoot == roots[k] && sampler.loopKeyMinor
  24692. && sampler.loopKeySource == sources[k] && c.followKey
  24693. && c.keyShift == expect[k] && std::abs (c.pitch - (float) expect[k]) < 1.0e-4f);
  24694. }
  24695. }
  24696. // the key changes: every following loop moves with it (one undo step)
  24697. offline.editSong ([] (lynx::Song& s) { lynx::projectkey::set (s, lynx::projectkey::Key { 9, lynx::projectkey::commonFirst()[1] }); });
  24698. offline.dispatchPendingMessages();
  24699. {
  24700. const auto& song = offline.getSong();
  24701. std::vector<int> shifts;
  24702. for (const auto& c : song.playlist)
  24703. if (c.kind == lynx::ClipKind::audio)
  24704. shifts.push_back (c.keyShift);
  24705. line ("after A minor: " + juce::String (shifts.size() > 2 ? shifts[0] : 99) + " " + juce::String (shifts.size() > 2 ? shifts[1] : 99) + " "
  24706. + juce::String (shifts.size() > 2 ? shifts[2] : 99));
  24707. check ("A minor: the loops move by +2, -5, +5", shifts == std::vector<int> { 2, -5, 5 });
  24708. }
  24709. // the loop tracks in the dock: the switch and what it does
  24710. int loopTrack = -1;
  24711. for (const auto& c : offline.getSong().playlist)
  24712. if (c.kind == lynx::ClipKind::audio && loopTrack < 0)
  24713. loopTrack = c.track;
  24714. playlist.selectTrack (loopTrack);
  24715. offline.dispatchPendingMessages();
  24716. auto* dock = simple->dockForSnapshot();
  24717. if (dock == nullptr)
  24718. {
  24719. juce::File (prefix + "-report.txt").replaceWithText (report + "ERROR no dock\n");
  24720. return;
  24721. }
  24722. simple->trackSelected (loopTrack);
  24723. offline.dispatchPendingMessages();
  24724. const auto shots = [&] (const juce::String& name) {
  24725. offline.dispatchPendingMessages();
  24726. for (float scale : { 1.0f, 2.0f })
  24727. {
  24728. const auto suffix = scale > 1.0f ? juce::String ("@2x") : juce::String();
  24729. writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, scale), name + suffix);
  24730. writeImage (dock->createComponentSnapshot (dock->getLocalBounds(), true, scale), "dock-" + name + suffix);
  24731. }
  24732. };
  24733. const auto menuShot = [&] (const juce::PopupMenu& menu, const juce::String& title, const juce::String& subTitle, const juce::String& name) {
  24734. juce::StringArray names { title };
  24735. std::vector<juce::PopupMenu> menus { menu };
  24736. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  24737. if (it.getItem().subMenu != nullptr && it.getItem().text.startsWith (subTitle))
  24738. {
  24739. names.add (subTitle);
  24740. menus.push_back (*it.getItem().subMenu);
  24741. }
  24742. saveMenus (names, menus, prefix + "-" + name + ".png");
  24743. };
  24744. check ("the dock shows the follow switch for the loop track", dock->followShownForCheck());
  24745. shots ("follow-on");
  24746. {
  24747. int clip = -1;
  24748. for (int i = 0; i < (int) offline.getSong().playlist.size() && clip < 0; ++i)
  24749. if (offline.getSong().playlist[(std::size_t) i].kind == lynx::ClipKind::audio)
  24750. clip = i;
  24751. const auto menu = playlist.getClipMenuForSnapshot (clip);
  24752. bool follow = false, keyItem = false;
  24753. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  24754. {
  24755. follow = follow || (it.getItem().text.startsWith (lynx::tr ("Follow the project key")) && it.getItem().isTicked);
  24756. keyItem = keyItem || it.getItem().text.startsWith (lynx::tr ("Loop key"));
  24757. }
  24758. check ("the clip menu has Follow the project key (ticked) and Loop key", follow && keyItem);
  24759. menuShot (menu, lynx::tr ("Audio clip"), lynx::tr ("Loop key"), "menu-clip-key");
  24760. }
  24761. dock->clickFollowForCheck(); // off: back to its own key
  24762. offline.dispatchPendingMessages();
  24763. {
  24764. float pitch = 99.0f;
  24765. bool following = true;
  24766. for (const auto& c : offline.getSong().playlist)
  24767. if (c.kind == lynx::ClipKind::audio && c.track == loopTrack)
  24768. pitch = c.pitch, following = c.followKey;
  24769. check ("switched off: the loop plays in its own key (pitch 0)", ! following && std::abs (pitch) < 1.0e-6f);
  24770. }
  24771. shots ("follow-off");
  24772. dock->clickFollowForCheck();
  24773. offline.dispatchPendingMessages();
  24774. // --- an instrument track from the tile: a pattern to write into, the Editor tab ------------------------------
  24775. {
  24776. st::Request q;
  24777. q.kind = st::Kind::instrument;
  24778. q.name = "Keys";
  24779. lynx::ChannelDef synth;
  24780. synth.instrument = lynx::InstrumentKind::synth;
  24781. q.channel = synth;
  24782. q.emptyBars = 4;
  24783. st::Result r;
  24784. offline.editSong ([&] (lynx::Song& s) { r = st::addTrack (s, q); });
  24785. offline.dispatchPendingMessages();
  24786. check ("the new Instrument track has an empty 4-bar pattern on it", r.ok() && r.pattern >= 0
  24787. && st::patternOf (offline.getSong(), r.track) == r.pattern
  24788. && offline.getSong().patterns[(std::size_t) r.pattern].notes.empty());
  24789. // a few notes, as the first clicks would write them (A minor: A C E, then G B D)
  24790. offline.editSong ([r] (lynx::Song& s) {
  24791. auto& p = s.patterns[(std::size_t) r.pattern];
  24792. const int keys[] { 57, 60, 64, 67, 71, 74, 69, 72 };
  24793. for (int i = 0; i < 8; ++i)
  24794. {
  24795. lynx::Note n;
  24796. n.channel = r.channels.front();
  24797. n.key = keys[i];
  24798. n.start = (std::int64_t) (i / 3) * lynx::ppq * 2 + (i % 3 == 0 ? 0 : 0);
  24799. n.length = lynx::ppq * 2;
  24800. n.velocity = 0.8f;
  24801. p.notes.push_back (n);
  24802. }
  24803. p.sortNotes();
  24804. });
  24805. offline.dispatchPendingMessages();
  24806. playlist.selectTrack (r.track);
  24807. simple->trackSelected (r.track);
  24808. offline.dispatchPendingMessages();
  24809. check ("the instrument track has the Keyboard and Editor tabs", dock->hasPlayTabsForCheck());
  24810. dock->setTab (lynx::SimpleDock::Tab::editor);
  24811. offline.dispatchPendingMessages();
  24812. check ("the Piano roll is docked in the Editor tab", dock->isEditorDocked());
  24813. check ("on the track's pattern", offline.getSong().currentPattern == r.pattern);
  24814. ui.getPianoRollForSnapshot().scrollToNotes(); // (done asynchronously when it docks)
  24815. shots ("editor");
  24816. dock->clickFoldForCheck (true); // "Only notes in key"
  24817. check ("Only notes in key folds the rows to A minor", ui.getPianoRollForSnapshot().isFoldedToScale());
  24818. ui.getPianoRollForSnapshot().scrollToNotes();
  24819. shots ("editor-in-key");
  24820. dock->clickFoldForCheck (false);
  24821. // --- the keyboard's modes ------------------------------------------------------------------------------
  24822. auto& keyboard = lynx::scalekeys::current();
  24823. const auto saved = keyboard;
  24824. keyboard = {};
  24825. keyboard.lockToKey = true;
  24826. dock->setTab (lynx::SimpleDock::Tab::keyboard);
  24827. if (auto* panel = dock->keyboardPanelForSnapshot())
  24828. {
  24829. lynx::refreshKeyboardPanel (*panel);
  24830. shots ("keys-locked");
  24831. keyboard.lockToKey = false;
  24832. keyboard.mode = lynx::scalekeys::Mode::scaleKeys;
  24833. lynx::refreshKeyboardPanel (*panel);
  24834. shots ("scale-keys");
  24835. keyboard.mode = lynx::scalekeys::Mode::chordPad;
  24836. keyboard.complexity = lynx::scalekeys::Complexity::seventh;
  24837. keyboard.strumMs = 40;
  24838. lynx::refreshKeyboardPanel (*panel);
  24839. shots ("chord-pad");
  24840. }
  24841. check ("the Keyboard tab shows the keyboard panel", dock->keyboardPanelForSnapshot() != nullptr);
  24842. // the same panel as the Touch keyboard window, each mode with a key / pad held
  24843. for (const auto& [mode, name, pressed] : { std::tuple { lynx::scalekeys::Mode::scaleKeys, juce::String ("window-scale-keys"), 4 },
  24844. std::tuple { lynx::scalekeys::Mode::chordPad, juce::String ("window-chord-pad"), 3 } })
  24845. {
  24846. auto panel = lynx::makeKeyboardPanelForSnapshot (offline, mode, pressed, [ch = r.channels.front()] { return ch; });
  24847. panel->setSize (1100, 260);
  24848. for (float scale : { 1.0f, 2.0f })
  24849. writeImage (panel->createComponentSnapshot (panel->getLocalBounds(), true, scale), name + (scale > 1.0f ? "@2x" : ""));
  24850. if (mode == lynx::scalekeys::Mode::chordPad)
  24851. menuShot (lynx::chordPadMenuForSnapshot (*panel, 3), lynx::tr ("Edit chord"), lynx::tr ("Chord type"), "menu-chord-edit");
  24852. }
  24853. // the Chord pad on an FL Studio Mobile chord set (the default set's shape: C Dm Em F G Am B° C)
  24854. {
  24855. 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})");
  24856. check ("an FLM chord set reads as 8 chords (B diminished)", set.size() == 8 && set[6].quality == 3);
  24857. offline.editSong ([set] (lynx::Song& s) { s.keyboardChords = set; });
  24858. keyboard.projectChords = true;
  24859. keyboard.complexity = lynx::scalekeys::Complexity::triad;
  24860. auto panel = lynx::makeKeyboardPanelForSnapshot (offline, lynx::scalekeys::Mode::chordPad, 5, [ch = r.channels.front()] { return ch; });
  24861. panel->setSize (1100, 260);
  24862. for (float scale : { 1.0f, 2.0f })
  24863. writeImage (panel->createComponentSnapshot (panel->getLocalBounds(), true, scale), juce::String ("window-chord-set") + (scale > 1.0f ? "@2x" : ""));
  24864. }
  24865. // the typing keys in each mode (A minor; Z = the root)
  24866. {
  24867. const auto& song = offline.getSong();
  24868. lynx::scalekeys::Settings s;
  24869. s.mode = lynx::scalekeys::Mode::scaleKeys;
  24870. juce::String z;
  24871. for (const int typed : { 60, 62, 64, 65, 67, 69, 71, 72, 61 })
  24872. {
  24873. const auto n = lynx::scalekeys::typedNotes (song, s, typed, 60);
  24874. z << (n.empty() ? juce::String ("-") : juce::String (n.front())) << " ";
  24875. }
  24876. line ("Scale keys, typing C D E F G A B C C#: " + z);
  24877. check ("Scale keys: the white typing keys play A minor from A", z.trim() == "69 71 72 74 76 77 79 81 -");
  24878. s.mode = lynx::scalekeys::Mode::chordPad;
  24879. s.projectChords = false;
  24880. const auto pad = lynx::scalekeys::typedNotes (song, s, 60, 60);
  24881. check ("Chord pad: Z plays A minor (A C E)", pad == std::vector<int> { 69, 72, 76 });
  24882. }
  24883. keyboard = saved;
  24884. }
  24885. // --- the project round trip --------------------------------------------------------------------------------
  24886. {
  24887. const auto json = lynx::ProjectFile::toJson (offline.getSong());
  24888. juce::String error;
  24889. const auto back = lynx::ProjectFile::fromJson (json, error);
  24890. bool same = back.has_value() && back->keyboardChords == offline.getSong().keyboardChords && back->playlist.size() == offline.getSong().playlist.size();
  24891. for (std::size_t i = 0; same && i < back->playlist.size(); ++i)
  24892. same = back->playlist[i].followKey == offline.getSong().playlist[i].followKey && back->playlist[i].keyShift == offline.getSong().playlist[i].keyShift
  24893. && back->playlist[i].pitch == offline.getSong().playlist[i].pitch;
  24894. for (std::size_t c = 0; same && c < back->channels.size(); ++c)
  24895. same = back->channels[c].sampler.loopKeyRoot == offline.getSong().channels[c].sampler.loopKeyRoot
  24896. && back->channels[c].sampler.loopKeySource == offline.getSong().channels[c].sampler.loopKeySource;
  24897. check ("follow, key moves, loop keys and the chord set survive .lynx", same);
  24898. }
  24899. dir.deleteRecursively();
  24900. line (report.contains ("ERROR ") ? "RESULT ERROR" : "RESULT OK");
  24901. juce::File (prefix + "-report.txt").replaceWithText (report);
  24902. }
  24903. void runSimple190dgShot (const juce::String& prefix)
  24904. {
  24905. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  24906. lynx::AudioEngine offline (false);
  24907. lynx::MainComponent ui (offline, false);
  24908. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  24909. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  24910. const auto writeImage = [&prefix] (const juce::Image& image, const juce::String& name) {
  24911. const auto file = juce::File (prefix + "-" + name + ".png");
  24912. file.deleteFile();
  24913. juce::FileOutputStream out (file);
  24914. juce::PNGImageFormat().writeImageToStream (image, out);
  24915. };
  24916. juce::String report;
  24917. const auto line = [&report] (const juce::String& text) { report << text << "\n"; };
  24918. const auto check = [&report] (const juce::String& what, bool ok) { report << (ok ? "OK " : "ERROR ") << what << "\n"; };
  24919. ui.selectTabForSnapshot (2);
  24920. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  24921. offline.dispatchPendingMessages();
  24922. auto* simple = ui.getSimpleWorkflowForSnapshot();
  24923. if (simple == nullptr)
  24924. {
  24925. juce::File (prefix + "-report.txt").replaceWithText ("ERROR no Simple workflow\n");
  24926. return;
  24927. }
  24928. simple->hideChooser();
  24929. offline.editSong ([] (lynx::Song& s) {
  24930. namespace st = lynx::simpletracks;
  24931. st::Request q;
  24932. q.kind = st::Kind::voice;
  24933. q.name = "Lead vocal";
  24934. st::addTrack (s, q);
  24935. q = {};
  24936. q.kind = st::Kind::instrument;
  24937. q.name = "Keys";
  24938. lynx::ChannelDef keys;
  24939. keys.instrument = lynx::InstrumentKind::synth;
  24940. q.channel = keys;
  24941. st::addTrack (s, q);
  24942. });
  24943. offline.dispatchPendingMessages();
  24944. simple->hideChooser();
  24945. auto& playlist = ui.getPlaylistForSnapshot();
  24946. int voiceTrack = -1, keysTrack = -1;
  24947. {
  24948. const auto& song = offline.getSong();
  24949. for (int t = 0; t < (int) song.playlistTracks.size(); ++t)
  24950. if (const auto kind = lynx::simpletracks::kindOf (song, t))
  24951. {
  24952. if (*kind == lynx::simpletracks::Kind::audio && voiceTrack < 0)
  24953. voiceTrack = t;
  24954. else if (*kind == lynx::simpletracks::Kind::instrument && keysTrack < 0)
  24955. keysTrack = t;
  24956. }
  24957. }
  24958. check ("two Simple tracks (voice, keys)", voiceTrack >= 0 && keysTrack >= 0);
  24959. playlist.selectTrack (voiceTrack);
  24960. offline.dispatchPendingMessages();
  24961. auto* dock = simple->dockForSnapshot();
  24962. if (dock == nullptr)
  24963. {
  24964. juce::File (prefix + "-report.txt").replaceWithText (report + "ERROR no dock\n");
  24965. return;
  24966. }
  24967. const auto shots = [&] (const juce::String& name) {
  24968. offline.dispatchPendingMessages();
  24969. for (float scale : { 1.0f, 2.0f })
  24970. {
  24971. const auto suffix = scale > 1.0f ? juce::String ("@2x") : juce::String();
  24972. writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, scale), name + suffix);
  24973. writeImage (dock->createComponentSnapshot (dock->getLocalBounds(), true, scale), "dock-" + name + suffix);
  24974. }
  24975. };
  24976. const auto menuShot = [&] (const juce::PopupMenu& menu, const juce::String& title, const juce::String& subTitle, const juce::String& name) {
  24977. juce::StringArray names { title };
  24978. std::vector<juce::PopupMenu> menus { menu };
  24979. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  24980. if (it.getItem().subMenu != nullptr && it.getItem().text == subTitle)
  24981. {
  24982. names.add (subTitle);
  24983. menus.push_back (*it.getItem().subMenu);
  24984. }
  24985. saveMenus (names, menus, prefix + "-" + name + ".png");
  24986. };
  24987. const auto insert = dock->insertForCheck();
  24988. // --- every one-knob effect as a card, each at a knob position of its own -------------------------------------
  24989. const float at[] { 0.0f, 0.55f, 0.40f, 0.70f, 0.30f, 0.60f, 0.45f, 0.35f, 0.80f };
  24990. for (int id = 1; id <= lynx::goals::count; ++id)
  24991. dock->addOneKnobForCheck (id);
  24992. offline.dispatchPendingMessages();
  24993. for (int id = 1; id <= lynx::goals::count; ++id)
  24994. dock->turnKnobForCheck (id - 1, at[id]);
  24995. offline.dispatchPendingMessages();
  24996. check ("eight one-knob cards on the insert", dock->cardCountForCheck() == 8 && dock->oneKnobCardsForCheck() == 8);
  24997. {
  24998. const auto& fx = offline.getSong().mixer[(std::size_t) insert].effects;
  24999. bool turned = fx.size() == 8;
  25000. for (std::size_t i = 0; turned && i < fx.size(); ++i)
  25001. turned = lynx::goals::active (fx[i]) && std::abs (fx[i].goalAmount - at[i + 1]) < 1.0e-6f;
  25002. check ("each knob wrote its effect's parameters", turned);
  25003. }
  25004. shots ("effects-all");
  25005. offline.dispatchPendingMessages();
  25006. for (int card = 0; card < dock->cardCountForCheck(); ++card)
  25007. {
  25008. const auto area = dock->cardBoundsForSnapshot (card);
  25009. const auto name = juce::String (lynx::goals::name (card + 1)).toLowerCase();
  25010. check ("card " + juce::String (card + 1) + " (" + name + ") is on screen", ! area.isEmpty() && dock->getLocalBounds().contains (area));
  25011. for (float scale : { 1.0f, 2.0f })
  25012. writeImage (dock->createComponentSnapshot (area.expanded (4), true, scale), "card-" + name + (scale > 1.0f ? "@2x" : ""));
  25013. }
  25014. // --- a chain preset with Blend --------------------------------------------------------------------------------
  25015. if (const auto* preset = lynx::chains::find ("Canyon"))
  25016. offline.editSongStructural ([insert, preset] (lynx::Song& s) { lynx::chains::apply (s, insert, *preset); });
  25017. offline.dispatchPendingMessages();
  25018. dock->setBlendForCheck (0.6f);
  25019. offline.dispatchPendingMessages();
  25020. check ("preset Canyon with Blend 60 % (shown as edited)", offline.getSong().mixer[(std::size_t) insert].chainPreset == "Canyon"
  25021. && std::abs (offline.getSong().mixer[(std::size_t) insert].chainBlend - 0.6f) < 1.0e-6f
  25022. && ! lynx::chains::unchanged (offline.getSong(), insert));
  25023. shots ("effects-preset-blend");
  25024. // favourites: the track's preset starred; the menu lists it first
  25025. const auto favFile = lynx::SimpleDock::favouritesFile();
  25026. const auto hadFavourites = favFile.existsAsFile();
  25027. const auto oldFavourites = favFile.loadFileAsString();
  25028. lynx::SimpleDock::setFavouritePreset ("Canyon", true);
  25029. lynx::SimpleDock::setFavouritePreset ("Clear Voice", true);
  25030. lynx::SimpleDock::setFavouritePreset ("Canyon", true); // (twice: once in the list)
  25031. check ("two favourites kept, in order", lynx::SimpleDock::favouritePresets() == juce::StringArray { "Canyon", "Clear Voice" });
  25032. {
  25033. bool first = false, toggle = false;
  25034. const auto menu = dock->presetMenuForSnapshot();
  25035. juce::PopupMenu::MenuItemIterator it (menu);
  25036. if (it.next())
  25037. first = it.getItem().subMenu != nullptr && it.getItem().text.contains (lynx::tr ("Favourites"));
  25038. for (juce::PopupMenu::MenuItemIterator all (menu); all.next();)
  25039. toggle = toggle || all.getItem().text == lynx::tr ("Remove \"{0}\" from favourites", { "Canyon" });
  25040. check ("the Preset menu starts with the favourites and offers to unstar the track's preset", first && toggle);
  25041. menuShot (menu, lynx::tr ("Preset"), juce::String::fromUTF8 ("\xe2\x98\x85 ") + lynx::tr ("Favourites"), "menu-preset-favourites");
  25042. }
  25043. lynx::SimpleDock::setFavouritePreset ("Canyon", false);
  25044. check ("unstarred", lynx::SimpleDock::favouritePresets() == juce::StringArray { "Clear Voice" });
  25045. if (hadFavourites)
  25046. favFile.replaceWithText (oldFavourites);
  25047. else
  25048. favFile.deleteFile();
  25049. // --- the sound picker: a search, and the installed plugins -----------------------------------------------------
  25050. playlist.selectTrack (keysTrack);
  25051. offline.dispatchPendingMessages();
  25052. check ("the Keys track opens on its sound", dock->getTab() == lynx::SimpleDock::Tab::instrument);
  25053. dock->showCategoryForSnapshot ((int) lynx::soundlib::Category::bass);
  25054. dock->setSearchForSnapshot ("sub");
  25055. offline.dispatchPendingMessages();
  25056. line ("search \"sub\" in Bass: " + juce::String (dock->soundRowsForCheck()) + " rows");
  25057. check ("a search narrows the category", dock->soundRowsForCheck() > 0 && dock->soundRowsForCheck() < (int) lynx::soundlib::filter (lynx::soundlib::builtIn(), lynx::soundlib::Category::bass).size());
  25058. shots ("picker-search");
  25059. dock->setSearchForSnapshot ({});
  25060. // a made-up list of installed plugins (nothing is scanned or loaded)
  25061. dock->setPluginsForSnapshot ({ { "VST3-demo-1", "Analog Mono", "Example Audio", "VST3", "Instrument|Synth" },
  25062. { "VST3-demo-2", "Grand Upright", "Example Audio", "VST3", "Instrument|Piano" },
  25063. { "VST3-demo-3", "Beat Kit 808", "Sample Lab", "VST3", "Instrument|Drum" },
  25064. { "CLAP-demo-4", "Orchestra Strings", "Sample Lab", "CLAP", "Instrument|Sampler" },
  25065. { "VST3-demo-5", "Wave Table One", "Example Audio", "VST3", "Instrument|Synth" },
  25066. { "VST-demo-6", "Sub Bass Machine", "Low End", "VST", "Synth" },
  25067. { "VST3-demo-7", "Sample Player", "Sample Lab", "VST3", "Instrument|Sampler" } });
  25068. dock->showCategoryForSnapshot ((int) lynx::soundlib::Category::synths);
  25069. offline.dispatchPendingMessages();
  25070. check ("My plugins: the generic synths and samplers in their own category (" + juce::String (dock->soundRowsForCheck()) + " of 7)", dock->soundRowsForCheck() == 3);
  25071. shots ("picker-plugins");
  25072. line (report.contains ("ERROR ") ? "RESULT ERROR" : "RESULT OK");
  25073. juce::File (prefix + "-report.txt").replaceWithText (report);
  25074. }
  25075. // LYNX --simple190jcshot prefix (round 190jc, design190ia slices 5, 14, 15, 22, 24 + Large controls): the Simple
  25076. // layout's tracks (only real rows, the round "+", M S, type icons, the track-colour volume and clips; muted, soloed,
  25077. // selected), the drop lane idle and lit, the dock (close X, icon tabs, a lone tab, the sound picker, the keyboard's
  25078. // keycaps and octave capsule, effect cards), the pads in all 8 colours (label contrast measured), the chooser,
  25079. // starter beats, Finish, the tour card beside its ring with the beacon (Animations on / off), and Large controls;
  25080. // windows at 1x and 2x, and a text report of the checks
  25081. void runSimple190jcShot (const juce::String& prefix)
  25082. {
  25083. namespace st = lynx::simpletracks;
  25084. namespace sp = lynx::simplepads;
  25085. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  25086. lynx::AudioEngine offline (false);
  25087. lynx::MainComponent ui (offline, false);
  25088. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  25089. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  25090. ui.setVisible (true);
  25091. const auto writeImage = [&prefix] (const juce::Image& image, const juce::String& name) {
  25092. const auto file = juce::File (prefix + "-" + name + ".png");
  25093. file.deleteFile();
  25094. juce::FileOutputStream out (file);
  25095. juce::PNGImageFormat().writeImageToStream (image, out);
  25096. };
  25097. juce::String report;
  25098. const auto line = [&report, &prefix] (const juce::String& text) {
  25099. report << text << "\n";
  25100. juce::File (prefix + "-report.txt").replaceWithText (report);
  25101. };
  25102. const auto check = [&line] (const juce::String& what, bool ok) { line ((ok ? "OK " : "ERROR ") + what); };
  25103. const auto settle = [&] {
  25104. for (int k = 0; k < 3; ++k)
  25105. offline.dispatchPendingMessages();
  25106. };
  25107. const auto whole = [&] (const juce::String& name, bool twoX = true) {
  25108. settle();
  25109. writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, 1.0f), name);
  25110. if (twoX)
  25111. writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, 2.0f), name + "@2x");
  25112. };
  25113. ui.selectTabForSnapshot (2);
  25114. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  25115. settle();
  25116. auto* simple = ui.getSimpleWorkflowForSnapshot();
  25117. auto& playlist = ui.getPlaylistForSnapshot();
  25118. if (simple == nullptr)
  25119. {
  25120. line ("ERROR no Simple workflow");
  25121. return;
  25122. }
  25123. // an empty project: the drop lane alone, the round "+"
  25124. offline.setSong ([] {
  25125. lynx::Song s;
  25126. s.mixer = lynx::Song::defaultMixer();
  25127. return s;
  25128. }());
  25129. settle();
  25130. simple->hideChooser();
  25131. whole ("empty");
  25132. check ("an empty song shows one row (the drop lane), with the round +", st::rowsShown (offline.getSong(), 500) == 1 && ! playlist.simpleAddButtonForSnapshot().isEmpty());
  25133. // --- sounds ------------------------------------------------------------------------------------------------------
  25134. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-190jc");
  25135. dir.deleteRecursively();
  25136. dir.createDirectory();
  25137. const auto writeWav = [] (const juce::File& wav, int frames, const std::function<float (int)>& f) {
  25138. wav.getParentDirectory().createDirectory();
  25139. juce::AudioBuffer<float> audio (1, frames);
  25140. for (int i = 0; i < frames; ++i)
  25141. audio.setSample (0, i, f (i));
  25142. juce::WavAudioFormat format;
  25143. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  25144. if (auto* w = format.createWriterFor (out.get(), 48000.0, 1, 16, {}, 0))
  25145. {
  25146. out.release();
  25147. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  25148. writer->writeFromAudioSampleBuffer (audio, 0, frames);
  25149. }
  25150. return wav;
  25151. };
  25152. const auto pi = juce::MathConstants<double>::pi;
  25153. juce::Random rnd (190);
  25154. const auto loop = writeWav (dir.getChildFile ("Vocal chop 100.wav"), 230400, [pi] (int i) {
  25155. const auto t = i / 48000.0, inBeat = std::fmod (t, 0.6);
  25156. return (float) (0.7 * std::exp (-inBeat * 5.0) * std::sin (2.0 * pi * 220.0 * t + 1.5 * std::sin (2.0 * pi * 440.0 * t)));
  25157. });
  25158. std::vector<juce::File> padSounds;
  25159. const char* padNames[] { "Kick", "Snare", "Hat", "Clap", "Chord stab", "Vox hey", "Perc", "Bass hit" };
  25160. for (int k = 0; k < 8; ++k)
  25161. padSounds.push_back (writeWav (dir.getChildFile (juce::String ("pads/") + padNames[k] + ".wav"), 12000 + 3000 * k, [&rnd, k] (int i) {
  25162. return (float) ((rnd.nextFloat() * 2.0f - 1.0f) * 0.6f * std::exp (-i / (600.0f + 500.0f * (float) k)));
  25163. }));
  25164. // --- tracks: a voice with a loop, keys with chords, drums, a bass take, a Sampler track --------------------------------
  25165. int vocal = -1, keys = -1, drums = -1, bass = -1;
  25166. offline.editSong ([&] (lynx::Song& s) {
  25167. st::Request q;
  25168. q.kind = st::Kind::audio;
  25169. q.name = "Vocal chop";
  25170. q.audioFile = loop.getFullPathName().toStdString();
  25171. q.audioLength = 8 * lynx::ppq;
  25172. q.audioBeats = 8.0f;
  25173. vocal = st::addTrack (s, q).track;
  25174. q = {};
  25175. q.kind = st::Kind::instrument;
  25176. q.name = "Keys";
  25177. lynx::ChannelDef synth;
  25178. synth.instrument = lynx::InstrumentKind::synth;
  25179. q.channel = synth;
  25180. lynx::Pattern chords;
  25181. for (int i = 0; i < 4; ++i)
  25182. for (int k : { 60, 64, 67 })
  25183. chords.notes.push_back (lynx::Note { (std::int64_t) i * 4 * lynx::ppq, 4 * lynx::ppq - lynx::ppq / 4, 0, k });
  25184. q.pattern = chords;
  25185. const auto r = st::addTrack (s, q);
  25186. keys = r.track;
  25187. q = {};
  25188. q.kind = st::Kind::drums;
  25189. q.name = "Drums";
  25190. for (auto kind : { lynx::InstrumentKind::kick, lynx::InstrumentKind::snare, lynx::InstrumentKind::hat })
  25191. {
  25192. lynx::ChannelDef c;
  25193. c.instrument = kind;
  25194. q.kit.push_back (c);
  25195. }
  25196. lynx::Pattern beat;
  25197. for (int step = 0; step < 16; step += 2)
  25198. beat.notes.push_back (lynx::Note { (std::int64_t) step * lynx::ticksPerStep, lynx::ticksPerStep, 2, 60 });
  25199. for (int step : { 0, 8 })
  25200. beat.notes.push_back (lynx::Note { (std::int64_t) step * lynx::ticksPerStep, lynx::ticksPerStep, 0, 60 });
  25201. q.pattern = beat;
  25202. q.fillBars = 4;
  25203. const auto d = st::addTrack (s, q);
  25204. drums = d.track;
  25205. q = {};
  25206. q.kind = st::Kind::bass;
  25207. q.name = "Bass";
  25208. bass = st::addTrack (s, q).track;
  25209. if (r.insert > 0)
  25210. {
  25211. s.mixer[(std::size_t) r.insert].volume = 0.55f;
  25212. s.mixer[(std::size_t) r.insert].pan = -0.4f;
  25213. s.mixer[(std::size_t) r.insert].solo = true;
  25214. }
  25215. if (d.insert > 0)
  25216. s.mixer[(std::size_t) d.insert].muted = true;
  25217. });
  25218. settle();
  25219. check ("the Sampler tile's track was added", simple->addPads());
  25220. settle();
  25221. const auto& song = offline.getSong();
  25222. int pads = -1;
  25223. for (int t = 0; t < (int) song.playlistTracks.size() && pads < 0; ++t)
  25224. if (st::kindOf (song, t) == st::Kind::pads)
  25225. pads = t;
  25226. lynx::ui::WaveformCache::getInstance()->find (loop.getFullPathName(), [&offline, &loop] { return offline.getSampleLibrary().load (loop.getFullPathName()); });
  25227. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (30000);
  25228. simple->hideChooser();
  25229. playlist.selectTrack (keys);
  25230. settle();
  25231. const auto rows = st::rowsShown (song, 500);
  25232. line ("tracks: vocal " + juce::String (vocal) + " keys " + juce::String (keys) + " drums " + juce::String (drums) + " bass " + juce::String (bass)
  25233. + " pads " + juce::String (pads) + "; rows shown " + juce::String (rows));
  25234. check ("five tracks + the drop lane are the rows shown (no placeholder rows)", rows == 6);
  25235. whole ("tracks");
  25236. {
  25237. // the Simple Playlist's whole paint (its rows only, no placeholder rows): CPU ms per frame
  25238. juce::Image img (juce::Image::ARGB, juce::jmax (1, playlist.getWidth()), juce::jmax (1, playlist.getHeight()), true);
  25239. std::vector<double> ms;
  25240. for (int f = -3; f < 40; ++f)
  25241. {
  25242. const auto t0 = lynx::threadCpuSeconds();
  25243. {
  25244. juce::Graphics g (img);
  25245. playlist.paintEntireComponent (g, true);
  25246. }
  25247. if (f >= 0)
  25248. ms.push_back (1000.0 * (lynx::threadCpuSeconds() - t0));
  25249. }
  25250. std::sort (ms.begin(), ms.end());
  25251. line ("simple playlist " + juce::String (playlist.getWidth()) + "x" + juce::String (playlist.getHeight()) + " whole paint: median "
  25252. + juce::String (ms[ms.size() / 2], 3) + " ms, p90 " + juce::String (ms[ms.size() * 9 / 10], 3) + " ms");
  25253. }
  25254. playlist.setDropLaneHotForSnapshot (true);
  25255. whole ("droplane-hot", false);
  25256. playlist.setDropLaneHotForSnapshot (false);
  25257. // --- the dock ------------------------------------------------------------------------------------------------------
  25258. auto* dock = simple->dockForSnapshot();
  25259. if (dock == nullptr)
  25260. {
  25261. line ("ERROR no dock");
  25262. return;
  25263. }
  25264. const auto dockShots = [&] (const juce::String& name) {
  25265. settle();
  25266. for (float scale : { 1.0f, 2.0f })
  25267. writeImage (dock->createComponentSnapshot (dock->getLocalBounds(), true, scale), "dock-" + name + (scale > 1.0f ? "@2x" : ""));
  25268. };
  25269. simple->trackSelected (keys);
  25270. dock->setTab (lynx::SimpleDock::Tab::instrument);
  25271. dockShots ("instrument");
  25272. whole ("window-dock-instrument", false);
  25273. dock->showKeyboard();
  25274. dockShots ("keyboard");
  25275. simple->trackSelected (vocal);
  25276. settle();
  25277. check ("an audio track's dock has one tab (drawn as a title)", dock->getTab() == lynx::SimpleDock::Tab::effects);
  25278. dockShots ("audio-lone-tab");
  25279. simple->showEffectsOfInsert (st::insertOf (offline.getSong(), keys));
  25280. dock->addOneKnobForCheck (1);
  25281. dock->addOneKnobForCheck (2);
  25282. dockShots ("effects");
  25283. // --- pads: 8 sounds in the 8 colours --------------------------------------------------------------------------------
  25284. if (pads >= 0)
  25285. {
  25286. simple->trackSelected (pads);
  25287. settle();
  25288. for (int p = 0; p < 8; ++p)
  25289. dock->padsLoadForCheck (p, padSounds[(std::size_t) p]);
  25290. offline.editSong ([pads] (lynx::Song& s) {
  25291. for (int p = 0; p < 8; ++p)
  25292. if (const auto c = sp::padChannel (s, pads, p); c >= 0)
  25293. s.channels[(std::size_t) c].simplePad.colour = (std::uint8_t) (p + 1);
  25294. });
  25295. dock->padsSelectForCheck (4);
  25296. dock->padsUpdateForCheck();
  25297. dockShots ("pads");
  25298. dock->padsHitForCheck (2);
  25299. dockShots ("pads-hit");
  25300. whole ("window-pads", false);
  25301. // the labels' contrast on the 8 colours, unlit and lit (the same colours the page draws)
  25302. static const juce::uint32 palette[] { 0xffe5383b, 0xffe8833a, 0xffe2c044, 0xff5fbf6a, 0xff3fb6b0, 0xff4f8ee0, 0xff9a6fe0, 0xffe06aa8 };
  25303. float worst = 99.0f;
  25304. for (auto argb : palette)
  25305. for (bool lit : { false, true })
  25306. {
  25307. const auto fill = juce::Colour (argb).withMultipliedBrightness (lit ? 1.0f : 0.55f).withMultipliedSaturation (lit ? 1.0f : 0.8f);
  25308. const auto ratio = lynx::ui::simplelook::contrast (lynx::ui::simplelook::inkOn (fill), fill);
  25309. worst = juce::jmin (worst, ratio);
  25310. line ("pad " + juce::String::toHexString ((int) argb).substring (2) + (lit ? " lit " : " unlit") + ": label " + juce::String (ratio, 2) + ":1");
  25311. }
  25312. check ("pad labels >= 4.5:1 on all 8 colours, lit and unlit (worst " + juce::String (worst, 2) + ":1)", worst >= 4.5f);
  25313. }
  25314. // --- chooser, starters, Finish ---------------------------------------------------------------------------------------
  25315. simple->showChooser();
  25316. whole ("chooser");
  25317. simple->showStarterPageForSnapshot();
  25318. whole ("starters");
  25319. simple->hideChooser();
  25320. simple->showFinish();
  25321. whole ("finish");
  25322. simple->hideFinish();
  25323. // --- the tour: the card beside its ring, the beacon with Animations on and off -----------------------------------------
  25324. if (auto* tour = simple->tourForSnapshot())
  25325. {
  25326. simple->showWelcome();
  25327. settle();
  25328. tour->clickForSnapshot ("welcome.tour");
  25329. settle();
  25330. const auto ring = tour->ringForSnapshot();
  25331. const auto card = tour->cardBoundsForSnapshot();
  25332. const auto distance = juce::jmax (0, juce::jmax (card.getY() - ring.getBottom(), ring.getY() - card.getBottom()))
  25333. + juce::jmax (0, juce::jmax (card.getX() - ring.getRight(), ring.getX() - card.getRight()));
  25334. line ("tour step 1: ring " + ring.toString() + " card " + card.toString() + " gap " + juce::String (distance) + " px");
  25335. check ("the card sits beside its ring (<= 24 px)", ! ring.isEmpty() && distance <= 24 && ! card.intersects (ring));
  25336. check ("the beacon pulses after a step change (Animations on)", tour->pulsingForCheck());
  25337. tour->setPulseForSnapshot (0.5f);
  25338. whole ("tour-pulse-on", false);
  25339. lynx::ui::motion::enabled() = false;
  25340. tour->clickForSnapshot ("next");
  25341. settle();
  25342. check ("no pulse timer with Animations off", ! tour->pulsingForCheck());
  25343. tour->setPulseForSnapshot (0.0f);
  25344. whole ("tour-pulse-off", false);
  25345. lynx::ui::motion::enabled() = true;
  25346. tour->clickForSnapshot ("skip");
  25347. settle();
  25348. }
  25349. // --- Large controls ---------------------------------------------------------------------------------------------------
  25350. ui.setSimpleLargeControls (true);
  25351. simple->hideChooser();
  25352. playlist.selectTrack (keys);
  25353. settle();
  25354. whole ("large-tracks", false);
  25355. if (pads >= 0)
  25356. {
  25357. simple->trackSelected (pads);
  25358. dockShots ("large-pads");
  25359. }
  25360. ui.setSimpleLargeControls (false);
  25361. line ("done");
  25362. }
  25363. void runSimpleShot (const juce::String& prefix)
  25364. {
  25365. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  25366. lynx::AudioEngine offline (false);
  25367. lynx::MainComponent ui (offline, false);
  25368. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  25369. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  25370. const auto writeImage = [&prefix] (const juce::Image& image, const char* name) {
  25371. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  25372. file.deleteFile();
  25373. juce::FileOutputStream out (file);
  25374. juce::PNGImageFormat().writeImageToStream (image, out);
  25375. };
  25376. const auto write = [&ui, &writeImage] (const char* name) { writeImage (lynx::shot::snapshot (ui), name); };
  25377. // View › Layout style, with its submenu, as it is with `style` chosen
  25378. const auto viewMenu = [&ui] {
  25379. const auto names = ui.getMenuNamesForSnapshot();
  25380. const auto view = names.indexOf (lynx::tr ("View"));
  25381. return ui.getMenuForSnapshot (juce::jmax (0, view));
  25382. };
  25383. const auto saveStyleMenus = [&] (const juce::String& suffix) {
  25384. const auto view = viewMenu();
  25385. juce::StringArray names { lynx::tr ("View") };
  25386. std::vector<juce::PopupMenu> menus { view };
  25387. for (juce::PopupMenu::MenuItemIterator it (view); it.next();)
  25388. if (it.getItem().subMenu != nullptr && it.getItem().text == lynx::tr ("Layout style"))
  25389. {
  25390. names.add (lynx::tr ("Layout style"));
  25391. menus.push_back (*it.getItem().subMenu);
  25392. }
  25393. saveMenus (names, menus, prefix + "-menu-" + suffix + ".png");
  25394. };
  25395. // Settings › General with `style` selected, and its style list
  25396. const auto saveSettings = [&] (lynx::layoutstyle::Style style, const char* name) {
  25397. lynx::SettingsHooks hooks;
  25398. hooks.getGeneral = [style] {
  25399. lynx::GeneralOptions o;
  25400. o.language = lynx::i18n::current();
  25401. o.layoutStyle = (int) style;
  25402. return o;
  25403. };
  25404. auto page = lynx::makeSettingsPanel (offline, lynx::SettingsPage::general, false, hooks);
  25405. const auto image = lynx::shot::paint (*page, lynx::theme::panel, -1, juce::jmin (page->getHeight(), 420));
  25406. writeImage (image, name);
  25407. std::function<juce::ComboBox* (juce::Component&)> find = [&find] (juce::Component& c) -> juce::ComboBox* {
  25408. if (c.getComponentID() == "layoutStyle")
  25409. return dynamic_cast<juce::ComboBox*> (&c);
  25410. for (auto* child : c.getChildren())
  25411. if (auto* box = find (*child))
  25412. return box;
  25413. return nullptr;
  25414. };
  25415. if (auto* box = find (*page); box != nullptr && box->getRootMenu() != nullptr)
  25416. saveMenus (juce::StringArray { lynx::tr ("Layout style") }, std::vector<juce::PopupMenu> { *box->getRootMenu() },
  25417. prefix + "-" + name + "-list.png");
  25418. };
  25419. const auto madeBefore = lynx::SimpleWorkflow::instances.load();
  25420. ui.selectTabForSnapshot (2); // the Playlist panel, maximized (as --gridshot)
  25421. write ("pattern");
  25422. saveStyleMenus ("pattern");
  25423. saveSettings (lynx::layoutstyle::Style::pattern, "settings-pattern");
  25424. const auto madePattern = lynx::SimpleWorkflow::instances.load();
  25425. ui.setLayoutStyle (lynx::layoutstyle::Style::clipLaunch);
  25426. saveStyleMenus ("cliplaunch");
  25427. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  25428. offline.dispatchPendingMessages();
  25429. if (auto* simple = ui.getSimpleWorkflowForSnapshot())
  25430. simple->showChooser(); // (an empty project opens on it by itself; the offline project may hold the default song)
  25431. write ("simple"); // the New track chooser (slice S3)
  25432. if (auto* simple = ui.getSimpleWorkflowForSnapshot())
  25433. {
  25434. simple->showStarterPageForSnapshot();
  25435. write ("simple-starter");
  25436. simple->hideChooser();
  25437. write ("simple-closed");
  25438. // round 190p: a loop keeps time. Two files with the same 4.8 s of audio dropped on the empty Simple timeline:
  25439. // "Guitar loop 100.wav" (2 bars at 100 BPM) lasts 2 bars at the project's tempo, "Guitar take.wav" plays at
  25440. // its own speed. Both are undone again, so the shots after this one are as they were.
  25441. {
  25442. const auto folder = juce::File (prefix + "-loops");
  25443. folder.createDirectory();
  25444. juce::StringArray files;
  25445. for (const auto* name : { "Guitar loop 100.wav", "Guitar take.wav" })
  25446. {
  25447. const auto file = folder.getChildFile (name);
  25448. file.deleteFile();
  25449. const auto rate = 44100.0;
  25450. const auto frames = (int) (4.8 * rate);
  25451. juce::AudioBuffer<float> audio (1, frames);
  25452. for (int i = 0; i < frames; ++i)
  25453. {
  25454. const auto t = (double) i / rate, inBeat = std::fmod (t, 0.6); // a plucked note on every beat at 100 BPM
  25455. audio.setSample (0, i, (float) (0.7 * std::exp (-inBeat * 7.0) * std::sin (juce::MathConstants<double>::twoPi * 196.0 * t)));
  25456. }
  25457. if (auto out = file.createOutputStream())
  25458. if (auto writer = std::unique_ptr<juce::AudioFormatWriter> (juce::WavAudioFormat().createWriterFor (out.get(), rate, 1, 16, {}, 0)))
  25459. {
  25460. out.release();
  25461. writer->writeFromAudioSampleBuffer (audio, 0, frames);
  25462. }
  25463. files.add (file.getFullPathName());
  25464. }
  25465. simple->dropFiles (files, 0);
  25466. offline.dispatchPendingMessages();
  25467. // the clips' waveforms are analysed in the background and drawn once ready (a live window repaints by
  25468. // itself; one off-screen paint came too early and showed empty clips)
  25469. for (const auto& path : files)
  25470. lynx::ui::WaveformCache::getInstance()->find (path, [&offline, path] { return offline.getSampleLibrary().load (path); });
  25471. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (30000);
  25472. offline.dispatchPendingMessages();
  25473. write ("simple-loop");
  25474. const auto& song = offline.getSong();
  25475. juce::String report;
  25476. for (const auto& clip : song.playlist)
  25477. if (clip.kind == lynx::ClipKind::audio)
  25478. report << song.channels[(std::size_t) clip.channel].name << ": " << juce::String ((double) clip.length / lynx::ppq, 3) << " beats, stretch "
  25479. << juce::String (song.channels[(std::size_t) clip.channel].sampler.stretchBeats, 2) << "\n";
  25480. juce::File (prefix + "-loop.txt").replaceWithText ("tempo " + juce::String (song.bpm, 1) + "\n" + report);
  25481. for (int i = 0; i < files.size() && offline.canUndo(); ++i) // (one undo step per dropped file)
  25482. offline.undo();
  25483. offline.dispatchPendingMessages();
  25484. simple->hideChooser();
  25485. }
  25486. // round 190t, slice A: one click on a starter beat adds it, placed for four bars (undone again)
  25487. {
  25488. const auto clipsBefore = offline.getSong().playlist.size();
  25489. const auto tempoBefore = offline.getSong().bpm;
  25490. simple->clickStarterForSnapshot (1);
  25491. offline.dispatchPendingMessages();
  25492. write ("simple-starter-added");
  25493. const auto& song = offline.getSong();
  25494. juce::String report ("tempo " + juce::String (tempoBefore, 1) + " -> " + juce::String (song.bpm, 1) + "\n");
  25495. for (auto i = clipsBefore; i < song.playlist.size(); ++i)
  25496. report << "clip at beat " << juce::String ((double) song.playlist[i].start / lynx::ppq, 2) << ", " << juce::String ((double) song.playlist[i].length / lynx::ppq, 2)
  25497. << " beats, pattern " << song.playlist[i].pattern << ", track " << song.playlist[i].track << "\n";
  25498. juce::File (prefix + "-starter.txt").replaceWithText (report);
  25499. if (song.playlist.size() > clipsBefore && offline.canUndo())
  25500. offline.undo();
  25501. offline.dispatchPendingMessages();
  25502. simple->hideChooser();
  25503. }
  25504. // slice S4: the Simple headers with a few tracks (voice, instrument, drums, an audio file), some levels moved
  25505. offline.editSong ([] (lynx::Song& s) {
  25506. namespace st = lynx::simpletracks;
  25507. st::Request q;
  25508. q.kind = st::Kind::voice;
  25509. q.name = "Lead vocal";
  25510. st::addTrack (s, q);
  25511. q = {};
  25512. q.kind = st::Kind::instrument;
  25513. q.name = "Keys";
  25514. lynx::ChannelDef keys;
  25515. keys.instrument = lynx::InstrumentKind::synth;
  25516. q.channel = keys;
  25517. lynx::Pattern chords;
  25518. for (int i = 0; i < 4; ++i)
  25519. for (int k : { 60, 64, 67 })
  25520. chords.notes.push_back (lynx::Note { (std::int64_t) i * 4 * lynx::ppq, 4 * lynx::ppq - lynx::ppq / 4, 0, k });
  25521. q.pattern = chords;
  25522. const auto r = st::addTrack (s, q);
  25523. q = {};
  25524. q.kind = st::Kind::drums;
  25525. for (auto kind : { lynx::InstrumentKind::kick, lynx::InstrumentKind::snare, lynx::InstrumentKind::hat })
  25526. {
  25527. lynx::ChannelDef c;
  25528. c.instrument = kind;
  25529. c.name = kind == lynx::InstrumentKind::kick ? "Kick" : kind == lynx::InstrumentKind::snare ? "Snare" : "Hat";
  25530. q.kit.push_back (c);
  25531. }
  25532. lynx::Pattern beat;
  25533. const auto hit = [&beat] (int step, int row) { beat.notes.push_back (lynx::Note { (std::int64_t) step * lynx::ticksPerStep, lynx::ticksPerStep, row, 60 }); };
  25534. for (int step = 0; step < 16; step += 2)
  25535. hit (step, 2); // hats on the 8ths, kick on 1 and 3, snare on 2 and 4
  25536. for (int step : { 0, 8 })
  25537. hit (step, 0);
  25538. for (int step : { 4, 12 })
  25539. hit (step, 1);
  25540. q.pattern = beat;
  25541. q.bpm = 96.0;
  25542. st::addTrack (s, q);
  25543. if (r.insert > 0)
  25544. {
  25545. s.mixer[(std::size_t) r.insert].volume = 0.55f;
  25546. s.mixer[(std::size_t) r.insert].pan = -0.4f;
  25547. s.mixer[(std::size_t) r.insert].solo = true;
  25548. }
  25549. });
  25550. offline.dispatchPendingMessages();
  25551. ui.getPlaylistForSnapshot().selectTrack (1);
  25552. write ("simple-tracks");
  25553. // round 190t, slice E: the backup status beside the title tools, in each of its states
  25554. {
  25555. const auto now = juce::Time::currentTimeMillis();
  25556. juce::String states;
  25557. int n = 0;
  25558. for (const auto& text : { lynx::MainComponent::simpleSaveStatusText (true, false, 0, now), lynx::MainComponent::simpleSaveStatusText (true, false, now - 5000, now),
  25559. lynx::MainComponent::simpleSaveStatusText (true, true, now - 125000, now), lynx::MainComponent::simpleSaveStatusText (false, true, 0, now),
  25560. lynx::MainComponent::simpleSaveStatusText (false, false, 0, now) })
  25561. {
  25562. simple->setStatusForSnapshot (text);
  25563. offline.dispatchPendingMessages();
  25564. states << n << ": " << text << "\n";
  25565. writeImage (lynx::shot::snapshot (ui, ui.getLocalBounds().withTop (juce::jmin (ui.getHeight() - 1, 70)).withHeight (juce::jmin (ui.getHeight(), 44))),
  25566. ("status-" + juce::String (n++)).toRawUTF8());
  25567. }
  25568. juce::File (prefix + "-status.txt").replaceWithText (states);
  25569. simple->setStatusForSnapshot (lynx::MainComponent::simpleSaveStatusText (true, true, now - 125000, now));
  25570. offline.dispatchPendingMessages();
  25571. write ("simple-status");
  25572. }
  25573. // slice S8: the Finish dock, empty, then with a look on the Master (Balanced, Normal, a little Tone)
  25574. simple->showFinish();
  25575. offline.dispatchPendingMessages();
  25576. write ("simple-finish-empty");
  25577. offline.editSongStructural ([] (lynx::Song& s) { lynx::looks::apply (s, lynx::MasterLookSettings { lynx::looks::balanced, 0.5f, { 1.5f, 0.0f, 1.0f }, -3.0f }); });
  25578. offline.dispatchPendingMessages();
  25579. simple->showFinish();
  25580. write ("simple-finish");
  25581. simple->hideFinish();
  25582. }
  25583. saveStyleMenus ("simple");
  25584. saveSettings (lynx::layoutstyle::Style::simple, "settings-simple");
  25585. // round 184a S11: the Key panel (no key, then an A minor riff and its guesses) and its menu
  25586. const auto toolbarShot = [&] (const char* name) {
  25587. writeImage (lynx::shot::snapshot (ui, ui.getLocalBounds().withHeight (juce::jmin (ui.getHeight(), 80))), name);
  25588. };
  25589. toolbarShot ("key-none");
  25590. saveMenus (juce::StringArray { lynx::tr ("Key") }, std::vector<juce::PopupMenu> { ui.getKeyMenuForSnapshot() }, prefix + "-key-menu-empty.png");
  25591. offline.editSong ([] (lynx::Song& s) {
  25592. if (s.channels.empty())
  25593. s.channels.resize (1);
  25594. if (s.patterns.empty())
  25595. s.patterns.emplace_back();
  25596. int t = 0;
  25597. for (int k : { 57, 60, 64, 67, 69, 67, 64, 60, 57, 59, 60, 62, 64, 62, 60, 59, 57, 57, 64, 45 })
  25598. {
  25599. lynx::Note n;
  25600. n.channel = 0;
  25601. n.key = k;
  25602. n.start = t * lynx::ppq / 2;
  25603. n.length = k == 57 || k == 45 ? lynx::ppq : lynx::ppq / 2;
  25604. s.patterns[0].notes.push_back (n);
  25605. ++t;
  25606. }
  25607. });
  25608. offline.dispatchPendingMessages();
  25609. saveMenus (juce::StringArray { lynx::tr ("Key") }, std::vector<juce::PopupMenu> { ui.getKeyMenuForSnapshot() }, prefix + "-key-menu-guess.png");
  25610. const auto guesses = lynx::keyguess::guess (offline.getSong(), 3);
  25611. if (! guesses.empty())
  25612. offline.editSong ([k = guesses[0].key] (lynx::Song& s) { lynx::projectkey::set (s, k); });
  25613. offline.dispatchPendingMessages();
  25614. toolbarShot ("key-set");
  25615. write ("simple-key");
  25616. juce::String keyCounts;
  25617. for (const auto& g : guesses)
  25618. keyCounts << "guess " << lynx::projectkey::name (g.key) << " " << g.notesInScale << "/" << g.notes << " score " << g.score << "\n";
  25619. offline.editSong ([] (lynx::Song& s) { lynx::projectkey::set (s, std::nullopt); });
  25620. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
  25621. offline.dispatchPendingMessages();
  25622. toolbarShot ("key-pattern-toolbar");
  25623. write ("pattern-after");
  25624. // round 184a S17: the setup wizard with its Workflow choice — a first start (Pattern selected), then reopened in Simple
  25625. for (int style : { 0, 2 })
  25626. {
  25627. auto wizard = lynx::makeSetupWizardContent (offline, {}, {}, style, {});
  25628. auto image = lynx::shot::paint (*wizard);
  25629. writeImage (image, style == 0 ? "wizard-pattern" : "wizard-simple");
  25630. }
  25631. juce::File (prefix + "-counts.txt").replaceWithText ("simple workflows before " + juce::String (madeBefore) + ", in pattern workflow "
  25632. + juce::String (madePattern) + ", after " + juce::String (lynx::SimpleWorkflow::instances.load())
  25633. + "\nstyle after " + lynx::layoutstyle::id (ui.getLayoutStyle()) + "\n" + keyCounts);
  25634. }
  25635. void runLiveRackShot190hr (const juce::String& prefix)
  25636. {
  25637. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  25638. lynx::AudioEngine offline (false);
  25639. lynx::MainComponent ui (offline, false);
  25640. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  25641. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  25642. const auto write = [&prefix, &ui, &offline] (const char* name) {
  25643. offline.dispatchPendingMessages();
  25644. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  25645. file.deleteFile();
  25646. juce::FileOutputStream out (file);
  25647. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (ui), out);
  25648. };
  25649. const auto writeView = [&prefix] (juce::Component& c, const char* name) {
  25650. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  25651. file.deleteFile();
  25652. juce::FileOutputStream out (file);
  25653. juce::PNGImageFormat().writeImageToStream (lynx::shot::paint (c, lynx::theme::panel), out);
  25654. };
  25655. juce::String checks;
  25656. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  25657. const auto itemEnabled = [] (const juce::PopupMenu& menu, const juce::String& start) {
  25658. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  25659. if (it.getItem().text.startsWith (start))
  25660. return it.getItem().isEnabled ? 1 : 0;
  25661. return -1;
  25662. };
  25663. ui.setVisible (true);
  25664. lynx::DetailView::shownSetting = lynx::DetailView::devicesPage = true;
  25665. ui.setClipLaunchWorkflow (true);
  25666. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::browser, lynx::workspace::Panel::playlist });
  25667. offline.editSong ([] (lynx::Song& s) {
  25668. if (s.channels.size() < 1)
  25669. s.channels.resize (1);
  25670. s.channels[0].name = "Lead";
  25671. s.channels[0].instrument = lynx::InstrumentKind::synth;
  25672. s.channels[0].mixerTrack = 2;
  25673. if (s.mixer.size() < 4)
  25674. s.mixer.resize (4);
  25675. s.mixer[2].name = "Lead";
  25676. s.mixer[2].effects.clear();
  25677. for (auto kind : { lynx::EffectKind::eq, lynx::EffectKind::delay })
  25678. s.mixer[2].effects.push_back (lynx::makeEffectSlot (kind));
  25679. while (s.patterns.size() < 1)
  25680. s.patterns.emplace_back();
  25681. lynx::Note note;
  25682. note.channel = 0;
  25683. note.key = 60;
  25684. s.patterns[0].notes = { note };
  25685. s.patterns[0].lengthTicks = 4 * lynx::ppq;
  25686. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 3));
  25687. s.playlistTracks[1].name = "Lead";
  25688. lynx::Clip clip;
  25689. clip.pattern = 0;
  25690. clip.length = 4 * lynx::ppq;
  25691. lynx::launcher::setClip (s, 1, 0, clip);
  25692. }, false);
  25693. offline.dispatchPendingMessages();
  25694. auto* detail = ui.getDetailViewForSnapshot();
  25695. if (detail == nullptr)
  25696. {
  25697. juce::File (prefix + "-checks.txt").replaceWithText ("FAIL no detail view\n");
  25698. return;
  25699. }
  25700. detail->showSelection (1, 0);
  25701. detail->setPage (lynx::DetailView::Page::devices);
  25702. detail->selectCardForCheck (0); // the instrument
  25703. write ("01-devices");
  25704. auto menu = detail->cardMenuForSnapshot (0);
  25705. saveMenus (juce::StringArray { "Instrument" }, std::vector<juce::PopupMenu> { menu }, prefix + "-02-instrument-menu.png");
  25706. check ("instrument menu: Group on, Ungroup off", itemEnabled (menu, lynx::tr ("Group")) == 1 && itemEnabled (menu, lynx::tr ("Ungroup")) == 0);
  25707. // Ctrl+G: the synth into an Instrument Rack (the card becomes the rack's)
  25708. check ("Ctrl+G groups the instrument into an Instrument Rack", detail->groupCardForCheck (0, false));
  25709. const auto& grouped = offline.getSong().channels[0];
  25710. check ("the channel keeps its insert and the rack holds the synth",
  25711. grouped.mixerTrack == 2 && lynx::rack::isRack (grouped) && lynx::rack::rackOf (grouped.patcher)->kind == lynx::RackDoc::Kind::instrument
  25712. && lynx::rack::devices (*lynx::rack::rackOf (grouped.patcher), 0).size() == 1);
  25713. detail->selectCardForCheck (0);
  25714. write ("03-grouped");
  25715. menu = detail->cardMenuForSnapshot (0);
  25716. saveMenus (juce::StringArray { "Instrument Rack" }, std::vector<juce::PopupMenu> { menu }, prefix + "-04-rack-menu.png");
  25717. check ("rack menu: Ungroup on, Save as Live rack preset", itemEnabled (menu, lynx::tr ("Ungroup")) == 1
  25718. && itemEnabled (menu, lynx::tr ("Save as Live rack preset (.adg)...")) == 1);
  25719. check ("Ctrl+Shift+G ungroups it", detail->groupCardForCheck (0, true) && offline.getSong().channels[0].instrument == lynx::InstrumentKind::synth);
  25720. write ("05-ungrouped");
  25721. // a rack's view: Live's Save Preset button at the foot of the strip, the drop area
  25722. offline.editSong ([] (lynx::Song& s) {
  25723. auto rack = lynx::rack::makeRackSlot (lynx::RackDoc::Kind::audioEffect);
  25724. lynx::rack::rackOf (rack.patcher)->showDevices = true;
  25725. s.mixer[3].effects = { rack };
  25726. }, false);
  25727. offline.dispatchPendingMessages();
  25728. {
  25729. auto view = lynx::RackWindows::makeSlotView (offline, 3, 0, true);
  25730. view->setSize (std::max (520, view->preferredWidth (228)), 228);
  25731. writeView (*view, "06-rack-empty");
  25732. lynx::PatchNode fx;
  25733. fx.effect = lynx::makeEffectSlot (lynx::EffectKind::delay);
  25734. const juce::Point<int> inDevices { view->getWidth() - 30, view->getHeight() / 2 };
  25735. check ("an effect dropped on the chain goes in", view->dropNodeForCheck (fx, inDevices));
  25736. lynx::PatchNode synth;
  25737. synth.generator = true;
  25738. synth.channel.instrument = lynx::InstrumentKind::synth;
  25739. check ("an instrument dropped on an Audio Effect Rack is refused", ! view->dropNodeForCheck (synth, inDevices));
  25740. const auto* r = lynx::rack::rackOf (offline.getSong().mixer[3].effects[0].patcher);
  25741. check ("the chain holds one device", r != nullptr && lynx::rack::devices (*r, 0).size() == 1);
  25742. view->setSize (std::max (520, view->preferredWidth (228)), 228);
  25743. writeView (*view, "07-rack-after-drop");
  25744. // the rack as a Live preset and back
  25745. const auto out = lynx::exportLiveRackPreset (offline.getSong().mixer[3].effects[0].patcher, "Shot Rack");
  25746. check ("Save as .adg writes Live's preset form", out.xml.find ("<GroupDevicePreset>") != std::string::npos
  25747. && out.xml.find ("<AudioEffectBranchPreset ") != std::string::npos);
  25748. const auto back = lynx::importLiveDevicePreset (out.bytes);
  25749. check ("the .adg reads back as the rack", back.has_value() && lynx::rack::isRack (back->slot)
  25750. && lynx::rack::rackOf (back->slot.patcher)->chains.size() == 1);
  25751. }
  25752. // Live's own .adg (Core Library, read-only): before round 190hr it opened without chains
  25753. const juce::File live ("C:/ProgramData/Ableton/Live 12 Trial/Resources/Core Library/Racks/Audio Effect Racks/Distortion/Smokey Water.adg");
  25754. const juce::File liveWsl ("/mnt/c/ProgramData/Ableton/Live 12 Trial/Resources/Core Library/Racks/Audio Effect Racks/Distortion/Smokey Water.adg");
  25755. const auto adg = live.existsAsFile() ? live : liveWsl;
  25756. if (adg.existsAsFile())
  25757. {
  25758. juce::MemoryBlock data;
  25759. adg.loadFileAsData (data);
  25760. const auto* bytes = static_cast<const std::uint8_t*> (data.getData());
  25761. auto p = lynx::importLiveDevicePreset (std::vector<std::uint8_t> (bytes, bytes + data.getSize()));
  25762. check ("Live's Smokey Water.adg opens with its chain and devices", p.has_value() && lynx::rack::isRack (p->slot)
  25763. && ! lynx::rack::rackOf (p->slot.patcher)->chains.empty()
  25764. && lynx::rack::devices (*lynx::rack::rackOf (p->slot.patcher), 0).size() >= 3);
  25765. if (p)
  25766. {
  25767. lynx::rack::rackOf (p->slot.patcher)->showDevices = true;
  25768. lynx::rack::rackOf (p->slot.patcher)->showChains = true;
  25769. offline.editSong ([slot = p->slot] (lynx::Song& s) { s.mixer[3].effects = { slot }; }, false);
  25770. offline.dispatchPendingMessages();
  25771. auto view = lynx::RackWindows::makeSlotView (offline, 3, 0, true);
  25772. view->setSize (std::max (520, view->preferredWidth (228)), 228);
  25773. writeView (*view, "08-live-adg-smokey-water");
  25774. }
  25775. }
  25776. else
  25777. checks << "skip Live's Core Library is not on this machine\n";
  25778. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  25779. }
  25780. void runHelixShot190ja (const juce::String& prefix, const juce::String& preset)
  25781. {
  25782. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  25783. lynx::AudioEngine offline (false);
  25784. lynx::MainComponent ui (offline, false);
  25785. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1920x1080"), "x", "");
  25786. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  25787. juce::String checks;
  25788. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  25789. const auto write = [&prefix, &ui, &offline] (const char* name) {
  25790. offline.dispatchPendingMessages();
  25791. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  25792. file.deleteFile();
  25793. juce::FileOutputStream out (file);
  25794. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (ui), out);
  25795. };
  25796. // the Helix channel: Helix's defaults, or a Live Wavetable preset's values through the .als import's own mapping
  25797. lynx::ChannelDef helix;
  25798. helix.instrument = lynx::InstrumentKind::helix;
  25799. helix.name = "Helix";
  25800. if (preset.isNotEmpty())
  25801. {
  25802. juce::MemoryBlock raw;
  25803. juce::File (preset).loadFileAsData (raw);
  25804. juce::MemoryInputStream in (raw, false);
  25805. juce::GZIPDecompressorInputStream gz (&in, false, juce::GZIPDecompressorInputStream::gzipFormat);
  25806. const auto text = juce::File (preset).getFileExtension() == ".adv" ? gz.readEntireStreamAsString() : juce::String();
  25807. lynx::xml::Document doc;
  25808. lynx::alsdev::Notes notes;
  25809. const auto parsed = doc.parse (text.toStdString());
  25810. auto device = parsed ? doc.root().child ("InstrumentVector") : lynx::xml::Element();
  25811. check ("preset read: " + preset, parsed && (bool) device && lynx::alsdev::wavetableToHelix (device, helix, notes));
  25812. helix.name = juce::File (preset).getFileNameWithoutExtension().toStdString();
  25813. }
  25814. ui.setVisible (true);
  25815. lynx::DetailView::shownSetting = lynx::DetailView::devicesPage = true;
  25816. ui.setClipLaunchWorkflow (true);
  25817. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::playlist });
  25818. offline.editSong ([&helix] (lynx::Song& s) {
  25819. if (s.channels.empty())
  25820. s.channels.resize (1);
  25821. helix.mixerTrack = s.channels[0].mixerTrack;
  25822. s.channels[0] = helix;
  25823. while (s.patterns.empty())
  25824. s.patterns.emplace_back();
  25825. lynx::Note note;
  25826. note.channel = 0;
  25827. note.key = 60;
  25828. s.patterns[0].name = "Chords";
  25829. s.patterns[0].notes = { note };
  25830. s.patterns[0].lengthTicks = 4 * lynx::ppq;
  25831. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 2));
  25832. s.playlistTracks[0].name = helix.name;
  25833. lynx::Clip clip;
  25834. clip.pattern = 0;
  25835. clip.length = 4 * lynx::ppq;
  25836. lynx::launcher::setClip (s, 0, 0, clip);
  25837. }, false);
  25838. offline.dispatchPendingMessages();
  25839. auto* detail = ui.getDetailViewForSnapshot();
  25840. check ("detail view", detail != nullptr);
  25841. if (detail != nullptr)
  25842. {
  25843. detail->showSelection (0, 0);
  25844. detail->setPage (lynx::DetailView::Page::devices);
  25845. offline.dispatchPendingMessages();
  25846. write ("01-device");
  25847. struct View
  25848. {
  25849. const char* name;
  25850. int modTab, source, osc;
  25851. };
  25852. for (const auto v : { View { "02-matrix", 1, 0, 0 }, View { "03-midi", 2, 0, 0 }, View { "04-mpe", 3, 0, 0 }, View { "05-env2", 0, 1, 0 },
  25853. View { "06-lfo1", 0, 3, 0 }, View { "07-osc2", 0, 0, 1 } })
  25854. {
  25855. check (juce::String ("Helix card shown for ") + v.name, lynx::helixcards::showView (*detail, v.modTab, v.source, v.osc) > 0);
  25856. write (v.name);
  25857. }
  25858. lynx::helixcards::showView (*detail, 0, 0, 0);
  25859. }
  25860. // the Pattern layout: the channel window's page alone
  25861. {
  25862. auto page = lynx::makeHelixEditor (offline, [] (lynx::Song& s) -> lynx::ChannelDef* { return s.channels.empty() ? nullptr : &s.channels[0]; }, 0);
  25863. const auto file = lynx::shot::file (juce::File (prefix + "-10-window.png"));
  25864. file.deleteFile();
  25865. juce::FileOutputStream out (file);
  25866. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (*page), out);
  25867. check ("channel window page", page->getWidth() > 0);
  25868. }
  25869. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  25870. }
  25871. void runLiveShot190ce (const juce::String& prefix)
  25872. {
  25873. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  25874. lynx::AudioEngine offline (false);
  25875. lynx::MainComponent ui (offline, false);
  25876. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  25877. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  25878. const auto write = [&prefix, &ui, &offline] (const char* name) {
  25879. offline.dispatchPendingMessages();
  25880. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  25881. file.deleteFile();
  25882. juce::FileOutputStream out (file);
  25883. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (ui), out);
  25884. };
  25885. juce::String checks;
  25886. const auto check = [&checks] (const char* what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  25887. // a small library of its own (empty files: only names are shown)
  25888. const auto lib = juce::File (prefix + "-library");
  25889. lib.deleteRecursively();
  25890. for (const auto* path : { "Drums/Kicks/Kick Hard.wav", "Drums/Kicks/Kick Soft.wav", "Drums/Snare Tight.wav", "Drums/Hat Closed.wav",
  25891. "Loops/Break 120.wav", "Loops/Shaker 98.wav", "Textures/Vinyl Noise.wav", "Textures/Rain.wav" })
  25892. lib.getChildFile (path).create();
  25893. auto& browser = ui.getBrowserForSnapshot();
  25894. auto& store = lynx::BrowserComponent::collectionStore();
  25895. store = {};
  25896. const auto item = [&lib] (const char* path) { return lib.getChildFile (path).getFullPathName().toStdString(); };
  25897. ui.setVisible (true);
  25898. lynx::DetailView::shownSetting = lynx::DetailView::devicesPage = true;
  25899. ui.setClipLaunchWorkflow (true);
  25900. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::browser, lynx::workspace::Panel::playlist });
  25901. offline.editSong ([] (lynx::Song& s) {
  25902. if (s.channels.size() < 2)
  25903. s.channels.resize (2);
  25904. s.channels[0].name = "Bass synth";
  25905. s.channels[0].mixerTrack = 2;
  25906. s.channels[1].mixerTrack = 3;
  25907. if (s.mixer.size() < 4)
  25908. s.mixer.resize (4);
  25909. s.mixer[2].name = "Bass";
  25910. s.mixer[2].effects.clear();
  25911. for (auto kind : { lynx::EffectKind::eq, lynx::EffectKind::compressor, lynx::EffectKind::delay })
  25912. {
  25913. lynx::EffectSlot fx;
  25914. fx.kind = kind;
  25915. const auto& info = lynx::effectInfo (kind);
  25916. for (std::size_t k = 0; k < info.params.size() && k < fx.params.size(); ++k)
  25917. fx.params[k] = info.params[k].defaultValue;
  25918. s.mixer[2].effects.push_back (fx);
  25919. }
  25920. s.mixer[2].effects[1].enabled = false; // the compressor: off, at half mix
  25921. s.mixer[2].effects[1].mix = 0.5f;
  25922. while (s.patterns.size() < 2)
  25923. s.patterns.emplace_back();
  25924. s.patterns[0].name = "Bass line";
  25925. lynx::Note note;
  25926. note.channel = 0;
  25927. note.key = 36;
  25928. s.patterns[0].notes = { note };
  25929. s.patterns[0].lengthTicks = 4 * lynx::ppq;
  25930. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 3));
  25931. s.playlistTracks[1].name = "Bass";
  25932. lynx::Clip clip;
  25933. clip.pattern = 0;
  25934. clip.length = 4 * lynx::ppq;
  25935. lynx::launcher::setClip (s, 1, 0, clip);
  25936. }, false);
  25937. offline.dispatchPendingMessages();
  25938. auto* detail = ui.getDetailViewForSnapshot();
  25939. if (detail == nullptr)
  25940. {
  25941. juce::File (prefix + "-checks.txt").replaceWithText ("FAIL no detail view\n");
  25942. return;
  25943. }
  25944. detail->showSelection (1, 0);
  25945. detail->setPage (lynx::DetailView::Page::devices);
  25946. detail->selectCardForCheck (2); // the compressor (card 0 is the instrument)
  25947. write ("01-devices"); // the cards' title buttons: hot-swap, save, fold
  25948. saveMenus (juce::StringArray { "Device (effect card)" }, std::vector<juce::PopupMenu> { detail->cardMenuForSnapshot (2) }, prefix + "-02-device-menu.png");
  25949. // hot-swap on for the compressor: the Browser's bar, the Plugin database's effects, the card's button lit
  25950. const auto compressor = lynx::hotswap::targetOfEffect (offline.getSong(), 2, 1);
  25951. browser.beginHotSwap (compressor);
  25952. write ("03-hotswap-effect");
  25953. check ("hot-swap links the compressor", browser.isHotSwapping() && browser.hotSwapTarget() == compressor);
  25954. // a swap through the Browser itself (the row of LYNX's Reverb, then Enter): the slot keeps its place, its off
  25955. // state and its Mix; the link moves to the new device
  25956. {
  25957. browser.showPluginDatabase ("LYNX SHARE", 0); // (the folder of LYNX's own effects, opened as a click would)
  25958. browser.selectRowForSnapshot (lynx::tr (lynx::effectInfo (lynx::EffectKind::reverb).name));
  25959. write ("03a-hotswap-row"); // the candidate's row selected
  25960. check ("swap: Enter on the Reverb row is taken by hot-swap", browser.hotSwapLoadSelected());
  25961. offline.dispatchPendingMessages();
  25962. const auto& slot = offline.getSong().mixer[2].effects[1];
  25963. // (round 190cy: the device comes in with its own on / off state, on, as in Live 12.4.16; the Mix stays)
  25964. 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);
  25965. check ("swap: three effects as before", offline.getSong().mixer[2].effects.size() == 3);
  25966. check ("swap: the Browser is linked to the new device", browser.isHotSwapping() && browser.hotSwapTarget() == lynx::hotswap::targetOfEffect (offline.getSong(), 2, 1)
  25967. && ! (browser.hotSwapTarget() == compressor));
  25968. write ("03b-hotswap-swapped");
  25969. offline.undo();
  25970. offline.dispatchPendingMessages();
  25971. const auto& back = offline.getSong().mixer[2].effects[1];
  25972. check ("undo: the compressor is back with its instance", back.kind == lynx::EffectKind::compressor && back.instance.id == compressor.instance);
  25973. check ("undo: the Browser is still linked to it", browser.isHotSwapping() && browser.hotSwapTarget() == compressor);
  25974. }
  25975. // round 190cy (Live 12.4.16 live check 190cw shot 02a): hot-swap starts on the device's current preset. The
  25976. // compressor got its settings from a saved preset of LYNX's ("Glue bus", in this run's own settings folder)
  25977. {
  25978. browser.endHotSwap();
  25979. const auto folder = lynx::pluginheader::userFolder (lynx::EffectKind::compressor);
  25980. folder.createDirectory();
  25981. const auto& fx = offline.getSong().mixer[2].effects[1];
  25982. for (const auto* name : { "Glue bus", "Gentle", "Parallel smash" })
  25983. folder.getChildFile (juce::String (name) + ".lynxpreset").replaceWithText (lynx::presets::toText (lynx::EffectKind::compressor, name, fx.params));
  25984. offline.editSong ([] (lynx::Song& s) { s.mixer[2].effects[1].presetName = "Glue bus"; }, false);
  25985. offline.dispatchPendingMessages();
  25986. browser.beginHotSwap (compressor);
  25987. write ("03c-hotswap-current-preset");
  25988. check ("hot-swap starts on the current preset", browser.getSelectedFile() == folder.getChildFile ("Glue bus.lynxpreset"));
  25989. // a preset of the same effect swapped in comes in on (the compressor was off)
  25990. browser.selectRowForSnapshot ("Gentle.lynxpreset");
  25991. check ("swap: the preset row is taken by hot-swap", browser.hotSwapLoadSelected());
  25992. offline.dispatchPendingMessages();
  25993. const auto& now = offline.getSong().mixer[2].effects[1];
  25994. check ("swap: the preset's settings, the device on", now.kind == lynx::EffectKind::compressor && now.presetName == "Gentle" && now.enabled);
  25995. write ("03d-hotswap-preset-swapped");
  25996. offline.undo();
  25997. offline.dispatchPendingMessages();
  25998. check ("undo: the compressor off again", ! offline.getSong().mixer[2].effects[1].enabled);
  25999. browser.endHotSwap();
  26000. check ("hot-swap ended: the preset list goes", ! browser.isHotSwapping());
  26001. browser.beginHotSwap (compressor);
  26002. }
  26003. // linked to the instrument instead
  26004. const auto bass = lynx::hotswap::targetOfChannel (offline.getSong(), 0);
  26005. browser.beginHotSwap (bass);
  26006. detail->selectCardForCheck (0);
  26007. write ("04-hotswap-instrument");
  26008. check ("re-link to the instrument", browser.hotSwapTarget() == bass);
  26009. browser.endHotSwap();
  26010. check ("hot-swap ended", ! browser.isHotSwapping());
  26011. write ("05-hotswap-ended"); // the Browser as it was before
  26012. // the device is deleted while linked: the mode ends by itself
  26013. browser.beginHotSwap (lynx::hotswap::targetOfEffect (offline.getSong(), 2, 2));
  26014. offline.editSong ([] (lynx::Song& s) { s.mixer[2].effects.pop_back(); });
  26015. offline.dispatchPendingMessages();
  26016. check ("deleting the linked device ends hot-swap", ! browser.isHotSwapping());
  26017. offline.undo();
  26018. offline.dispatchPendingMessages();
  26019. // Duplicate (Ctrl+D) of the EQ
  26020. check ("duplicate", detail->duplicateCardForCheck (1));
  26021. offline.dispatchPendingMessages();
  26022. check ("duplicate: four effects, EQ twice", offline.getSong().mixer[2].effects.size() == 4 && offline.getSong().mixer[2].effects[1].kind == lynx::EffectKind::eq
  26023. && offline.getSong().mixer[2].effects[0].instance.id != offline.getSong().mixer[2].effects[1].instance.id);
  26024. write ("06-duplicated");
  26025. // --- collections ---
  26026. browser.showFilterForSnapshot (lib, lynx::browserview::ContentFilter::all);
  26027. ui.waitForBrowserForSnapshot();
  26028. browser.setInCollection (item ("Drums/Kicks/Kick Hard.wav"), 0, true);
  26029. browser.setInCollection (item ("Drums/Snare Tight.wav"), 0, true);
  26030. browser.setInCollection (item ("Loops"), 0, true);
  26031. browser.setTab (lynx::BrowserComponent::starredTab);
  26032. write ("07-starred-only"); // only Starred shown: the tab as it always was
  26033. browser.setInCollection (item ("Drums/Kicks/Kick Hard.wav"), 4, true); // also Blue
  26034. browser.setInCollection (item ("Loops/Break 120.wav"), 4, true);
  26035. browser.setInCollection (item ("Textures/Vinyl Noise.wav"), 3, true);
  26036. browser.setInCollection (item ("Textures/Rain.wav"), 3, true);
  26037. browser.setInCollection (item ("Drums/Hat Closed.wav"), 1, true);
  26038. store.rename (3, "Textures");
  26039. browser.setCollectionShown (1, true);
  26040. browser.setCollectionShown (3, true);
  26041. browser.setCollectionShown (4, true);
  26042. write ("08-collections"); // a heading per collection shown
  26043. check ("collections: four shown", store.shown().size() == 4);
  26044. check ("collections: an item in two", store.mask (item ("Drums/Kicks/Kick Hard.wav")) == 0b10001);
  26045. // round 190cy: the Clip-launch workflow's row menu lists the collections flat, as Live's item menu (shot 05);
  26046. // the Pattern workflow keeps the "Collections" sub-menu
  26047. browser.setLiveItemMenus (false);
  26048. saveMenus (juce::StringArray { "Collections (Pattern workflow: a row's sub-menu)" }, std::vector<juce::PopupMenu> { browser.collectionsMenuForSnapshot (item ("Drums/Kicks/Kick Hard.wav")) },
  26049. prefix + "-09-collections-menu.png");
  26050. browser.setLiveItemMenus (true);
  26051. saveMenus (juce::StringArray { "Collections (Clip-launch workflow: a row's menu)" }, std::vector<juce::PopupMenu> { browser.collectionsMenuForSnapshot (item ("Drums/Kicks/Kick Hard.wav")) },
  26052. prefix + "-09b-collections-flat.png");
  26053. // the key of a hidden collection (6, Purple) labels the row and the collection appears
  26054. check ("hidden collection: not shown before", ! store.isShown (5));
  26055. browser.setInCollection (item ("Textures/Rain.wav"), 5, true);
  26056. check ("hidden collection: its key shows it", store.isShown (5) && store.has (item ("Textures/Rain.wav"), 5));
  26057. write ("08b-hidden-collection-shown");
  26058. saveMenus (juce::StringArray { "Browser options" }, std::vector<juce::PopupMenu> { browser.buildViewMenu() }, prefix + "-10-browser-options.png");
  26059. browser.setTab (lynx::BrowserComponent::allTab);
  26060. write ("11-all-tab-chips"); // the colour chips on the rows of the ALL tab
  26061. browser.setSearchForSnapshot ("textures");
  26062. ui.waitForBrowserForSnapshot();
  26063. write ("12-search-collection-name"); // found by the collection's name
  26064. browser.setSearchForSnapshot ({});
  26065. // the file round trip
  26066. {
  26067. const auto text = store.toText();
  26068. check ("collections: text round trip", lynx::collections::Store::fromText (text) == store);
  26069. }
  26070. store = {};
  26071. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  26072. lib.deleteRecursively();
  26073. }
  26074. void runLinkShot190gl (const juce::String& prefix)
  26075. {
  26076. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  26077. lynx::AudioEngine offline (false);
  26078. lynx::MainComponent ui (offline, false);
  26079. ui.setSize (1600, 900);
  26080. ui.setVisible (true);
  26081. juce::String checks;
  26082. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  26083. const auto writeImage = [&prefix] (const juce::Image& image, const char* name) {
  26084. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  26085. file.deleteFile();
  26086. juce::FileOutputStream out (file);
  26087. juce::PNGImageFormat().writeImageToStream (image, out);
  26088. };
  26089. const auto toolbarShot = [&] (const char* name) {
  26090. ui.tickLinkForSnapshot();
  26091. writeImage (lynx::shot::snapshot (ui, ui.getToolbarBoundsForSnapshot()), name);
  26092. };
  26093. auto& link = offline.getLink();
  26094. auto& transport = offline.getTransport();
  26095. link.deviceStarted (44100.0);
  26096. // the audio callbacks the offline engine has none of: Link's per-block step, in real time
  26097. const auto pump = [&] (double seconds, std::function<bool()> until = {}) {
  26098. const auto end = juce::Time::getMillisecondCounterHiRes() + seconds * 1000.0;
  26099. while (juce::Time::getMillisecondCounterHiRes() < end)
  26100. {
  26101. const auto start = link.beginBlock (transport, 256, 0.0);
  26102. if (start >= 0)
  26103. transport.playing.store (true);
  26104. if (transport.playing.load())
  26105. transport.positionTicks.store (transport.positionTicks.load() + 256 * transport.ticksPerSample());
  26106. juce::Thread::sleep (6);
  26107. if (until && until())
  26108. return true;
  26109. }
  26110. return ! until || until();
  26111. };
  26112. auto peer = lynx::AbletonLink::makeTestPeer (97.0); // the other app in the session (it was there first)
  26113. juce::Thread::sleep (1500); // (a session that started at the same moment as LYNX's could take either tempo)
  26114. using lynx::toolbarlayout::Group;
  26115. // FL's Pattern layout: no Link toggle on a new install
  26116. check ("Pattern layout: the Link toggle is hidden by default", ! ui.getToolbarLayoutForSnapshot().isShown (Group::link));
  26117. toolbarShot ("toolbar-fl-default");
  26118. // shown by hand (Settings › Ableton Link › Show Link Toggle): "Link", off
  26119. auto layout = ui.getToolbarLayoutForSnapshot();
  26120. layout.setShown (Group::link, true);
  26121. ui.setToolbarLayoutForSnapshot (layout);
  26122. toolbarShot ("toolbar-fl-link-off");
  26123. check ("off: the toggle says Link", ui.getLinkToggleForSnapshot().text() == lynx::trc ("@Ableton Link: Link"));
  26124. // on: the session the other peer runs (its tempo, 97 BPM, wins over the project's)
  26125. link.setEnabled (true, offline.getSong().bpm);
  26126. // (a new peer is counted at once; its session's tempo is taken after Link measured it, a moment later)
  26127. const auto joined = pump (8.0, [&] { return link.peers() > 0 && link.startProgress() >= 0.0 && std::abs (link.sessionTempo() - 97.0) < 1e-3; });
  26128. check ("Link on: one peer found", joined && link.peers() == 1);
  26129. 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);
  26130. toolbarShot ("toolbar-fl-link-on");
  26131. check ("on with one peer: the toggle says 1 Link", ui.getLinkToggleForSnapshot().text() == lynx::trc ("@Ableton Link: {0} Link").replace ("{0}", "1"));
  26132. check ("stopped with a peer: the position display shows the session's progress", link.startProgress() >= 0.0);
  26133. // the Clip-launch layout: the toggle is shown by default (the reference DAW's "Show Link Toggle": Show)
  26134. ui.setToolbarLayoutForSnapshot (lynx::toolbarlayout::Layout::makeDefault());
  26135. ui.setClipLaunchWorkflow (true);
  26136. check ("Clip-launch layout: the Link toggle is shown by default", ui.getToolbarLayoutForSnapshot().isShown (Group::link));
  26137. pump (0.4);
  26138. toolbarShot ("toolbar-cliplaunch-1link");
  26139. writeImage (lynx::shot::snapshot (ui), "window-cliplaunch");
  26140. // Play: it waits for the session's phase (the play button lit, the progress bar running), then starts
  26141. transport.playing.store (true);
  26142. pump (0.05);
  26143. const auto waited = offline.isLinkWaiting();
  26144. check ("Play with a peer waits for the session's phase", waited);
  26145. toolbarShot ("toolbar-cliplaunch-waiting");
  26146. const auto started = pump (4.0, [&] { return transport.playing.load() && ! offline.isLinkWaiting(); });
  26147. check ("then playback starts on the session's phase", started);
  26148. pump (0.5);
  26149. toolbarShot ("toolbar-cliplaunch-playing");
  26150. check ("playing: no progress bar", link.startProgress() < 0.0);
  26151. // the toggle's drop-down and the Options menu
  26152. saveMenus (juce::StringArray { lynx::trc ("@Ableton Link: Link") }, std::vector<juce::PopupMenu> { ui.getLinkToggleForSnapshot().makeMenu() },
  26153. prefix + "-menu-link.png");
  26154. {
  26155. const auto names = ui.getMenuNamesForSnapshot();
  26156. for (int m = 0; m < names.size(); ++m)
  26157. if (names[m] == lynx::tr ("Options"))
  26158. saveMenus (juce::StringArray { names[m] }, std::vector<juce::PopupMenu> { ui.getMenuForSnapshot (m) }, prefix + "-menu-options.png");
  26159. }
  26160. // Settings › Ableton Link
  26161. {
  26162. lynx::SettingsHooks hooks;
  26163. hooks.linkToggleShown = [] { return true; };
  26164. auto panel = lynx::makeSettingsPanel (offline, lynx::SettingsPage::link, false, hooks);
  26165. panel->setSize (680, 620);
  26166. writeImage (lynx::shot::snapshot (*panel), "settings-link");
  26167. }
  26168. // off: the project's own tempo comes back on the display
  26169. transport.playing.store (false);
  26170. pump (0.1);
  26171. link.setEnabled (false, offline.getSong().bpm);
  26172. pump (0.1);
  26173. toolbarShot ("toolbar-cliplaunch-link-off");
  26174. check ("off: the tempo display shows the project's tempo again", std::abs (offline.shownTempo() - offline.getSong().bpm) < 1e-9);
  26175. const auto stats = link.stats();
  26176. checks << "audio-thread cost of the Link step: mean " << juce::String (stats.meanUs, 2) << " us, max " << juce::String (stats.maxUs, 1)
  26177. << " us over " << (juce::int64) stats.blocks << " blocks\n";
  26178. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  26179. }
  26180. // LYNX --communityshot190hp <prefix> (round 190hp): the three community slices off-screen, with checks in
  26181. // prefix-checks.txt — B9 the MIDI Map Mode's "In every project (LYNX)" (the row menu, the Mapping Browser with the
  26182. // global rows, a new project still playing on the mapped CC, Settings' list), B16 the Mixer menu's Mix snapshots
  26183. // (take, recall, Compare A/B, the .lynx round trip), B18 the audio clip menu's "Split at silence..." (the dialog and
  26184. // the Playlist before / after).
  26185. void runCommunityShot190hp (const juce::String& prefix)
  26186. {
  26187. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  26188. lynx::AudioEngine offline (false);
  26189. lynx::MainComponent ui (offline, false);
  26190. ui.setSize (1600, 900);
  26191. const auto write = [&prefix] (juce::Component& c, const char* name) {
  26192. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  26193. file.deleteFile();
  26194. juce::FileOutputStream out (file);
  26195. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (c), out);
  26196. };
  26197. juce::String checks;
  26198. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  26199. const auto plain = [] (juce::String t) { return t.upToFirstOccurrenceOf ("\t", false, false).removeCharacters ("&"); };
  26200. const auto find = [&plain] (const juce::PopupMenu& menu, const juce::String& text) -> const juce::PopupMenu::Item* {
  26201. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  26202. if (plain (it.getItem().text) == plain (text))
  26203. return &it.getItem();
  26204. return nullptr;
  26205. };
  26206. const auto click = [&find] (const juce::PopupMenu& menu, const juce::String& text) {
  26207. const auto* item = find (menu, text);
  26208. if (item == nullptr || ! item->isEnabled || item->action == nullptr)
  26209. return false;
  26210. item->action();
  26211. return true;
  26212. };
  26213. using namespace lynx::remotemap;
  26214. ui.setVisible (true);
  26215. // ---- B9: the MIDI Map Mode's mappings for every project ---------------------------------------------------------
  26216. ui.setClipLaunchWorkflow (true);
  26217. offline.editSong ([] (lynx::Song& s) {
  26218. auto& grid = lynx::launcher::ensureGrid (s);
  26219. grid.scenes.resize (4);
  26220. assignMidi (s, Target::of (lynx::RemoteAction::play), { 0, 118, -1 });
  26221. assignMidi (s, Target::of (lynx::RemoteAction::stop), { 0, 117, -1 });
  26222. assignMidi (s, Target::sceneLaunch (0), { 0, lynx::linkNoteBase + 44, -1 });
  26223. assignMidi (s, Target::slot (0, 0), { 0, lynx::linkNoteBase + 36, -1 });
  26224. assignMidi (s, Target::parameter ({ lynx::AutomationTargetKind::mixerVolume, 0, 0, 0 }), { 0, 7, -1 });
  26225. }, false);
  26226. offline.dispatchPendingMessages();
  26227. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::playlist, lynx::workspace::Panel::browser });
  26228. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  26229. ui.setMapMode (Mode::midi);
  26230. auto* list = ui.mappingBrowserForSnapshot();
  26231. if (list == nullptr)
  26232. {
  26233. juce::File (prefix + "-checks.txt").replaceWithText (checks + "FAIL no Mapping Browser\n");
  26234. return;
  26235. }
  26236. list->setMode (Mode::midi);
  26237. ui.resized();
  26238. const auto rowOf = [&] (const Target& t) {
  26239. const auto rows = list->rowsShown();
  26240. for (int r = 0; r < (int) rows.size(); ++r)
  26241. if (rows[(std::size_t) r].target == t)
  26242. return r;
  26243. return -1;
  26244. };
  26245. const auto everyProject = lynx::tr ("In every project (LYNX)");
  26246. {
  26247. const auto slotMenu = list->rowMenu (rowOf (Target::slot (0, 0)));
  26248. const auto* item = find (slotMenu, everyProject);
  26249. check ("row menu: a clip slot cannot be for every project (greyed)", item != nullptr && ! item->isEnabled);
  26250. const auto playRow = rowOf (Target::of (lynx::RemoteAction::play));
  26251. list->selectRow (playRow);
  26252. const auto playMenu = list->rowMenu (playRow);
  26253. const auto* p = find (playMenu, everyProject);
  26254. check ("row menu: Play can, unticked", p != nullptr && p->isEnabled && ! p->isTicked);
  26255. saveMenus (juce::StringArray { "Row" }, std::vector<juce::PopupMenu> { playMenu }, prefix + "-b9-01-row-menu.png");
  26256. check ("Play goes to every project", click (playMenu, everyProject) && offline.getMidiPrefs().globalMappings.size() == 1);
  26257. }
  26258. check ("Stop goes too", click (list->rowMenu (rowOf (Target::of (lynx::RemoteAction::stop))), everyProject));
  26259. check ("the Master volume link goes too (FL's global links)",
  26260. click (list->rowMenu (rowOf (Target::parameter ({ lynx::AutomationTargetKind::mixerVolume, 0, 0, 0 }))), everyProject)
  26261. && offline.getMidiPrefs().globalLinks.size() == 1 && offline.getSong().midiLinks.empty());
  26262. list->setMode (Mode::midi);
  26263. const auto shown = list->rowsShown();
  26264. check ("Mapping Browser: 2 project rows, then 3 global ones (" + juce::String ((int) shown.size()) + ")",
  26265. shown.size() == 5 && ! shown[0].global && ! shown[1].global && shown[2].global && shown[4].global);
  26266. {
  26267. const auto* ticked = find (list->rowMenu (2), everyProject);
  26268. check ("a global row's item is ticked", ticked != nullptr && ticked->isTicked);
  26269. }
  26270. write (*list, "b9-02-mapping-browser-global");
  26271. // a new project: the global mappings are there and act (CC 118 plays, CC 117 stops)
  26272. offline.setSong (lynx::Song::makeDefault());
  26273. offline.dispatchPendingMessages();
  26274. list->setMode (Mode::midi);
  26275. const auto fresh = list->rowsShown();
  26276. check ("new project: the 3 global rows (" + juce::String ((int) fresh.size()) + ")", fresh.size() == 3 && fresh[0].global);
  26277. write (*list, "b9-03-new-project-browser");
  26278. ui.setMapMode (Mode::off);
  26279. offline.injectControllerForTest (118, 0, 127);
  26280. offline.dispatchPendingMessages();
  26281. check ("new project: CC 118 plays", offline.getTransport().playing.load());
  26282. offline.injectControllerForTest (118, 0, 0);
  26283. offline.injectControllerForTest (117, 0, 127);
  26284. offline.dispatchPendingMessages();
  26285. check ("new project: CC 117 stops", ! offline.getTransport().playing.load());
  26286. offline.injectControllerForTest (7, 0, 0);
  26287. offline.dispatchPendingMessages();
  26288. check ("new project: CC 7 moves the Master", offline.currentTargetValue ({ lynx::AutomationTargetKind::mixerVolume, 0, 0, 0 }) < 0.01f);
  26289. // the Pattern layout: they act there too, and Settings › MIDI lists them
  26290. ui.setClipLaunchWorkflow (false);
  26291. offline.injectControllerForTest (117, 0, 0);
  26292. offline.injectControllerForTest (118, 0, 127);
  26293. offline.dispatchPendingMessages();
  26294. check ("Pattern layout: CC 118 plays", offline.getTransport().playing.load());
  26295. offline.stop();
  26296. // back into one project, then cleared (the settings of this test engine are never written)
  26297. ui.setClipLaunchWorkflow (true);
  26298. ui.setMapMode (Mode::midi);
  26299. list->setMode (Mode::midi);
  26300. check ("back into this project", click (list->rowMenu (rowOf (Target::of (lynx::RemoteAction::play))), everyProject)
  26301. && offline.getMidiPrefs().globalMappings.size() == 1 && offline.getSong().remoteMappings.size() == 1);
  26302. ui.setMapMode (Mode::off);
  26303. ui.setClipLaunchWorkflow (false);
  26304. // ---- B16: Mix snapshots ----------------------------------------------------------------------------------------
  26305. offline.setSong (lynx::Song::makeDefault());
  26306. offline.dispatchPendingMessages();
  26307. offline.editSong ([] (lynx::Song& s) {
  26308. const char* names[] { "Master", "Drums", "Bass", "Keys", "Vox", "Reverb" };
  26309. for (int i = 1; i < 6 && i < (int) s.mixer.size(); ++i)
  26310. s.mixer[(std::size_t) i].name = names[i];
  26311. s.mixer[1].volume = 0.7f;
  26312. s.mixer[4].pan = -0.3f;
  26313. s.setRoute (4, 5, true, 0.5f);
  26314. });
  26315. juce::PopupMenu mixerMenu;
  26316. lynx::mixeroptions::addItems (mixerMenu, offline, false);
  26317. const auto* snaps = find (mixerMenu, lynx::tr ("Mix snapshots (LYNX)"));
  26318. check ("Mixer menu: Mix snapshots (LYNX)", snaps != nullptr && snaps->subMenu != nullptr);
  26319. check ("Take snapshot", click (lynx::mixeroptions::snapshotsMenu (offline), lynx::tr ("Take snapshot")) && offline.getSong().mixSnapshots.size() == 1);
  26320. offline.editSong ([] (lynx::Song& s) {
  26321. s.mixer[1].volume = 0.4f;
  26322. s.mixer[4].pan = 0.6f;
  26323. s.mixer[3].muted = true;
  26324. s.setRoute (4, 5, false);
  26325. });
  26326. check ("Take snapshot again", click (lynx::mixeroptions::snapshotsMenu (offline), lynx::tr ("Take snapshot")) && offline.getSong().mixSnapshots.size() == 2);
  26327. {
  26328. const auto menu = lynx::mixeroptions::snapshotsMenu (offline);
  26329. const auto* first = find (menu, juce::String ("Snapshot 1 (B)"));
  26330. check ("snapshot 1 listed as B", first != nullptr && first->subMenu != nullptr && ! first->isTicked);
  26331. const auto* second = find (menu, juce::String ("Snapshot 2 (A)"));
  26332. check ("snapshot 2 ticked: the mix is it", second != nullptr && second->isTicked);
  26333. saveMenus (juce::StringArray { "Mixer", "Mix snapshots (LYNX)", "Snapshot 1" },
  26334. std::vector<juce::PopupMenu> { mixerMenu, menu, first != nullptr ? *first->subMenu : juce::PopupMenu() }, prefix + "-b16-01-menus.png");
  26335. check ("Recall snapshot 1", first != nullptr && click (*first->subMenu, lynx::tr ("Recall")));
  26336. }
  26337. const auto& m = offline.getSong().mixer;
  26338. check ("recalled: fader, pan, mute, send", m[1].volume == 0.7f && m[4].pan == -0.3f && ! m[3].muted && offline.getSong().routes (4, 5));
  26339. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::mixer });
  26340. ui.resized();
  26341. offline.dispatchPendingMessages();
  26342. write (ui, "b16-02-mixer-recalled");
  26343. check ("Compare A/B", click (lynx::mixeroptions::snapshotsMenu (offline), lynx::tr ("Compare A/B: back to \"{0}\"", { "Snapshot 2" }))
  26344. && m[1].volume == 0.4f && m[3].muted);
  26345. offline.undo();
  26346. check ("one undo step: back to snapshot 1", m[1].volume == 0.7f);
  26347. {
  26348. const auto file = juce::File (prefix + "-b16-snapshots.lynx");
  26349. juce::String error;
  26350. const auto saved = lynx::ProjectFile::save (offline.getSong(), file, error);
  26351. const auto back = lynx::ProjectFile::load (file, error);
  26352. check ("saved and loaded: the snapshots and A/B", saved && back && back->mixSnapshots == offline.getSong().mixSnapshots
  26353. && back->mixSnapshotCurrent == offline.getSong().mixSnapshotCurrent
  26354. && back->mixSnapshotPrevious == offline.getSong().mixSnapshotPrevious);
  26355. file.deleteFile();
  26356. }
  26357. // ---- B18: Split at silence -------------------------------------------------------------------------------------
  26358. {
  26359. // a "vocal take": 0.5 s silence, three phrases with pauses of 0.6 s and 0.15 s, quiet hiss in the gaps
  26360. const double rate = 44100.0;
  26361. juce::AudioBuffer<float> buffer (1, (int) (rate * 4.0));
  26362. buffer.clear();
  26363. juce::Random noise (190);
  26364. for (int i = 0; i < buffer.getNumSamples(); ++i)
  26365. {
  26366. const auto t = i / rate;
  26367. const auto phrase = (t >= 0.5 && t < 1.4) || (t >= 2.0 && t < 2.6) || (t >= 2.75 && t < 3.3);
  26368. 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)))
  26369. : (noise.nextFloat() - 0.5f) * 0.0004f);
  26370. }
  26371. const auto wav = juce::File (prefix + "-b18-take.wav");
  26372. wav.deleteFile();
  26373. juce::WavAudioFormat format;
  26374. if (auto out = std::unique_ptr<juce::AudioFormatWriter> (format.createWriterFor (wav.createOutputStream().release(), rate, 1, 16, {}, 0)))
  26375. out->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
  26376. auto song = lynx::Song::makeDefault();
  26377. song.channels.push_back ({});
  26378. song.channels.back().name = "Vocal take";
  26379. song.channels.back().instrument = lynx::InstrumentKind::audioClip;
  26380. song.channels.back().samplePath = wav.getFullPathName().toStdString();
  26381. lynx::Clip c;
  26382. c.kind = lynx::ClipKind::audio;
  26383. c.channel = (int) song.channels.size() - 1;
  26384. c.track = 1;
  26385. c.start = 4 * lynx::ppq;
  26386. c.length = (std::int64_t) std::llround (4.0 * song.bpm / 60.0 * lynx::ppq); // (the whole file at the song tempo)
  26387. song.playlist.push_back (c);
  26388. offline.setSong (std::move (song));
  26389. offline.dispatchPendingMessages();
  26390. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::playlist });
  26391. ui.resized();
  26392. auto& playlist = ui.getPlaylistForSnapshot();
  26393. const auto index = (int) offline.getSong().playlist.size() - 1;
  26394. const auto menu = playlist.getClipMenuForSnapshot (index);
  26395. const auto* item = find (menu, lynx::tr ("Split at silence..."));
  26396. const auto* splitHere = find (menu, lynx::tr ("Split here"));
  26397. check ("clip menu: Split at silence... in LYNX extras, enabled", item != nullptr && item->isEnabled && splitHere != nullptr);
  26398. savePng (columnMenuImage (menu), prefix + "-b18-01-clip-menu.png");
  26399. {
  26400. auto dialog = playlist.makeSplitSilenceDialogForSnapshot (index);
  26401. write (*dialog, "b18-02-dialog");
  26402. }
  26403. offline.dispatchPendingMessages();
  26404. write (ui, "b18-03-playlist-before");
  26405. juce::String why;
  26406. const auto made = playlist.splitClipsAtSilence ({ index }, lynx::PlaylistComponent::splitSilenceOptions(), &why);
  26407. offline.dispatchPendingMessages();
  26408. const auto& clips = offline.getSong().playlist;
  26409. std::vector<const lynx::Clip*> audio;
  26410. for (const auto& x : clips)
  26411. if (x.kind == lynx::ClipKind::audio)
  26412. audio.push_back (&x);
  26413. std::sort (audio.begin(), audio.end(), [] (const lynx::Clip* a, const lynx::Clip* b) { return a->start < b->start; });
  26414. const auto secondsAt = [&] (std::int64_t ticks) { return (double) (ticks - 4 * lynx::ppq) / lynx::ppq * 60.0 / offline.getSong().bpm; };
  26415. check ("split into 2 clips (the 0.15 s pause stays inside): " + juce::String (made) + ", " + why, made == 2 && audio.size() == 2);
  26416. if (audio.size() == 2)
  26417. check ("the clips start at the phrases less the pre-roll, end after them: " + juce::String (secondsAt (audio[0]->start), 3) + "-"
  26418. + juce::String (secondsAt (audio[0]->end()), 3) + ", " + juce::String (secondsAt (audio[1]->start), 3) + "-" + juce::String (secondsAt (audio[1]->end()), 3),
  26419. std::abs (secondsAt (audio[0]->start) - 0.49) < 0.02 && std::abs (secondsAt (audio[0]->end()) - 1.45) < 0.02
  26420. && std::abs (secondsAt (audio[1]->start) - 1.99) < 0.02 && std::abs (secondsAt (audio[1]->end()) - 3.35) < 0.02
  26421. && audio[1]->offset - audio[0]->offset == audio[1]->start - audio[0]->start);
  26422. write (ui, "b18-04-playlist-after");
  26423. offline.undo();
  26424. check ("one undo step", offline.getSong().playlist.size() == clips.size() && std::count_if (offline.getSong().playlist.begin(), offline.getSong().playlist.end(),
  26425. [] (const lynx::Clip& x) { return x.kind == lynx::ClipKind::audio; }) == 1);
  26426. lynx::stripsilence::Options loud;
  26427. loud.thresholdDb = -1.0f;
  26428. check ("all below the threshold: nothing split", playlist.splitClipsAtSilence ({ index }, loud, &why) == 0);
  26429. wav.deleteFile();
  26430. }
  26431. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  26432. }
  26433. void runMapShot190ef (const juce::String& prefix)
  26434. {
  26435. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  26436. lynx::AudioEngine offline (false);
  26437. lynx::MainComponent ui (offline, false);
  26438. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  26439. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  26440. const auto write = [&prefix] (juce::Component& c, const char* name) {
  26441. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  26442. file.deleteFile();
  26443. juce::FileOutputStream out (file);
  26444. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (c), out);
  26445. };
  26446. juce::String checks;
  26447. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  26448. using namespace lynx::remotemap;
  26449. ui.setVisible (true);
  26450. // the Pattern layout first: Ctrl+M stays FL's metronome there and no map mode starts
  26451. {
  26452. const auto before = offline.getTransport().metronome.load();
  26453. ui.keyPressed (juce::KeyPress ('M', juce::ModifierKeys::ctrlModifier, 0));
  26454. check ("Pattern layout: Ctrl+M is the metronome, no map mode", ui.getMapMode() == Mode::off && offline.getTransport().metronome.load() != before);
  26455. ui.keyPressed (juce::KeyPress ('M', juce::ModifierKeys::ctrlModifier, 0));
  26456. ui.setMapMode (Mode::midi);
  26457. check ("Pattern layout: setMapMode stays off", ui.getMapMode() == Mode::off);
  26458. }
  26459. ui.setClipLaunchWorkflow (true);
  26460. offline.editSong ([] (lynx::Song& s) {
  26461. if (s.mixer.size() < 6)
  26462. s.mixer.resize (6);
  26463. const char* inserts[] { "Master", "Drums", "Bass", "Keys", "Vox", "Reverb" };
  26464. for (int i = 1; i < 6; ++i)
  26465. s.mixer[(std::size_t) i].name = inserts[i];
  26466. const int channels = (int) s.channels.size();
  26467. s.channels.resize ((std::size_t) channels + 3);
  26468. const char* names[] { "Drum kit", "Bass synth", "Keys" };
  26469. for (int k = 0; k < 3; ++k)
  26470. {
  26471. auto& ch = s.channels[(std::size_t) (channels + k)];
  26472. ch.name = names[k];
  26473. ch.instrument = k == 0 ? lynx::InstrumentKind::sampler : lynx::InstrumentKind::synth;
  26474. ch.mixerTrack = k + 1;
  26475. }
  26476. s.mixer[2].effects.clear();
  26477. for (auto kind : { lynx::EffectKind::eq, lynx::EffectKind::compressor })
  26478. {
  26479. lynx::EffectSlot fx;
  26480. fx.kind = kind;
  26481. const auto& info = lynx::effectInfo (kind);
  26482. for (std::size_t k = 0; k < info.params.size() && k < fx.params.size(); ++k)
  26483. fx.params[k] = info.params[k].defaultValue;
  26484. s.mixer[2].effects.push_back (fx);
  26485. }
  26486. while (s.patterns.size() < 3)
  26487. s.patterns.emplace_back();
  26488. const char* patterns[] { "Beat", "Bassline", "Chords" };
  26489. for (int p = 0; p < 3; ++p)
  26490. {
  26491. auto& pattern = s.patterns[(std::size_t) p];
  26492. pattern.name = patterns[p];
  26493. lynx::Note n;
  26494. n.channel = channels + p;
  26495. n.key = 48 + p * 5;
  26496. pattern.notes = { n };
  26497. pattern.lengthTicks = 4 * lynx::ppq;
  26498. }
  26499. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 8));
  26500. const char* tracks[] { "Drums", "Bass", "Keys", "Vox" };
  26501. for (int t = 0; t < 4; ++t)
  26502. s.playlistTracks[(std::size_t) t].name = tracks[t];
  26503. for (int t = 0; t < 3; ++t)
  26504. for (int r = 0; r < 3; ++r)
  26505. {
  26506. lynx::Clip clip;
  26507. clip.pattern = t;
  26508. clip.length = 4 * lynx::ppq;
  26509. lynx::launcher::setClip (s, t, r, clip);
  26510. }
  26511. auto& grid = lynx::launcher::ensureGrid (s);
  26512. const char* scenes[] { "Intro", "Verse", "Drop" };
  26513. grid.scenes.resize (4);
  26514. for (int r = 0; r < 3; ++r)
  26515. grid.scenes[(std::size_t) r].name = scenes[r];
  26516. // some mappings, as the lesson's pictures show them (pads on slots and scenes, knobs on volume and pan)
  26517. assignMidi (s, Target::slot (0, 0), { 0, lynx::linkNoteBase + 36, -1 });
  26518. assignMidi (s, Target::slot (1, 0), { 0, lynx::linkNoteBase + 37, -1 });
  26519. assignMidi (s, Target::sceneLaunch (1), { 0, lynx::linkNoteBase + 44, -1 });
  26520. assignMidi (s, Target::parameter ({ lynx::AutomationTargetKind::mixerVolume, 1, 0, 0 }), { 0, 17, -1 });
  26521. assignMidi (s, Target::parameter ({ lynx::AutomationTargetKind::mixerPan, 1, 0, 0 }), { 0, 16, -1 });
  26522. assignMidi (s, Target::of (lynx::RemoteAction::play), { 0, 118, -1 });
  26523. setRange (s, rows (s, Mode::midi)[0], 0.0f, 0.85f);
  26524. assignKey (s, Target::slot (0, 1), 'A');
  26525. assignKey (s, Target::slot (1, 1), 'S');
  26526. assignKey (s, Target::sceneLaunch (2), '3');
  26527. assignKey (s, Target::parameter ({ lynx::AutomationTargetKind::mixerVolume, 2, 0, 0 }), 'V');
  26528. }, false);
  26529. offline.dispatchPendingMessages();
  26530. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::playlist, lynx::workspace::Panel::browser }); // (no floating Channel Rack over the grid)
  26531. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  26532. offline.dispatchPendingMessages();
  26533. ui.resized();
  26534. if (auto* detail = ui.getDetailViewForSnapshot())
  26535. {
  26536. detail->showSelection (1, 0);
  26537. detail->setPage (lynx::DetailView::Page::devices);
  26538. }
  26539. ui.resized();
  26540. offline.dispatchPendingMessages();
  26541. write (ui, "00-clip-launch-before");
  26542. // Ctrl+M in the Clip-launch layout: MIDI Map Mode (the metronome stays as it was)
  26543. const auto metronome = offline.getTransport().metronome.load();
  26544. ui.keyPressed (juce::KeyPress ('M', juce::ModifierKeys::ctrlModifier, 0));
  26545. check ("Clip-launch layout: Ctrl+M starts MIDI Map Mode", ui.getMapMode() == Mode::midi && offline.getTransport().metronome.load() == metronome);
  26546. auto* overlay = ui.mapOverlayForSnapshot();
  26547. auto* list = ui.mappingBrowserForSnapshot();
  26548. if (overlay == nullptr || list == nullptr)
  26549. {
  26550. juce::File (prefix + "-checks.txt").replaceWithText (checks + "FAIL no overlay\n");
  26551. return;
  26552. }
  26553. overlay->refresh();
  26554. const auto& spots = overlay->spots();
  26555. 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; }); };
  26556. const auto params = [&] (lynx::AutomationTargetKind k) {
  26557. 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; });
  26558. };
  26559. check ("overlay: clip slots (" + juce::String (count (lynx::RemoteAction::clipSlot)) + ")", count (lynx::RemoteAction::clipSlot) >= 12);
  26560. check ("overlay: scene launch buttons (" + juce::String (count (lynx::RemoteAction::sceneLaunch)) + ")", count (lynx::RemoteAction::sceneLaunch) >= 4);
  26561. check ("overlay: track stop buttons", count (lynx::RemoteAction::trackStop) >= 4);
  26562. check ("overlay: Stop all clips, Session Record", count (lynx::RemoteAction::stopAllClips) == 1 && count (lynx::RemoteAction::sessionRecord) == 1);
  26563. check ("overlay: transport play / stop / record / metronome", count (lynx::RemoteAction::play) == 1 && count (lynx::RemoteAction::stop) == 1
  26564. && count (lynx::RemoteAction::record) == 1 && count (lynx::RemoteAction::metronome) == 1);
  26565. check ("overlay: tempo", params (lynx::AutomationTargetKind::tempo) == 1);
  26566. check ("overlay: mixer volume / pan (" + juce::String (params (lynx::AutomationTargetKind::mixerVolume)) + " / " + juce::String (params (lynx::AutomationTargetKind::mixerPan)) + ")",
  26567. params (lynx::AutomationTargetKind::mixerVolume) >= 3 && params (lynx::AutomationTargetKind::mixerPan) >= 3);
  26568. check ("overlay: device knobs (" + juce::String (params (lynx::AutomationTargetKind::effectParam)) + ")", params (lynx::AutomationTargetKind::effectParam) >= 2);
  26569. // a click on Keys' first slot selects it; a MIDI control assigns it (as the engine's catch would)
  26570. for (const auto& spot : spots)
  26571. if (spot.target == Target::slot (2, 0))
  26572. {
  26573. auto source = juce::Desktop::getInstance().getMainMouseSource();
  26574. const auto now = juce::Time::getCurrentTime();
  26575. const auto at = spot.area.getCentre().toFloat();
  26576. overlay->mouseDown (juce::MouseEvent (source, at, juce::ModifierKeys (juce::ModifierKeys::leftButtonModifier), 1.0f, 0.0f, 0.0f, 0.0f, 0.0f,
  26577. overlay, overlay, now, at, now, 1, false));
  26578. break;
  26579. }
  26580. if (spots.empty())
  26581. {
  26582. juce::File (prefix + "-checks.txt").replaceWithText (checks + "FAIL no spots\n");
  26583. return;
  26584. }
  26585. check ("a click selects the slot", overlay->selection() == std::optional<Target> (Target::slot (2, 0)));
  26586. check ("the overlay takes clicks only on elements", overlay->hitTest (spots.front().area.getCentreX(), spots.front().area.getCentreY()) && ! overlay->hitTest (2, ui.getHeight() - 2));
  26587. check ("a pad assigns it", overlay->assignMidi ({ 0, lynx::linkNoteBase + 38, -1 }) && midiOf (offline.getSong(), Target::slot (2, 0)).number == lynx::linkNoteBase + 38);
  26588. check ("the same pad again on track 0 is refused", ! (overlay->select (Target::slot (0, 2)), overlay->assignMidi ({ 0, lynx::linkNoteBase + 36, -1 })));
  26589. overlay->select (Target::slot (2, 0));
  26590. list->setMode (Mode::midi);
  26591. list->selectRow (0);
  26592. ui.resized();
  26593. overlay->refresh();
  26594. write (ui, "01-midi-map-mode");
  26595. check ("Mapping Browser rows (MIDI): " + juce::String ((int) list->rowsShown().size()), list->rowsShown().size() == 7);
  26596. write (*list, "02-mapping-browser-midi");
  26597. saveMenus (juce::StringArray { "Row" }, std::vector<juce::PopupMenu> { list->rowMenu (0) }, prefix + "-03-row-menu.png");
  26598. // Ctrl+K: Key Map Mode; a key assigns the selected element
  26599. ui.keyPressed (juce::KeyPress ('K', juce::ModifierKeys::ctrlModifier, 0));
  26600. check ("Ctrl+K switches to Key Map Mode", ui.getMapMode() == Mode::key && offline.getMapMode() == Mode::key);
  26601. overlay->select (Target::sceneLaunch (0));
  26602. ui.keyPressed (juce::KeyPress ('1', {}, '1'));
  26603. check ("a key assigns the selected scene", keyOf (offline.getSong(), Target::sceneLaunch (0)).key == '1');
  26604. overlay->select (Target::sceneLaunch (1));
  26605. ui.keyPressed (juce::KeyPress ('A', {}, 'a'));
  26606. check ("a key already on a slot is refused for a scene", ! keyOf (offline.getSong(), Target::sceneLaunch (1)).found);
  26607. overlay->refresh();
  26608. write (ui, "04-key-map-mode");
  26609. write (*list, "05-mapping-browser-key");
  26610. {
  26611. // round 190em: Min / Max in the parameter's unit, Path "<track> | Mixer", Name "Track Volume" / "Slot n"
  26612. const lynx::remotemap::Target volume = Target::parameter ({ lynx::AutomationTargetKind::mixerVolume, 2, 0, 0 });
  26613. const auto [path, name] = lynx::mapmode::describe (offline, volume);
  26614. check ("browser: volume row Path / Name = " + path + " / " + name, path == "Bass | Mixer" && name == "Track Volume");
  26615. check ("browser: volume Min / Max = " + lynx::mapmode::rangeText (offline, volume, 0.0f) + " / " + lynx::mapmode::rangeText (offline, volume, 1.0f),
  26616. lynx::mapmode::rangeText (offline, volume, 0.0f) == juce::String::fromUTF8 ("\xe2\x88\x92\xe2\x88\x9e dB")
  26617. && lynx::mapmode::rangeText (offline, volume, 1.0f).endsWith (" dB"));
  26618. const lynx::remotemap::Target pan = Target::parameter ({ lynx::AutomationTargetKind::mixerPan, 1, 0, 0 });
  26619. check ("browser: pan Min / Max = " + lynx::mapmode::rangeText (offline, pan, 0.25f) + " / " + lynx::mapmode::rangeText (offline, pan, 0.5f),
  26620. lynx::mapmode::rangeText (offline, pan, 0.25f) == "50L" && lynx::mapmode::rangeText (offline, pan, 0.5f) == "C"
  26621. && lynx::mapmode::rangeText (offline, pan, 1.0f) == "100R");
  26622. const auto typed = lynx::mapmode::rangeValueOf (offline, volume, "0 dB");
  26623. check ("browser: typing 0 dB", typed.has_value() && std::abs (lynx::mapmode::rangeText (offline, volume, *typed).getDoubleValue()) < 0.15);
  26624. check ("browser: typing 50L", lynx::mapmode::rangeValueOf (offline, pan, "50L") == std::optional<float> (0.25f));
  26625. check ("browser: Key column = " + lynx::mapmode::listKeyText ('V') + ", " + lynx::mapmode::listKeyText ('3'),
  26626. lynx::mapmode::listKeyText ('V') == "Key v" && lynx::mapmode::listKeyText ('3') == "Key 3");
  26627. check ("browser: slot row Name = " + lynx::mapmode::describe (offline, Target::slot (0, 2)).second,
  26628. lynx::mapmode::describe (offline, Target::slot (0, 2)) == std::pair<juce::String, juce::String> ("Drums", "Slot 3"));
  26629. }
  26630. // off again: the key mapping on a parameter toggles it between Min and Max
  26631. ui.keyPressed (juce::KeyPress ('K', juce::ModifierKeys::ctrlModifier, 0));
  26632. check ("Ctrl+K again ends it", ui.getMapMode() == Mode::off && ! overlay->isVisible() && ! list->isVisible());
  26633. const lynx::AutomationTarget keysVolume { lynx::AutomationTargetKind::mixerVolume, 2, 0, 0 };
  26634. // (round 190em, Live 12.4.16: the first press goes to Min, then Max, then Min)
  26635. ui.keyPressed (juce::KeyPress ('V', {}, 'v'));
  26636. check ("the mapped key V moves Bass's volume to Min first", std::abs (offline.currentTargetValue (keysVolume)) < 0.01f);
  26637. ui.keyStateChanged (false); // (V is not down any more: its release)
  26638. ui.keyPressed (juce::KeyPress ('V', {}, 'v'));
  26639. check ("again: to Max", std::abs (offline.currentTargetValue (keysVolume) - 1.0f) < 0.01f);
  26640. ui.keyStateChanged (false);
  26641. ui.keyPressed (juce::KeyPress ('V', {}, 'v'));
  26642. check ("again: to Min", std::abs (offline.currentTargetValue (keysVolume)) < 0.01f);
  26643. ui.keyStateChanged (false);
  26644. // the title bar switches
  26645. ui.setMapMode (Mode::midi);
  26646. write (ui, "06-switches-midi-on");
  26647. ui.setMapMode (Mode::off);
  26648. ui.setClipLaunchWorkflow (false);
  26649. check ("leaving the Clip-launch layout ends the map mode", ui.getMapMode() == Mode::off);
  26650. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  26651. }
  26652. void runSceneShot190ef (const juce::String& prefix)
  26653. {
  26654. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  26655. lynx::AudioEngine offline (false);
  26656. lynx::MainComponent ui (offline, false);
  26657. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  26658. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  26659. const auto write = [&prefix] (juce::Component& c, const char* name) {
  26660. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  26661. file.deleteFile();
  26662. juce::FileOutputStream out (file);
  26663. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (c), out);
  26664. };
  26665. juce::String checks;
  26666. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  26667. ui.setVisible (true);
  26668. lynx::DetailView::shownSetting = false;
  26669. ui.setClipLaunchWorkflow (true);
  26670. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::playlist });
  26671. offline.editSong ([] (lynx::Song& s) {
  26672. const int channels = (int) s.channels.size();
  26673. s.channels.resize ((std::size_t) channels + 3);
  26674. const char* names[] { "Drum kit", "Bass synth", "Keys" };
  26675. for (int k = 0; k < 3; ++k)
  26676. {
  26677. auto& ch = s.channels[(std::size_t) (channels + k)];
  26678. ch.name = names[k];
  26679. ch.instrument = k == 0 ? lynx::InstrumentKind::sampler : lynx::InstrumentKind::synth;
  26680. }
  26681. while (s.patterns.size() < 3)
  26682. s.patterns.emplace_back();
  26683. const char* patterns[] { "Beat", "Bassline", "Chords" };
  26684. for (int p = 0; p < 3; ++p)
  26685. {
  26686. auto& pattern = s.patterns[(std::size_t) p];
  26687. pattern.name = patterns[p];
  26688. lynx::Note n;
  26689. n.channel = channels + p;
  26690. n.key = 48 + p * 5;
  26691. pattern.notes = { n };
  26692. pattern.lengthTicks = 4 * lynx::ppq;
  26693. }
  26694. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 6));
  26695. const char* tracks[] { "Drums", "Bass", "Keys" };
  26696. const std::uint32_t colours[] { 0xFFE0533Bu, 0xFF3B8BE0u, 0xFF46C27Au };
  26697. for (int t = 0; t < 3; ++t)
  26698. {
  26699. s.playlistTracks[(std::size_t) t].name = tracks[t];
  26700. s.playlistTracks[(std::size_t) t].colour = colours[t];
  26701. }
  26702. for (int t = 0; t < 3; ++t)
  26703. for (int r = 0; r < 3; ++r)
  26704. if (! (t == 2 && r == 0))
  26705. {
  26706. lynx::Clip clip;
  26707. clip.pattern = t;
  26708. clip.length = 4 * lynx::ppq;
  26709. lynx::launcher::setClip (s, t, r, clip);
  26710. }
  26711. auto& grid = lynx::launcher::ensureGrid (s);
  26712. grid.scenes.resize (4);
  26713. const char* scenes[] { "Intro", "Verse", "Drop" };
  26714. for (int r = 0; r < 3; ++r)
  26715. grid.scenes[(std::size_t) r].name = scenes[r];
  26716. lynx::session::setSceneTempo (s, 1, 128.0);
  26717. lynx::session::setSceneSignature (s, 1, 3, 4); // (as the live check's "Verse": 3 / 4)
  26718. lynx::session::setSceneSignature (s, 2, 6, 8); // (round 190em: a denominator of its own)
  26719. grid.scenes[2].colour = 0xFF8E5BD6u;
  26720. }, false);
  26721. offline.dispatchPendingMessages();
  26722. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  26723. offline.dispatchPendingMessages();
  26724. ui.resized();
  26725. auto* gridView = ui.getClipGridForSnapshot();
  26726. if (gridView == nullptr)
  26727. {
  26728. juce::File (prefix + "-checks.txt").replaceWithText ("FAIL no grid\n");
  26729. return;
  26730. }
  26731. lynx::clipGridSceneTempoShown() = true;
  26732. lynx::refreshClipGrid (*gridView);
  26733. lynx::selectClipGridScene (*gridView, 1);
  26734. write (*gridView, "01-scene-fields");
  26735. {
  26736. // round 190em: a plain scene's launch triangle in Live's dark grey (#1E1E1E), scene 4 (row 3)
  26737. const auto image = lynx::shot::snapshot (*gridView);
  26738. int dark = 0;
  26739. for (int y = 0; y < image.getHeight(); ++y)
  26740. for (int x = image.getWidth() - 240; x < image.getWidth() - 180; ++x)
  26741. if (const auto p = image.getPixelAt (x, y); y > 3 * 24 + 26 && y < 4 * 24 + 26 && std::abs (p.getRed() - 0x1e) <= 2
  26742. && std::abs (p.getGreen() - 0x1e) <= 2 && std::abs (p.getBlue() - 0x1e) <= 2)
  26743. ++dark;
  26744. check ("plain scene triangle in Live's #1E1E1E (" + juce::String (dark) + " px)", dark >= 20);
  26745. }
  26746. saveMenus (juce::StringArray { "Scene menu (Verse)" }, std::vector<juce::PopupMenu> { lynx::clipGridSceneMenu (*gridView, 1) }, prefix + "-02-scene-menu.png");
  26747. saveMenus (juce::StringArray { "Scene tempo field", "Scene time signature field" },
  26748. std::vector<juce::PopupMenu> { lynx::clipGridSceneFieldMenu (*gridView, 1, 1), lynx::clipGridSceneFieldMenu (*gridView, 2, 2) },
  26749. prefix + "-03-field-menus.png");
  26750. saveMenus (juce::StringArray { "Column title (Bass)" }, std::vector<juce::PopupMenu> { lynx::clipGridHeaderMenu (*gridView, 1) }, prefix + "-04-title-menu.png");
  26751. const auto clipsIn = [&offline] (int row) {
  26752. int n = 0;
  26753. if (const auto& g = offline.getSong().clipGrid)
  26754. for (int t = 0; t < 8; ++t)
  26755. n += lynx::launcher::clipAt (*g, t, row) != nullptr ? 1 : 0;
  26756. return n;
  26757. };
  26758. const auto before = clipsIn (1);
  26759. const auto dup = lynx::duplicateClipGridScene (*gridView, 1);
  26760. offline.dispatchPendingMessages();
  26761. const auto& scenesNow = offline.getSong().clipGrid->scenes;
  26762. check ("duplicate: Verse's copy is row 2, with its clips and tempo", dup == 2 && clipsIn (2) == before && scenesNow.size() > 2
  26763. && scenesNow[2].name == "Verse" && scenesNow[2].tempo == 128.0);
  26764. write (*gridView, "05-scene-duplicated");
  26765. const auto cap = lynx::captureClipGridScene (*gridView, 3, { 0, 2, 1 }); // Drums row 0, Bass row 2, Keys row 1
  26766. offline.dispatchPendingMessages();
  26767. check ("capture: a new row 4 with the three playing clips", cap == 4 && clipsIn (4) == 3);
  26768. {
  26769. const auto& sc = offline.getSong().clipGrid->scenes;
  26770. check ("capture while playing: the new scene is plain (no name, fields off)", sc.size() > 4 && sc[4] == lynx::ClipGridScene {});
  26771. }
  26772. write (*gridView, "06-scene-captured");
  26773. // round 190em: nothing plays: an empty scene like the selected one (name, tempo, signature), selected
  26774. const auto empty = lynx::captureClipGridScene (*gridView, 1, { -1, -1 });
  26775. offline.dispatchPendingMessages();
  26776. {
  26777. const auto& sc = offline.getSong().clipGrid->scenes;
  26778. check ("capture with nothing playing: an empty row 2 named Verse, 128 BPM, 3 / 4", empty == 2 && clipsIn (2) == 0 && sc[2].name == "Verse"
  26779. && sc[2].tempo == 128.0 && sc[2].beatsPerBar == 3 && sc[2].beatUnit == 4);
  26780. }
  26781. write (*gridView, "06b-scene-captured-stopped");
  26782. // round 190em: Capture and Insert while clips play: playback moves to the new row (the runtime view shows what
  26783. // the player reports once the published song holds the moved slots)
  26784. {
  26785. const auto rowsBefore = offline.getSong().clipGrid->scenes.size();
  26786. lynx::selectClipGridScene (*gridView, 0);
  26787. const auto at = lynx::captureClipGridScene (*gridView, 0, { 0, 0, -1 });
  26788. offline.dispatchPendingMessages();
  26789. const auto& g = *offline.getSong().clipGrid;
  26790. check ("capture while playing: row 1 holds the moved playing slots", at == 1 && g.scenes.size() == rowsBefore + 1
  26791. && clipsIn (1) == 2 && clipsIn (0) == 2 && g.scenes[1] == lynx::ClipGridScene {});
  26792. if (auto* runtime = offline.launcherStateForSnapshot())
  26793. for (int t = 0; t < 2; ++t)
  26794. runtime->tracks[(std::size_t) t].playing.store (1);
  26795. lynx::refreshClipGrid (*gridView);
  26796. write (*gridView, "09-capture-playing-moves");
  26797. if (auto* runtime = offline.launcherStateForSnapshot())
  26798. for (int t = 0; t < 2; ++t)
  26799. runtime->tracks[(std::size_t) t].playing.store (-1);
  26800. }
  26801. // round 190em: the fields as "n / d", a selected field, Del = Return to Default
  26802. lynx::clipGridSceneTempoShown() = true;
  26803. lynx::refreshClipGrid (*gridView);
  26804. {
  26805. const auto& sc = offline.getSong().clipGrid->scenes;
  26806. int verse = -1;
  26807. for (int r = 0; r < (int) sc.size() && verse < 0; ++r)
  26808. if (sc[(std::size_t) r].name == "Verse" && sc[(std::size_t) r].tempo > 0.0)
  26809. verse = r;
  26810. lynx::selectClipGridSceneField (*gridView, verse, 1);
  26811. write (*gridView, "10-field-selected");
  26812. gridView->keyPressed (juce::KeyPress (juce::KeyPress::deleteKey));
  26813. offline.dispatchPendingMessages();
  26814. const auto& after = offline.getSong().clipGrid->scenes;
  26815. check ("Del on a selected tempo field returns it to default (scene kept)", verse >= 0 && after.size() == sc.size()
  26816. && after[(std::size_t) verse].tempo == 0.0 && after[(std::size_t) verse].beatsPerBar == 3);
  26817. write (*gridView, "11-field-returned-to-default");
  26818. }
  26819. // round 190em: Capture MIDI to the armed track (Bass), the selected scene's slot, the tempo from the phrase
  26820. {
  26821. offline.stop();
  26822. offline.setGridTrackArmed (1, true, true);
  26823. lynx::selectClipGridScene (*gridView, 0);
  26824. int empty = 0;
  26825. while (lynx::launcher::clipAt (*offline.getSong().clipGrid, 1, empty) != nullptr)
  26826. ++empty;
  26827. const auto now = juce::Time::getMillisecondCounterHiRes();
  26828. const auto beat = 60000.0 / 148.0;
  26829. for (int i = 0; i < 8; ++i)
  26830. {
  26831. const auto at = now - 9.0 * beat + i * beat;
  26832. offline.logPlayedNoteForTest (at, 0, 60 + (i % 4) * 2, 0.8f, true);
  26833. offline.logPlayedNoteForTest (at + beat * 0.5, 0, 60 + (i % 4) * 2, 0.8f, false);
  26834. }
  26835. int placed = -1;
  26836. bool into = true;
  26837. const auto r = offline.captureMidiToSlot (1, empty, placed, into);
  26838. offline.dispatchPendingMessages();
  26839. check ("Capture MIDI: 8 notes into Bass row " + juce::String (placed) + ", tempo " + juce::String (offline.getSong().bpm, 2),
  26840. r.notes == 8 && placed == empty && ! into && std::abs (offline.getSong().bpm - 148.0) < 0.5 && offline.getTransport().playing.load());
  26841. const auto& capturedGrid = *offline.getSong().clipGrid;
  26842. const auto* capturedClip = lynx::launcher::clipAt (capturedGrid, 1, placed);
  26843. const auto* slot = capturedClip != nullptr ? &capturedGrid.slots[(std::size_t) capturedClip->gridSlot] : nullptr;
  26844. check ("Capture MIDI: the clip has no name of its own (blank label, as Live)", slot != nullptr && slot->name.empty() && slot->blankName);
  26845. if (auto* runtime = offline.launcherStateForSnapshot())
  26846. runtime->tracks[1].playing.store (placed);
  26847. lynx::refreshClipGrid (*gridView);
  26848. write (*gridView, "12-capture-midi");
  26849. if (auto* runtime = offline.launcherStateForSnapshot())
  26850. runtime->tracks[1].playing.store (-1);
  26851. offline.stop();
  26852. }
  26853. write (ui, "07-window");
  26854. lynx::clipGridSceneTempoShown() = false;
  26855. lynx::refreshClipGrid (*gridView);
  26856. write (*gridView, "08-fields-off");
  26857. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  26858. }
  26859. void runDrawShot190ef (const juce::String& prefix)
  26860. {
  26861. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  26862. lynx::AudioEngine offline (false);
  26863. lynx::MainComponent ui (offline, false);
  26864. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  26865. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  26866. const auto write = [&prefix] (juce::Component& c, const char* name) {
  26867. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  26868. file.deleteFile();
  26869. juce::FileOutputStream out (file);
  26870. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (c), out);
  26871. };
  26872. juce::String checks;
  26873. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  26874. ui.setVisible (true);
  26875. ui.setClipLaunchWorkflow (true);
  26876. ui.setClipGridView (lynx::PlaylistArea::GridView::song);
  26877. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::playlist });
  26878. lynx::autolanes::setShown (true);
  26879. offline.editSong ([] (lynx::Song& s) {
  26880. if (s.mixer.size() < 4)
  26881. s.mixer.resize (4);
  26882. s.mixer[1].name = "Bass";
  26883. s.mixer[2].name = "Pad";
  26884. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 6));
  26885. s.playlistTracks[0].name = "Bass";
  26886. s.playlistTracks[0].mode = lynx::PlaylistTrackMode::audio;
  26887. s.playlistTracks[0].mixerTrack = 1;
  26888. s.playlistTracks[1].name = "Pad";
  26889. s.playlistTracks[1].mode = lynx::PlaylistTrackMode::audio;
  26890. s.playlistTracks[1].mixerTrack = 2;
  26891. }, false);
  26892. lynx::createAutomationLane (offline, { lynx::AutomationTargetKind::mixerVolume, 1, 0, 0 }, 0);
  26893. lynx::createAutomationLane (offline, { lynx::AutomationTargetKind::mixerPan, 2, 0, 0 }, 1);
  26894. offline.editSong ([] (lynx::Song& s) {
  26895. for (int t = 0; t < 2; ++t)
  26896. if (! s.playlistTracks[(std::size_t) t].lanes.empty())
  26897. s.playlistTracks[(std::size_t) t].lanes[0].height = 110;
  26898. }, false);
  26899. offline.dispatchPendingMessages();
  26900. auto& playlist = ui.getPlaylistForSnapshot();
  26901. playlist.setViewForSnapshot (180.0, 0, 0);
  26902. ui.resized();
  26903. offline.dispatchPendingMessages();
  26904. const auto& song = offline.getSong();
  26905. const auto laneA = song.playlistTracks[0].lanes.empty() ? -1 : song.playlistTracks[0].lanes[0].automation;
  26906. const auto laneB = song.playlistTracks[1].lanes.empty() ? -1 : song.playlistTracks[1].lanes[0].automation;
  26907. check ("two lanes made", laneA >= 0 && laneB >= 0);
  26908. if (laneA < 0 || laneB < 0)
  26909. {
  26910. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  26911. return;
  26912. }
  26913. write (ui, "00-lanes-before");
  26914. const auto before = song.automations[(std::size_t) laneA].points;
  26915. // a drag through the Playlist's own handlers (the events a real mouse sends)
  26916. auto source = juce::Desktop::getInstance().getMainMouseSource();
  26917. const auto now = juce::Time::getCurrentTime();
  26918. const auto stroke = [&] (int track, const std::vector<juce::Point<float>>& path, juce::ModifierKeys extra) {
  26919. const juce::ModifierKeys mods (juce::ModifierKeys::leftButtonModifier | extra.getRawFlags());
  26920. const auto event = [&] (juce::Point<float> p, juce::ModifierKeys m, bool dragged) {
  26921. return juce::MouseEvent (source, p, m, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, &playlist, &playlist, now, path.front(), now, 1, dragged);
  26922. };
  26923. juce::ignoreUnused (track);
  26924. // (the engine joins the edits of one press into one undo step while a button is down)
  26925. const auto held = juce::ModifierKeys::currentModifiers;
  26926. juce::ModifierKeys::currentModifiers = mods;
  26927. playlist.mouseDown (event (path.front(), mods, false));
  26928. for (std::size_t i = 1; i < path.size(); ++i)
  26929. playlist.mouseDrag (event (path[i], mods, true));
  26930. juce::ModifierKeys::currentModifiers = held;
  26931. playlist.mouseUp (event (path.back(), extra, true));
  26932. };
  26933. const auto bodyA = playlist.laneBodyForSnapshot (0, 0), bodyB = playlist.laneBodyForSnapshot (1, 0);
  26934. const auto bar = (double) (4 * lynx::ppq);
  26935. const auto x = [&] (double bars) { return (float) playlist.xOfTickForSnapshot (bars * bar); };
  26936. const auto y = [] (juce::Rectangle<float> body, float v) { return body.getBottom() - v * body.getHeight(); };
  26937. lynx::drawmode::set (true);
  26938. // steps: a rise over bar 1 and a fall over bar 2, at the Playlist's grid (Line, at this zoom)
  26939. std::vector<juce::Point<float>> steps;
  26940. for (int k = 0; k <= 16; ++k)
  26941. steps.push_back ({ x (1.0 + k / 16.0) + 2.0f, y (bodyA, 0.15f + 0.05f * (float) k) });
  26942. for (int k = 0; k <= 16; ++k)
  26943. steps.push_back ({ x (2.0 + k / 16.0) + 2.0f, y (bodyA, 0.95f - 0.05f * (float) k) });
  26944. stroke (0, steps, {});
  26945. const auto& afterSteps = offline.getSong().automations[(std::size_t) laneA].points;
  26946. check ("Draw Mode drag made steps (" + juce::String ((int) afterSteps.size()) + " points)", afterSteps.size() > before.size() + 4);
  26947. bool unchangedOutside = true;
  26948. for (double t = 0.0; t < 6.0 * bar; t += 37.0)
  26949. if ((t < bar - 1.0 || t > 3.1 * bar) && std::abs (lynx::automationCurveAt (before, t) - lynx::automationCurveAt (afterSteps, t)) > 1.0e-4f)
  26950. unchangedOutside = false;
  26951. check ("the curve outside the drawn bars is unchanged", unchangedOutside);
  26952. {
  26953. // flat inside each drawn cell: the values in a cell's first and last tick are the same
  26954. int flatCells = 0, cells = 0;
  26955. for (double t = bar; t < 3.0 * bar; t += lynx::ppq / 4.0)
  26956. {
  26957. ++cells;
  26958. if (std::abs (lynx::automationCurveAt (afterSteps, t + 1.0) - lynx::automationCurveAt (afterSteps, t + lynx::ppq / 4.0 - 1.0)) < 1.0e-5f)
  26959. ++flatCells;
  26960. }
  26961. check ("each sixteenth inside bars 2-3 is flat (" + juce::String (flatCells) + " / " + juce::String (cells) + ")", flatCells == cells);
  26962. }
  26963. // freehand: Alt (no grid) on the pad's pan lane, a wave over bars 1-4
  26964. const auto panBefore = offline.getSong().automations[(std::size_t) laneB].points;
  26965. // (off-screen every press has the same mouse-down time, which the undo history uses to join one press's edits:
  26966. // an edit with no button down in between separates the two strokes, as a real second press does)
  26967. offline.editSong ([] (lynx::Song&) {});
  26968. std::vector<juce::Point<float>> wave;
  26969. for (int k = 0; k <= 60; ++k)
  26970. wave.push_back ({ x (1.0 + 3.0 * k / 60.0), y (bodyB, 0.5f + 0.4f * std::sin ((float) k * 0.3f)) });
  26971. stroke (1, wave, juce::ModifierKeys (juce::ModifierKeys::altModifier));
  26972. const auto& pan = offline.getSong().automations[(std::size_t) laneB].points;
  26973. check ("Alt drag drew freehand (" + juce::String ((int) pan.size()) + " points)", pan.size() > 30);
  26974. playlist.repaint();
  26975. write (ui, "01-draw-mode-steps-and-freehand");
  26976. if (auto* parent = playlist.getParentComponent())
  26977. write (*parent, "01b-playlist");
  26978. // one stroke is one undo step
  26979. offline.undo();
  26980. check ("one undo takes the whole freehand stroke back", offline.getSong().automations[(std::size_t) laneB].points == panBefore);
  26981. // Draw Mode off: the same press adds one point, as before
  26982. lynx::drawmode::set (false);
  26983. const auto countOff = offline.getSong().automations[(std::size_t) laneA].points.size();
  26984. stroke (0, { { x (4.5), y (bodyA, 0.8f) } }, {});
  26985. check ("Draw Mode off: a press adds one point", offline.getSong().automations[(std::size_t) laneA].points.size() == countOff + 1);
  26986. // the Options menu (Clip-launch layout) with the switch
  26987. lynx::drawmode::set (true);
  26988. {
  26989. const auto names = ui.getMenuNamesForSnapshot();
  26990. const auto index = names.indexOf (TRANS ("Options"));
  26991. if (index >= 0)
  26992. saveMenus (juce::StringArray { "Options" }, std::vector<juce::PopupMenu> { ui.getMenuForSnapshot (index) }, prefix + "-02-options-menu.png");
  26993. check ("Options menu found", index >= 0);
  26994. }
  26995. lynx::drawmode::set (false);
  26996. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  26997. }
  26998. void runClipEnvShot190gi (const juce::String& prefix)
  26999. {
  27000. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  27001. lynx::AudioEngine offline (false);
  27002. lynx::MainComponent ui (offline, false);
  27003. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  27004. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  27005. const auto write = [&prefix] (juce::Component& c, const char* name) {
  27006. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  27007. file.deleteFile();
  27008. juce::FileOutputStream out (file);
  27009. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (c), out);
  27010. };
  27011. juce::String checks;
  27012. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  27013. // two files: a sustained pad (4 s, a slow swell, for the envelope over its waveform) and a one-bar loop of clicks
  27014. const auto writeWav = [] (const juce::File& file, int seconds, const std::function<float (int, double)>& fn) {
  27015. const double rate = 48000.0;
  27016. juce::AudioBuffer<float> buffer (2, (int) (rate * seconds));
  27017. for (int ch = 0; ch < 2; ++ch)
  27018. for (int i = 0; i < buffer.getNumSamples(); ++i)
  27019. buffer.setSample (ch, i, fn (i, rate));
  27020. file.deleteFile();
  27021. if (auto out = std::unique_ptr<juce::FileOutputStream> (file.createOutputStream()))
  27022. if (auto* writer = juce::WavAudioFormat().createWriterFor (out.get(), rate, 2, 16, {}, 0))
  27023. {
  27024. out.release();
  27025. std::unique_ptr<juce::AudioFormatWriter> owned (writer);
  27026. owned->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
  27027. }
  27028. return file;
  27029. };
  27030. const auto pad = writeWav (juce::File (prefix + "-pad.wav"), 4, [] (int i, double rate) {
  27031. const auto t = i / rate;
  27032. return (float) (0.45 * (std::sin (juce::MathConstants<double>::twoPi * 220.0 * t) + 0.5 * std::sin (juce::MathConstants<double>::twoPi * 331.0 * t))
  27033. * (0.7 + 0.3 * std::sin (juce::MathConstants<double>::twoPi * 1.5 * t)));
  27034. });
  27035. const auto loop = writeWav (juce::File (prefix + "-loop.wav"), 2, [] (int i, double) {
  27036. const auto k = i % 12000;
  27037. const auto hit = i / 12000;
  27038. return k < 3000 ? (float) (std::sin (k * (hit % 4 == 0 ? 0.05 : 0.3)) * std::exp (-k / 500.0) * 0.8) : 0.0f;
  27039. });
  27040. ui.setVisible (true);
  27041. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::playlist });
  27042. offline.editSong ([&] (lynx::Song& s) {
  27043. const auto add = [&s] (const char* name, const juce::File& file) {
  27044. lynx::ChannelDef ch;
  27045. ch.name = name;
  27046. ch.instrument = lynx::InstrumentKind::audioClip;
  27047. ch.samplePath = file.getFullPathName().toStdString();
  27048. s.channels.push_back (ch);
  27049. return (int) s.channels.size() - 1;
  27050. };
  27051. const auto padChannel = add ("Pad", pad), loopChannel = add ("Loop", loop);
  27052. s.playlist.clear();
  27053. lynx::Clip a;
  27054. a.kind = lynx::ClipKind::audio;
  27055. a.channel = padChannel;
  27056. a.length = 8 * lynx::ppq;
  27057. a.track = 0;
  27058. s.playlist.push_back (a);
  27059. a.track = 1;
  27060. s.playlist.push_back (a);
  27061. lynx::Clip b = a;
  27062. b.channel = loopChannel;
  27063. b.track = 2;
  27064. b.length = 4 * lynx::ppq;
  27065. s.playlist.push_back (b);
  27066. // the first clip: a volume envelope (a swell, a dip, FL's curve modes on two segments)
  27067. auto& e = lynx::clipenv::own (s, s.playlist[0]);
  27068. e.shown = lynx::clipenv::volumeLane;
  27069. e.volume = { { 0, 0.15f, 0.0f, 0 }, { lynx::ppq * 2, 1.0f, -0.6f, 0 }, { lynx::ppq * 4, 1.0f, 0.0f, 0 },
  27070. { lynx::ppq * 5, 0.45f, 0.0f, 2 }, { lynx::ppq * 6, 0.9f, 0.0f, 0 }, { lynx::ppq * 8, 0.9f, 0.0f, 0 } };
  27071. // the second: its pan lane shown (only pan made)
  27072. lynx::clipenv::show (s, s.playlist[1], lynx::clipenv::panLane);
  27073. auto& p = lynx::clipenv::own (s, s.playlist[1]);
  27074. 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 } };
  27075. if (s.playlistTracks.size() < 3)
  27076. s.playlistTracks.resize (3);
  27077. for (int t = 0; t < 3; ++t)
  27078. s.playlistTracks[(std::size_t) t].height = 96;
  27079. }, false);
  27080. offline.dispatchPendingMessages();
  27081. auto& playlist = ui.getPlaylistForSnapshot();
  27082. playlist.setViewForSnapshot (360.0, 0, 0);
  27083. ui.resized();
  27084. offline.dispatchPendingMessages();
  27085. (void) lynx::shot::snapshot (ui); // (a paint starts the waveform analyses; the shot waits for them)
  27086. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (8000);
  27087. offline.dispatchPendingMessages();
  27088. write (ui, "01-playlist-envelopes");
  27089. // the clip menu: LYNX's extras with Clip envelope ›, Auto-warp, Quantize audio (Auto-warp run from it on the loop)
  27090. {
  27091. const auto menu = playlist.getClipMenuForSnapshot (2);
  27092. const juce::PopupMenu* envelopeMenu = nullptr;
  27093. bool autoWarp = false, quantize = false;
  27094. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  27095. {
  27096. if (it.getItem().text == lynx::tr ("Clip envelope") && it.getItem().subMenu != nullptr)
  27097. envelopeMenu = it.getItem().subMenu.get();
  27098. autoWarp = autoWarp || (it.getItem().text == lynx::tr ("Auto-warp") && it.getItem().isEnabled);
  27099. quantize = quantize || (it.getItem().text == lynx::tr ("Quantize audio") && it.getItem().isEnabled);
  27100. }
  27101. check ("clip menu: Clip envelope submenu, Auto-warp, Quantize audio", envelopeMenu != nullptr && autoWarp && quantize);
  27102. saveMenus (juce::StringArray { lynx::tr ("Audio clip"), lynx::tr ("Clip envelope") },
  27103. std::vector<juce::PopupMenu> { menu, envelopeMenu != nullptr ? *envelopeMenu : juce::PopupMenu() }, prefix + "-02-clip-menu.png");
  27104. check ("Auto-warp from the clip menu places markers", clickMenuItem (menu, lynx::tr ("Auto-warp")));
  27105. offline.dispatchPendingMessages();
  27106. const auto& s = offline.getSong();
  27107. const auto& loopClip = s.playlist[2];
  27108. check ("the loop's channel is warped", s.channels[(std::size_t) loopClip.channel].sampler.warp.size() >= 2
  27109. && s.channels[(std::size_t) loopClip.channel].sampler.keepPitch);
  27110. // the first clip's menu: Show volume envelope ticked
  27111. const auto first = playlist.getClipMenuForSnapshot (0);
  27112. bool ticked = false;
  27113. for (juce::PopupMenu::MenuItemIterator it (first); it.next();)
  27114. if (it.getItem().text == lynx::tr ("Clip envelope") && it.getItem().subMenu != nullptr)
  27115. for (juce::PopupMenu::MenuItemIterator sub (*it.getItem().subMenu); sub.next();)
  27116. ticked = ticked || (sub.getItem().text == lynx::tr ("Show volume envelope") && sub.getItem().isTicked);
  27117. check ("Show volume envelope is ticked on the first clip", ticked);
  27118. }
  27119. // gestures through the Playlist's own handlers
  27120. auto source = juce::Desktop::getInstance().getMainMouseSource();
  27121. const auto now = juce::Time::getCurrentTime();
  27122. const auto press = [&] (juce::Point<float> from, juce::Point<float> to, juce::ModifierKeys button, juce::ModifierKeys extra) {
  27123. const juce::ModifierKeys mods (button.getRawFlags() | extra.getRawFlags());
  27124. const auto event = [&] (juce::Point<float> p, juce::ModifierKeys m, bool dragged) {
  27125. return juce::MouseEvent (source, p, m, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, &playlist, &playlist, now, from, now, 1, dragged);
  27126. };
  27127. const auto held = juce::ModifierKeys::currentModifiers;
  27128. juce::ModifierKeys::currentModifiers = mods;
  27129. playlist.mouseDown (event (from, mods, false));
  27130. if (to != from)
  27131. playlist.mouseDrag (event (to, mods, true));
  27132. juce::ModifierKeys::currentModifiers = held;
  27133. playlist.mouseUp (event (to, extra, to != from));
  27134. };
  27135. const auto x = [&] (double beats) { return (float) playlist.xOfTickForSnapshot (beats * lynx::ppq); };
  27136. {
  27137. const auto body = playlist.curveBodyForSnapshot (0);
  27138. const auto points = offline.getSong().clipEnvelopes[(std::size_t) offline.getSong().playlist[0].envelope].volume.size();
  27139. // [RMB] in the curve's area adds a point there (FL's in-Playlist automation editing, round 165)
  27140. press ({ x (7.0), body.getBottom() - 0.3f * body.getHeight() }, { x (7.0), body.getBottom() - 0.3f * body.getHeight() },
  27141. juce::ModifierKeys::rightButtonModifier, {});
  27142. offline.dispatchPendingMessages();
  27143. const auto& s = offline.getSong();
  27144. const auto* e = lynx::clipenv::of (s, s.playlist[0]);
  27145. check ("[RMB] on the clip's volume lane adds a point", e != nullptr && e->volume.size() == points + 1
  27146. && std::abs (lynx::automationCurveAt (e->volume, 7.0 * lynx::ppq) - 0.3f) < 0.05f);
  27147. // drag that point up with the Pencil
  27148. press ({ x (7.0), body.getBottom() - 0.3f * body.getHeight() }, { x (7.0), body.getBottom() - 0.7f * body.getHeight() },
  27149. juce::ModifierKeys::leftButtonModifier, {});
  27150. offline.dispatchPendingMessages();
  27151. const auto* moved = lynx::clipenv::of (offline.getSong(), offline.getSong().playlist[0]);
  27152. check ("dragging the point moves it", moved != nullptr && std::abs (lynx::automationCurveAt (moved->volume, 7.0 * lynx::ppq) - 0.7f) < 0.05f);
  27153. check ("the edits are undoable", offline.canUndo());
  27154. }
  27155. write (ui, "03-playlist-edited");
  27156. {
  27157. // warp: a double-click on the loop clip's flag strip adds a marker; Alt + drag on its line (mid clip) moves it
  27158. const auto bounds = playlist.clipBoundsForSnapshot (2);
  27159. const auto channelOf = [&] { return offline.getSong().playlist[2].channel; };
  27160. const auto markers = [&] { return offline.getSong().channels[(std::size_t) channelOf()].sampler.warp; };
  27161. const auto before = markers().size();
  27162. const juce::Point<float> strip { x (1.5), (float) bounds.getY() + 13.0f + 3.0f };
  27163. playlist.mouseDoubleClick (juce::MouseEvent (source, strip, juce::ModifierKeys::leftButtonModifier, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, &playlist, &playlist,
  27164. now, strip, now, 2, false));
  27165. offline.dispatchPendingMessages();
  27166. check ("a double-click on the flag strip adds a warp marker", markers().size() == before + 1);
  27167. if (markers().size() != before + 1)
  27168. checks << " (strip seconds " << playlist.warpStripSecondsForSnapshot (2, strip.toInt()) << ", played markers "
  27169. << (int) playlist.warpMarkerCountForSnapshot (2) << ", file seconds " << playlist.clipFileSecondsForSnapshot (2)
  27170. << ", channel markers " << (int) before << ", clip at " << bounds.toString() << ", strip " << strip.toString() << ")\n";
  27171. int added = -1;
  27172. for (int k = 0; k < (int) markers().size(); ++k)
  27173. if (std::abs (markers()[(std::size_t) k].beats - 1.5) < 0.05)
  27174. added = k;
  27175. check ("the marker sits on the beat it was added on", added > 0);
  27176. if (added > 0)
  27177. {
  27178. const juce::Point<float> line { x (1.5), (float) bounds.getCentreY() + 10.0f };
  27179. press (line, line.translated (x (1.75) - x (1.5), 0.0f), juce::ModifierKeys::leftButtonModifier, juce::ModifierKeys::altModifier);
  27180. offline.dispatchPendingMessages();
  27181. 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);
  27182. }
  27183. }
  27184. write (ui, "04-playlist-warp");
  27185. // the Clip-launch layout: the Clip View's Envelopes tab of a grid audio clip
  27186. offline.editSong ([&] (lynx::Song& s) {
  27187. auto clip = s.playlist[0];
  27188. clip.start = 0;
  27189. lynx::launcher::setClip (s, 0, 0, clip);
  27190. lynx::launcher::ensureGrid (s).scenes.resize (std::max<std::size_t> (1, lynx::launcher::ensureGrid (s).scenes.size()));
  27191. }, false);
  27192. offline.dispatchPendingMessages();
  27193. const auto shootPanel = [&] (const char* name, bool envelopes, std::uint8_t lane) {
  27194. auto panel = lynx::makeClipAudioPanel (offline, 0, 0);
  27195. if (panel == nullptr)
  27196. return false;
  27197. panel->setSize (1100, 300);
  27198. for (auto* child : panel->getChildren())
  27199. if (auto* b = dynamic_cast<juce::TextButton*> (child); b != nullptr && b->getButtonText() == (envelopes ? lynx::tr ("Envelopes") : lynx::tr ("Sample")))
  27200. if (b->onClick)
  27201. b->onClick();
  27202. if (lane != 0)
  27203. offline.editSong ([lane] (lynx::Song& s) {
  27204. if (s.clipGrid)
  27205. if (auto* c = const_cast<lynx::Clip*> (lynx::launcher::clipAt (*s.clipGrid, 0, 0)); c != nullptr)
  27206. lynx::clipenv::show (s, *c, lane);
  27207. }, false);
  27208. offline.dispatchPendingMessages();
  27209. write (*panel, name);
  27210. return true;
  27211. };
  27212. check ("Clip View: Sample tab", shootPanel ("05-clipview-sample", false, 0));
  27213. check ("Clip View: Envelopes tab, Clip > Gain", shootPanel ("06-clipview-envelopes-gain", true, lynx::clipenv::volumeLane));
  27214. check ("Clip View: Envelopes tab, Mixer > Track Panning", shootPanel ("07-clipview-envelopes-pan", true, lynx::clipenv::panLane));
  27215. {
  27216. const auto* c = offline.getSong().clipGrid ? lynx::launcher::clipAt (*offline.getSong().clipGrid, 0, 0) : nullptr;
  27217. check ("the grid clip keeps the volume envelope", c != nullptr && lynx::clipenv::activeOf (offline.getSong(), *c) != nullptr);
  27218. }
  27219. shootPanel ("08-clipview-sample-again", false, 0); // (the tab choice back to Sample for the next run)
  27220. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  27221. }
  27222. void runGapsShot190kf (const juce::String& prefix, const juce::String& wavPath)
  27223. {
  27224. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  27225. lynx::AudioEngine offline (false);
  27226. juce::String checks;
  27227. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  27228. // the probe's file, else a LYNX-made stand-in (8.42 s of a decaying 220 Hz tone every half second, 44.1 kHz)
  27229. auto wav = juce::File (wavPath);
  27230. if (! wav.existsAsFile())
  27231. {
  27232. wav = juce::File (prefix + "-probe.wav");
  27233. wav.deleteFile();
  27234. const double rate = 44100.0;
  27235. juce::AudioBuffer<float> buffer (1, (int) (rate * 8.421));
  27236. for (int k = 0; k < buffer.getNumSamples(); ++k)
  27237. {
  27238. const auto t = std::fmod (k / rate, 0.5);
  27239. buffer.setSample (0, k, (float) (0.5 * std::exp (-t * 6.0) * std::sin (2.0 * juce::MathConstants<double>::pi * 220.0 * k / rate)));
  27240. }
  27241. if (auto out = std::unique_ptr<juce::FileOutputStream> (wav.createOutputStream()))
  27242. if (auto* writer = juce::WavAudioFormat().createWriterFor (out.get(), rate, 1, 16, {}, 0))
  27243. {
  27244. out.release();
  27245. std::unique_ptr<juce::AudioFormatWriter> owned (writer);
  27246. owned->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
  27247. }
  27248. }
  27249. double seconds = 0.0;
  27250. {
  27251. juce::AudioFormatManager formats;
  27252. formats.registerBasicFormats();
  27253. if (std::unique_ptr<juce::AudioFormatReader> r (formats.createReaderFor (wav)); r != nullptr && r->sampleRate > 0.0)
  27254. seconds = (double) r->lengthInSamples / r->sampleRate;
  27255. }
  27256. check ("probe file " + wav.getFileName() + " " + juce::String (seconds, 3) + " s", seconds > 1.0);
  27257. const auto beats = seconds * 2.0; // (warped at 120 BPM, its own tempo)
  27258. offline.editSong ([&] (lynx::Song& s) {
  27259. s.bpm = 120.0;
  27260. lynx::ChannelDef ch;
  27261. ch.name = "warped";
  27262. ch.instrument = lynx::InstrumentKind::audioClip;
  27263. ch.samplePath = wav.getFullPathName().toStdString();
  27264. ch.sampler.keepPitch = true;
  27265. ch.sampler.stretchMethod = lynx::StretchMethod::complex;
  27266. ch.sampler.stretchBeats = (float) beats;
  27267. ch.sampler.warp = { { 0.0, 0.0 }, { seconds * 0.3, beats * 0.25 }, { seconds * 0.55, beats * 0.5 }, { seconds, beats } };
  27268. s.channels.push_back (ch);
  27269. const auto c = (int) s.channels.size() - 1;
  27270. lynx::Clip audio;
  27271. audio.kind = lynx::ClipKind::audio;
  27272. audio.channel = c;
  27273. audio.offset = 2 * lynx::ppq; // (Loop Position 1.3, Length 2.0.0 → 3.3, Start 1.4: the probe set's)
  27274. audio.length = 8 * lynx::ppq;
  27275. lynx::launcher::setClip (s, 0, 0, audio);
  27276. lynx::launcher::ensureGrid (s).scenes.resize (1);
  27277. auto& grid = *s.clipGrid;
  27278. for (auto& g : grid.clips)
  27279. if (g.gridSlot >= 0)
  27280. {
  27281. grid.slots[(std::size_t) g.gridSlot].loop = true;
  27282. grid.slots[(std::size_t) g.gridSlot].startMarker = lynx::ppq;
  27283. }
  27284. }, false);
  27285. offline.dispatchPendingMessages();
  27286. const auto editorOf = [] (juce::Component& panel) -> juce::Component* {
  27287. for (auto* child : panel.getChildren())
  27288. if (child->isVisible() && child->getWidth() > 400 && dynamic_cast<juce::Button*> (child) == nullptr)
  27289. return child;
  27290. return nullptr;
  27291. };
  27292. const auto write = [&] (juce::Component& panel, const char* name) {
  27293. offline.dispatchPendingMessages();
  27294. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  27295. file.deleteFile();
  27296. juce::FileOutputStream out (file);
  27297. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (panel), out);
  27298. };
  27299. const auto slotOf = [&] (auto&& fn) {
  27300. offline.editSong ([&] (lynx::Song& s) {
  27301. for (auto& g : s.clipGrid->clips)
  27302. if (g.gridSlot >= 0)
  27303. fn (g, s.clipGrid->slots[(std::size_t) g.gridSlot]);
  27304. }, false);
  27305. offline.dispatchPendingMessages();
  27306. };
  27307. {
  27308. auto panel = lynx::makeClipAudioPanel (offline, 0, 0);
  27309. check ("the Clip View panel", panel != nullptr);
  27310. if (panel == nullptr)
  27311. return;
  27312. panel->setSize (1390, 670);
  27313. if (auto* e = editorOf (*panel)) // (the Clip-launch layout's beat-time view; off-screen there is no layout)
  27314. lynx::setAudioEditorBeatTimeForSnapshot (*e, 1);
  27315. write (*panel, "01-loop-on-start-marker");
  27316. // perf (round gaps190kf): the sample editor painted 40 times with the warp time line (a grid clip's editor)
  27317. // and without it (the same channel's editor panel, no grid clip) — ms per full paint
  27318. {
  27319. const auto timeIt = [] (juce::Component& c) {
  27320. juce::Image image (juce::Image::ARGB, c.getWidth(), c.getHeight(), true);
  27321. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  27322. for (int k = 0; k < 40; ++k)
  27323. {
  27324. juce::Graphics g (image);
  27325. c.paintEntireComponent (g, false);
  27326. }
  27327. return (juce::Time::getMillisecondCounterHiRes() - t0) / 40.0;
  27328. };
  27329. if (auto* withLane = editorOf (*panel))
  27330. {
  27331. auto plain = lynx::makeAudioEditorPanel (offline, (int) offline.getSong().channels.size() - 1, -1, true);
  27332. plain->setSize (withLane->getWidth(), withLane->getHeight());
  27333. lynx::setAudioEditorBeatTimeForSnapshot (*plain, 1);
  27334. offline.dispatchPendingMessages();
  27335. timeIt (*withLane);
  27336. timeIt (*plain);
  27337. double a = 0.0, b = 0.0;
  27338. for (int round = 0; round < 3; ++round)
  27339. {
  27340. a += timeIt (*withLane) / 3.0;
  27341. b += timeIt (*plain) / 3.0;
  27342. }
  27343. check ("paint ms: with the warp time line " + juce::String (a, 3) + ", without " + juce::String (b, 3), true);
  27344. }
  27345. }
  27346. auto* editor = editorOf (*panel);
  27347. check ("its sample editor", editor != nullptr);
  27348. if (editor != nullptr)
  27349. {
  27350. lynx::selectAudioEditorBraceForSnapshot (*editor, true);
  27351. write (*panel, "02-brace-selected");
  27352. lynx::selectAudioEditorBraceForSnapshot (*editor, false);
  27353. lynx::holdAudioEditorBraceForSnapshot (*editor, 2, 12 * lynx::ppq); // (the loop's end dragged to 4.1)
  27354. write (*panel, "03-loop-end-held-at-4.1");
  27355. lynx::holdAudioEditorBraceForSnapshot (*editor, 0, 0);
  27356. }
  27357. }
  27358. slotOf ([] (lynx::Clip& c, lynx::ClipGridSlot& slot) {
  27359. slot.loop = false;
  27360. slot.startMarker = 0;
  27361. c.offset = 0;
  27362. c.length = (std::int64_t) std::llround (10.0 * lynx::ppq);
  27363. });
  27364. {
  27365. auto panel = lynx::makeClipAudioPanel (offline, 0, 0);
  27366. if (panel != nullptr)
  27367. {
  27368. panel->setSize (1390, 670);
  27369. if (auto* e = editorOf (*panel))
  27370. lynx::setAudioEditorBeatTimeForSnapshot (*e, 1);
  27371. write (*panel, "04-loop-off-start-end");
  27372. }
  27373. }
  27374. offline.editSong ([&] (lynx::Song& s) { lynx::clipsample::setWarp (s, (int) s.channels.size() - 1, false, seconds); }, false);
  27375. offline.dispatchPendingMessages();
  27376. {
  27377. auto panel = lynx::makeClipAudioPanel (offline, 0, 0);
  27378. if (panel != nullptr)
  27379. {
  27380. panel->setSize (1390, 670);
  27381. if (auto* e = editorOf (*panel))
  27382. lynx::setAudioEditorBeatTimeForSnapshot (*e, 1);
  27383. write (*panel, "05-unwarped-seconds");
  27384. }
  27385. }
  27386. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  27387. }
  27388. void runLiveFactsShot190gx (const juce::String& prefix)
  27389. {
  27390. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  27391. lynx::AudioEngine offline (false);
  27392. juce::String checks;
  27393. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  27394. // a 1 kHz sine, 20 s at 48 kHz (Live's 190gu clip-envelope stimulus), −9 dBFS
  27395. const auto wav = juce::File (prefix + "-sine1k.wav");
  27396. wav.deleteFile();
  27397. {
  27398. const double rate = 48000.0;
  27399. juce::AudioBuffer<float> buffer (2, (int) (rate * 20.0));
  27400. for (int k = 0; k < buffer.getNumSamples(); ++k)
  27401. for (int ch = 0; ch < 2; ++ch)
  27402. buffer.setSample (ch, k, (float) (0.3535 * std::sin (2.0 * juce::MathConstants<double>::pi * 1000.0 * k / rate)));
  27403. if (auto out = std::unique_ptr<juce::FileOutputStream> (wav.createOutputStream()))
  27404. if (auto* writer = juce::WavAudioFormat().createWriterFor (out.get(), rate, 2, 16, {}, 0))
  27405. {
  27406. out.release();
  27407. std::unique_ptr<juce::AudioFormatWriter> owned (writer);
  27408. owned->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
  27409. }
  27410. }
  27411. offline.editSong ([&wav] (lynx::Song& s) {
  27412. s.bpm = 120.0;
  27413. lynx::ChannelDef ch;
  27414. ch.name = "sine1k";
  27415. ch.instrument = lynx::InstrumentKind::audioClip;
  27416. ch.samplePath = wav.getFullPathName().toStdString();
  27417. s.channels.push_back (ch);
  27418. const auto c = (int) s.channels.size() - 1;
  27419. lynx::clipsample::setWarp (s, c, true, 20.0);
  27420. lynx::warpmodes::setMode (s, c, (int) lynx::StretchMethod::beats);
  27421. lynx::Clip audio;
  27422. audio.kind = lynx::ClipKind::audio;
  27423. audio.channel = c;
  27424. audio.length = 40 * lynx::ppq;
  27425. // Live's Clip Gain staircase of the 190gu render (−1 … 1 in 0.1 steps, 2 beats each), as LYNX lane values
  27426. lynx::ClipEnvelope e;
  27427. for (int k = 0; k <= 20; ++k)
  27428. {
  27429. const auto v = lynx::clipenv::fromLive (lynx::clipenv::volumeLane, -1.0 + 0.1 * k);
  27430. for (const auto at : { 2 * k, 2 * k + 2 })
  27431. {
  27432. lynx::AutomationPoint p;
  27433. p.tick = (std::int64_t) at * lynx::ppq;
  27434. p.value = v;
  27435. e.volume.push_back (p);
  27436. }
  27437. }
  27438. e.shown = lynx::clipenv::volumeLane;
  27439. s.clipEnvelopes.push_back (e);
  27440. audio.envelope = (int) s.clipEnvelopes.size() - 1;
  27441. lynx::launcher::setClip (s, 0, 0, audio);
  27442. lynx::launcher::ensureGrid (s).scenes.resize (1);
  27443. }, false);
  27444. offline.dispatchPendingMessages();
  27445. const auto channelOf = [&] {
  27446. const auto* c = lynx::warpmodes::gridAudioClip (const_cast<lynx::Song&> (offline.getSong()), 0, 0);
  27447. return c != nullptr ? c->channel : -1;
  27448. };
  27449. const auto shoot = [&] (const char* name, int w, int h, int tab) {
  27450. auto panel = lynx::makeClipAudioPanel (offline, 0, 0);
  27451. if (panel == nullptr)
  27452. return std::unique_ptr<juce::Component>();
  27453. panel->setSize (w, h);
  27454. if (tab != 0)
  27455. for (auto* child : panel->getChildren())
  27456. if (auto* b = dynamic_cast<juce::TextButton*> (child); b != nullptr && b->getButtonText() == (tab == 2 ? lynx::tr ("Envelopes") : lynx::tr ("Sample")))
  27457. if (b->onClick)
  27458. b->onClick();
  27459. offline.dispatchPendingMessages();
  27460. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  27461. file.deleteFile();
  27462. juce::FileOutputStream out (file);
  27463. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (*panel), out);
  27464. return panel;
  27465. };
  27466. const auto visibleText = [] (juce::Component& panel, const juce::String& text) {
  27467. for (auto* child : panel.getChildren())
  27468. if (auto* b = dynamic_cast<juce::TextButton*> (child); b != nullptr && b->getButtonText() == text)
  27469. return b->isVisible();
  27470. return false;
  27471. };
  27472. const auto setMode = [&] (int method) {
  27473. offline.editSong ([&] (lynx::Song& s) { lynx::warpmodes::setMode (s, channelOf(), method); }, false);
  27474. offline.dispatchPendingMessages();
  27475. };
  27476. check ("01 Beats (Preserve label + chooser, loop icon + Transient Envelope)", shoot ("01-audio-beats", 900, 250, 1) != nullptr);
  27477. setMode ((int) lynx::StretchMethod::tones);
  27478. check ("02 Tones (Grain Size 30.00)", shoot ("02-audio-tones", 900, 250, 1) != nullptr);
  27479. setMode ((int) lynx::StretchMethod::texture);
  27480. check ("03 Texture (Grain Size 65.00, Flux only when it plays)", shoot ("03-audio-texture", 900, 250, 1) != nullptr);
  27481. { // (round 190ik: Complex Pro plays, its Formants and Envelope show)
  27482. offline.editSong ([&] (lynx::Song& s) { lynx::warpmodes::setComplexPro (s, channelOf()); }, false);
  27483. offline.dispatchPendingMessages();
  27484. check ("04 Complex Pro (Formants 100.00, Envelope 128)", shoot ("04-audio-complex-pro", 900, 250, 1) != nullptr);
  27485. offline.editSong ([&] (lynx::Song& s) { lynx::warpmodes::setWarpLaw (s, channelOf(), 0); }, false);
  27486. offline.dispatchPendingMessages();
  27487. check ("04b Complex Pro of a project saved before 0.1.30 (law chooser, no Formants / Envelope)",
  27488. shoot ("04b-audio-complex-pro-classic", 900, 250, 1) != nullptr);
  27489. offline.editSong ([&] (lynx::Song& s) { lynx::warpmodes::setWarpLaw (s, channelOf(), 1); }, false);
  27490. offline.dispatchPendingMessages();
  27491. }
  27492. setMode ((int) lynx::StretchMethod::beats);
  27493. {
  27494. auto panel = shoot ("05-envelopes-clip-gain-staircase", 1390, 420, 2);
  27495. check ("05 Envelopes tab shown on a warped clip", panel != nullptr && visibleText (*panel, lynx::tr ("Envelopes")));
  27496. }
  27497. offline.editSong ([&] (lynx::Song& s) { lynx::clipsample::setWarp (s, channelOf(), false, 20.0); }, false);
  27498. offline.dispatchPendingMessages();
  27499. {
  27500. auto panel = shoot ("06-unwarped-sample-only", 1390, 420, 2);
  27501. check ("06 an unwarped clip has no Envelopes tab (Live)", panel != nullptr && ! visibleText (*panel, lynx::tr ("Envelopes"))
  27502. && visibleText (*panel, lynx::tr ("Sample")));
  27503. }
  27504. // the law: Live's staircase values round trip through the lane values
  27505. bool law = true;
  27506. for (int k = 0; k <= 20; ++k)
  27507. {
  27508. const auto L = -1.0 + 0.1 * k;
  27509. law = law && std::abs (lynx::clipenv::toLive (lynx::clipenv::volumeLane, lynx::clipenv::fromLive (lynx::clipenv::volumeLane, L)) - L) < 2.0e-3;
  27510. }
  27511. check ("Clip Gain values round trip (Live → lane → Live)", law);
  27512. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  27513. }
  27514. void runDvShot190hr (const juce::String& prefix)
  27515. {
  27516. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  27517. lynx::AudioEngine offline (false);
  27518. lynx::MainComponent ui (offline, false);
  27519. ui.setSize (1600, 900);
  27520. juce::String checks;
  27521. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  27522. const auto write = [&prefix] (juce::Component& c, const char* name) {
  27523. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  27524. file.deleteFile();
  27525. juce::FileOutputStream out (file);
  27526. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (c), out);
  27527. };
  27528. ui.setVisible (true);
  27529. lynx::DetailView::shownSetting = true;
  27530. ui.selectTabForSnapshot (2);
  27531. ui.setLayoutStyle (lynx::layoutstyle::Style::clipLaunch);
  27532. offline.editSong ([] (lynx::Song& s) {
  27533. const int ch = (int) s.channels.size();
  27534. s.channels.resize ((std::size_t) ch + 1);
  27535. s.channels[(std::size_t) ch].name = "Keys";
  27536. s.channels[(std::size_t) ch].instrument = lynx::InstrumentKind::synth;
  27537. while (s.patterns.empty())
  27538. s.patterns.emplace_back();
  27539. auto& p = s.patterns[0];
  27540. p.name = "Riff";
  27541. p.notes.clear();
  27542. const int keys[] { 62, 65, 69, 72, 64, 67 };
  27543. for (int i = 0; i < 6; ++i)
  27544. {
  27545. lynx::Note n;
  27546. n.channel = ch;
  27547. n.key = keys[i];
  27548. n.start = i * lynx::ppq / 2 + (i % 2 ? 37 : -0) + 11; // a little off the 1/16 grid
  27549. n.length = lynx::ppq / 3;
  27550. p.notes.push_back (n);
  27551. }
  27552. p.lengthTicks = 4 * lynx::ppq;
  27553. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 3));
  27554. s.playlistTracks[0].name = "Keys";
  27555. lynx::Clip clip;
  27556. clip.pattern = 0;
  27557. clip.length = 4 * lynx::ppq;
  27558. const auto id = lynx::launcher::setClip (s, 0, 0, clip);
  27559. lynx::launcher::setClip (s, 0, 1, clip);
  27560. auto& grid = lynx::launcher::ensureGrid (s);
  27561. grid.scenes.resize (3);
  27562. if (id >= 0)
  27563. {
  27564. auto& slot = grid.slots[(std::size_t) id];
  27565. slot.name = "Riff";
  27566. slot.startMarker = 2 * lynx::ppq; // Start 1. 3. 1 inside the loop 1. 1. 1 + 1 bar
  27567. slot.ownScale = true;
  27568. slot.scaleRoot = 2; // D, the scale list's first (Major)
  27569. slot.scaleIndex = (std::int16_t) lynx::projectkey::commonFirst().front();
  27570. slot.follow.enabled = true;
  27571. slot.follow.a = lynx::FollowKind::next;
  27572. slot.follow.b = lynx::FollowKind::jump;
  27573. slot.follow.jumpB = 1;
  27574. slot.follow.chanceA = 70;
  27575. slot.follow.chanceB = 30;
  27576. slot.follow.linked = true;
  27577. slot.follow.iterations = 2;
  27578. }
  27579. }, false);
  27580. offline.dispatchPendingMessages();
  27581. ui.resized();
  27582. auto* detail = ui.getDetailViewForSnapshot();
  27583. if (detail == nullptr)
  27584. {
  27585. juce::File (prefix + "-checks.txt").replaceWithText ("FAIL no detail view\n");
  27586. return;
  27587. }
  27588. detail->showSelection (0, 0);
  27589. detail->setPage (lynx::DetailView::Page::clip);
  27590. offline.dispatchPendingMessages();
  27591. ui.resized();
  27592. write (ui, "01-clip-view-midi");
  27593. write (*detail, "01b-detail-alone");
  27594. auto& roll = ui.getPianoRollForSnapshot();
  27595. check ("the docked editor uses the reference's grid (" + roll.liveGridTextForCheck() + ")", roll.liveGridOn() && roll.liveGridTextForCheck().isNotEmpty());
  27596. 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);
  27597. {
  27598. std::vector<juce::PopupMenu> menus { roll.liveGridMenu() };
  27599. saveMenus (juce::StringArray { "Grid" }, menus, prefix + "-02-grid-menu.png");
  27600. }
  27601. roll.liveGrid.fixed = true;
  27602. roll.liveGrid.fixedIndex = lynx::livegrid::defaultFixed;
  27603. roll.resized();
  27604. const auto sixteenth = roll.gridStepForCheck();
  27605. roll.runAction ("pianoRoll.liveGridNarrower");
  27606. const auto narrower = roll.gridStepForCheck();
  27607. roll.runAction ("pianoRoll.liveGridTriplet");
  27608. const auto triplet = roll.gridStepForCheck();
  27609. 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) + ")",
  27610. sixteenth == lynx::ppq / 4 && narrower == lynx::ppq / 8 && triplet == lynx::ppq / 12);
  27611. write (roll, "03-editor-grid-1-32T");
  27612. roll.runAction ("pianoRoll.liveGridTriplet");
  27613. roll.runAction ("pianoRoll.liveGridWider");
  27614. const auto before = offline.getSong().patterns[0].notes;
  27615. roll.runAction ("pianoRoll.liveQuantize"); // (Live 12: Edit › Quantize, the Quantize tool's settings: Grid = 1/16 here)
  27616. offline.dispatchPendingMessages();
  27617. {
  27618. const auto& after = offline.getSong().patterns[0].notes;
  27619. bool onGrid = ! after.empty();
  27620. for (const auto& n : after)
  27621. onGrid = onGrid && n.start % (lynx::ppq / 4) == 0;
  27622. check ("Ctrl+U quantized every note start onto the editor's 1/16 grid", onGrid && after.size() == before.size() && after != before);
  27623. }
  27624. roll.runAction ("pianoRoll.liveQuantizeSettings"); // (Live 12: Quantize Settings… opens the MIDI Tools' Quantize tool)
  27625. offline.dispatchPendingMessages();
  27626. check ("Ctrl+Shift+U shows the MIDI Tools' Quantize tool", detail->midiToolsForSnapshot().getTool() == lynx::MidiToolsPanel::quantize
  27627. && detail->midiToolsForSnapshot().isVisible());
  27628. ui.resized();
  27629. write (*detail, "04-after-quantize-tool");
  27630. // an audio clip transposed +30 st 25 ct (Live's ±48 st)
  27631. const auto wav = juce::File (prefix + "-tone.wav");
  27632. wav.deleteFile();
  27633. {
  27634. const double rate = 48000.0;
  27635. juce::AudioBuffer<float> buffer (1, (int) (rate * 2.0));
  27636. for (int k = 0; k < buffer.getNumSamples(); ++k)
  27637. buffer.setSample (0, k, (float) (0.5 * std::sin (k * 0.05)));
  27638. if (auto out = std::unique_ptr<juce::FileOutputStream> (wav.createOutputStream()))
  27639. if (auto* writer = juce::WavAudioFormat().createWriterFor (out.get(), rate, 1, 16, {}, 0))
  27640. {
  27641. out.release();
  27642. std::unique_ptr<juce::AudioFormatWriter> owned (writer);
  27643. owned->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
  27644. }
  27645. }
  27646. offline.editSong ([&wav] (lynx::Song& s) {
  27647. lynx::ChannelDef ch;
  27648. ch.name = "Tone";
  27649. ch.instrument = lynx::InstrumentKind::audioClip;
  27650. ch.samplePath = wav.getFullPathName().toStdString();
  27651. s.channels.push_back (ch);
  27652. lynx::Clip audio;
  27653. audio.kind = lynx::ClipKind::audio;
  27654. audio.channel = (int) s.channels.size() - 1;
  27655. audio.length = 4 * lynx::ppq;
  27656. audio.pitch = 30.25f;
  27657. lynx::launcher::setClip (s, 1, 0, audio);
  27658. }, false);
  27659. offline.dispatchPendingMessages();
  27660. if (auto panel = lynx::makeClipAudioPanel (offline, 1, 0))
  27661. {
  27662. panel->setSize (900, 250);
  27663. write (*panel, "06-audio-transpose-30");
  27664. check ("audio clip transpose +30.25 st kept", std::abs (lynx::launcher::clipAt (*offline.getSong().clipGrid, 1, 0)->pitch - 30.25f) < 1e-4f);
  27665. }
  27666. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  27667. }
  27668. void runWarpShot190fm (const juce::String& prefix)
  27669. {
  27670. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  27671. lynx::AudioEngine offline (false);
  27672. juce::String checks;
  27673. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  27674. // a one-bar loop of clicks (2 s at 48 kHz) for the audio clips
  27675. const auto wav = juce::File (prefix + "-loop.wav");
  27676. wav.deleteFile();
  27677. {
  27678. const double rate = 48000.0;
  27679. juce::AudioBuffer<float> buffer (2, (int) (rate * 2.0));
  27680. buffer.clear();
  27681. for (int hit = 0; hit < 8; ++hit)
  27682. for (int k = 0; k < 3000; ++k)
  27683. for (int ch = 0; ch < 2; ++ch)
  27684. buffer.setSample (ch, hit * 12000 + k, (float) (std::sin (k * (hit % 4 == 0 ? 0.05 : 0.3)) * std::exp (-k / 500.0) * 0.8));
  27685. if (auto out = std::unique_ptr<juce::FileOutputStream> (wav.createOutputStream()))
  27686. if (auto* writer = juce::WavAudioFormat().createWriterFor (out.get(), rate, 2, 16, {}, 0))
  27687. {
  27688. out.release();
  27689. std::unique_ptr<juce::AudioFormatWriter> owned (writer);
  27690. owned->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
  27691. }
  27692. }
  27693. offline.editSong ([&wav] (lynx::Song& s) {
  27694. lynx::ChannelDef ch;
  27695. ch.name = "Loop";
  27696. ch.instrument = lynx::InstrumentKind::audioClip;
  27697. ch.samplePath = wav.getFullPathName().toStdString();
  27698. s.channels.push_back (ch);
  27699. const auto c = (int) s.channels.size() - 1;
  27700. lynx::clipsample::setWarp (s, c, true, 2.0);
  27701. lynx::warpmodes::setMode (s, c, (int) lynx::StretchMethod::beats); // (keeps the pitch: Beats, not Re-Pitch)
  27702. lynx::Clip audio;
  27703. audio.kind = lynx::ClipKind::audio;
  27704. audio.channel = c;
  27705. audio.length = 4 * lynx::ppq;
  27706. lynx::launcher::setClip (s, 0, 0, audio);
  27707. lynx::launcher::setClip (s, 0, 1, audio); // (a second clip on the same channel: O16)
  27708. lynx::launcher::ensureGrid (s).scenes.resize (2);
  27709. }, false);
  27710. offline.dispatchPendingMessages();
  27711. const auto shoot = [&] (const char* name) {
  27712. auto panel = lynx::makeClipAudioPanel (offline, 0, 0);
  27713. if (panel == nullptr)
  27714. return false;
  27715. panel->setSize (900, 250);
  27716. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  27717. file.deleteFile();
  27718. juce::FileOutputStream out (file);
  27719. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (*panel), out);
  27720. return true;
  27721. };
  27722. const auto channelOf = [&] (int scene) {
  27723. const auto* c = lynx::warpmodes::gridAudioClip (const_cast<lynx::Song&> (offline.getSong()), 0, scene);
  27724. return c != nullptr ? c->channel : -1;
  27725. };
  27726. const auto beatsOn = [&] { const auto& sm = offline.getSong().channels[(std::size_t) channelOf (0)].sampler; return sm.keepPitch && sm.stretchMethod == lynx::StretchMethod::beats; };
  27727. check ("01 Beats panel (defaults: Transients, Back-and-Forth, 100)", beatsOn() && shoot ("01-beats-defaults"));
  27728. offline.editSong ([&] (lynx::Song& s) {
  27729. const auto c = lynx::warpmodes::ownChannelForGridClip (s, 0, 0);
  27730. lynx::warpmodes::setPreserve (s, c, 3);
  27731. lynx::warpmodes::setLoopMode (s, c, 0);
  27732. lynx::warpmodes::setEnvelope (s, c, 40.0);
  27733. }, false);
  27734. offline.dispatchPendingMessages();
  27735. 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);
  27736. check ("02 Beats panel (1/8, Loop Off, 40)", beatsOn() && shoot ("02-beats-set"));
  27737. offline.editSong ([&] (lynx::Song& s) { lynx::warpmodes::setMode (s, channelOf (0), (int) lynx::StretchMethod::tones); }, false);
  27738. offline.dispatchPendingMessages();
  27739. check ("03 Tones panel (Grain Size 30)", shoot ("03-tones"));
  27740. offline.editSong ([&] (lynx::Song& s) {
  27741. lynx::warpmodes::setMode (s, channelOf (0), (int) lynx::StretchMethod::texture);
  27742. lynx::warpmodes::setGrain (s, channelOf (0), 120.0);
  27743. }, false);
  27744. offline.dispatchPendingMessages();
  27745. check ("04 Texture panel (Grain Size 120)", shoot ("04-texture"));
  27746. check ("Texture grain kept 120, Tones grain still 30", offline.getSong().channels[(std::size_t) channelOf (0)].sampler.warpModes.textureGrain == 120.0f
  27747. && offline.getSong().channels[(std::size_t) channelOf (0)].sampler.warpModes.tonesGrain == 30.0f);
  27748. offline.editSong ([&] (lynx::Song& s) { lynx::warpmodes::setMode (s, channelOf (0), (int) lynx::StretchMethod::complex); }, false);
  27749. offline.dispatchPendingMessages();
  27750. check ("05 Complex panel (no settings row)", shoot ("05-complex"));
  27751. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  27752. }
  27753. // LYNX --livelook190jnshot prefix [set.als]: round 190jn off screen (design190ia slices 13 CL-D, 17 CL-E, 18 CL-H,
  27754. // 19 CL-F, 25 CL-I: the Clip-launch layout in Ableton Live's look) — the Session mixer (selected, armed, muted,
  27755. // soloed, I/O on and off, peak pills), the Device View (cards, a card off and one folded, the hot-swap link, a Drum
  27756. // Rack's pads, an Instrument Rack's macros), the Clip View (MIDI and audio, three detail heights), the Info View with a
  27757. // hovered control and the status strip; with a Live set: its Arrangement in 19 px lanes, the 38 px option and a tall
  27758. // audio lane; every view once more in the classic LYNX look (View › Classic LYNX look). prefix-checks.txt
  27759. void runLiveLook190jnShot (const juce::String& prefix, const juce::String& set)
  27760. {
  27761. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  27762. const juce::ScopedValueSetter<bool> shown (lynx::ui::showingForShots(), true);
  27763. juce::String checks;
  27764. const auto flush = [&] { juce::File (lynx::shot::file (juce::File (prefix + "-checks.txt"))).replaceWithText (checks); };
  27765. const auto check = [&] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; flush(); };
  27766. const auto line = [&] (const juce::String& what) { checks << " " << what << "\n"; flush(); };
  27767. const auto write = [&prefix] (juce::Component& c, const juce::String& name) { savePng (lynx::shot::snapshot (c), prefix + "-" + name + ".png"); };
  27768. const auto area = [&prefix] (juce::Component& c, juce::Rectangle<int> r, const juce::String& name) { saveArea (c, r, prefix + "-" + name + ".png"); };
  27769. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1920x1080"), "x", "");
  27770. const auto w = juce::jlimit (800, 3840, size[0].getIntValue()), h = juce::jlimit (450, 2160, size[1].getIntValue());
  27771. const auto classicBefore = lynx::clipGridClassicLook();
  27772. const auto tallBefore = lynx::playlistTallLiveLanes();
  27773. lynx::clipGridClassicLook() = false;
  27774. lynx::playlistTallLiveLanes() = false;
  27775. lynx::DetailView::infoViewShown = true;
  27776. // ---- A. a synthetic set (round 190dr's, with a Drum Rack and an audio loop) -----------------------------------
  27777. const auto wav = juce::File (prefix + "-loop.wav");
  27778. wav.deleteFile();
  27779. {
  27780. const double rate = 48000.0;
  27781. juce::AudioBuffer<float> buffer (2, (int) (rate * 4.0));
  27782. buffer.clear();
  27783. for (int hit = 0; hit < 16; ++hit)
  27784. for (int k = 0; k < 9000 && hit * 12000 + k < buffer.getNumSamples(); ++k)
  27785. for (int ch = 0; ch < 2; ++ch)
  27786. buffer.setSample (ch, hit * 12000 + k, (float) (std::sin (k * (hit % 4 == 0 ? 0.05 : 0.3)) * std::exp (-k / 2500.0) * 0.8));
  27787. if (auto out = std::unique_ptr<juce::FileOutputStream> (wav.createOutputStream()))
  27788. if (auto* writer = juce::WavAudioFormat().createWriterFor (out.get(), rate, 2, 16, {}, 0))
  27789. {
  27790. out.release();
  27791. std::unique_ptr<juce::AudioFormatWriter> owned (writer);
  27792. owned->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
  27793. }
  27794. }
  27795. {
  27796. lynx::AudioEngine offline (false);
  27797. lynx::MainComponent ui (offline, false);
  27798. ui.setSize (w, h);
  27799. const auto settle = [&] {
  27800. for (int k = 0; k < 3; ++k)
  27801. offline.dispatchPendingMessages();
  27802. };
  27803. ui.setVisible (true);
  27804. lynx::DetailView::shownSetting = true;
  27805. lynx::DetailView::devicesPage = true;
  27806. lynx::DetailView::preferredHeight = 228;
  27807. ui.setClipLaunchWorkflow (true);
  27808. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::browser, lynx::workspace::Panel::playlist });
  27809. ui.getPlaylistForSnapshot().addAudioClipAtPlayhead (wav);
  27810. settle();
  27811. int audioChannel = -1;
  27812. const auto selectedChannel = offline.getSelectedChannel();
  27813. offline.editSong ([&audioChannel, selectedChannel] (lynx::Song& s) {
  27814. lynx::Clip audio;
  27815. if (! s.playlist.empty())
  27816. {
  27817. audio = s.playlist.front();
  27818. audioChannel = audio.channel;
  27819. s.playlist.clear();
  27820. }
  27821. const int channels = (int) s.channels.size();
  27822. s.channels.resize ((std::size_t) channels + 3);
  27823. const char* names[] { "Drum kit", "Bass synth", "Keys" };
  27824. for (int k = 0; k < 3; ++k)
  27825. {
  27826. auto& ch = s.channels[(std::size_t) (channels + k)];
  27827. ch.name = names[k];
  27828. ch.instrument = k == 0 ? lynx::InstrumentKind::patcher : lynx::InstrumentKind::synth;
  27829. ch.mixerTrack = k + 1;
  27830. }
  27831. // the Drum kit: a Drum Rack with Live's 909 pad names, its two first macros mapped
  27832. {
  27833. auto& kit = s.channels[(std::size_t) channels].patcher;
  27834. kit = lynx::rack::makeDrumRack();
  27835. const char* pads[] { "Bass Drum", "Rim Shot", "Snare Drum", "Hand Clap", "Snare Drum", "Closed Hi Hat", "Snare Drum", "Bass Drum",
  27836. "Low Tom", "Mid Tom", "Open Hi Hat", "Hi Tom", "Crash", "Crash", "Ride", "Ride" };
  27837. for (int p = 0; p < 16; ++p)
  27838. {
  27839. lynx::PatchNode n;
  27840. n.generator = true;
  27841. n.channel.instrument = lynx::InstrumentKind::sampler;
  27842. n.channel.name = pads[p];
  27843. lynx::rack::addPad (kit, 36 + p, pads[p], n);
  27844. }
  27845. if (auto* r = lynx::rack::rackOf (kit))
  27846. {
  27847. r->name = "909 Core Kit";
  27848. r->showMacros = true;
  27849. r->showPads = true;
  27850. r->shownMacros = 8;
  27851. r->macros[0].name = "Low Gain";
  27852. r->macros[1].name = "Mid Gain";
  27853. }
  27854. for (int m = 0; m < 2; ++m)
  27855. {
  27856. lynx::RackMapping map;
  27857. map.target = lynx::RackMapping::Target::chainVolume;
  27858. map.chain = m;
  27859. lynx::rack::map (kit, m, map);
  27860. }
  27861. lynx::rack::compile (kit);
  27862. }
  27863. if (audioChannel >= 0)
  27864. s.channels[(std::size_t) audioChannel].mixerTrack = 5;
  27865. if (s.mixer.size() < 8)
  27866. s.mixer.resize (8);
  27867. const char* inserts[] { "Master", "Drums", "Bass", "Keys", "Vox", "Loop", "Reverb", "Delay" };
  27868. for (int i = 1; i < 8; ++i)
  27869. s.mixer[(std::size_t) i].name = inserts[i];
  27870. s.mixer[1].volume = lynx::sessionmixer::positionForDb (-3.0);
  27871. s.mixer[2].pan = 0.3f;
  27872. s.mixer[2].effects.clear();
  27873. for (auto kind : { lynx::EffectKind::eq, lynx::EffectKind::compressor, lynx::EffectKind::delay, lynx::EffectKind::reverb })
  27874. {
  27875. lynx::EffectSlot fx;
  27876. fx.kind = kind;
  27877. const auto& info = lynx::effectInfo (kind);
  27878. for (std::size_t k = 0; k < info.params.size() && k < fx.params.size(); ++k)
  27879. fx.params[k] = info.params[k].defaultValue;
  27880. s.mixer[2].effects.push_back (fx);
  27881. }
  27882. s.mixer[2].effects[2].enabled = false; // (the Delay off: Live dims a device that is off)
  27883. s.mixer[3].muted = true; // the Keys' activator off
  27884. s.mixer[4].inputChannel = 0;
  27885. s.mixer[4].inputStereo = true;
  27886. s.mixer[4].monitor = lynx::InputMonitor::automatic;
  27887. s.mixer[5].solo = false; // (soloed later: Live greys every activator while a track is soloed)
  27888. 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 } })
  27889. {
  27890. lynx::MixerSend send;
  27891. send.target = to;
  27892. send.level = lynx::faderGain (level);
  27893. s.mixer[(std::size_t) from].sends.push_back (send);
  27894. }
  27895. while (s.patterns.size() < 3)
  27896. s.patterns.emplace_back();
  27897. const char* patterns[] { "Beat", "Bassline", "Chords" };
  27898. for (int p = 0; p < 3; ++p)
  27899. {
  27900. auto& pattern = s.patterns[(std::size_t) p];
  27901. pattern.name = patterns[p];
  27902. pattern.notes.clear();
  27903. for (int k = 0; k < 6; ++k)
  27904. {
  27905. lynx::Note n;
  27906. n.channel = channels + p;
  27907. n.key = (p == 0 ? 36 : 48) + (k * 5) % 12 + p * 2;
  27908. n.start = (std::int64_t) k * lynx::ppq / 2;
  27909. n.length = lynx::ppq / 2;
  27910. n.velocity = 0.55f + 0.07f * (float) k;
  27911. pattern.notes.push_back (n);
  27912. }
  27913. pattern.lengthTicks = 4 * lynx::ppq;
  27914. }
  27915. // a "Lead" clip on the FX track for the Clip View's MIDI shot: notes of the rack's selected channel (the docked
  27916. // Piano roll edits its notes) in the Piano roll's opening rows
  27917. {
  27918. const auto kick = juce::jlimit (0, channels - 1, selectedChannel); // (the docked Piano roll edits the selected channel's notes)
  27919. lynx::Pattern lead;
  27920. lead.name = "Lead";
  27921. for (int k = 0; k < 6; ++k)
  27922. {
  27923. lynx::Note n;
  27924. n.channel = kick;
  27925. n.key = 79 + (k * 5) % 6; // (G6 .. C7 in FL's names, C5 = 60: the rows the docked Piano roll opens on)
  27926. n.start = (std::int64_t) k * lynx::ppq / 2;
  27927. n.length = lynx::ppq / 2;
  27928. n.velocity = 0.55f + 0.07f * (float) k;
  27929. lead.notes.push_back (n);
  27930. }
  27931. lead.lengthTicks = 4 * lynx::ppq;
  27932. s.patterns.push_back (lead);
  27933. }
  27934. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 8));
  27935. const char* tracks[] { "Drums", "Bass", "Keys", "Vox", "Loop", "FX" };
  27936. const std::uint32_t colours[] { 0xff9bc48d, 0xffd2e498, 0xffa595b5, 0xffcdf1f8, 0xfff7f47c, 0xffc6928b }; // (Live's palette)
  27937. for (int t = 0; t < 6; ++t)
  27938. {
  27939. s.playlistTracks[(std::size_t) t].name = tracks[t];
  27940. s.playlistTracks[(std::size_t) t].colour = colours[t];
  27941. }
  27942. s.playlistTracks[3].mode = lynx::PlaylistTrackMode::audio;
  27943. s.playlistTracks[3].mixerTrack = 4;
  27944. for (int t = 0; t < 3; ++t)
  27945. for (int r = 0; r < 3; ++r)
  27946. if (! (t == 2 && r == 0))
  27947. {
  27948. lynx::Clip clip;
  27949. clip.pattern = t;
  27950. clip.length = 4 * lynx::ppq;
  27951. lynx::launcher::setClip (s, t, r, clip);
  27952. }
  27953. {
  27954. lynx::Clip lead;
  27955. lead.pattern = (int) s.patterns.size() - 1;
  27956. lead.length = 4 * lynx::ppq;
  27957. lynx::launcher::setClip (s, 5, 0, lead);
  27958. }
  27959. if (audioChannel >= 0)
  27960. {
  27961. lynx::clipsample::setWarp (s, audioChannel, true, 4.0);
  27962. audio.track = 4;
  27963. audio.start = 0;
  27964. lynx::launcher::setClip (s, 4, 0, audio);
  27965. lynx::launcher::setClip (s, 4, 1, audio);
  27966. }
  27967. auto& grid = lynx::launcher::ensureGrid (s);
  27968. const char* scenes[] { "Intro", "Verse", "Drop" };
  27969. grid.scenes.resize (5);
  27970. for (int r = 0; r < 3; ++r)
  27971. grid.scenes[(std::size_t) r].name = scenes[r];
  27972. }, false);
  27973. settle();
  27974. offline.setGridTrackArmed (3, true);
  27975. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  27976. settle();
  27977. ui.resized();
  27978. auto* gridView = ui.getClipGridForSnapshot();
  27979. auto* mixer = gridView != nullptr ? lynx::clipGridMixer (*gridView) : nullptr;
  27980. auto* detail = ui.getDetailViewForSnapshot();
  27981. if (gridView == nullptr || mixer == nullptr || detail == nullptr)
  27982. {
  27983. check ("a grid, a Session mixer and a detail view", false);
  27984. return;
  27985. }
  27986. check ("the Live look is on (Clip-launch, classic off)", lynx::theme::livelook::active());
  27987. const auto meters = [&] {
  27988. mixer->tick();
  27989. const float peaks[] { 0.9f, 0.5f, 0.7f, 0.0f, 0.3f, 0.45f, 0.2f, 0.12f };
  27990. for (int i = 0; i < 8; ++i)
  27991. mixer->setMeterForSnapshot (i, peaks[i], peaks[i] * 0.85f, peaks[i] * 1.1f, peaks[i], i == 1 ? 1.2f : peaks[i] * 1.15f);
  27992. };
  27993. if (auto* runtime = offline.launcherStateForSnapshot())
  27994. {
  27995. runtime->tracks[0].playing.store (1);
  27996. runtime->tracks[0].progress.store (0.3f);
  27997. runtime->tracks[1].playing.store (1);
  27998. runtime->tracks[1].progress.store (0.3f);
  27999. runtime->tracks[4].playing.store (0);
  28000. runtime->tracks[4].progress.store (0.5f);
  28001. runtime->running.store (true);
  28002. }
  28003. lynx::selectClipGridSlotForSnapshot (*gridView, 1, 1); // (the Bass track selected: its strip #464646)
  28004. settle();
  28005. meters();
  28006. gridView->resized();
  28007. write (ui, "13-window");
  28008. write (*gridView, "13-grid-mixer");
  28009. area (*gridView, mixer->getBoundsInParent(), "13-mixer");
  28010. using Part = lynx::SessionMixerComponent::Part;
  28011. check ("mixer: the Drums strip has a peak pill in Live's look", ! mixer->partBounds (0, Part::peak).isEmpty());
  28012. check ("mixer: the Drums peak pill reads the clipped peak", mixer->loudestPeak (1) >= 1.0f);
  28013. line ("mixer: activator " + mixer->partBounds (0, Part::activator).toString() + ", solo " + mixer->partBounds (0, Part::solo).toString()
  28014. + ", arm " + mixer->partBounds (0, Part::arm).toString() + ", pan " + mixer->partBounds (0, Part::pan).toString()
  28015. + ", volume " + mixer->partBounds (0, Part::volume).toString() + ", peak " + mixer->partBounds (0, Part::peak).toString());
  28016. check ("mixer: the activator is Live's 21-23 px square", juce::jlimit (21, 23, mixer->partBounds (0, Part::activator).getWidth()) == mixer->partBounds (0, Part::activator).getWidth());
  28017. mixer->setHoverForSnapshot ({ 1, Part::solo, 0 });
  28018. area (*gridView, mixer->getBoundsInParent(), "13-mixer-hover-solo");
  28019. mixer->setHoverForSnapshot ({});
  28020. // the I/O section off (View › Mixer › I/O)
  28021. offline.editSong ([] (lynx::Song& s) { lynx::launcher::ensureGrid (s).mixerView.io = false; }, false);
  28022. settle();
  28023. gridView->resized();
  28024. meters();
  28025. area (*gridView, mixer->getBoundsInParent(), "13-mixer-io-off");
  28026. // a track soloed: Live greys every active activator (#757575, captured in shots/ref/live-mixer-solo-deactivated.png)
  28027. offline.editSong ([] (lynx::Song& s) { s.mixer[5].solo = true; }, false);
  28028. settle();
  28029. meters();
  28030. area (*gridView, mixer->getBoundsInParent(), "13-mixer-soloing");
  28031. offline.editSong ([] (lynx::Song& s) { s.mixer[5].solo = false; }, false);
  28032. settle();
  28033. offline.editSong ([] (lynx::Song& s) { lynx::launcher::ensureGrid (s).mixerView.io = true; }, false);
  28034. settle();
  28035. gridView->resized();
  28036. // ---- 19 + 25: the Device View of the Bass track (EQ, Compressor, Delay off, Reverb folded), the Info View ----
  28037. detail->showSelection (1, 1);
  28038. detail->setPage (lynx::DetailView::Page::devices);
  28039. settle();
  28040. ui.resized();
  28041. settle();
  28042. const auto cards = detail->cardCountForCheck();
  28043. line ("device view: " + juce::String (cards) + " cards, insert " + juce::String (detail->chainInsertForCheck()));
  28044. if (cards >= 5)
  28045. detail->toggleFoldForCheck (4);
  28046. detail->selectCardForCheck (1);
  28047. meters();
  28048. // the Info View with a hovered control: the Bass strip's activator, as the hint timer would give it
  28049. {
  28050. lynx::ui::Hint hint; // (the mixer's hint is its tooltip, read at the mouse: off screen its text for the part)
  28051. hint.text = mixer->tipForSnapshot ({ 1, Part::activator, 0 });
  28052. detail->setInfoHint (hint);
  28053. line ("info view: title '" + detail->infoViewForSnapshot().getTitleText() + "', body '" + detail->infoViewForSnapshot().getBodyText() + "'");
  28054. check ("info view: the hovered activator's hint shows", detail->infoViewForSnapshot().getBodyText().isNotEmpty());
  28055. }
  28056. write (ui, "19-window-devices");
  28057. write (*detail, "19-detail-devices");
  28058. area (*detail, detail->getLocalBounds().withTrimmedTop (detail->getHeight() - lynx::DetailView::stripHeight), "25-status-strip");
  28059. area (*detail, detail->getLocalBounds().withWidth (260), "25-info-view");
  28060. check ("device view: four effect cards and the instrument", cards >= 5);
  28061. check ("device view: the folded card stays folded", cards < 5 || detail->isFoldedForCheck (4));
  28062. // the hot-swap link on the selected card (Q)
  28063. ui.runActionForSnapshot ("view.hotSwap");
  28064. settle();
  28065. write (*detail, "19-detail-hotswap");
  28066. ui.runActionForSnapshot ("view.hotSwap");
  28067. settle();
  28068. // the Drum Rack (the Drums track's instrument)
  28069. detail->showSelection (0, 1);
  28070. settle();
  28071. detail->selectCardForCheck (0);
  28072. write (*detail, "19-detail-drumrack");
  28073. // an Instrument Rack (Keys grouped: Ctrl+G on the instrument card)
  28074. detail->showSelection (2, 1);
  28075. settle();
  28076. check ("device view: the Keys instrument grouped into an Instrument Rack", detail->groupCardForCheck (0, false));
  28077. settle();
  28078. write (*detail, "19-detail-instrumentrack");
  28079. // the Info View off (its (i) button), then back
  28080. detail->toggleInfoView();
  28081. write (*detail, "25-detail-info-off");
  28082. detail->toggleInfoView();
  28083. // ---- 17: the Clip View: a MIDI clip, then the audio clip at three detail heights --------------------------
  28084. detail->showSelection (5, 0); // (the FX track's Lead clip)
  28085. detail->setPage (lynx::DetailView::Page::clip);
  28086. settle();
  28087. ui.resized();
  28088. settle();
  28089. write (ui, "17-window-clip-midi");
  28090. write (*detail, "17-detail-clip-midi");
  28091. // Launch (folded at first, as Live shows it) and Pitch & Time open, the column scrolled to them
  28092. detail->clipSectionsForSnapshot (true, true, true, 0);
  28093. write (*detail, "17-detail-clip-midi-launch-open");
  28094. detail->clipSectionsForSnapshot (true, true, true, 160);
  28095. write (*detail, "17-detail-clip-midi-scrolled");
  28096. detail->clipSectionsForSnapshot (true, false, true, 0);
  28097. detail->showSelection (4, 0);
  28098. settle();
  28099. for (const auto height : { 190, 260, 350 })
  28100. {
  28101. lynx::DetailView::preferredHeight = height;
  28102. ui.resized();
  28103. if (auto* parent = detail->getParentComponent()) // (the Playlist area lays its docked detail view out)
  28104. parent->resized();
  28105. settle();
  28106. write (*detail, "17-detail-clip-audio-" + juce::String (height));
  28107. check ("audio box at " + juce::String (height) + " px: the detail view is that high", detail->getHeight() == height);
  28108. }
  28109. lynx::DetailView::preferredHeight = 228;
  28110. ui.resized();
  28111. if (auto* parent = detail->getParentComponent())
  28112. parent->resized();
  28113. settle();
  28114. write (ui, "17-window-clip-audio");
  28115. // ---- the same views in the classic LYNX look (View › Classic LYNX look in the Clip-launch layout) --------
  28116. lynx::clipGridClassicLook() = true;
  28117. lynx::refreshClipGrid (*gridView);
  28118. ui.getPlaylistForSnapshot().liveLanesChanged();
  28119. ui.resized();
  28120. detail->resized();
  28121. settle();
  28122. check ("classic look: the Live look is off", ! lynx::theme::livelook::active());
  28123. write (ui, "classic-window-clip-audio");
  28124. detail->setPage (lynx::DetailView::Page::devices);
  28125. detail->showSelection (1, 1);
  28126. settle();
  28127. meters();
  28128. write (ui, "classic-window-devices");
  28129. lynx::clipGridClassicLook() = false;
  28130. lynx::refreshClipGrid (*gridView);
  28131. ui.getPlaylistForSnapshot().liveLanesChanged();
  28132. ui.resized();
  28133. settle();
  28134. // ---- 18: the synthetic set's Arrangement (Song view) ------------------------------------------------------
  28135. offline.editSong ([audioChannel] (lynx::Song& s) {
  28136. for (int t = 0; t < 3; ++t)
  28137. for (int bar = 0; bar < 8; bar += 2)
  28138. {
  28139. lynx::Clip clip;
  28140. clip.pattern = t;
  28141. clip.track = t;
  28142. clip.start = (std::int64_t) bar * 4 * lynx::ppq + (t == 2 ? 4 * lynx::ppq : 0);
  28143. clip.length = 4 * lynx::ppq * (t == 1 ? 2 : 1);
  28144. if (! (t == 1 && bar % 4 != 0))
  28145. s.playlist.push_back (clip);
  28146. }
  28147. if (audioChannel >= 0)
  28148. for (int bar = 0; bar < 8; bar += 2)
  28149. {
  28150. lynx::Clip audio;
  28151. audio.channel = audioChannel;
  28152. audio.track = 4;
  28153. audio.start = (std::int64_t) bar * 4 * lynx::ppq;
  28154. audio.length = 8 * lynx::ppq;
  28155. audio.kind = lynx::ClipKind::audio;
  28156. s.playlist.push_back (audio);
  28157. }
  28158. }, false);
  28159. settle();
  28160. ui.setClipGridView (lynx::PlaylistArea::GridView::song);
  28161. settle();
  28162. ui.resized();
  28163. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (30000);
  28164. settle();
  28165. ui.getPlaylistForSnapshot().repaint();
  28166. write (ui, "18-synthetic-arrangement-19");
  28167. lynx::playlistTallLiveLanes() = true;
  28168. ui.getPlaylistForSnapshot().liveLanesChanged();
  28169. settle();
  28170. write (ui, "18-synthetic-arrangement-38");
  28171. lynx::playlistTallLiveLanes() = false;
  28172. ui.getPlaylistForSnapshot().liveLanesChanged();
  28173. settle();
  28174. }
  28175. // ---- B. the Live set (its Arrangement with real audio) ----------------------------------------------------------
  28176. if (set.isNotEmpty() && juce::File (set).existsAsFile())
  28177. {
  28178. lynx::AudioEngine offline (false);
  28179. lynx::MainComponent ui (offline, false);
  28180. ui.setSize (w, h);
  28181. const auto settle = [&] {
  28182. for (int k = 0; k < 3; ++k)
  28183. offline.dispatchPendingMessages();
  28184. };
  28185. ui.setVisible (true);
  28186. lynx::DetailView::shownSetting = true;
  28187. lynx::DetailView::devicesPage = true;
  28188. ui.selectTabForSnapshot (2);
  28189. ui.setClipLaunchWorkflow (true); // (first: the import takes Live's colour table in this layout, CL-6)
  28190. settle();
  28191. ui.openFile (juce::File (set));
  28192. settle();
  28193. ui.setClipGridView (lynx::PlaylistArea::GridView::song);
  28194. settle();
  28195. ui.resized();
  28196. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (60000);
  28197. settle();
  28198. const auto& song = offline.getSong();
  28199. line ("set: " + juce::String ((int) song.playlist.size()) + " Arrangement clips, " + juce::String ((int) song.playlistTracks.size()) + " tracks");
  28200. int drums = -1;
  28201. for (int t = 0; t < (int) song.playlistTracks.size() && drums < 0; ++t)
  28202. if (juce::String::fromUTF8 (song.playlistTracks[(std::size_t) t].name.c_str()).containsIgnoreCase ("drum"))
  28203. drums = t;
  28204. if (drums >= 0)
  28205. line ("set: Drums track colour #" + juce::String::toHexString ((int) (song.playlistTracks[(std::size_t) drums].colour & 0xffffff)).paddedLeft ('0', 6));
  28206. check ("set: the Drums track has Live's colour #9BC48D (CL-6)", drums >= 0 && (song.playlistTracks[(std::size_t) drums].colour & 0xffffff) == 0x9bc48d);
  28207. write (ui, "18-als-arrangement-19");
  28208. // the set's Session mixer (the coordinator's 190jn follow-up: every Patience track has its strip)
  28209. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  28210. settle();
  28211. ui.resized();
  28212. settle();
  28213. if (auto* gridView = ui.getClipGridForSnapshot())
  28214. if (auto* mixer = lynx::clipGridMixer (*gridView))
  28215. {
  28216. int strips = 0;
  28217. for (int t = 0; t < 64; ++t)
  28218. strips += mixer->partBounds (t, lynx::SessionMixerComponent::Part::volume).isEmpty() ? 0 : 1;
  28219. line ("set: Session mixer strips with a volume: " + juce::String (strips) + ", mixer " + mixer->getBounds().toString()
  28220. + ", grid " + gridView->getBounds().toString());
  28221. write (ui, "13-als-window");
  28222. area (*gridView, mixer->getBoundsInParent(), "13-als-mixer");
  28223. }
  28224. ui.setClipGridView (lynx::PlaylistArea::GridView::song);
  28225. settle();
  28226. write (ui.getPlaylistForSnapshot(), "18-als-playlist-19");
  28227. lynx::playlistTallLiveLanes() = true;
  28228. ui.getPlaylistForSnapshot().liveLanesChanged();
  28229. settle();
  28230. write (ui, "18-als-arrangement-38");
  28231. // a tall audio lane (live-arrangement-audiolane.png: Vocal Main at ~250 px)
  28232. int vocal = -1;
  28233. for (int t = 0; t < (int) song.playlistTracks.size() && vocal < 0; ++t)
  28234. if (juce::String::fromUTF8 (song.playlistTracks[(std::size_t) t].name.c_str()).containsIgnoreCase ("vocal"))
  28235. vocal = t;
  28236. if (vocal >= 0)
  28237. {
  28238. offline.editSong ([vocal] (lynx::Song& s) { s.playlistTracks[(std::size_t) vocal].height = 250; }, false);
  28239. lynx::playlistTallLiveLanes() = false;
  28240. ui.getPlaylistForSnapshot().liveLanesChanged();
  28241. settle();
  28242. write (ui, "18-als-audiolane");
  28243. }
  28244. line ("set: Vocal track " + juce::String (vocal));
  28245. lynx::clipGridClassicLook() = true;
  28246. ui.getPlaylistForSnapshot().liveLanesChanged();
  28247. settle();
  28248. write (ui, "classic-als-arrangement");
  28249. lynx::clipGridClassicLook() = false;
  28250. }
  28251. lynx::clipGridClassicLook() = classicBefore;
  28252. lynx::playlistTallLiveLanes() = tallBefore;
  28253. wav.deleteFile();
  28254. line ("done");
  28255. }
  28256. // LYNX --fllook190joshot prefix project.flp: round 190jo off screen (design190ia slices 12 FM-S6, 21 FM-S4, 23 FW-S4)
  28257. void runFllook190joShot (const juce::String& prefix, const juce::String& project)
  28258. {
  28259. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  28260. const juce::ScopedValueSetter<bool> shown (lynx::ui::showingForShots(), true);
  28261. lynx::ui::motion::enabled() = false; // (hover states drawn at once, no fade)
  28262. juce::String checks;
  28263. const auto flush = [&] { juce::File (lynx::shot::file (juce::File (prefix + "-checks.txt"))).replaceWithText (checks); };
  28264. const auto check = [&] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; flush(); };
  28265. const auto line = [&] (const juce::String& what) { checks << " " << what << "\n"; flush(); };
  28266. lynx::AudioEngine offline (false);
  28267. lynx::MainComponent ui (offline, false);
  28268. ui.setSize (1920, 1080);
  28269. const auto settle = [&] {
  28270. for (int k = 0; k < 3; ++k)
  28271. offline.dispatchPendingMessages();
  28272. };
  28273. const auto area = [&] (juce::Rectangle<int> r, const juce::String& name) { saveArea (ui, r, prefix + "-" + name + ".png"); };
  28274. ui.selectTabForSnapshot (2);
  28275. if (project.isNotEmpty())
  28276. {
  28277. ui.openFile (juce::File (project));
  28278. settle();
  28279. }
  28280. check ("the project opened", ! offline.getSong().channels.empty());
  28281. const auto bar = [&ui] { return ui.getLocalBounds().withHeight (juce::jmin (ui.getHeight(), 90)); };
  28282. const std::pair<int, int> sizes[] { { 1920, 1080 }, { 1600, 900 }, { 1366, 768 }, { 1280, 800 } };
  28283. // ---- slice 12: the Pattern toolbar ------------------------------------------------------------------------------
  28284. for (const auto& [w, h] : sizes)
  28285. {
  28286. ui.setSize (w, h);
  28287. settle();
  28288. area (bar(), "tb-" + juce::String (w));
  28289. int tiles = 0;
  28290. for (auto* c : ui.getChildren())
  28291. if (auto* b = dynamic_cast<lynx::IconButton*> (c); b != nullptr && b->isVisible() && b->getLook() == lynx::IconButton::Look::flTile)
  28292. ++tiles;
  28293. line ("toolbar " + juce::String (w) + ": " + juce::String (tiles) + " tiled buttons");
  28294. }
  28295. ui.setSize (1920, 1080);
  28296. settle();
  28297. std::vector<lynx::IconButton*> tiled;
  28298. for (auto* c : ui.getChildren())
  28299. if (auto* b = dynamic_cast<lynx::IconButton*> (c); b != nullptr && b->isVisible() && b->getLook() == lynx::IconButton::Look::flTile)
  28300. tiled.push_back (b);
  28301. check ("the Pattern toolbar's buttons are FL tiles (" + juce::String ((int) tiled.size()) + ")", tiled.size() >= 25);
  28302. std::vector<bool> lit;
  28303. for (auto* b : tiled)
  28304. lit.push_back (b->getToggleState());
  28305. area (bar(), "tb-states-idle");
  28306. for (const auto& [state, name] : { std::pair<juce::Button::ButtonState, const char*> { juce::Button::buttonOver, "hover" }, { juce::Button::buttonDown, "pressed" } })
  28307. {
  28308. for (auto* b : tiled)
  28309. b->setState (state);
  28310. area (bar(), juce::String ("tb-states-") + name);
  28311. for (auto* b : tiled)
  28312. b->setState (juce::Button::buttonNormal);
  28313. }
  28314. for (auto* b : tiled)
  28315. b->setToggleState (true, juce::dontSendNotification);
  28316. area (bar(), "tb-states-on");
  28317. for (auto* b : tiled)
  28318. b->setState (juce::Button::buttonOver);
  28319. area (bar(), "tb-states-on-hover");
  28320. for (std::size_t k = 0; k < tiled.size(); ++k)
  28321. {
  28322. tiled[k]->setState (juce::Button::buttonNormal);
  28323. tiled[k]->setToggleState (lit[k], juce::dontSendNotification);
  28324. tiled[k]->setEnabled (false);
  28325. }
  28326. area (bar(), "tb-states-disabled");
  28327. for (auto* b : tiled)
  28328. b->setEnabled (true);
  28329. // one switch and one plain button under the mouse, as FL's capture (its audio editor button lit)
  28330. if (auto* metronome = dynamic_cast<lynx::IconButton*> (ui.toolbarPartForSnapshot ("metronome")))
  28331. {
  28332. metronome->setState (juce::Button::buttonOver);
  28333. area (bar(), "tb-hover-switch");
  28334. metronome->setState (juce::Button::buttonNormal);
  28335. }
  28336. // the time panel in B:S:T at bar 3, step 05, tick 12 (FL: "3:05:12"), the tempo, and the hint bar
  28337. {
  28338. auto& transport = offline.getTransport();
  28339. const auto& song = offline.getSong();
  28340. transport.positionTicks.store ((double) (2 * song.barTicks()) + 4.0 * lynx::ticksPerStep + lynx::ticksPerStep / 2.0);
  28341. ui.transportTickForSnapshot();
  28342. auto* time = ui.toolbarPartForSnapshot ("position");
  28343. auto* tempo = ui.toolbarPartForSnapshot ("tempo");
  28344. if (time != nullptr && tempo != nullptr)
  28345. {
  28346. area (time->getBounds().getUnion (tempo->getBounds()).expanded (8, 6), "tb-time");
  28347. if (auto* hs = dynamic_cast<lynx::ui::HintSource*> (time))
  28348. line ("time panel: " + hs->hintAt ({}).value);
  28349. check ("the time panel reads FL's B:S:T (3:05:12)", dynamic_cast<lynx::ui::HintSource*> (time) != nullptr
  28350. && dynamic_cast<lynx::ui::HintSource*> (time)->hintAt ({}).value == "3:05:12");
  28351. }
  28352. transport.positionTicks.store (0.0);
  28353. ui.transportTickForSnapshot();
  28354. }
  28355. const auto hintColumn = juce::Rectangle<int> (0, 0, 360, 80);
  28356. if (auto* knob = dynamic_cast<lynx::ui::HintSource*> (ui.toolbarPartForSnapshot ("masterVolume")))
  28357. {
  28358. ui.setHintForSnapshot (knob->hintAt ({}));
  28359. area (hintColumn, "tb-hint-knob");
  28360. }
  28361. if (auto* rec = dynamic_cast<juce::Button*> (ui.toolbarPartForSnapshot ("record")))
  28362. {
  28363. ui.setHintForSnapshot ({ rec->getTooltip().upToFirstOccurrenceOf ("\n", false, false), {}, false, true });
  28364. area (hintColumn, "tb-hint-button");
  28365. }
  28366. ui.setHintForSnapshot ({});
  28367. area (hintColumn, "tb-menu");
  28368. // ---- slice 21: the Piano roll ----------------------------------------------------------------------------------
  28369. ui.selectTabForSnapshot (1);
  28370. settle();
  28371. saveSnapshot (ui, prefix + "-pr.png");
  28372. auto& roll = ui.getPianoRollForSnapshot();
  28373. line ("piano roll rows: " + juce::String (roll.rowHeight) + " px");
  28374. check ("FL's 18 px rows by default", roll.rowHeight == 18);
  28375. lynx::PianoRollComponent::keyStyle = lynx::pianokeys::Style::piano;
  28376. roll.repaint();
  28377. saveSnapshot (ui, prefix + "-pr-pianokeys.png");
  28378. lynx::PianoRollComponent::keyStyle = lynx::pianokeys::Style::flat;
  28379. lynx::notenames::everyKey.store (true);
  28380. roll.repaint();
  28381. saveSnapshot (ui, prefix + "-pr-allnames.png");
  28382. lynx::notenames::everyKey.store (false);
  28383. roll.repaint();
  28384. ui.setHintForSnapshot (roll.hoverForSnapshot());
  28385. saveSnapshot (ui, prefix + "-pr-hover.png");
  28386. ui.setHintForSnapshot ({});
  28387. {
  28388. // FL's ghost capture: "Synth Bass" (no notes of its own in this pattern) over the other channels' notes
  28389. const auto& song = offline.getSong();
  28390. int bass = -1;
  28391. for (int c = 0; c < (int) song.channels.size() && bass < 0; ++c)
  28392. if (juce::String (song.channels[(std::size_t) c].name).equalsIgnoreCase ("Synth Bass"))
  28393. bass = c;
  28394. const auto kept = offline.getSelectedChannel();
  28395. if (bass >= 0)
  28396. {
  28397. offline.setSelectedChannel (bass);
  28398. settle();
  28399. roll.rowHeight = 18;
  28400. roll.repaint();
  28401. saveSnapshot (ui, prefix + "-pr-ghosts.png");
  28402. offline.setSelectedChannel (kept);
  28403. settle();
  28404. }
  28405. check ("Synth Bass found for the ghosts", bass >= 0);
  28406. }
  28407. {
  28408. // the note label against the note over the velocity range of each note colour group (WCAG)
  28409. float worst = 99.0f;
  28410. for (int group = 0; group < 16; ++group)
  28411. for (float v = 0.0f; v <= 1.0001f; v += 0.05f)
  28412. {
  28413. const auto fill = lynx::theme::noteGroupColour (group, v);
  28414. const auto label = fill.getPerceivedBrightness() > 0.5f ? lynx::theme::colour::bg0 : lynx::theme::colour::textPrimary;
  28415. worst = juce::jmin (worst, lynx::theme::contrast (label, fill));
  28416. }
  28417. line ("note label contrast, worst of 16 colour groups x velocity 0..1: " + juce::String (worst, 2) + ":1");
  28418. const auto red = lynx::theme::noteGroupColour (0, 0.78f);
  28419. line ("default note " + red.toDisplayString (false) + " label " + juce::String (lynx::theme::contrast (lynx::theme::colour::bg0, red), 2) + ":1");
  28420. check ("note labels >= 4.5:1 on the default red notes", lynx::theme::contrast (lynx::theme::colour::bg0, red) >= 4.5f);
  28421. }
  28422. ui.selectTabForSnapshot (2);
  28423. settle();
  28424. // ---- slice 23: the audio editor in Edison's layout -------------------------------------------------------------
  28425. {
  28426. const juce::File breaker ("C:\\Program Files\\Image-Line\\FL Studio 2026\\Data\\Patches\\Packs\\Loops\\DL Breaker.wav");
  28427. const auto wav = breaker.existsAsFile() ? breaker : juce::File (juce::SystemStats::getEnvironmentVariable ("LYNX_190JO_WAV", ""));
  28428. check ("FL's DL Breaker.wav", wav.existsAsFile());
  28429. if (wav.existsAsFile())
  28430. if (auto editor = lynx::makeAudioEditorForFileSnapshot (offline, wav))
  28431. {
  28432. for (const auto& [w, h] : { std::pair { 1120, 600 }, std::pair { 960, 520 } })
  28433. {
  28434. editor->setSize (w, h);
  28435. saveSnapshot (*editor, prefix + "-ed-breaker-" + juce::String (w) + ".png");
  28436. }
  28437. editor->setSize (760, 320); // (the compact form: a short dock)
  28438. saveSnapshot (*editor, prefix + "-ed-compact.png");
  28439. }
  28440. const auto at = lynx::addEdisonSlot (offline, 1);
  28441. settle();
  28442. if (at >= 0)
  28443. if (auto slot = lynx::makeEdisonSlotEditor (offline, 1, at))
  28444. {
  28445. slot->setSize (1120, 630);
  28446. saveSnapshot (*slot, prefix + "-ed-slot.png");
  28447. }
  28448. check ("an Edison slot editor", at >= 0);
  28449. const auto& song = offline.getSong();
  28450. int sampled = -1;
  28451. for (int c = 0; c < (int) song.channels.size() && sampled < 0; ++c)
  28452. if (! song.channels[(std::size_t) c].samplePath.empty())
  28453. sampled = c;
  28454. if (sampled >= 0)
  28455. if (auto panel = lynx::makeAudioEditorPanel (offline, sampled, -1))
  28456. {
  28457. panel->setSize (1100, 300);
  28458. saveSnapshot (*panel, prefix + "-ed-panel.png");
  28459. }
  28460. }
  28461. lynx::ui::motion::enabled() = true;
  28462. }
  28463. // Round 190kc (see --cliplaunch190kcshot above): the Patience set in the Clip-launch layout
  28464. void runClipLaunch190kcShot (const juce::String& prefix, const juce::String& set)
  28465. {
  28466. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  28467. const juce::ScopedValueSetter<bool> shown (lynx::ui::showingForShots(), true);
  28468. juce::String checks;
  28469. const auto flush = [&] { juce::File (lynx::shot::file (juce::File (prefix + "-checks.txt"))).replaceWithText (checks); };
  28470. const auto check = [&] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; flush(); };
  28471. const auto line = [&] (const juce::String& what) { checks << " " << what << "\n"; flush(); };
  28472. const auto write = [&prefix] (juce::Component& c, const juce::String& name) { savePng (lynx::shot::snapshot (c), prefix + "-" + name + ".png"); };
  28473. const auto area = [&prefix] (juce::Component& c, juce::Rectangle<int> r, const juce::String& name) { saveArea (c, r, prefix + "-" + name + ".png"); };
  28474. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1920x1080"), "x", "");
  28475. const auto w = juce::jlimit (800, 3840, size[0].getIntValue()), h = juce::jlimit (450, 2160, size[1].getIntValue());
  28476. const auto classicBefore = lynx::clipGridClassicLook();
  28477. lynx::clipGridClassicLook() = false;
  28478. if (set.isEmpty() || ! juce::File (set).existsAsFile())
  28479. {
  28480. check ("the Live set given", false);
  28481. return;
  28482. }
  28483. using Part = lynx::SessionMixerComponent::Part;
  28484. lynx::AudioEngine offline (false);
  28485. lynx::MainComponent ui (offline, false);
  28486. ui.setSize (w, h);
  28487. const auto settle = [&] {
  28488. for (int k = 0; k < 3; ++k)
  28489. offline.dispatchPendingMessages();
  28490. };
  28491. ui.setVisible (true);
  28492. lynx::DetailView::shownSetting = true;
  28493. lynx::DetailView::devicesPage = true;
  28494. ui.selectTabForSnapshot (2);
  28495. ui.setClipLaunchWorkflow (true);
  28496. settle();
  28497. ui.openFile (juce::File (set));
  28498. settle();
  28499. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  28500. settle();
  28501. ui.resized();
  28502. settle();
  28503. auto* gridView = ui.getClipGridForSnapshot();
  28504. auto* mixer = gridView != nullptr ? lynx::clipGridMixer (*gridView) : nullptr;
  28505. if (gridView == nullptr || mixer == nullptr)
  28506. {
  28507. check ("a clip grid with its Session mixer", false);
  28508. return;
  28509. }
  28510. const auto& song = offline.getSong();
  28511. const auto returns = lynx::sessionmixer::returnsOf (song);
  28512. line ("returns: " + juce::String ((int) returns.size()) + ", return strips " + juce::String (mixer->returnColumnCount()));
  28513. check ("the set's two returns are Live return tracks (A Reverb, B Delay)",
  28514. returns.size() == 2 && lynx::sessionmixer::returnTitle (song, returns[0]) == "A Reverb" && lynx::sessionmixer::returnTitle (song, returns[1]) == "B Delay");
  28515. check ("two return strips beside the tracks", mixer->returnColumnCount() == 2);
  28516. check ("every track shows a Sends row per return (the sends at -inf)",
  28517. mixer->sendTargets() == returns && ! mixer->partBounds (0, Part::send, 1).isEmpty());
  28518. const auto retA = lynx::SessionMixerComponent::returnColumn (0);
  28519. check ("a return strip: Sends, volume, activator, Solo, no Arm",
  28520. ! mixer->partBounds (retA, Part::send, 1).isEmpty() && ! mixer->partBounds (retA, Part::activator).isEmpty()
  28521. && ! mixer->partBounds (retA, Part::solo).isEmpty() && mixer->partBounds (retA, Part::arm).isEmpty());
  28522. check ("the Main strip: a Pre / Post toggle per return", ! mixer->partBounds (-2, Part::post, 0).isEmpty() && ! mixer->partBounds (-2, Part::post, 1).isEmpty());
  28523. line ("Post A " + mixer->partBounds (-2, Part::post, 0).toString() + ", Post B " + mixer->partBounds (-2, Part::post, 1).toString()
  28524. + ", return A activator " + mixer->partBounds (retA, Part::activator).toString());
  28525. write (ui, "window");
  28526. area (*gridView, mixer->getBoundsInParent(), "mixer");
  28527. area (*gridView, { 0, 0, gridView->getWidth(), 240 }, "grid-top");
  28528. area (*gridView, mixer->getBoundsInParent().withTrimmedLeft (mixer->getWidth() - 260), "mixer-returns");
  28529. // a return's send to the other one, switched on; Pre on return B
  28530. offline.editSong ([&returns] (lynx::Song& s) {
  28531. lynx::sessionmixer::setSendEnabled (s, returns[0], returns[1], true);
  28532. lynx::sessionmixer::setPre (s, returns[1], true);
  28533. });
  28534. settle();
  28535. area (*gridView, mixer->getBoundsInParent(), "mixer-sendon-pre");
  28536. area (*gridView, mixer->getBoundsInParent().withTrimmedLeft (mixer->getWidth() - 260), "mixer-returns-sendon-pre");
  28537. check ("return A's send to B switched on, B Pre", lynx::sessionmixer::sendEnabled (song, returns[0], returns[1]) && lynx::sessionmixer::isPre (song, returns[1]));
  28538. saveMenus (juce::StringArray { "Return send" }, std::vector<juce::PopupMenu> { mixer->sendMenu ({ lynx::SessionMixerComponent::returnColumn (1), Part::send, 0 }) },
  28539. prefix + "-menu-send.png");
  28540. offline.editSong ([&returns] (lynx::Song& s) {
  28541. lynx::sessionmixer::setSendEnabled (s, returns[0], returns[1], false);
  28542. lynx::sessionmixer::setPre (s, returns[1], false);
  28543. });
  28544. // the crossfader section: track 1 on A, track 2 on B, the crossfader a little towards A
  28545. const auto i0 = lynx::sessionmixer::stripOf (song, 0).insert, i1 = lynx::sessionmixer::stripOf (song, 1).insert;
  28546. offline.editSong ([i0, i1] (lynx::Song& s) {
  28547. lynx::launcher::ensureGrid (s).mixerView.crossfader = true;
  28548. if (i0 > 0)
  28549. s.mixer[(std::size_t) i0].crossfade = lynx::CrossfadeAssign::a;
  28550. if (i1 > 0)
  28551. s.mixer[(std::size_t) i1].crossfade = lynx::CrossfadeAssign::b;
  28552. s.crossfader = -0.3f;
  28553. });
  28554. settle();
  28555. gridView->resized(); // (the menu item does this: the grid gives the mixer its new height)
  28556. settle();
  28557. check ("the Crossfader section: A / B on a track, the crossfader on Main",
  28558. ! mixer->partBounds (0, Part::xfadeA).isEmpty() && ! mixer->partBounds (0, Part::xfadeB).isEmpty() && ! mixer->partBounds (-2, Part::crossfader).isEmpty());
  28559. line ("A " + mixer->partBounds (0, Part::xfadeA).toString() + ", B " + mixer->partBounds (0, Part::xfadeB).toString() + ", crossfader "
  28560. + mixer->partBounds (-2, Part::crossfader).toString());
  28561. area (*gridView, mixer->getBoundsInParent(), "mixer-crossfader");
  28562. area (*gridView, mixer->getBoundsInParent().withTrimmedLeft (mixer->getWidth() - 260), "mixer-returns-crossfader");
  28563. saveMenus (juce::StringArray { "Crossfader" }, std::vector<juce::PopupMenu> { mixer->crossfaderMenu() }, prefix + "-menu-curve.png");
  28564. lynx::clipGridClassicLook() = true;
  28565. lynx::refreshClipGrid (*gridView);
  28566. ui.resized();
  28567. settle();
  28568. area (*gridView, mixer->getBoundsInParent(), "classic-mixer-crossfader");
  28569. write (ui, "classic-window");
  28570. lynx::clipGridClassicLook() = false;
  28571. lynx::refreshClipGrid (*gridView);
  28572. ui.resized();
  28573. settle();
  28574. // the map modes: a key on a slot, a scene, Scene Down, the crossfader's left position
  28575. using namespace lynx::remotemap;
  28576. offline.editSong ([] (lynx::Song& s) {
  28577. assignKey (s, Target::slot (0, 0), 'Q');
  28578. assignKey (s, Target::sceneLaunch (0), 'W');
  28579. assignKey (s, Target::of (lynx::RemoteAction::sceneDown), 'J');
  28580. assignKey (s, Target::of (lynx::RemoteAction::crossfaderLeft), 'Z');
  28581. });
  28582. for (const auto mode : { Mode::key, Mode::midi })
  28583. {
  28584. ui.setMapMode (mode);
  28585. settle();
  28586. if (auto* overlay = ui.mapOverlayForSnapshot())
  28587. {
  28588. overlay->refresh();
  28589. const auto& spots = overlay->spots();
  28590. const auto count = [&spots] (lynx::RemoteAction a) { return (int) std::count_if (spots.begin(), spots.end(), [a] (const auto& sp) { return sp.target.action == a; }); };
  28591. line (juce::String (mode == Mode::key ? "key" : "midi") + " map: " + juce::String ((int) spots.size()) + " spots; relative strip "
  28592. + juce::String (count (lynx::RemoteAction::sceneUp) + count (lynx::RemoteAction::sceneDown) + count (lynx::RemoteAction::launchSelectedScene)
  28593. + count (lynx::RemoteAction::cancelLaunch))
  28594. + ", per-track launch " + juce::String (count (lynx::RemoteAction::launchSelectedClip)) + ", crossfader positions "
  28595. + juce::String (count (lynx::RemoteAction::crossfaderLeft) + count (lynx::RemoteAction::crossfaderCentre) + count (lynx::RemoteAction::crossfaderRight)));
  28596. check (juce::String (mode == Mode::key ? "Key" : "MIDI") + " Map Mode: the relative strip and the crossfader's three positions are mappable",
  28597. count (lynx::RemoteAction::sceneUp) == 1 && count (lynx::RemoteAction::sceneDown) == 1 && count (lynx::RemoteAction::launchSelectedScene) == 1
  28598. && count (lynx::RemoteAction::cancelLaunch) == 1 && count (lynx::RemoteAction::launchSelectedClip) >= 4
  28599. && count (lynx::RemoteAction::crossfaderLeft) == 1 && count (lynx::RemoteAction::crossfaderRight) == 1);
  28600. }
  28601. write (ui, mode == Mode::key ? "keymap" : "midimap");
  28602. }
  28603. ui.setMapMode (Mode::off);
  28604. settle();
  28605. // grooves on clips: a groove of LYNX's bank on the first MIDI clip and on an audio clip; the Clip View's Commit
  28606. int midiTrack = -1, midiScene = -1, audioTrack = -1, audioScene = -1;
  28607. if (song.clipGrid)
  28608. for (const auto& c : song.clipGrid->clips)
  28609. {
  28610. const auto scene = c.gridSlot >= 0 && c.gridSlot < (int) song.clipGrid->slots.size() ? song.clipGrid->slots[(std::size_t) c.gridSlot].scene : -1;
  28611. if (c.kind == lynx::ClipKind::pattern && midiTrack < 0)
  28612. midiTrack = c.track, midiScene = scene;
  28613. if (c.kind == lynx::ClipKind::audio && audioTrack < 0)
  28614. audioTrack = c.track, audioScene = scene;
  28615. }
  28616. line ("MIDI clip " + juce::String (midiTrack) + "/" + juce::String (midiScene) + ", audio clip " + juce::String (audioTrack) + "/" + juce::String (audioScene));
  28617. std::uint32_t grooveId = 0;
  28618. offline.editSong ([&grooveId, midiTrack, midiScene, audioTrack, audioScene] (lynx::Song& s) {
  28619. auto g = lynx::groove::factoryBank().front().groove;
  28620. g.timing = 1.0f;
  28621. grooveId = lynx::groove::add (s.grooves, g);
  28622. lynx::groove::setClipGroove (s, midiTrack, midiScene, grooveId);
  28623. lynx::groove::setClipGroove (s, audioTrack, audioScene, grooveId);
  28624. });
  28625. settle();
  28626. if (auto* detail = ui.getDetailViewForSnapshot(); detail != nullptr && midiTrack >= 0 && audioTrack >= 0)
  28627. {
  28628. detail->showSelection (midiTrack, midiScene);
  28629. detail->setPage (lynx::DetailView::Page::clip);
  28630. settle();
  28631. write (*detail, "clip-midi-groove");
  28632. detail->showSelection (audioTrack, audioScene);
  28633. detail->setPage (lynx::DetailView::Page::clip);
  28634. settle();
  28635. write (*detail, "clip-audio-groove");
  28636. const auto* audio = lynx::launcher::clipAt (*song.clipGrid, audioTrack, audioScene);
  28637. const auto sample = audio != nullptr && audio->channel >= 0 ? offline.getSampleLibrary().load (juce::String::fromUTF8 (song.channels[(std::size_t) audio->channel].samplePath.c_str()))
  28638. : nullptr;
  28639. check ("the audio clip's file loads", sample != nullptr);
  28640. if (sample != nullptr && audio != nullptr)
  28641. {
  28642. const auto hits = lynx::grooveaudio::hitsOf (song, *audio, *sample);
  28643. {
  28644. const auto all = lynx::clipwarp::attacks (*sample);
  28645. const auto& sm = song.channels[(std::size_t) audio->channel].sampler;
  28646. line ("audio file: " + juce::String ((int) sample->frames()) + " frames at " + juce::String (sample->sampleRate) + " Hz, "
  28647. + juce::String ((int) all.size()) + " attacks (first " + juce::String (all.empty() ? -1.0 : all.front(), 3) + " s); clip offset "
  28648. + juce::String (audio->offset) + " length " + juce::String (audio->length) + " stretch " + juce::String (audio->stretch, 3)
  28649. + "; warp " + juce::String ((int) sm.warp.size()) + " markers, keepPitch " + juce::String ((int) sm.keepPitch)
  28650. + ", first content beat " + juce::String (all.empty() ? 0.0 : lynx::grooveaudio::contentBeat (sm, all.front(), song.bpm), 3));
  28651. }
  28652. const auto pool = song.grooves.grooves.size();
  28653. offline.editSong ([&] (lynx::Song& s) {
  28654. if (const auto* c = lynx::launcher::clipAt (*s.clipGrid, audioTrack, audioScene))
  28655. if (auto g = lynx::grooveaudio::extract (s, *c, *sample, lynx::GrooveBase::sixteenth, "Vocal groove"); ! g.points.empty())
  28656. lynx::groove::add (s.grooves, std::move (g));
  28657. });
  28658. line ("audio clip: " + juce::String ((int) hits.size()) + " attacks; pool " + juce::String ((int) pool) + " -> " + juce::String ((int) song.grooves.grooves.size()));
  28659. check ("Extract Groove from the audio clip adds a groove", song.grooves.grooves.size() == pool + 1);
  28660. int placed = -1;
  28661. offline.editSong ([&] (lynx::Song& s) { placed = lynx::grooveaudio::commit (s, audioTrack, audioScene, *sample); });
  28662. auto gridCopy = *song.clipGrid;
  28663. const auto* slot = lynx::launcher::settingsAt (gridCopy, audioTrack, audioScene);
  28664. line ("commit on audio: " + juce::String (placed) + " warp markers");
  28665. check ("Commit on the audio clip writes warp markers and sets its groove to None", placed > 0 && slot != nullptr && slot->groove == 0);
  28666. }
  28667. }
  28668. lynx::clipGridClassicLook() = classicBefore;
  28669. line ("done");
  28670. }
  28671. // LYNX --capfix190jjshot prefix project.flp set.als: round 190jj off screen (capture190ji's "Change in LYNX" lines) —
  28672. // the Simple capsule idle / playing / count-in / recording with the master meter, the pads at rest and pressed, the
  28673. // keys held in the track's colour, the drop lane's ghosts; Live's control bar idle / playing / recording / punch;
  28674. // FL's C-11 picker drop ghost with the drag image, the drop, and the picker's playing mark; prefix-checks.txt
  28675. void runCapfix190jjShot (const juce::String& prefix, const juce::String& project, const juce::String& set)
  28676. {
  28677. namespace st = lynx::simpletracks;
  28678. namespace sp = lynx::simplepads;
  28679. using Look = lynx::toolbarlayout::Look;
  28680. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  28681. const juce::ScopedValueSetter<bool> shown (lynx::ui::showingForShots(), true);
  28682. juce::String checks;
  28683. const auto flush = [&] { juce::File (lynx::shot::file (juce::File (prefix + "-checks.txt"))).replaceWithText (checks); };
  28684. const auto check = [&] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; flush(); };
  28685. const auto line = [&] (const juce::String& what) { checks << " " << what << "\n"; flush(); };
  28686. const auto write = [&prefix] (juce::Component& c, const juce::String& name) { savePng (lynx::shot::snapshot (c), prefix + "-" + name + ".png"); };
  28687. const auto area = [&prefix] (juce::Component& c, juce::Rectangle<int> r, const juce::String& name) { saveArea (c, r, prefix + "-" + name + ".png"); };
  28688. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1920x1080"), "x", "");
  28689. const auto w = juce::jlimit (800, 3840, size[0].getIntValue()), h = juce::jlimit (450, 2160, size[1].getIntValue());
  28690. // ---- A. Simple ----------------------------------------------------------------------------------------------------
  28691. {
  28692. lynx::AudioEngine offline (false);
  28693. lynx::MainComponent ui (offline, false);
  28694. ui.setSize (w, h);
  28695. const auto settle = [&] {
  28696. for (int k = 0; k < 3; ++k)
  28697. offline.dispatchPendingMessages();
  28698. };
  28699. ui.selectTabForSnapshot (2);
  28700. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  28701. settle();
  28702. auto* simple = ui.getSimpleWorkflowForSnapshot();
  28703. auto& playlist = ui.getPlaylistForSnapshot();
  28704. if (simple == nullptr)
  28705. {
  28706. check ("a Simple workflow", false);
  28707. return;
  28708. }
  28709. offline.setSong ([] {
  28710. lynx::Song s;
  28711. s.mixer = lynx::Song::defaultMixer();
  28712. s.bpm = 120.0;
  28713. return s;
  28714. }());
  28715. settle();
  28716. simple->hideChooser();
  28717. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-190jj");
  28718. dir.deleteRecursively();
  28719. dir.createDirectory();
  28720. const auto writeWav = [] (const juce::File& wav, int frames, const std::function<float (int)>& f) {
  28721. wav.getParentDirectory().createDirectory();
  28722. juce::AudioBuffer<float> audio (1, frames);
  28723. for (int i = 0; i < frames; ++i)
  28724. audio.setSample (0, i, f (i));
  28725. juce::WavAudioFormat format;
  28726. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  28727. if (auto* wr = format.createWriterFor (out.get(), 48000.0, 1, 16, {}, 0))
  28728. {
  28729. out.release();
  28730. std::unique_ptr<juce::AudioFormatWriter> writer (wr);
  28731. writer->writeFromAudioSampleBuffer (audio, 0, frames);
  28732. }
  28733. return wav;
  28734. };
  28735. const auto pi = juce::MathConstants<double>::pi;
  28736. juce::Random rnd (190);
  28737. // a 4-bar loop at 120 bpm (8 s), as BandLab's "TRAP_160_Piano1_Bm_4bars" is four bars
  28738. const auto loop = writeWav (dir.getChildFile ("TRAP_120_Piano1_Bm_4bars.wav"), 384000, [pi] (int i) {
  28739. const auto t = i / 48000.0, inBeat = std::fmod (t, 0.5);
  28740. return (float) (0.6 * std::exp (-inBeat * 6.0) * std::sin (2.0 * pi * 247.0 * t));
  28741. });
  28742. std::vector<juce::File> padSounds;
  28743. const char* padNames[] { "Kick", "Snare", "Hat", "Clap", "Stab", "Vox", "Perc", "Bass" };
  28744. for (int k = 0; k < 8; ++k)
  28745. padSounds.push_back (writeWav (dir.getChildFile (juce::String ("pads/") + padNames[k] + ".wav"), 12000 + 3000 * k, [&rnd, k] (int i) {
  28746. return (float) ((rnd.nextFloat() * 2.0f - 1.0f) * 0.6f * std::exp (-i / (600.0f + 500.0f * (float) k)));
  28747. }));
  28748. int vocal = -1, keys = -1;
  28749. offline.editSong ([&] (lynx::Song& s) {
  28750. st::Request q;
  28751. q.kind = st::Kind::audio;
  28752. q.name = "Piano loop";
  28753. q.audioFile = loop.getFullPathName().toStdString();
  28754. q.audioLength = 16 * lynx::ppq;
  28755. q.audioBeats = 16.0f;
  28756. vocal = st::addTrack (s, q).track;
  28757. q = {};
  28758. q.kind = st::Kind::instrument;
  28759. q.name = "Instrument";
  28760. lynx::ChannelDef synth;
  28761. synth.instrument = lynx::InstrumentKind::synth;
  28762. q.channel = synth;
  28763. keys = st::addTrack (s, q).track;
  28764. });
  28765. settle();
  28766. check ("the Sampler (pads) track was added", simple->addPads());
  28767. settle();
  28768. const auto& song = offline.getSong();
  28769. int pads = -1;
  28770. for (int t = 0; t < (int) song.playlistTracks.size() && pads < 0; ++t)
  28771. if (st::kindOf (song, t) == st::Kind::pads)
  28772. pads = t;
  28773. simple->hideChooser();
  28774. playlist.selectTrack (keys);
  28775. settle();
  28776. // 1. the transport capsule (+ tempo, key, master) in its four states
  28777. const auto bar = [&ui] {
  28778. juce::Rectangle<int> r;
  28779. for (const auto* name : { "play", "stop", "record", "position", "metronome", "tempo", "signature", "key", "masterVolume", "masterPitch" })
  28780. if (auto* c = ui.toolbarPartForSnapshot (name); c != nullptr && c->isVisible())
  28781. r = r.isEmpty() ? c->getBounds() : r.getUnion (c->getBounds());
  28782. return r.expanded (8, 6);
  28783. };
  28784. auto& transport = offline.getTransport();
  28785. auto* tempo = ui.toolbarPartForSnapshot ("tempo");
  28786. auto* stopButton = dynamic_cast<lynx::IconButton*> (ui.toolbarPartForSnapshot ("stop"));
  28787. auto* playButton = dynamic_cast<lynx::IconButton*> (ui.toolbarPartForSnapshot ("play"));
  28788. auto* master = dynamic_cast<lynx::toolbar::MasterKnob*> (ui.toolbarPartForSnapshot ("masterVolume"));
  28789. ui.transportTickForSnapshot();
  28790. area (ui, bar(), "simple-bar-idle");
  28791. check ("idle: Play shows Play, the second button Back-to-start", playButton != nullptr && playButton->getIcon() == lynx::Icon::play
  28792. && stopButton != nullptr && stopButton->getIcon() == lynx::Icon::toStart);
  28793. transport.positionTicks.store ((double) (2 * song.barTicks()) + 0.3 * lynx::ppq);
  28794. transport.playing.store (true);
  28795. if (master != nullptr)
  28796. master->meterForSnapshot ({ 0.62f, 0.57f });
  28797. ui.transportTickForSnapshot();
  28798. area (ui, bar(), "simple-bar-playing");
  28799. check ("playing: Pause and Stop (BandLab)", playButton != nullptr && playButton->getIcon() == lynx::Icon::pause && stopButton->getIcon() == lynx::Icon::stop);
  28800. transport.playing.store (false);
  28801. transport.positionTicks.store (0.0);
  28802. offline.setRecording (true);
  28803. transport.countIn.store (0.85 * (double) song.barTicks()); // (-1.7 s of a 2 s bar at 120 bpm)
  28804. ui.transportTickForSnapshot();
  28805. area (ui, bar(), "simple-bar-countin");
  28806. check ("count-in: tempo greyed, Pause shown", tempo != nullptr && ! tempo->isEnabled() && playButton->getIcon() == lynx::Icon::pause);
  28807. transport.countIn.store (0.0);
  28808. transport.playing.store (true);
  28809. transport.positionTicks.store (0.45 * (double) song.barTicks());
  28810. ui.transportTickForSnapshot();
  28811. area (ui, bar(), "simple-bar-recording");
  28812. line ("record start kept: " + juce::String (ui.simpleRecordStartForCheck(), 1) + " ticks");
  28813. check ("recording: the take's start is kept (the count-in's target, 0)", ui.simpleRecordStartForCheck() == 0.0);
  28814. auto* rec = dynamic_cast<juce::Button*> (ui.toolbarPartForSnapshot ("record"));
  28815. const auto litA = rec != nullptr && rec->getToggleState();
  28816. juce::Thread::sleep (260);
  28817. ui.transportTickForSnapshot();
  28818. const auto litB = rec != nullptr && rec->getToggleState();
  28819. check ("recording: Record steady (lit 260 ms apart, no blink in Simple)", litA && litB);
  28820. transport.seekRequest.store (-1.0);
  28821. ui.stopForCheck();
  28822. line ("seek after Stop: " + juce::String (transport.seekRequest.load(), 1));
  28823. check ("Stop after a take goes back to where it started", transport.seekRequest.load() == 0.0);
  28824. offline.setRecording (false);
  28825. transport.playing.store (false);
  28826. ui.transportTickForSnapshot();
  28827. check ("stopped: tempo enabled again", tempo != nullptr && tempo->isEnabled());
  28828. if (master != nullptr)
  28829. {
  28830. area (ui, master->getBounds().expanded (6, 4), "simple-master-idle");
  28831. master->meterForSnapshot ({ 0.62f, 0.57f });
  28832. area (ui, master->getBounds().expanded (6, 4), "simple-master-playing");
  28833. master->meterForSnapshot ({ 0.0f, 0.0f });
  28834. }
  28835. // 2. the dock: pads at rest and pressed, keys held
  28836. if (auto* dock = simple->dockForSnapshot(); dock != nullptr && pads >= 0)
  28837. {
  28838. simple->trackSelected (pads);
  28839. settle();
  28840. for (int p = 0; p < 8; ++p)
  28841. dock->padsLoadForCheck (p, padSounds[(std::size_t) p]);
  28842. offline.editSong ([pads] (lynx::Song& s) {
  28843. for (int p = 0; p < 8; ++p)
  28844. if (const auto c = sp::padChannel (s, pads, p); c >= 0)
  28845. s.channels[(std::size_t) c].simplePad.colour = (std::uint8_t) (p + 1);
  28846. });
  28847. dock->padsSelectForCheck (0);
  28848. dock->padsUpdateForCheck();
  28849. settle();
  28850. write (*dock, "dock-pads-rest");
  28851. dock->padsPressForSnapshot (3, 1.0f);
  28852. dock->padsPressForSnapshot (5, 0.5f);
  28853. write (*dock, "dock-pads-pressed");
  28854. dock->padsPressForSnapshot (3, 0.0f);
  28855. dock->padsPressForSnapshot (5, 0.0f);
  28856. simple->trackSelected (keys);
  28857. settle();
  28858. dock->showKeyboard();
  28859. settle();
  28860. if (auto* kb = dock->keyboardForSnapshot())
  28861. {
  28862. lynx::keyboardPressForSnapshot (*kb);
  28863. write (*dock, "dock-keys-held");
  28864. }
  28865. }
  28866. // 3. the drop lane while the loop is dragged (the Browser's file drag)
  28867. simple->hideChooser();
  28868. playlist.selectTrack (vocal);
  28869. settle();
  28870. const auto lane = st::nextEmptyTrack (offline.getSong());
  28871. const juce::var drag (juce::String ("lynx-arquivo|") + loop.getFullPathName());
  28872. const auto x = (int) playlist.xOfTickForSnapshot (9.0 * (double) song.barTicks()) + 6;
  28873. playlist.dragOverForSnapshot (drag, { x, playlist.trackRowForSnapshot (lane).getCentreY() });
  28874. write (playlist, "simple-drop-lane");
  28875. check ("over the lane: a ghost, no reason", ! playlist.dropGhostAreaForCheck().isEmpty() && playlist.dropGhostReasonForCheck().isEmpty());
  28876. playlist.dragOverForSnapshot (drag, { x, playlist.trackRowForSnapshot (vocal).getCentreY() });
  28877. write (playlist, "simple-drop-audio-track");
  28878. check ("over an audio track: no reason", playlist.dropGhostReasonForCheck().isEmpty());
  28879. playlist.dragOverForSnapshot (drag, { x, playlist.trackRowForSnapshot (pads).getCentreY() });
  28880. write (playlist, "simple-drop-refused");
  28881. check ("over the Sampler track: red, with the reason", playlist.dropGhostReasonForCheck().isNotEmpty());
  28882. playlist.dragOverForSnapshot (drag, { x, playlist.trackRowForSnapshot (keys).getCentreY() });
  28883. check ("over an instrument track: red, with the reason", playlist.dropGhostReasonForCheck().isNotEmpty());
  28884. playlist.dragOverForSnapshot (drag, { x, playlist.trackRowForSnapshot (lane).getBottom() + 60 });
  28885. write (playlist, "simple-drop-below");
  28886. check ("below the lane: only the tag", playlist.dropGhostTagOnlyForCheck());
  28887. playlist.dragOverForSnapshot ({}, {});
  28888. check ("after the drag: nothing left to paint", playlist.dropGhostAreaForCheck().isEmpty());
  28889. const auto clipsBefore = offline.getSong().playlist.size();
  28890. playlist.filesDropped ({ loop.getFullPathName() }, x, playlist.trackRowForSnapshot (pads).getCentreY());
  28891. settle();
  28892. check ("a loop dropped on the Sampler track is refused", offline.getSong().playlist.size() == clipsBefore);
  28893. write (ui, "simple-window");
  28894. dir.deleteRecursively();
  28895. }
  28896. // ---- B. Clip-launch: Live's control bar ----------------------------------------------------------------------------
  28897. if (set.isNotEmpty())
  28898. {
  28899. lynx::AudioEngine offline (false);
  28900. lynx::MainComponent ui (offline, false);
  28901. ui.setSize (w, h);
  28902. ui.openFile (juce::File (set));
  28903. offline.dispatchPendingMessages();
  28904. ui.setLayoutStyle (lynx::layoutstyle::Style::clipLaunch, false);
  28905. offline.dispatchPendingMessages();
  28906. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  28907. offline.dispatchPendingMessages();
  28908. const auto centre = [&ui] {
  28909. juce::Rectangle<int> r;
  28910. for (const auto* name : { "backToArrangement", "position", "play", "stop", "record", "overdub", "capture", "sessionRecord", "punch" })
  28911. if (auto* c = ui.toolbarPartForSnapshot (name); c != nullptr && c->isVisible())
  28912. r = r.isEmpty() ? c->getBounds() : r.getUnion (c->getBounds());
  28913. return r.expanded (8, 8);
  28914. };
  28915. auto& transport = offline.getTransport();
  28916. ui.transportTickForSnapshot();
  28917. area (ui, centre(), "live-bar-idle");
  28918. transport.playing.store (true);
  28919. ui.transportTickForSnapshot();
  28920. area (ui, centre(), "live-bar-playing");
  28921. offline.setRecording (true);
  28922. ui.transportTickForSnapshot();
  28923. area (ui, centre(), "live-bar-recording");
  28924. auto* rec = dynamic_cast<juce::Button*> (ui.toolbarPartForSnapshot ("record"));
  28925. const auto litA = rec != nullptr && rec->getToggleState();
  28926. juce::Thread::sleep (260);
  28927. ui.transportTickForSnapshot();
  28928. check ("Live look: Record steady while recording (no blink)", litA && rec->getToggleState());
  28929. if (auto* punch = dynamic_cast<juce::Button*> (ui.toolbarPartForSnapshot ("punch")))
  28930. {
  28931. punch->setToggleState (true, juce::dontSendNotification);
  28932. area (ui, centre(), "live-bar-punch-lit");
  28933. punch->setToggleState (false, juce::dontSendNotification);
  28934. }
  28935. offline.setRecording (false);
  28936. transport.playing.store (false);
  28937. ui.transportTickForSnapshot();
  28938. }
  28939. // ---- C. Pattern (FL): C-11 drop ghost + drag image, the drop, the picker's playing mark ----------------------------------
  28940. if (project.isNotEmpty())
  28941. {
  28942. lynx::layoutstyle::setCurrent (lynx::layoutstyle::Style::pattern); // (the style is global: A and B changed it)
  28943. lynx::AudioEngine offline (false);
  28944. lynx::MainComponent ui (offline, false);
  28945. ui.setSize (w, h);
  28946. ui.openFile (juce::File (project));
  28947. offline.dispatchPendingMessages();
  28948. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern, false);
  28949. ui.selectTabForSnapshot (2);
  28950. offline.dispatchPendingMessages();
  28951. auto& playlist = ui.getPlaylistForSnapshot();
  28952. auto& picker = ui.getPickerForSnapshot();
  28953. const auto& song = offline.getSong();
  28954. write (playlist, "warmup");
  28955. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (60000);
  28956. offline.dispatchPendingMessages();
  28957. juce::File (lynx::shot::file (juce::File (prefix + "-warmup.png"))).deleteFile();
  28958. int synthBass = 0;
  28959. for (int p = 0; p < (int) song.patterns.size(); ++p)
  28960. if (juce::String::fromUTF8 (song.patterns[(std::size_t) p].name.c_str()).equalsIgnoreCase ("Synth Bass"))
  28961. {
  28962. synthBass = p;
  28963. break;
  28964. }
  28965. // an empty track low in the view (FL's capture: Track 43 / 47, past the song's tracks)
  28966. // (an unnamed track past the song's own, as FL's Track 43 / 47)
  28967. const auto target = (int) song.playlistTracks.size() + 2;
  28968. for (int first = juce::jmax (0, target - 30); first <= target; ++first) // (the row in the lower part of the view)
  28969. {
  28970. playlist.setViewForSnapshot (15.6, 0, first);
  28971. if (playlist.trackRowForSnapshot (target).getBottom() < playlist.getHeight() - 40)
  28972. break;
  28973. }
  28974. offline.dispatchPendingMessages();
  28975. const auto row = playlist.trackRowForSnapshot (target);
  28976. const auto mouse = juce::Point<int> ((int) playlist.xOfTickForSnapshot (9.1 * (double) song.barTicks()), row.getCentreY());
  28977. const juce::var drag (lynx::PlaylistComponent::pickerDragDescription (lynx::ClipKind::pattern, { synthBass }));
  28978. playlist.dragOverForSnapshot (drag, mouse);
  28979. {
  28980. // the window as the drag shows it: the ghost in the row, the entry's picture below right of the mouse
  28981. auto image = lynx::shot::snapshot (ui);
  28982. const auto scale = (float) image.getWidth() / (float) juce::jmax (1, ui.getWidth());
  28983. const auto listRow = picker.listRowOfPattern (synthBass);
  28984. if (listRow >= 0)
  28985. {
  28986. const auto entry = picker.dragImageOf (listRow);
  28987. const auto at = ui.getLocalPoint (&playlist, mouse) + lynx::PatternPicker::dragImageOffset();
  28988. juce::Graphics g (image);
  28989. g.addTransform (juce::AffineTransform::scale (scale));
  28990. g.drawImageAt (entry, at.x, at.y);
  28991. g.setColour (juce::Colours::white);
  28992. juce::Path arrow; // (the mouse pointer, so the pair reads as FL's film still)
  28993. arrow.startNewSubPath ((float) ui.getLocalPoint (&playlist, mouse).x, (float) ui.getLocalPoint (&playlist, mouse).y);
  28994. arrow.lineTo (arrow.getCurrentPosition() + juce::Point<float> (0.0f, 16.0f));
  28995. arrow.lineTo (arrow.getCurrentPosition() + juce::Point<float> (4.0f, -4.0f));
  28996. arrow.lineTo (arrow.getCurrentPosition() + juce::Point<float> (7.0f, 0.0f));
  28997. arrow.closeSubPath();
  28998. g.fillPath (arrow);
  28999. g.setColour (juce::Colours::black);
  29000. g.strokePath (arrow, juce::PathStrokeType (1.0f));
  29001. }
  29002. savePng (image, prefix + "-fl-c11-drag.png");
  29003. }
  29004. const auto ghost = playlist.dropGhostAreaForCheck();
  29005. line ("ghost " + ghost.toString() + ", row " + row.toString() + ", mouse " + mouse.toString());
  29006. check ("C-11: the ghost lies in the row under the mouse", ! ghost.isEmpty() && ghost.getY() >= row.getY() - 2 && ghost.getBottom() <= row.getBottom() + 2);
  29007. const auto first = (int) offline.getSong().playlist.size();
  29008. playlist.dropForSnapshot (drag, mouse);
  29009. offline.dispatchPendingMessages();
  29010. const auto& dropped = offline.getSong(); // (an edit publishes a new Song: read it again; the Playlist sorts its clips)
  29011. int onRow = 0, at = -1;
  29012. for (int c = 0; c < (int) dropped.playlist.size(); ++c)
  29013. if (dropped.playlist[(std::size_t) c].track == target)
  29014. {
  29015. ++onRow;
  29016. at = c;
  29017. }
  29018. line ("clips " + juce::String (first) + " -> " + juce::String ((int) dropped.playlist.size()) + ", on the row " + juce::String (onRow));
  29019. check ("C-11: the drop places one clip on the row", (int) dropped.playlist.size() == first + 1 && onRow == 1);
  29020. check ("C-11: the dropped clip is selected", at >= 0 && playlist.isClipSelectedForCheck (at));
  29021. check ("C-11: nothing of the ghost is left", playlist.dropGhostAreaForCheck().isEmpty());
  29022. write (ui, "fl-c11-dropped");
  29023. // the picker's playing mark: Synth Bass plays in the first bars; then another pattern selected
  29024. offline.getTransport().positionTicks.store (0.5 * (double) offline.getSong().barTicks());
  29025. offline.getTransport().playing.store (true);
  29026. offline.getTransport().songMode = true;
  29027. playlist.frameStepForSnapshot();
  29028. playlist.frameStepForSnapshot();
  29029. write (picker, "fl-picker-playing");
  29030. line ("playing patterns: " + juce::String ((int) picker.playingForCheck().size()));
  29031. const auto other = juce::jmin ((int) offline.getSong().patterns.size() - 1, 7);
  29032. offline.editSong ([other] (lynx::Song& s) { s.currentPattern = other; }, false);
  29033. offline.dispatchPendingMessages();
  29034. playlist.frameStepForSnapshot();
  29035. write (picker, "fl-picker-playing-other-selected");
  29036. check ("DC-3: the mark follows what plays, not the selection",
  29037. std::find (picker.playingForCheck().begin(), picker.playingForCheck().end(), other) == picker.playingForCheck().end()
  29038. || std::count_if (offline.getSong().playlist.begin(), offline.getSong().playlist.end(), [&] (const lynx::Clip& c) {
  29039. return c.kind == lynx::ClipKind::pattern && c.pattern == other && (double) c.start <= 0.5 * (double) offline.getSong().barTicks()
  29040. && (double) c.end() > 0.5 * (double) offline.getSong().barTicks();
  29041. }) > 0);
  29042. offline.getTransport().playing.store (false);
  29043. playlist.frameStepForSnapshot();
  29044. write (picker, "fl-picker-stopped");
  29045. check ("DC-3: no mark once stopped", picker.playingForCheck().empty());
  29046. }
  29047. line ("done");
  29048. }
  29049. void runDetails190imShot (const juce::String& prefix, const juce::String& project, const juce::String& set)
  29050. {
  29051. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  29052. const juce::ScopedValueSetter<bool> shown (lynx::ui::showingForShots(), true); // (the live frame steps run off-screen)
  29053. juce::String checks;
  29054. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  29055. const auto line = [&checks] (const juce::String& what) { checks << " " << what << "\n"; };
  29056. const auto write = [&prefix] (juce::Component& c, const juce::String& name) { savePng (lynx::shot::snapshot (c), prefix + "-" + name + ".png"); };
  29057. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1920x1080"), "x", "");
  29058. {
  29059. // ---- Pattern layout, the FL demo
  29060. lynx::AudioEngine offline (false);
  29061. lynx::MainComponent ui (offline, false);
  29062. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  29063. if (project.isNotEmpty())
  29064. ui.openFile (juce::File (project));
  29065. offline.dispatchPendingMessages();
  29066. ui.selectTabForSnapshot (2);
  29067. auto& playlist = ui.getPlaylistForSnapshot();
  29068. offline.dispatchPendingMessages();
  29069. const auto settle = [&] {
  29070. write (playlist, "warmup");
  29071. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (60000);
  29072. offline.dispatchPendingMessages();
  29073. juce::File (prefix + "-warmup.png").deleteFile();
  29074. };
  29075. const auto& song = offline.getSong();
  29076. offline.editSong ([] (lynx::Song& s) { for (auto& t : s.playlistTracks) t.height = 50; }, false);
  29077. offline.dispatchPendingMessages();
  29078. const auto toolbar = ui.getToolbarBoundsForSnapshot();
  29079. // R1: the automation clip with the most points in view, its second point dragged, its first segment bent
  29080. int autoClip = -1;
  29081. for (int c = 0; c < (int) song.playlist.size(); ++c)
  29082. if (const auto& clip = song.playlist[(std::size_t) c]; clip.kind == lynx::ClipKind::automation && clip.automation >= 0
  29083. && clip.automation < (int) song.automations.size() && song.automations[(std::size_t) clip.automation].points.size() >= 3
  29084. && (autoClip < 0 || song.automations[(std::size_t) clip.automation].points.size() > song.automations[(std::size_t) song.playlist[(std::size_t) autoClip].automation].points.size()))
  29085. autoClip = c;
  29086. check ("R1: an automation clip with points in the project", autoClip >= 0);
  29087. if (autoClip >= 0)
  29088. {
  29089. const auto& clip = song.playlist[(std::size_t) autoClip];
  29090. const auto bar = (int) (clip.start / song.barTicks());
  29091. playlist.setViewForSnapshot (39.75, juce::jmax (0, bar - 2), juce::jmax (0, clip.track - 3));
  29092. settle();
  29093. const auto point = playlist.dragHintForSnapshot (autoClip, 1, false);
  29094. line ("point drag hint: " + point.text + " | " + point.value);
  29095. check ("R1: a dragged automation-clip point shows its value (DE-117)", point.value.isNotEmpty());
  29096. ui.setHintForSnapshot (point);
  29097. saveArea (ui, toolbar, prefix + "-r1-hint-point.png");
  29098. write (ui, "r1-window-point");
  29099. int bent = 0; // (a segment that is bent, when the clip has one)
  29100. const auto& points = song.automations[(std::size_t) clip.automation].points;
  29101. for (int k = 0; k + 1 < (int) points.size(); ++k)
  29102. if (points[(std::size_t) k].tension != 0.0f)
  29103. {
  29104. bent = k;
  29105. break;
  29106. }
  29107. const auto tension = playlist.dragHintForSnapshot (autoClip, bent, true);
  29108. line ("tension drag hint: " + tension.text + " | " + tension.value);
  29109. check ("R1: a bent segment shows its tension (DE-118)", tension.value.startsWith (lynx::tr ("Tension: {0}", { "" }).upToFirstOccurrenceOf (" ", false, false).trimEnd()));
  29110. ui.setHintForSnapshot (tension);
  29111. saveArea (ui, toolbar, prefix + "-r1-hint-tension.png");
  29112. const auto body = playlist.curveBodyForSnapshot (autoClip);
  29113. const auto hoverX = juce::jlimit (playlist.headerWidthForSnapshot() + 20, playlist.getWidth() - 40, (int) body.getX() + 80);
  29114. const auto hover = playlist.hintAt ({ hoverX, (int) body.getCentreY() });
  29115. line ("hover hint: " + hover.text + " | " + hover.value);
  29116. check ("R1: hovering the curve shows the value at the mouse (DE-119)", hover.value.contains (" "));
  29117. ui.setHintForSnapshot (hover);
  29118. saveArea (ui, toolbar, prefix + "-r1-hint-hover.png");
  29119. }
  29120. // R5: playing at bar 33 (FL's fl-playing.png), the meters fed so the activity strips show their steps
  29121. playlist.setViewForSnapshot (39.75, 20, 24);
  29122. settle();
  29123. offline.getTransport().positionTicks.store ((double) (32 * song.barTicks()));
  29124. offline.getTransport().playing.store (true);
  29125. const auto feed = [&offline] {
  29126. const float levels[] { 1.0f, 0.3f, 0.08f, 0.02f };
  29127. for (int k = 1; k < lynx::maxMixerTracks; ++k)
  29128. offline.getMeters().accumulate (k, levels[k % 4], levels[k % 4]);
  29129. };
  29130. feed();
  29131. playlist.frameStepForSnapshot();
  29132. feed();
  29133. playlist.frameStepForSnapshot();
  29134. write (ui, "r5-playing");
  29135. write (ui.getPickerForSnapshot(), "r5-picker-playing");
  29136. const auto px = (int) playlist.xOfTickForSnapshot (32.0 * (double) song.barTicks());
  29137. saveArea (playlist, { px - 40, lynx::PlaylistComponent::headerHeight, 60, 120 }, prefix + "-r5-playhead.png");
  29138. saveArea (playlist, { 0, lynx::PlaylistComponent::toolbarHeight, playlist.getWidth(), lynx::PlaylistComponent::overviewHeight }, prefix + "-r5-overview.png");
  29139. saveArea (playlist, { 0, lynx::PlaylistComponent::headerHeight, playlist.headerWidthForSnapshot() + 4, playlist.getHeight() - lynx::PlaylistComponent::headerHeight }, prefix + "-r5-headers.png");
  29140. lynx::ui::motion::enabled() = false;
  29141. playlist.frameStepForSnapshot();
  29142. saveArea (playlist, { px - 40, lynx::PlaylistComponent::headerHeight, 60, 120 }, prefix + "-r5-playhead-noanim.png");
  29143. lynx::ui::motion::enabled() = true;
  29144. playlist.frameStepForSnapshot();
  29145. // a drop preview: two patterns dragged from the Picker (issue #177's description) over track 4, bar 36
  29146. const auto row = playlist.trackRowForSnapshot (27);
  29147. playlist.dragOverForSnapshot (juce::var ("lynx-picker|0|0,1"), { (int) playlist.xOfTickForSnapshot (35.6 * (double) song.barTicks()), row.getCentreY() });
  29148. write (ui, "r5-drop-preview");
  29149. playlist.dragOverForSnapshot ({}, {});
  29150. offline.getTransport().playing.store (false);
  29151. playlist.frameStepForSnapshot();
  29152. write (ui, "r5-stopped");
  29153. write (ui.getPickerForSnapshot(), "r5-picker-stopped");
  29154. saveArea (playlist, { 0, lynx::PlaylistComponent::toolbarHeight, playlist.getWidth(), lynx::PlaylistComponent::overviewHeight }, prefix + "-r5-overview-stopped.png");
  29155. // R15: a scroll by hand while playing — Pattern layout: Follow goes on (off by default); the option on: it pauses
  29156. auto& globals = lynx::EditorGlobals::get();
  29157. const auto scrollWhilePlaying = [&] {
  29158. offline.getTransport().playing.store (true);
  29159. playlist.frameStepForSnapshot();
  29160. playlist.setScrollTickForSnapshot (playlist.scrollTicksForSnapshot() + 4.0 * (double) song.barTicks());
  29161. playlist.frameStepForSnapshot();
  29162. const auto paused = playlist.followPausedForSnapshot();
  29163. offline.getTransport().playing.store (false);
  29164. playlist.frameStepForSnapshot();
  29165. return paused;
  29166. };
  29167. check ("R15: Pattern layout (option off by default): no pause", ! globals.followPausing() && ! scrollWhilePlaying());
  29168. globals.followPausesOnEdit = 1;
  29169. check ("R15: option on: a scroll while playing pauses Follow", scrollWhilePlaying());
  29170. check ("R15: a stop lifts the pause", ! playlist.followPausedForSnapshot());
  29171. globals.followPausesOnEdit = -1;
  29172. }
  29173. {
  29174. // ---- R11: the Sampler's handles (a 1 s tone, loop points on)
  29175. lynx::AudioEngine engine (false);
  29176. const auto tone = juce::File (prefix).getParentDirectory().getChildFile ("details190im-tone.wav");
  29177. {
  29178. juce::AudioBuffer<float> buffer (1, 44100);
  29179. for (int i = 0; i < buffer.getNumSamples(); ++i)
  29180. buffer.setSample (0, i, (float) (0.6 * std::sin (juce::MathConstants<double>::twoPi * 110.0 * i / 44100.0) * (1.0 - i / 44100.0)));
  29181. tone.deleteFile();
  29182. juce::WavAudioFormat wav;
  29183. if (auto out = std::unique_ptr<juce::AudioFormatWriter> (wav.createWriterFor (tone.createOutputStream().release(), 44100.0, 1, 16, {}, 0)))
  29184. out->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
  29185. }
  29186. engine.editSong ([&] (lynx::Song& s) {
  29187. if (s.channels.empty())
  29188. s.channels.resize (1);
  29189. lynx::audioclips::loadSampleInto (s.channels[0], tone.getFullPathName().toStdString(), "Tone");
  29190. });
  29191. const auto sampler = [&engine] { return engine.getSong().channels[0].sampler; };
  29192. auto frame = lynx::makeChannelFrame (engine, 0, 0);
  29193. frame->setSize (frame->getWidth() > 0 ? frame->getWidth() : 700, frame->getHeight() > 0 ? frame->getHeight() : 720);
  29194. frame->createComponentSnapshot (frame->getLocalBounds());
  29195. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (8000);
  29196. auto& f = *frame;
  29197. lynx::samplerPageTurn (f, "useLoops", 1.0);
  29198. lynx::samplerPageTurn (f, "loopStart", 11025.0);
  29199. lynx::samplerPageTurn (f, "loopEnd", 22050.0);
  29200. lynx::samplerPageTurn (f, "smpStart", 0.0);
  29201. savePng (f.createComponentSnapshot (f.getLocalBounds()), prefix + "-r11-sampler-before.png");
  29202. for (const auto* h : { "Start", "LoopStart", "LoopEnd" })
  29203. line (juce::String ("press on the drawn ") + h + " handle takes: " + lynx::samplerPageQuery (f, juce::String ("handleAt") + h));
  29204. check ("R11: a press on the loop start line takes the loop start", lynx::samplerPageQuery (f, "handleAtLoopStart") == "loopStart");
  29205. check ("R11: a press on the loop end line takes the loop end", lynx::samplerPageQuery (f, "handleAtLoopEnd") == "loopEnd");
  29206. check ("R11: a press on the Start marker takes the start", lynx::samplerPageQuery (f, "handleAtStart") == "start");
  29207. lynx::samplerPageTurn (f, "dragLoopEnd", 0.75);
  29208. check ("R11: the loop end dragged to 3/4", std::abs ((double) sampler().loopEnd - 0.75 * 44099.0) < 2.0);
  29209. lynx::samplerPageTurn (f, "dragLoopStart", 0.375, true);
  29210. check ("R11: Shift drags the whole loop", sampler().loopStart > 16000 && sampler().loopEnd - sampler().loopStart > 22000);
  29211. line ("loop after the drags: " + juce::String (sampler().loopStart) + " - " + juce::String (sampler().loopEnd));
  29212. lynx::samplerPageTurn (f, "dragStart", 0.2);
  29213. check ("R11: the Start marker dragged to 20 %", std::abs (sampler().startOffset - 0.2f) < 0.01f);
  29214. savePng (f.createComponentSnapshot (f.getLocalBounds()), prefix + "-r11-sampler-after.png");
  29215. tone.deleteFile();
  29216. }
  29217. if (set.isNotEmpty())
  29218. {
  29219. // ---- Clip-launch layout, the Live set
  29220. lynx::AudioEngine offline (false);
  29221. lynx::MainComponent ui (offline, false);
  29222. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  29223. ui.setVisible (true);
  29224. ui.selectTabForSnapshot (2);
  29225. ui.setClipLaunchWorkflow (true);
  29226. offline.dispatchPendingMessages();
  29227. ui.openFile (juce::File (set));
  29228. offline.dispatchPendingMessages();
  29229. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  29230. offline.dispatchPendingMessages();
  29231. ui.resized();
  29232. auto* gridView = ui.getClipGridForSnapshot();
  29233. auto* runtime = offline.launcherStateForSnapshot();
  29234. const auto& song = offline.getSong();
  29235. check ("grid and launcher", gridView != nullptr && runtime != nullptr && song.clipGrid.has_value());
  29236. if (gridView == nullptr || runtime == nullptr || ! song.clipGrid.has_value())
  29237. {
  29238. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  29239. return;
  29240. }
  29241. auto& grid = *gridView;
  29242. gridView->resized();
  29243. const auto firstClip = [&song] (int track, lynx::ClipKind kind) {
  29244. for (int r = 0; r < 64; ++r)
  29245. if (const auto* c = lynx::launcher::clipAt (*song.clipGrid, track, r); c != nullptr && c->kind == kind)
  29246. return r;
  29247. return -1;
  29248. };
  29249. const auto bigCrop = [&] (const juce::String& name, juce::Rectangle<int> area) { saveArea (grid, area, prefix + "-" + name + ".png"); };
  29250. // R6: track 0 plays a one-shot (Loop off), track 1 loops in its 2nd pass, track 2's clip has a follow action
  29251. int rows[3] { -1, -1, -1 };
  29252. for (int t = 0; t < 3; ++t)
  29253. for (const auto kind : { lynx::ClipKind::audio, lynx::ClipKind::pattern })
  29254. if (rows[t] < 0)
  29255. rows[t] = firstClip (t, kind);
  29256. offline.editSong ([&rows] (lynx::Song& s) {
  29257. if (rows[0] >= 0)
  29258. lynx::launcher::settingsAt (*s.clipGrid, 0, rows[0])->loop = false;
  29259. if (rows[2] >= 0)
  29260. {
  29261. auto& f = lynx::launcher::settingsAt (*s.clipGrid, 2, rows[2])->follow;
  29262. f.enabled = true;
  29263. f.a = lynx::FollowKind::next;
  29264. }
  29265. }, false);
  29266. offline.dispatchPendingMessages();
  29267. runtime->running.store (true);
  29268. for (int t = 0; t < 2; ++t)
  29269. if (rows[t] >= 0)
  29270. {
  29271. const auto length = (double) lynx::launcher::clipAt (*song.clipGrid, t, rows[t])->length;
  29272. runtime->tracks[(std::size_t) t].playing.store (rows[t]);
  29273. runtime->tracks[(std::size_t) t].progress.store (0.4f);
  29274. runtime->tracks[(std::size_t) t].anchor.store (0.0);
  29275. runtime->clockNow.store (length * 1.4);
  29276. }
  29277. lynx::tickClipGridForSnapshot (grid);
  29278. grid.repaint();
  29279. write (grid, "r6-grid-playing");
  29280. bigCrop ("r6-status-oneshot", lynx::clipGridCellForSnapshot (grid, 1, 0, 0).getUnion (lynx::clipGridCellForSnapshot (grid, 1, 1, 0)));
  29281. if (rows[2] >= 0)
  29282. {
  29283. const auto cell = lynx::clipGridCellForSnapshot (grid, 0, 2, rows[2]);
  29284. bigCrop ("r6-follow-stripes", cell);
  29285. }
  29286. // the queued scene's pulse, both phases, then the next scene selected
  29287. const auto scene = juce::jmax (0, rows[1]);
  29288. lynx::setClipGridBlinkPhaseForSnapshot (1);
  29289. lynx::launchClipGridSceneForSnapshot (grid, scene);
  29290. grid.repaint();
  29291. bigCrop ("r6-scene-queued-lit", lynx::clipGridCellForSnapshot (grid, 2, 0, scene));
  29292. lynx::setClipGridBlinkPhaseForSnapshot (0);
  29293. grid.repaint();
  29294. bigCrop ("r6-scene-queued-dark", lynx::clipGridCellForSnapshot (grid, 2, 0, scene));
  29295. lynx::setClipGridBlinkPhaseForSnapshot (-1);
  29296. const auto [selected, sceneSelected] = lynx::clipGridSceneSelectionForSnapshot (grid);
  29297. check ("R6: after a scene launch the scene below is selected (DL-6)", selected == juce::jmin (scene + 1, (int) song.clipGrid->scenes.size() - 1) && sceneSelected);
  29298. write (grid, "r6-grid-scene-launched");
  29299. // the hints of each part
  29300. const auto hintAt = [&] (const juce::String& what, juce::Point<int> p) {
  29301. const auto [text, value] = lynx::clipGridHintForSnapshot (grid, p);
  29302. line ("hint " + what + ": " + text + " | " + value);
  29303. return text;
  29304. };
  29305. const auto slot = lynx::clipGridCellForSnapshot (grid, 0, 1, juce::jmax (0, rows[1]));
  29306. const auto launchHint = hintAt ("clip launch button", { slot.getX() + 7, slot.getCentreY() });
  29307. hintAt ("clip", { slot.getCentreX(), slot.getCentreY() });
  29308. hintAt ("stop button", { lynx::clipGridCellForSnapshot (grid, 1, 1, 0).getX() + 7, lynx::clipGridCellForSnapshot (grid, 1, 1, 0).getCentreY() });
  29309. hintAt ("status", { lynx::clipGridCellForSnapshot (grid, 1, 1, 0).getCentreX(), lynx::clipGridCellForSnapshot (grid, 1, 1, 0).getCentreY() });
  29310. const auto sceneCell = lynx::clipGridCellForSnapshot (grid, 2, 0, 0);
  29311. hintAt ("scene launch button", { sceneCell.getX() + 6, sceneCell.getCentreY() });
  29312. hintAt ("scene", { sceneCell.getCentreX(), sceneCell.getCentreY() });
  29313. check ("R6: the grid's parts have hints (DL-21)", launchHint.isNotEmpty());
  29314. ui.setHintForSnapshot ({ launchHint, {}, false, false });
  29315. saveArea (ui, ui.getToolbarBoundsForSnapshot(), prefix + "-r6-hint-launch.png");
  29316. // R12: 0 on the selected clip deactivates it (greyed), again activates it; the scene column's font
  29317. lynx::selectClipGridSlotForSnapshot (grid, 1, juce::jmax (0, rows[1]));
  29318. grid.grabKeyboardFocus();
  29319. const auto activeNow = [&] { const auto* s = lynx::launcher::settingsAt (*const_cast<lynx::Song&> (song).clipGrid, 1, juce::jmax (0, rows[1])); return s == nullptr || s->active; };
  29320. check ("R12: 0 is taken by the grid", lynx::clipGridKeyForSnapshot (grid, juce::KeyPress ('0')));
  29321. offline.dispatchPendingMessages();
  29322. check ("R12: 0 deactivates the selected clip", ! activeNow());
  29323. for (auto& v : runtime->tracks)
  29324. v.playing.store (-1);
  29325. grid.repaint();
  29326. write (grid, "r12-clip-deactivated");
  29327. bigCrop ("r12-clip-deactivated-cell", slot);
  29328. lynx::clipGridKeyForSnapshot (grid, juce::KeyPress ('0'));
  29329. offline.dispatchPendingMessages();
  29330. check ("R12: 0 again activates it", activeNow());
  29331. bigCrop ("r12-scene-column", lynx::clipGridCellForSnapshot (grid, 2, 0, 0).getUnion (lynx::clipGridCellForSnapshot (grid, 2, 0, juce::jmin (7, (int) song.clipGrid->scenes.size() - 1))));
  29332. // R13: the Clip View of a launched MIDI clip: the Piano roll's playhead at the clip's position
  29333. int midiTrack = -1, midiRow = -1;
  29334. for (int t = 0; t < 16 && midiTrack < 0; ++t)
  29335. if (const auto r = firstClip (t, lynx::ClipKind::pattern); r >= 0)
  29336. {
  29337. midiTrack = t;
  29338. midiRow = r;
  29339. }
  29340. check ("R13: the set has a MIDI clip", midiTrack >= 0);
  29341. if (auto* detail = ui.getDetailViewForSnapshot(); detail != nullptr && midiTrack >= 0)
  29342. {
  29343. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  29344. lynx::DetailView::shownSetting = true;
  29345. detail->showSelection (midiTrack, midiRow);
  29346. detail->setPage (lynx::DetailView::Page::clip);
  29347. offline.dispatchPendingMessages();
  29348. ui.resized();
  29349. const auto& clip = *lynx::launcher::clipAt (*song.clipGrid, midiTrack, midiRow);
  29350. runtime->running.store (true);
  29351. runtime->tracks[(std::size_t) midiTrack].playing.store (midiRow);
  29352. runtime->tracks[(std::size_t) midiTrack].anchor.store (0.0);
  29353. runtime->clockNow.store ((double) clip.length * 2.3);
  29354. offline.getTransport().playing.store (true);
  29355. auto& roll = ui.getPianoRollForSnapshot();
  29356. roll.frameStepForSnapshot();
  29357. const auto expect = (double) clip.offset + 0.3 * (double) clip.length;
  29358. line ("piano roll playhead " + juce::String (roll.playheadForSnapshot(), 1) + ", the launched clip at " + juce::String (expect, 1));
  29359. check ("R13: the docked Piano roll shows the launched clip's position (DL-74)", std::abs (roll.playheadForSnapshot() - expect) < (double) lynx::ppq);
  29360. write (ui, "r13-clipview-midi");
  29361. offline.getTransport().playing.store (false);
  29362. runtime->tracks[(std::size_t) midiTrack].playing.store (-1);
  29363. roll.frameStepForSnapshot();
  29364. }
  29365. }
  29366. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  29367. }
  29368. void runDesign190igShot (const juce::String& prefix, const juce::String& project)
  29369. {
  29370. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  29371. lynx::AudioEngine offline (false);
  29372. lynx::MainComponent ui (offline, false);
  29373. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1920x1080"), "x", "");
  29374. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  29375. const auto write = [&prefix] (juce::Component& c, const char* name) {
  29376. savePng (lynx::shot::snapshot (c), prefix + "-" + name + ".png");
  29377. };
  29378. if (project.isNotEmpty())
  29379. ui.openFile (juce::File (project));
  29380. offline.dispatchPendingMessages();
  29381. ui.selectTabForSnapshot (2); // the Playlist, maximized
  29382. auto& playlist = ui.getPlaylistForSnapshot();
  29383. offline.dispatchPendingMessages();
  29384. const auto settle = [&] { // (the waveforms are analysed in the background on the first paint)
  29385. write (playlist, "warmup");
  29386. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (60000);
  29387. offline.dispatchPendingMessages();
  29388. juce::File (prefix + "-warmup.png").deleteFile();
  29389. };
  29390. const auto heights = [&] (int h) {
  29391. offline.editSong ([h] (lynx::Song& s) {
  29392. for (auto& t : s.playlistTracks)
  29393. t.height = h;
  29394. }, false);
  29395. offline.dispatchPendingMessages();
  29396. };
  29397. // 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
  29398. heights (26);
  29399. playlist.setViewForSnapshot (15.6, 20, 0);
  29400. playlist.setScrollYForSnapshot (19 * 26);
  29401. settle();
  29402. write (ui, "01-default");
  29403. write (playlist, "01-default-playlist");
  29404. // 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
  29405. heights (50);
  29406. playlist.setViewForSnapshot (39.75, 20, 0);
  29407. playlist.setScrollYForSnapshot (24 * 50 + 4);
  29408. settle();
  29409. write (ui, "02-zoom17");
  29410. write (playlist, "02-zoom17-playlist");
  29411. // playing (shots/ref/fl-playing.png): the playhead at bar 33, the activity column lit for the tracks that sound
  29412. offline.getTransport().positionTicks.store ((double) (32 * offline.getSong().barTicks()));
  29413. offline.getTransport().playing.store (true);
  29414. playlist.frameStepForSnapshot();
  29415. playlist.frameStepForSnapshot();
  29416. write (ui, "03-playing");
  29417. offline.getTransport().playing.store (false);
  29418. playlist.frameStepForSnapshot();
  29419. heights (26);
  29420. playlist.setViewForSnapshot (15.6, 0, 0);
  29421. playlist.setScrollYForSnapshot (0);
  29422. write (ui, "04-default-start");
  29423. // round 190jd (live check 190iw Q4): FL's grid levels at its Ctrl+wheel steps — bars only at 9.9 px a beat, beat
  29424. // lines from 11.5, half-beat lines from 21.5 (shots/q4-fl-zoom-levels-ruler-grid.png), at bar 9 like FL's shot
  29425. heights (32);
  29426. for (const auto beat : { 9.9, 11.5, 18.4, 21.5 })
  29427. {
  29428. playlist.setViewForSnapshot (beat * 4.0, 8, 0);
  29429. playlist.setScrollYForSnapshot (0);
  29430. write (playlist, ("05-grid-" + juce::String (beat, 1) + "px-beat").toRawUTF8());
  29431. }
  29432. // round 190jd: NEW automation clips from the first channel's volume and pan knobs take FL's colours by parameter
  29433. // (#8C5F5F, #7F8C5E; shots/q4-fl-new-automation-clip-zoom2.png); the editor windows they open are closed again
  29434. if (! offline.getSong().channels.empty())
  29435. {
  29436. // (the channels of FL's capture: Synth Bass pan + volume, Grv Kick 27 volume + pan; else the first channel)
  29437. const auto channelNamed = [&offline] (const char* name) {
  29438. const auto& channels = offline.getSong().channels;
  29439. for (int c = 0; c < (int) channels.size(); ++c)
  29440. if (juce::String (channels[(std::size_t) c].name).startsWithIgnoreCase (name))
  29441. return c;
  29442. return 0;
  29443. };
  29444. juce::String report;
  29445. offline.editSong ([] (lynx::Song& s) { s.loopStart = s.loopEnd = 0; }, false);
  29446. offline.getTransport().positionTicks.store (0.0);
  29447. const auto before = offline.getSong().automations.size();
  29448. for (const auto& [name, kind] : { std::pair { "Synth Bass", lynx::AutomationTargetKind::channelPan },
  29449. std::pair { "Grv Kick", lynx::AutomationTargetKind::channelVolume },
  29450. std::pair { "Synth Bass", lynx::AutomationTargetKind::channelVolume },
  29451. std::pair { "Grv Kick", lynx::AutomationTargetKind::channelPan } })
  29452. {
  29453. lynx::AutomationTarget t;
  29454. t.kind = kind;
  29455. t.index = channelNamed (name);
  29456. lynx::createAutomationClip (offline, t);
  29457. offline.dispatchPendingMessages();
  29458. }
  29459. lynx::closeAutomationEditors();
  29460. offline.dispatchPendingMessages();
  29461. int first = -1;
  29462. for (std::size_t a = before; a < offline.getSong().automations.size(); ++a)
  29463. {
  29464. const auto& au = offline.getSong().automations[a];
  29465. for (const auto& c : offline.getSong().playlist)
  29466. if (c.kind == lynx::ClipKind::automation && c.automation == (int) a)
  29467. {
  29468. first = first < 0 ? c.track : std::min (first, c.track);
  29469. report << "new clip '" << au.name << "' track " << (c.track + 1) << " colour #"
  29470. << juce::String::toHexString ((int) (au.colour & 0xFFFFFF)).paddedLeft ('0', 6).toUpperCase() << "\n";
  29471. }
  29472. }
  29473. report << "automations " << (int) before << " -> " << (int) offline.getSong().automations.size() << "\n";
  29474. juce::File (prefix + "-190jd-automation.txt").replaceWithText (report);
  29475. heights (50);
  29476. playlist.setViewForSnapshot (39.75, 0, 0);
  29477. playlist.setScrollYForSnapshot (std::max (0, first - 1) * 50);
  29478. write (playlist, "06-new-automation-clips");
  29479. }
  29480. // round 190jd (live check 190iw Q7, shots/q7-fl-countin-sheet.png): a 1-bar count-in — the time display reads
  29481. // "REC IN 4" on its first beat and "REC IN 1" on its last, Play shows its Pause glyph, Record stays lit
  29482. for (const auto beatsLeft : { 4, 1 })
  29483. {
  29484. offline.getTransport().countIn.store ((double) beatsLeft * lynx::ppq - 1.0);
  29485. ui.tickLinkForSnapshot();
  29486. ui.transportForSnapshot (true, true);
  29487. write (ui, ("07-countin-" + juce::String (beatsLeft)).toRawUTF8());
  29488. }
  29489. offline.getTransport().countIn.store (0.0);
  29490. }
  29491. void runDesign190igS4Shot (const juce::String& prefix, const juce::String& projectPath)
  29492. {
  29493. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  29494. lynx::AudioEngine offline (false);
  29495. lynx::MainComponent ui (offline, false);
  29496. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  29497. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  29498. juce::String checks;
  29499. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  29500. const auto write = [&prefix] (juce::Component& c, const juce::String& name) {
  29501. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  29502. file.deleteFile();
  29503. juce::FileOutputStream out (file);
  29504. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (c), out);
  29505. };
  29506. ui.setVisible (true);
  29507. ui.selectTabForSnapshot (2);
  29508. ui.setClipLaunchWorkflow (true); // (first: an .als opened in the Clip-launch layout takes Live's own colours)
  29509. offline.dispatchPendingMessages();
  29510. if (projectPath.isNotEmpty())
  29511. {
  29512. ui.openFile (juce::File (projectPath));
  29513. offline.dispatchPendingMessages();
  29514. }
  29515. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  29516. offline.dispatchPendingMessages();
  29517. ui.resized();
  29518. auto* gridView = ui.getClipGridForSnapshot();
  29519. auto* runtime = offline.launcherStateForSnapshot();
  29520. const auto& song = offline.getSong();
  29521. if (gridView == nullptr || ! song.clipGrid)
  29522. {
  29523. juce::File (prefix + "-checks.txt").replaceWithText ("FAIL no grid\n");
  29524. return;
  29525. }
  29526. if (! song.mixer.empty())
  29527. checks << "first mixer colours:";
  29528. for (std::size_t m = 1; m < std::min<std::size_t> (song.mixer.size(), 6); ++m)
  29529. checks << " " << juce::String::toHexString ((int) (song.mixer[m].colour & 0xffffff)).paddedLeft ('0', 6);
  29530. checks << "\n";
  29531. gridView->resized();
  29532. write (ui, "01-window-idle");
  29533. write (*gridView, "02-grid-idle");
  29534. if (runtime == nullptr)
  29535. {
  29536. check ("a launcher runtime exists", false);
  29537. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  29538. return;
  29539. }
  29540. // the frame strip: the first five tracks; the scene each plays or waits for, by the clips the set has
  29541. const auto& grid = *song.clipGrid;
  29542. const auto rowWithClip = [&grid] (int track, int from) {
  29543. for (int r = from; r < 64; ++r)
  29544. if (lynx::launcher::clipAt (grid, track, r) != nullptr)
  29545. return r;
  29546. return -1;
  29547. };
  29548. const auto reset = [&] {
  29549. for (auto& v : runtime->tracks)
  29550. {
  29551. v.playing.store (-1);
  29552. v.pending.store (-1);
  29553. v.stopping.store (false);
  29554. v.recording.store (-1);
  29555. v.recordPending.store (-1);
  29556. v.progress.store (0.0f);
  29557. }
  29558. runtime->running.store (true);
  29559. };
  29560. const auto bar = (double) song.barTicks();
  29561. const auto state = [&] (const juce::String& name) {
  29562. gridView->repaint();
  29563. write (*gridView, name);
  29564. };
  29565. // playing (Live frame 1): tracks 0..3 play their first clip, a third of the way into its second loop
  29566. reset();
  29567. for (int t = 0; t < 4; ++t)
  29568. if (const auto r = rowWithClip (t, 0); r >= 0)
  29569. {
  29570. runtime->tracks[(std::size_t) t].playing.store (r);
  29571. runtime->tracks[(std::size_t) t].progress.store (0.33f);
  29572. const auto length = (double) lynx::launcher::clipAt (grid, t, r)->length;
  29573. runtime->tracks[(std::size_t) t].anchor.store (0.0);
  29574. runtime->clockNow.store (length * 1.33);
  29575. }
  29576. state ("10-playing");
  29577. // queued (Live frames 2 and 3): the same, and each track's next clip waits for its start; both blink phases
  29578. for (int t = 0; t < 4; ++t)
  29579. if (const auto r = runtime->tracks[(std::size_t) t].playing.load(); r >= 0)
  29580. if (const auto next = rowWithClip (t, r + 1); next >= 0)
  29581. runtime->tracks[(std::size_t) t].pending.store (next);
  29582. lynx::setClipGridBlinkPhaseForSnapshot (0);
  29583. state ("11-queued-dark");
  29584. lynx::setClipGridBlinkPhaseForSnapshot (1);
  29585. state ("12-queued-lit");
  29586. // Animations off: the lit green, steady
  29587. lynx::ui::motion::enabled() = false;
  29588. lynx::setClipGridBlinkPhaseForSnapshot (-1);
  29589. state ("13-queued-animations-off");
  29590. lynx::ui::motion::enabled() = true;
  29591. // a stop waiting (both phases)
  29592. reset();
  29593. for (int t = 0; t < 4; ++t)
  29594. if (const auto r = rowWithClip (t, 0); r >= 0)
  29595. {
  29596. runtime->tracks[(std::size_t) t].playing.store (r);
  29597. runtime->tracks[(std::size_t) t].progress.store (0.5f);
  29598. runtime->tracks[(std::size_t) t].stopping.store (t % 2 == 0);
  29599. }
  29600. lynx::setClipGridBlinkPhaseForSnapshot (0);
  29601. state ("14-stopping-dark");
  29602. lynx::setClipGridBlinkPhaseForSnapshot (1);
  29603. state ("15-stopping-lit");
  29604. // recording into an empty slot of track 1 (the counter one beat in) and a launch waiting on an empty slot (a stop)
  29605. reset();
  29606. {
  29607. int empty = -1;
  29608. for (int r = 0; r < 16 && empty < 0; ++r)
  29609. if (lynx::launcher::clipAt (grid, 1, r) == nullptr)
  29610. empty = r;
  29611. if (empty >= 0)
  29612. {
  29613. runtime->tracks[1].recording.store (empty);
  29614. runtime->tracks[1].recordFrom.store (0.0);
  29615. runtime->clockNow.store ((double) lynx::ppq);
  29616. }
  29617. check ("recording: an empty slot on track 2", empty >= 0);
  29618. }
  29619. state ("16-recording");
  29620. // the status pie at 25 / 50 / 75 % in the second loop
  29621. 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) })
  29622. {
  29623. reset();
  29624. for (int t = 0; t < 4; ++t)
  29625. if (const auto r = rowWithClip (t, 0); r >= 0)
  29626. {
  29627. const auto length = (double) lynx::launcher::clipAt (grid, t, r)->length;
  29628. runtime->tracks[(std::size_t) t].playing.store (r);
  29629. runtime->tracks[(std::size_t) t].progress.store (p);
  29630. runtime->tracks[(std::size_t) t].anchor.store (0.0);
  29631. runtime->clockNow.store (length * (1.0 + (double) p));
  29632. }
  29633. state (name);
  29634. }
  29635. juce::ignoreUnused (bar);
  29636. // round 181a's look, the option (View › Classic LYNX look for the clip grid)
  29637. reset();
  29638. for (int t = 0; t < 4; ++t)
  29639. if (const auto r = rowWithClip (t, 0); r >= 0)
  29640. runtime->tracks[(std::size_t) t].playing.store (r);
  29641. lynx::clipGridClassicLook() = true;
  29642. lynx::refreshClipGrid (*gridView);
  29643. state ("20-classic-look-option");
  29644. lynx::clipGridClassicLook() = false;
  29645. lynx::refreshClipGrid (*gridView);
  29646. lynx::setClipGridBlinkPhaseForSnapshot (-1);
  29647. reset();
  29648. runtime->running.store (false);
  29649. write (ui, "21-window-after");
  29650. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  29651. ui.setClipLaunchWorkflow (false);
  29652. }
  29653. void runLiveShot190dr (const juce::String& prefix)
  29654. {
  29655. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  29656. lynx::AudioEngine offline (false);
  29657. lynx::MainComponent ui (offline, false);
  29658. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  29659. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  29660. const auto write = [&prefix] (juce::Component& c, const char* name) {
  29661. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  29662. file.deleteFile();
  29663. juce::FileOutputStream out (file);
  29664. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (c), out);
  29665. };
  29666. juce::String checks;
  29667. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  29668. // a two-bar loop of clicks for the audio clip
  29669. const auto wav = juce::File (prefix + "-loop.wav");
  29670. wav.deleteFile();
  29671. {
  29672. const double rate = 48000.0;
  29673. juce::AudioBuffer<float> buffer (2, (int) (rate * 4.0));
  29674. buffer.clear();
  29675. for (int hit = 0; hit < 16; ++hit)
  29676. for (int k = 0; k < 3000 && hit * 12000 + k < buffer.getNumSamples(); ++k)
  29677. for (int ch = 0; ch < 2; ++ch)
  29678. buffer.setSample (ch, hit * 12000 + k, (float) (std::sin (k * (hit % 4 == 0 ? 0.05 : 0.3)) * std::exp (-k / 500.0) * 0.8));
  29679. if (auto out = std::unique_ptr<juce::FileOutputStream> (wav.createOutputStream()))
  29680. if (auto* writer = juce::WavAudioFormat().createWriterFor (out.get(), rate, 2, 16, {}, 0))
  29681. {
  29682. out.release();
  29683. std::unique_ptr<juce::AudioFormatWriter> owned (writer);
  29684. owned->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
  29685. }
  29686. }
  29687. ui.setVisible (true);
  29688. lynx::DetailView::shownSetting = true;
  29689. lynx::DetailView::devicesPage = false;
  29690. ui.setClipLaunchWorkflow (true);
  29691. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::browser, lynx::workspace::Panel::playlist });
  29692. ui.getPlaylistForSnapshot().addAudioClipAtPlayhead (wav);
  29693. offline.dispatchPendingMessages();
  29694. int audioChannel = -1;
  29695. offline.editSong ([&audioChannel] (lynx::Song& s) {
  29696. lynx::Clip audio;
  29697. if (! s.playlist.empty())
  29698. {
  29699. audio = s.playlist.front();
  29700. audioChannel = audio.channel;
  29701. s.playlist.clear();
  29702. }
  29703. const int channels = (int) s.channels.size();
  29704. s.channels.resize ((std::size_t) channels + 3);
  29705. const char* names[] { "Drum kit", "Bass synth", "Keys" };
  29706. for (int k = 0; k < 3; ++k)
  29707. {
  29708. auto& ch = s.channels[(std::size_t) (channels + k)];
  29709. ch.name = names[k];
  29710. ch.instrument = k == 0 ? lynx::InstrumentKind::sampler : lynx::InstrumentKind::synth;
  29711. ch.mixerTrack = k + 1;
  29712. }
  29713. if (audioChannel >= 0)
  29714. s.channels[(std::size_t) audioChannel].mixerTrack = 5;
  29715. if (s.mixer.size() < 8)
  29716. s.mixer.resize (8);
  29717. const char* inserts[] { "Master", "Drums", "Bass", "Keys", "Vox", "Loop", "Reverb", "Delay" };
  29718. for (int i = 1; i < 8; ++i)
  29719. s.mixer[(std::size_t) i].name = inserts[i];
  29720. s.mixer[1].volume = lynx::sessionmixer::positionForDb (-3.0);
  29721. s.mixer[2].pan = 0.3f;
  29722. s.mixer[2].effects.clear();
  29723. for (auto kind : { lynx::EffectKind::eq, lynx::EffectKind::compressor, lynx::EffectKind::delay })
  29724. {
  29725. lynx::EffectSlot fx;
  29726. fx.kind = kind;
  29727. const auto& info = lynx::effectInfo (kind);
  29728. for (std::size_t k = 0; k < info.params.size() && k < fx.params.size(); ++k)
  29729. fx.params[k] = info.params[k].defaultValue;
  29730. s.mixer[2].effects.push_back (fx);
  29731. }
  29732. s.mixer[3].muted = true; // the Keys' activator off
  29733. s.mixer[4].inputChannel = 0;
  29734. s.mixer[4].inputStereo = true;
  29735. s.mixer[4].monitor = lynx::InputMonitor::automatic;
  29736. s.mixer[4].effects.clear();
  29737. {
  29738. lynx::EffectSlot fx;
  29739. fx.kind = lynx::EffectKind::reverb;
  29740. s.mixer[4].effects.push_back (fx);
  29741. }
  29742. s.mixer[5].solo = true;
  29743. 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 } })
  29744. {
  29745. lynx::MixerSend send;
  29746. send.target = to;
  29747. send.level = lynx::faderGain (level);
  29748. s.mixer[(std::size_t) from].sends.push_back (send);
  29749. }
  29750. while (s.patterns.size() < 3)
  29751. s.patterns.emplace_back();
  29752. const char* patterns[] { "Beat", "Bassline", "Chords" };
  29753. for (int p = 0; p < 3; ++p)
  29754. {
  29755. auto& pattern = s.patterns[(std::size_t) p];
  29756. pattern.name = patterns[p];
  29757. lynx::Note n;
  29758. n.channel = channels + p;
  29759. n.key = 48 + p * 5;
  29760. pattern.notes = { n };
  29761. pattern.lengthTicks = 4 * lynx::ppq;
  29762. }
  29763. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 8));
  29764. const char* tracks[] { "Drums", "Bass", "Keys", "Vox", "Loop", "FX" };
  29765. for (int t = 0; t < 6; ++t)
  29766. s.playlistTracks[(std::size_t) t].name = tracks[t];
  29767. s.playlistTracks[3].mode = lynx::PlaylistTrackMode::audio;
  29768. s.playlistTracks[3].mixerTrack = 4;
  29769. for (int t = 0; t < 3; ++t)
  29770. for (int r = 0; r < 3; ++r)
  29771. if (! (t == 2 && r == 0))
  29772. {
  29773. lynx::Clip clip;
  29774. clip.pattern = t;
  29775. clip.length = 4 * lynx::ppq;
  29776. lynx::launcher::setClip (s, t, r, clip);
  29777. }
  29778. if (audioChannel >= 0)
  29779. {
  29780. lynx::clipsample::setWarp (s, audioChannel, true, 4.0); // (Warp on, as a dropped loop in Live)
  29781. audio.track = 4;
  29782. audio.start = 0;
  29783. lynx::launcher::setClip (s, 4, 0, audio);
  29784. lynx::launcher::setClip (s, 4, 1, audio);
  29785. }
  29786. auto& grid = lynx::launcher::ensureGrid (s);
  29787. const char* scenes[] { "Intro", "Verse", "Drop" };
  29788. grid.scenes.resize (5);
  29789. for (int r = 0; r < 3; ++r)
  29790. grid.scenes[(std::size_t) r].name = scenes[r];
  29791. }, false);
  29792. offline.dispatchPendingMessages();
  29793. offline.setGridTrackArmed (3, true);
  29794. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  29795. offline.dispatchPendingMessages();
  29796. ui.resized();
  29797. auto* gridView = ui.getClipGridForSnapshot();
  29798. auto* mixer = gridView != nullptr ? lynx::clipGridMixer (*gridView) : nullptr;
  29799. auto* detail = ui.getDetailViewForSnapshot();
  29800. if (gridView == nullptr || mixer == nullptr || detail == nullptr)
  29801. {
  29802. juce::File (prefix + "-checks.txt").replaceWithText ("FAIL no grid, mixer or detail view\n");
  29803. return;
  29804. }
  29805. // the meters: a level per insert, as a playing song leaves them (offscreen nothing plays), two ticks
  29806. const auto levels = [&] {
  29807. for (int k = 0; k < 2; ++k)
  29808. {
  29809. const float peaks[] { 0.9f, 0.5f, 0.7f, 0.0f, 0.3f, 0.45f, 0.2f, 0.12f };
  29810. for (int i = 0; i < 8; ++i)
  29811. offline.getMeters().accumulate (i, peaks[i], peaks[i] * 0.85f);
  29812. mixer->tick();
  29813. }
  29814. };
  29815. if (auto* runtime = offline.launcherStateForSnapshot())
  29816. {
  29817. runtime->tracks[0].playing.store (1);
  29818. runtime->tracks[0].progress.store (0.3f);
  29819. runtime->tracks[1].playing.store (1);
  29820. runtime->tracks[1].progress.store (0.3f);
  29821. runtime->tracks[4].playing.store (0);
  29822. runtime->tracks[4].progress.store (0.5f);
  29823. runtime->running.store (true);
  29824. }
  29825. levels();
  29826. gridView->resized();
  29827. write (ui, "01-session-mixer");
  29828. write (*gridView, "01b-grid-alone");
  29829. using Part = lynx::SessionMixerComponent::Part;
  29830. check ("mixer: Sends rows are the two buses (Reverb 6, Delay 7)", mixer->sendTargets() == std::vector<int> { 6, 7 });
  29831. check ("mixer: the arm buttons moved into the Volume section", mixer->armsShown());
  29832. check ("mixer: Drums strip has activator, solo, arm, pan, volume", ! mixer->partBounds (0, Part::activator).isEmpty() && ! mixer->partBounds (0, Part::solo).isEmpty()
  29833. && ! mixer->partBounds (0, Part::arm).isEmpty() && ! mixer->partBounds (0, Part::pan).isEmpty()
  29834. && ! mixer->partBounds (0, Part::volume).isEmpty());
  29835. check ("mixer: Vox strip (audio track) has Audio From, its channel, Monitor and Audio To", ! mixer->partBounds (3, Part::inType).isEmpty()
  29836. && ! mixer->partBounds (3, Part::inChannel).isEmpty()
  29837. && ! mixer->partBounds (3, Part::monAuto).isEmpty()
  29838. && ! mixer->partBounds (3, Part::output).isEmpty());
  29839. check ("mixer: Bass strip (instrument) shows MIDI From, no Monitor", mixer->partBounds (1, Part::monIn).isEmpty() && ! mixer->partBounds (1, Part::output).isEmpty());
  29840. check ("mixer: FX strip (no clips) has no activator but an arm", mixer->partBounds (5, Part::activator).isEmpty() && ! mixer->partBounds (5, Part::arm).isEmpty());
  29841. check ("mixer: Main strip has volume and pan, no activator", ! mixer->partBounds (-2, Part::volume).isEmpty() && mixer->partBounds (-2, Part::activator).isEmpty());
  29842. {
  29843. const auto hit = mixer->hitAt (mixer->partBounds (2, Part::solo).getCentre());
  29844. check ("mixer: a click on the Keys' S is its solo", hit.column == 2 && hit.part == Part::solo);
  29845. const auto send = mixer->hitAt (mixer->partBounds (1, Part::send, 1).getCentre());
  29846. check ("mixer: the Bass' second knob is its send to Delay", send.column == 1 && send.part == Part::send && send.row == 1);
  29847. }
  29848. {
  29849. juce::PopupMenu menu;
  29850. mixer->addViewItems (menu);
  29851. saveMenus (juce::StringArray { "Mixer (footer button)" }, std::vector<juce::PopupMenu> { menu }, prefix + "-02-mixer-view-menu.png");
  29852. }
  29853. offline.editSong ([] (lynx::Song& s) { lynx::launcher::ensureGrid (s).mixerView.trackOptions = true; }, false);
  29854. offline.dispatchPendingMessages();
  29855. gridView->resized();
  29856. levels();
  29857. write (*gridView, "03-mixer-track-options");
  29858. offline.editSong ([] (lynx::Song& s) {
  29859. auto& v = lynx::launcher::ensureGrid (s).mixerView;
  29860. v.trackOptions = v.io = v.sends = false;
  29861. }, false);
  29862. offline.dispatchPendingMessages();
  29863. gridView->resized();
  29864. levels();
  29865. write (*gridView, "04-mixer-volume-only");
  29866. offline.editSong ([] (lynx::Song& s) { lynx::launcher::ensureGrid (s).mixerView.shown = false; }, false);
  29867. offline.dispatchPendingMessages();
  29868. gridView->resized();
  29869. write (*gridView, "05-mixer-hidden");
  29870. check ("mixer hidden: the arm buttons are back in the status row", ! mixer->armsShown() && mixer->getHeight() == 0);
  29871. offline.editSong ([] (lynx::Song& s) { lynx::launcher::ensureGrid (s).mixerView = {}; }, false);
  29872. offline.dispatchPendingMessages();
  29873. gridView->resized();
  29874. // the Clip page of the Loop clip (track 4, scene 0) while it plays: Warp on, the Set buttons lit, the title
  29875. detail->showSelection (4, 0);
  29876. detail->setPage (lynx::DetailView::Page::clip);
  29877. offline.editSong ([] (lynx::Song&) {}, false); // (a change message: the Clip panel reads the playing state)
  29878. offline.dispatchPendingMessages();
  29879. write (ui, "06-clip-audio-warp-on");
  29880. // round 190ig (round 190ia CL-20a, the BPM row bug): the Audio box at Live's 190 px, 260 px and 350 px detail
  29881. // heights, in Re-Pitch (no settings rows) and in Beats (three rows: the most a mode shows)
  29882. if (audioChannel >= 0)
  29883. {
  29884. const auto heightBefore = lynx::DetailView::preferredHeight;
  29885. for (const auto beats : { false, true })
  29886. {
  29887. offline.editSong ([audioChannel, beats] (lynx::Song& s) {
  29888. auto& sampler = s.channels[(std::size_t) audioChannel].sampler;
  29889. sampler.keepPitch = beats;
  29890. sampler.stretchMethod = beats ? lynx::StretchMethod::beats : sampler.stretchMethod;
  29891. }, false);
  29892. offline.dispatchPendingMessages();
  29893. for (const auto h : { 190, 260, 350 })
  29894. {
  29895. lynx::DetailView::preferredHeight = h;
  29896. ui.resized();
  29897. if (auto* area = detail->getParentComponent()) // (the Playlist area lays its docked detail view out)
  29898. area->resized();
  29899. offline.dispatchPendingMessages();
  29900. write (ui, (juce::String ("06h-audio-box-") + (beats ? "beats-" : "repitch-") + juce::String (h)).toRawUTF8());
  29901. check ("audio box at " + juce::String (h) + " px: the detail view is that high", detail->getHeight() == h);
  29902. }
  29903. }
  29904. offline.editSong ([audioChannel] (lynx::Song& s) { s.channels[(std::size_t) audioChannel].sampler.keepPitch = false; }, false);
  29905. offline.dispatchPendingMessages();
  29906. lynx::DetailView::preferredHeight = heightBefore;
  29907. ui.resized();
  29908. if (auto* area = detail->getParentComponent())
  29909. area->resized();
  29910. offline.dispatchPendingMessages();
  29911. }
  29912. if (audioChannel >= 0)
  29913. {
  29914. const auto beforeLength = lynx::launcher::clipAt (*offline.getSong().clipGrid, 4, 0)->length;
  29915. offline.editSong ([audioChannel] (lynx::Song& s) { lynx::clipsample::setWarp (s, audioChannel, false, 4.0); });
  29916. offline.dispatchPendingMessages();
  29917. write (ui, "07-clip-audio-warp-off");
  29918. check ("warp off: the channel plays at its own speed", ! lynx::clipsample::isWarped (offline.getSong().channels[(std::size_t) audioChannel].sampler));
  29919. offline.undo();
  29920. offline.dispatchPendingMessages();
  29921. check ("warp: undo gives the clip back as it was", lynx::launcher::clipAt (*offline.getSong().clipGrid, 4, 0)->length == beforeLength
  29922. && lynx::clipsample::isWarped (offline.getSong().channels[(std::size_t) audioChannel].sampler));
  29923. // Set (start) at the play position, half way: one undo step
  29924. const auto clipBefore = *lynx::launcher::clipAt (*offline.getSong().clipGrid, 4, 0);
  29925. offline.editSong ([] (lynx::Song& s) {
  29926. for (auto& c : s.clipGrid->clips)
  29927. if (c.track == 4 && c.gridSlot >= 0 && s.clipGrid->slots[(std::size_t) c.gridSlot].scene == 0)
  29928. lynx::clipsample::setStartAt (c, lynx::clipsample::playPosition (c, 0.5f));
  29929. });
  29930. const auto& after = *lynx::launcher::clipAt (*offline.getSong().clipGrid, 4, 0);
  29931. check ("set start: the clip starts half way and ends where it did", after.offset == clipBefore.offset + clipBefore.length / 2
  29932. && after.offset + after.length == clipBefore.offset + clipBefore.length);
  29933. offline.undo();
  29934. offline.dispatchPendingMessages();
  29935. }
  29936. // a MIDI clip's Clip page too (the Set buttons are there for every clip), playing through a groove of the pool
  29937. offline.editSong ([] (lynx::Song& s) {
  29938. const auto& bank = lynx::groove::factoryBank();
  29939. if (bank.size() > 9)
  29940. lynx::groove::setClipGroove (s, 0, 1, lynx::groove::add (s.grooves, bank[9].groove));
  29941. }, false);
  29942. detail->showSelection (0, 1);
  29943. offline.editSong ([] (lynx::Song&) {}, false);
  29944. offline.dispatchPendingMessages();
  29945. write (ui, "08-clip-midi-set-buttons");
  29946. // the Device View of Bass (insert 2): its compressor dragged onto Keys (insert 3), then Ctrl-dragged onto Vox
  29947. detail->showSelection (1, 0);
  29948. detail->setPage (lynx::DetailView::Page::devices);
  29949. offline.dispatchPendingMessages();
  29950. write (ui, "09-devices-bass-before");
  29951. lynx::setClipGridDeviceDropForSnapshot (*gridView, 2);
  29952. write (ui, "10-device-dragged-over-keys");
  29953. lynx::setClipGridDeviceDropForSnapshot (*gridView, -1);
  29954. int fromId = 0;
  29955. {
  29956. const auto& s = offline.getSong();
  29957. fromId = (int) (s.mixer[2].effects[1].instance.id & 0x7fffffff);
  29958. }
  29959. offline.editSongStructural ([] (lynx::Song& s) { lynx::detailchain::moveEffectToInsert (s, 2, 1, 3, false); });
  29960. offline.dispatchPendingMessages();
  29961. check ("drag to Keys: the compressor moved (same device)", offline.getSong().mixer[2].effects.size() == 2 && offline.getSong().mixer[3].effects.size() == 1
  29962. && (int) (offline.getSong().mixer[3].effects[0].instance.id & 0x7fffffff) == fromId);
  29963. detail->showSelection (2, 1);
  29964. offline.dispatchPendingMessages();
  29965. write (ui, "11-devices-keys-after-move");
  29966. offline.editSongStructural ([] (lynx::Song& s) { lynx::detailchain::moveEffectToInsert (s, 2, 0, 4, true); });
  29967. offline.dispatchPendingMessages();
  29968. check ("Ctrl-drag to Vox: a copy of the EQ after its reverb, Bass keeps its own", offline.getSong().mixer[4].effects.size() == 2
  29969. && offline.getSong().mixer[4].effects[1].kind == lynx::EffectKind::eq
  29970. && offline.getSong().mixer[2].effects[0].kind == lynx::EffectKind::eq);
  29971. offline.undo();
  29972. offline.undo();
  29973. offline.dispatchPendingMessages();
  29974. check ("undo twice: Bass has its three devices again, Keys none", offline.getSong().mixer[2].effects.size() == 3 && offline.getSong().mixer[3].effects.empty()
  29975. && offline.getSong().mixer[4].effects.size() == 1);
  29976. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  29977. wav.deleteFile();
  29978. }
  29979. void runWarpShot (const juce::String& prefix)
  29980. {
  29981. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  29982. lynx::AudioEngine offline (false);
  29983. lynx::MainComponent ui (offline, false);
  29984. ui.setSize (1600, 900);
  29985. const auto write = [&prefix] (juce::Component& c, const char* name) {
  29986. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  29987. file.deleteFile();
  29988. juce::FileOutputStream out (file);
  29989. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (c), out);
  29990. };
  29991. // a two-bar loop of clicks, a little off the grid (what Quantize is for)
  29992. const auto wav = juce::File (prefix + "-loop.wav");
  29993. wav.deleteFile();
  29994. {
  29995. const double rate = 44100.0;
  29996. juce::AudioBuffer<float> buffer (1, (int) (rate * 4.0));
  29997. buffer.clear();
  29998. for (int hit = 0; hit < 8; ++hit)
  29999. {
  30000. const auto at = (int) ((hit * 0.5 + (hit % 3) * 0.035) * rate);
  30001. for (int k = 0; k < 4000 && at + k < buffer.getNumSamples(); ++k)
  30002. buffer.setSample (0, at + k, (float) (std::sin (k * (hit % 2 ? 0.25 : 0.06)) * std::exp (-k / 700.0) * 0.8));
  30003. }
  30004. if (auto out = std::unique_ptr<juce::FileOutputStream> (wav.createOutputStream()))
  30005. if (auto* writer = juce::WavAudioFormat().createWriterFor (out.get(), rate, 1, 16, {}, 0))
  30006. {
  30007. out.release();
  30008. std::unique_ptr<juce::AudioFormatWriter> owned (writer);
  30009. owned->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
  30010. }
  30011. }
  30012. ui.setVisible (true);
  30013. lynx::DetailView::shownSetting = true;
  30014. ui.selectTabForSnapshot (2);
  30015. ui.setLayoutStyle (lynx::layoutstyle::Style::clipLaunch);
  30016. lynx::autolanes::setShown (true);
  30017. ui.getPlaylistForSnapshot().addAudioClipAtPlayhead (wav);
  30018. offline.dispatchPendingMessages();
  30019. int channel = -1;
  30020. offline.editSong ([&channel] (lynx::Song& s) {
  30021. if (s.playlist.empty())
  30022. return;
  30023. auto audio = s.playlist.front();
  30024. channel = audio.channel;
  30025. audio.track = 1;
  30026. s.playlist.front() = audio;
  30027. for (int k = 1; k < 3; ++k)
  30028. {
  30029. auto more = audio;
  30030. more.start = audio.start + k * 8 * lynx::ppq;
  30031. s.playlist.push_back (more);
  30032. }
  30033. while (s.patterns.size() < 1)
  30034. s.patterns.emplace_back();
  30035. for (int t = 2; t < 5; ++t)
  30036. for (int k = 0; k < 4; ++k)
  30037. {
  30038. lynx::Clip c;
  30039. c.pattern = 0;
  30040. c.track = t;
  30041. c.start = k * 4 * lynx::ppq;
  30042. c.length = 4 * lynx::ppq;
  30043. s.playlist.push_back (c);
  30044. }
  30045. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 6));
  30046. s.playlistTracks[1].name = "Loop";
  30047. s.playlistTracks[2].name = "Drums";
  30048. s.playlistTracks[3].name = "Kick";
  30049. s.playlistTracks[4].name = "Hats";
  30050. s.playlistTracks[4].folded = true;
  30051. lynx::noteedit::groupWithAbove (s, 3);
  30052. lynx::noteedit::groupWithAbove (s, 4);
  30053. lynx::arrange::makeGroupBus (s, 3);
  30054. lynx::autolanes::addLane (s, 1, { lynx::AutomationTargetKind::tempo, 0, 0, 0 }, "Tempo", lynx::valueFromTempo (s.bpm));
  30055. if (! s.automations.empty())
  30056. s.automations.back().points = { { 0, lynx::valueFromTempo (120.0), 0.0f }, { 8 * lynx::ppq, lynx::valueFromTempo (120.0), 0.0f },
  30057. { 12 * lynx::ppq, lynx::valueFromTempo (180.0), 0.0f }, { 16 * lynx::ppq, lynx::valueFromTempo (140.0), 0.0f } };
  30058. s.addMarker ({ 4 * lynx::ppq, "Verse", 0, 0 });
  30059. s.addMarker ({ 8 * lynx::ppq, {}, 3, 4 });
  30060. s.addMarker ({ 14 * lynx::ppq, {}, 4, 4 });
  30061. s.loopStart = 4 * lynx::ppq;
  30062. s.loopEnd = 12 * lynx::ppq;
  30063. s.loopOff = true;
  30064. s.tempoViewLow = 60.0; // the tempo lane's range
  30065. s.tempoViewHigh = 200.0;
  30066. std::stable_sort (s.playlist.begin(), s.playlist.end(), [] (const lynx::Clip& a, const lynx::Clip& b) { return a.start < b.start; });
  30067. // the same audio in the clip grid, for the Clip page
  30068. lynx::Clip slot = audio;
  30069. slot.start = 0;
  30070. slot.pitch = -2.25f;
  30071. slot.gain = 0.7f;
  30072. lynx::launcher::setClip (s, 1, 0, slot);
  30073. // a few warp markers, as Quantize leaves them
  30074. if (channel >= 0 && channel < (int) s.channels.size())
  30075. {
  30076. auto& sampler = s.channels[(std::size_t) channel].sampler;
  30077. lynx::warpedit::ensureMarkers (sampler, 4.0, s.bpm);
  30078. std::vector<double> attacks;
  30079. for (int hit = 1; hit < 8; ++hit)
  30080. attacks.push_back (hit * 0.5 + (hit % 3) * 0.035);
  30081. lynx::warptools::quantize (sampler, attacks, 0.0, 4.0, 0.5, 1.0);
  30082. lynx::warpedit::syncLength (sampler, 4.0);
  30083. }
  30084. }, false);
  30085. offline.dispatchPendingMessages();
  30086. ui.resized();
  30087. write (ui, "arrangement-loop-off");
  30088. offline.editSong ([] (lynx::Song& s) { s.loopOff = false; }, false);
  30089. offline.dispatchPendingMessages();
  30090. write (ui, "arrangement-loop-on");
  30091. juce::String facts;
  30092. {
  30093. const auto& s = offline.getSong();
  30094. facts << "channel " << channel << ", warp markers " << (channel >= 0 ? (int) s.channels[(std::size_t) channel].sampler.warp.size() : -1)
  30095. << ", group bus insert " << lynx::arrange::groupBus (s, 3) << ", folded track 4: " << (lynx::arrange::isFolded (s, 4) ? 1 : 0) << "\n";
  30096. }
  30097. if (auto* detail = ui.getDetailViewForSnapshot())
  30098. {
  30099. detail->showSelection (1, 0);
  30100. detail->setPage (lynx::DetailView::Page::clip);
  30101. offline.dispatchPendingMessages();
  30102. write (ui, "clip-audio");
  30103. }
  30104. if (channel >= 0)
  30105. if (auto editor = lynx::makeAudioEditorPanel (offline, channel, 0, true))
  30106. {
  30107. editor->setSize (1120, 600);
  30108. write (*editor, "audio-editor-warp");
  30109. // round 190cy (Live 12.4.16 live check 190cw shot 09): a plain drag of marker 3 holds it two sixteenths
  30110. // later (its audio goes there); Shift + drag slides the audio under it. Round 190db: the Clip-launch
  30111. // workflow draws the warped clip in beats, so the held drag shows the audio stretched around the marker
  30112. // (plain) or slid under it, its attack later (Shift, to the right as in Live's shot)
  30113. const auto& w = offline.getSong().channels[(std::size_t) channel].sampler.warp;
  30114. if (w.size() > 4)
  30115. {
  30116. lynx::holdAudioEditorWarpDragForSnapshot (*editor, 3, w[3].beats + 0.5, false);
  30117. write (*editor, "audio-editor-drag-stretch");
  30118. lynx::holdAudioEditorWarpDragForSnapshot (*editor, 3, w[3].seconds - 0.12, true);
  30119. write (*editor, "audio-editor-drag-slide");
  30120. }
  30121. // the same clip in file time (the Pattern workflow's view, or "Show the audio in beats" off)
  30122. if (auto inFileTime = lynx::makeAudioEditorPanel (offline, channel, 0, true))
  30123. {
  30124. inFileTime->setSize (1120, 600);
  30125. lynx::setAudioEditorBeatTimeForSnapshot (*inFileTime, 0);
  30126. write (*inFileTime, "audio-editor-file-time");
  30127. if (w.size() > 4)
  30128. {
  30129. lynx::holdAudioEditorWarpDragForSnapshot (*inFileTime, 3, w[3].beats + 0.5, false);
  30130. write (*inFileTime, "audio-editor-file-time-drag");
  30131. }
  30132. }
  30133. }
  30134. // round 190cy (Live 12.4.16 live check 190cw shot 02): ÷2 from the editor of the first Playlist clip halves that
  30135. // clip's length with the markers' beats; ÷2 on the grid clip's Clip page halves the grid clip
  30136. {
  30137. const auto lengthOf = [&offline] (int index) { return index < (int) offline.getSong().playlist.size() ? offline.getSong().playlist[(std::size_t) index].length : -1; };
  30138. const auto gridLength = [&offline] {
  30139. const auto& s = offline.getSong();
  30140. const auto* c = s.clipGrid ? lynx::launcher::clipAt (*s.clipGrid, 1, 0) : nullptr;
  30141. return c != nullptr ? c->length : (std::int64_t) -1;
  30142. };
  30143. const auto first = [&offline] {
  30144. const auto& s = offline.getSong();
  30145. for (int i = 0; i < (int) s.playlist.size(); ++i)
  30146. if (s.playlist[(std::size_t) i].kind == lynx::ClipKind::audio)
  30147. return i;
  30148. return -1;
  30149. }();
  30150. facts << "halve: playlist clip " << first << " length " << lengthOf (first);
  30151. if (first >= 0)
  30152. if (auto editor = lynx::makeAudioEditorPanel (offline, offline.getSong().playlist[(std::size_t) first].channel, first, true))
  30153. {
  30154. lynx::scaleAudioEditorTempoForSnapshot (*editor, 0.5);
  30155. offline.dispatchPendingMessages();
  30156. }
  30157. facts << " -> " << lengthOf (first) << "; grid clip length " << gridLength();
  30158. if (channel >= 0)
  30159. if (auto editor = lynx::makeAudioEditorPanel (offline, channel, -1, true))
  30160. {
  30161. lynx::setAudioEditorGridClip (*editor, 1, 0);
  30162. lynx::scaleAudioEditorTempoForSnapshot (*editor, 0.5);
  30163. offline.dispatchPendingMessages();
  30164. }
  30165. facts << " -> " << gridLength() << "\n";
  30166. ui.resized();
  30167. write (ui, "arrangement-halved");
  30168. // Duplicate Time over beats 4-8 holding the locator "Verse" (beat 4): a second "Verse" at beat 8
  30169. offline.editSong ([] (lynx::Song& s) { lynx::arrange::duplicateTime (s, 4 * lynx::ppq, 8 * lynx::ppq); });
  30170. offline.dispatchPendingMessages();
  30171. int verses = 0;
  30172. for (const auto& m : offline.getSong().markers())
  30173. verses += m.name == "Verse" ? 1 : 0;
  30174. facts << "duplicate time: locators named Verse " << verses << "\n";
  30175. write (ui, "arrangement-duplicated-time");
  30176. }
  30177. juce::File (prefix + "-facts.txt").replaceWithText (facts);
  30178. lynx::autolanes::setShown (false);
  30179. }
  30180. void runMtShot190fm (const juce::String& prefix)
  30181. {
  30182. lynx::AudioEngine offline (false);
  30183. offline.editSong ([] (lynx::Song& s) {
  30184. if (s.patterns.empty())
  30185. s.patterns.emplace_back();
  30186. s.patterns[0].notes.clear();
  30187. s.patterns[0].lengthTicks = 4 * lynx::ppq;
  30188. s.currentPattern = 0;
  30189. }, false);
  30190. lynx::MidiToolsPanel panel (offline, [] {
  30191. lynx::MidiToolsPanel::Target t;
  30192. t.pattern = 0;
  30193. t.grid = lynx::ppq / 4;
  30194. t.channel = 0;
  30195. t.length = 4 * lynx::ppq; // one bar, no time selection
  30196. return t;
  30197. });
  30198. panel.setSize (lynx::MidiToolsPanel::panelWidth, lynx::MidiToolsPanel::panelHeight);
  30199. panel.setSection (lynx::MidiToolsPanel::generateSection);
  30200. panel.setGenerateShotSettingsForSnapshot();
  30201. const auto write = [&prefix] (const juce::Image& image, const juce::String& name) {
  30202. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  30203. file.deleteFile();
  30204. juce::FileOutputStream out (file);
  30205. juce::PNGImageFormat().writeImageToStream (image, out);
  30206. };
  30207. std::vector<juce::Image> images;
  30208. juce::String checks;
  30209. for (int g = 0; g < lynx::midigen::Settings::toolCount; ++g)
  30210. {
  30211. panel.setGenerator (g);
  30212. const auto name = juce::String (lynx::midigen::toolName (g)).toLowerCase();
  30213. images.push_back (lynx::shot::paint (panel, lynx::theme::colour::bg2));
  30214. write (images.back(), "generate-" + name);
  30215. panel.generateNow();
  30216. offline.dispatchPendingMessages();
  30217. const auto made = (int) offline.getSong().patterns[0].notes.size();
  30218. offline.undo();
  30219. offline.dispatchPendingMessages();
  30220. const auto after = (int) offline.getSong().patterns[0].notes.size();
  30221. checks << name << ": generated " << made << " notes, after undo " << after << (made > 0 && after == 0 ? " OK" : " FAIL") << "\n";
  30222. }
  30223. // the five side by side (6 px apart, on the window's background)
  30224. const auto gap = juce::roundToInt (6.0f * lynx::shot::scale());
  30225. int width = gap, height = 0;
  30226. for (const auto& image : images)
  30227. {
  30228. width += image.getWidth() + gap;
  30229. height = std::max (height, image.getHeight());
  30230. }
  30231. juce::Image strip (juce::Image::RGB, width, height + 2 * gap, true);
  30232. {
  30233. juce::Graphics g (strip);
  30234. g.fillAll (lynx::theme::colour::bg0);
  30235. int x = gap;
  30236. for (const auto& image : images)
  30237. {
  30238. g.drawImageAt (image, x, gap);
  30239. x += image.getWidth() + gap;
  30240. }
  30241. }
  30242. write (strip, "generate-panels");
  30243. checks << "settings saved with the project: " << (offline.getSong().midiGenerate.stacksOptions.sequence.size() == 2 ? "OK" : "FAIL") << "\n";
  30244. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  30245. }
  30246. // Round 190hy: see --mpeshot190hy
  30247. void runMpeShot190hy (const juce::String& prefix)
  30248. {
  30249. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  30250. lynx::AudioEngine offline (false);
  30251. lynx::MainComponent ui (offline, false);
  30252. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  30253. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  30254. const auto write = [&prefix, &ui] (const char* name) {
  30255. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  30256. file.deleteFile();
  30257. juce::FileOutputStream out (file);
  30258. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (ui), out);
  30259. };
  30260. ui.setVisible (true); // (not on the desktop: only so the Clip page sees itself shown and docks the Piano roll)
  30261. offline.editSong ([] (lynx::Song& s) {
  30262. if (s.channels.empty())
  30263. s.channels.resize (1);
  30264. s.channels[0].name = "MPE lead";
  30265. s.channels[0].mixerTrack = 1;
  30266. if (s.mixer.size() < 2)
  30267. s.mixer.resize (2);
  30268. while (s.patterns.empty())
  30269. s.patterns.emplace_back();
  30270. auto& p = s.patterns[0];
  30271. p.name = "MPE take";
  30272. p.notes.clear();
  30273. // four notes as an MPE controller plays them: a slide up an octave, a vibrato, a fall, a held chord tone
  30274. const auto note = [&p] (std::int64_t start, std::int64_t length, int key, lynx::NoteCurves c, float modX = 0.5f) {
  30275. lynx::Note n;
  30276. n.channel = 0;
  30277. n.start = start;
  30278. n.length = length;
  30279. n.key = key;
  30280. n.modX = modX;
  30281. n.curves = std::move (c);
  30282. p.notes.push_back (n);
  30283. };
  30284. const auto beat = (float) lynx::ppq;
  30285. lynx::NoteCurves glide;
  30286. glide.lane (lynx::NoteCurveLane::pitch) = { { 0.0f, 0.0f }, { beat * 0.5f, 0.0f }, { beat * 1.5f, 1200.0f }, { beat * 2.0f, 1200.0f } };
  30287. glide.lane (lynx::NoteCurveLane::timbre) = { { 0.0f, 0.3f }, { beat * 2.0f, 0.85f } };
  30288. glide.lane (lynx::NoteCurveLane::pressure) = { { 0.0f, 0.2f }, { beat * 0.4f, 0.9f }, { beat * 1.6f, 0.7f }, { beat * 2.0f, 0.0f } };
  30289. note (0, 2 * lynx::ppq, 60, glide, 0.3f);
  30290. lynx::NoteCurves vibrato;
  30291. for (int k = 0; k <= 24; ++k)
  30292. vibrato.lane (lynx::NoteCurveLane::pitch).push_back ({ beat * 0.0833f * (float) k, k < 4 ? 0.0f : 40.0f * std::sin ((float) k * 1.5708f) });
  30293. vibrato.lane (lynx::NoteCurveLane::pressure) = { { 0.0f, 0.5f }, { beat * 1.0f, 0.95f }, { beat * 2.0f, 0.4f } };
  30294. note (2 * lynx::ppq, 2 * lynx::ppq, 67, vibrato);
  30295. lynx::NoteCurves fall;
  30296. fall.lane (lynx::NoteCurveLane::pitch) = { { 0.0f, 0.0f }, { beat * 0.75f, 0.0f }, { beat * 1.0f, -500.0f } };
  30297. fall.lane (lynx::NoteCurveLane::timbre) = { { 0.0f, 0.6f }, { beat * 1.0f, 0.2f } };
  30298. note (4 * lynx::ppq, lynx::ppq, 72, fall, 0.6f);
  30299. note (5 * lynx::ppq, 3 * lynx::ppq, 64, {}); // (a note without curves: its own values, dashed)
  30300. p.lengthTicks = 8 * lynx::ppq;
  30301. }, false);
  30302. offline.dispatchPendingMessages();
  30303. juce::String checks;
  30304. auto& roll = ui.getPianoRollForSnapshot();
  30305. ui.selectTabForSnapshot (1);
  30306. roll.selectMidiToolResult ({ 0 });
  30307. roll.scrollToNotes();
  30308. for (const auto& [lane, name] : { std::pair { lynx::PianoRollComponent::laneMpePitch, "pitch" },
  30309. { lynx::PianoRollComponent::laneMpeSlide, "slide" },
  30310. { lynx::PianoRollComponent::laneMpePressure, "pressure" } })
  30311. {
  30312. roll.setLaneForSnapshot (lane);
  30313. offline.dispatchPendingMessages();
  30314. write (name);
  30315. checks << "lane " << name << ": areas " << (int) roll.mpeLaneAreasForTests().size() << "\n";
  30316. }
  30317. roll.setLaneForSnapshot (lynx::PianoRollComponent::laneVelocity);
  30318. int curved = 0;
  30319. for (const auto& n : offline.getSong().patterns[0].notes)
  30320. curved += n.curves.has() ? 1 : 0;
  30321. checks << "notes with curves: " << curved << " of " << (int) offline.getSong().patterns[0].notes.size() << "\n";
  30322. // the Clip-launch layout: the clip's Notes tab, then its MPE tab (Live 11+'s note expression lanes)
  30323. ui.selectTabForSnapshot (2);
  30324. lynx::DetailView::shownSetting = true;
  30325. lynx::DetailView::devicesPage = false;
  30326. ui.setClipLaunchWorkflow (true);
  30327. offline.editSong ([] (lynx::Song& s) {
  30328. lynx::Clip clip;
  30329. clip.pattern = 0;
  30330. clip.length = 8 * lynx::ppq;
  30331. lynx::launcher::setClip (s, 0, 0, clip);
  30332. }, false);
  30333. offline.dispatchPendingMessages();
  30334. if (auto* detail = ui.getDetailViewForSnapshot())
  30335. {
  30336. detail->showSelection (0, 0);
  30337. detail->setPage (lynx::DetailView::Page::clip);
  30338. detail->setClipTab (false);
  30339. offline.dispatchPendingMessages();
  30340. roll.scrollToNotes();
  30341. write ("clip-notes");
  30342. checks << "clip notes tab: mpe view " << (roll.isMpeView() ? 1 : 0) << "\n";
  30343. detail->setMpeTab();
  30344. offline.dispatchPendingMessages();
  30345. roll.selectMidiToolResult ({ 0 });
  30346. roll.scrollToNotes();
  30347. write ("clip-mpe");
  30348. checks << "clip MPE tab: mpe view " << (roll.isMpeView() ? 1 : 0) << ", lanes " << (int) roll.mpeLaneAreasForTests().size() << "\n";
  30349. // round 190jd (Live 12.4's MPE tab): the value ghost point on note 1's Pressure line, the "Show Lane:" menu,
  30350. // then all four lanes shown (Slide, Pressure, Velocity, Release Velocity)
  30351. checks << "ghost on the Pressure line: '" << roll.hoverMpeLineForSnapshot (lynx::PianoRollComponent::laneMpePressure, (double) lynx::ppq) << "'\n";
  30352. write ("clip-mpe-ghost190jd");
  30353. roll.hoverMpeLineForSnapshot (0, 0.0);
  30354. saveMenus (juce::StringArray { "MPE tab: Show Lane" }, std::vector<juce::PopupMenu> { roll.getMpeLaneMenuForSnapshot() },
  30355. prefix + "-clip-mpe-showlane190jd.png");
  30356. roll.setMpeLanesForSnapshot (lynx::mpetab::allLanes);
  30357. offline.dispatchPendingMessages();
  30358. write ("clip-mpe-lanes4-190jd");
  30359. checks << "four lanes: " << (int) roll.mpeLaneAreasForTests().size() << "\n";
  30360. roll.setMpeLanesForSnapshot (lynx::mpetab::defaultLanes);
  30361. detail->setClipTab (false);
  30362. offline.dispatchPendingMessages();
  30363. checks << "back to Notes: mpe view " << (roll.isMpeView() ? 1 : 0) << "\n";
  30364. }
  30365. else
  30366. checks << "no detail view\n";
  30367. lynx::shot::file (juce::File (prefix + "-checks.txt")).replaceWithText (checks);
  30368. }
  30369. // round 190kk: Live's Erosion / Vinyl Distortion / Corpus imported, their LYNX engines on the Device View
  30370. void runLiveDevShot190kk (const juce::String& prefix)
  30371. {
  30372. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  30373. lynx::AudioEngine offline (false);
  30374. lynx::MainComponent ui (offline, false);
  30375. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  30376. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  30377. const auto par = [] (const char* name, double v) { return juce::String ("<") + name + "><Manual Value=\"" + juce::String (v) + "\" /></" + name + ">"; };
  30378. // the Core Library presets' values (Erosion "Fizzle", Vinyl Distortion "Crack" with Tracing on, Corpus "Pipe Resonator" closed)
  30379. const juce::String erosion = "<Erosion2 Id=\"1\"><On><Manual Value=\"true\" /></On>" + par ("Amount", 0.9) + par ("Frequency", 16000) +
  30380. par ("FilterWidth", 1.734) + par ("NoiseBlend", 1) + par ("StereoWidth", 1) + "</Erosion2>";
  30381. const juce::String vinyl = "<Vinyl Id=\"1\"><On><Manual Value=\"true\" /></On><Band1On><Manual Value=\"true\" /></Band1On>" + par ("Gain1", 0.5) +
  30382. par ("BandFreq1", 7500) + par ("BandQ1", 3) + "<Band2On><Manual Value=\"false\" /></Band2On>" + par ("Gain2", 0.35) +
  30383. par ("BandFreq2", 5366) + par ("BandQ2", 0.32) + par ("Drive", 1) + par ("SoftHard", 0) + par ("NormalMono", 0) +
  30384. par ("CracleDensity", 50) + par ("CracleVolume", 1) + "</Vinyl>";
  30385. juce::String corpus = "<Corpus Id=\"1\"><On><Manual Value=\"true\" /></On><FilterOn><Manual Value=\"false\" /></FilterOn>";
  30386. for (const auto& [k, v] : std::initializer_list<std::pair<const char*, double>> { { "ResonanceType", 5 }, { "ResonatorQuality", 3 },
  30387. { "Frequency", 0.4603 }, { "Decay", 0.6032 }, { "FreqDamping", 0 }, { "AmpFreq", 0 }, { "Inharmonics", 0 }, { "Radius", 0.8642 },
  30388. { "TubeOpening", 1 }, { "Ratio", 0.5 }, { "ExcitationX", 0.5 }, { "ListeningXL", 0.1 }, { "ListeningXR", 0.9 }, { "Detune", 0.047 },
  30389. { "Drive", 0.405 }, { "Bleed", 0 }, { "DryWet", 0.696 }, { "StereoWidth", 1 }, { "FilterMidFreq", 1000 }, { "FilterBandWidth", 4 } })
  30390. corpus += par (k, v);
  30391. corpus += "</Corpus>";
  30392. std::vector<lynx::EffectSlot> slots;
  30393. juce::String checks;
  30394. for (const auto& text : { erosion, vinyl, corpus })
  30395. {
  30396. lynx::xml::Document doc;
  30397. doc.parse (text.toStdString());
  30398. if (const auto t = lynx::alsdev::effectFromLiveDevice (doc.root()))
  30399. {
  30400. slots.push_back (t->slot);
  30401. checks << t->from << " -> " << t->to << "\n";
  30402. }
  30403. else
  30404. checks << "NOT TRANSLATED\n";
  30405. }
  30406. offline.editSong ([&slots] (lynx::Song& s) {
  30407. if (s.channels.empty())
  30408. s.channels.resize (1);
  30409. s.channels[0].name = "Drums";
  30410. s.channels[0].mixerTrack = 2;
  30411. if (s.mixer.size() < 3)
  30412. s.mixer.resize (3);
  30413. s.mixer[2].name = "Drums";
  30414. s.mixer[2].effects = slots;
  30415. while (s.patterns.empty())
  30416. s.patterns.emplace_back();
  30417. s.patterns[0].name = "Beat";
  30418. s.patterns[0].notes.clear();
  30419. for (int n = 0; n < 4; ++n)
  30420. {
  30421. lynx::Note note;
  30422. note.channel = 0;
  30423. note.start = n * lynx::ppq;
  30424. note.key = 36;
  30425. s.patterns[0].notes.push_back (note);
  30426. }
  30427. s.patterns[0].lengthTicks = 4 * lynx::ppq;
  30428. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 2));
  30429. s.playlistTracks[1].name = "Drums";
  30430. }, false);
  30431. offline.dispatchPendingMessages();
  30432. ui.setVisible (true);
  30433. lynx::DetailView::shownSetting = lynx::DetailView::devicesPage = true;
  30434. ui.selectTabForSnapshot (2);
  30435. ui.setClipLaunchWorkflow (true);
  30436. offline.editSong ([] (lynx::Song& s) {
  30437. lynx::Clip clip;
  30438. clip.pattern = 0;
  30439. clip.length = 4 * lynx::ppq;
  30440. lynx::launcher::setClip (s, 1, 0, clip);
  30441. }, false);
  30442. offline.dispatchPendingMessages();
  30443. if (auto* detail = ui.getDetailViewForSnapshot())
  30444. {
  30445. detail->showSelection (1, 0);
  30446. detail->setPage (lynx::DetailView::Page::devices);
  30447. const auto file = lynx::shot::file (juce::File (prefix + "-devices.png"));
  30448. file.deleteFile();
  30449. juce::FileOutputStream out (file);
  30450. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (ui), out);
  30451. checks << "cards " << detail->cardCountForCheck() << ", insert " << detail->chainInsertForCheck() << "\n";
  30452. }
  30453. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  30454. }
  30455. void runDetailShot (const juce::String& prefix)
  30456. {
  30457. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  30458. lynx::AudioEngine offline (false);
  30459. lynx::MainComponent ui (offline, false);
  30460. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  30461. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  30462. const auto write = [&prefix, &ui] (const char* name) {
  30463. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  30464. file.deleteFile();
  30465. juce::FileOutputStream out (file);
  30466. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (ui), out);
  30467. };
  30468. ui.setVisible (true); // (not on the desktop: only so the Clip page sees itself shown and docks the Piano roll)
  30469. lynx::DetailView::shownSetting = lynx::DetailView::devicesPage = true;
  30470. ui.selectTabForSnapshot (2); // the Playlist panel, maximized
  30471. offline.editSong ([] (lynx::Song& s) {
  30472. if (s.channels.size() < 2)
  30473. s.channels.resize (2);
  30474. s.channels[0].name = "Bass synth";
  30475. s.channels[0].mixerTrack = 2;
  30476. s.channels[1].mixerTrack = 3;
  30477. if (s.mixer.size() < 4)
  30478. s.mixer.resize (4);
  30479. s.mixer[2].name = "Bass";
  30480. s.mixer[2].effects.clear();
  30481. for (auto kind : { lynx::EffectKind::eq, lynx::EffectKind::compressor, lynx::EffectKind::reverb, lynx::EffectKind::delay })
  30482. {
  30483. lynx::EffectSlot fx;
  30484. fx.kind = kind;
  30485. const auto& info = lynx::effectInfo (kind);
  30486. for (std::size_t k = 0; k < info.params.size() && k < fx.params.size(); ++k)
  30487. fx.params[k] = info.params[k].defaultValue;
  30488. fx.enabled = kind != lynx::EffectKind::compressor; // one switched off
  30489. s.mixer[2].effects.push_back (fx);
  30490. }
  30491. while (s.patterns.size() < 2)
  30492. s.patterns.emplace_back();
  30493. s.patterns[0].name = "Bass line";
  30494. s.patterns[0].notes.clear();
  30495. for (int n = 0; n < 4; ++n)
  30496. {
  30497. lynx::Note note;
  30498. note.channel = 0;
  30499. note.start = n * lynx::ppq;
  30500. note.key = 36 + (n % 2) * 7;
  30501. s.patterns[0].notes.push_back (note);
  30502. }
  30503. s.patterns[0].lengthTicks = 4 * lynx::ppq;
  30504. lynx::PatternEvents lane; // a volume swell for the Envelopes tab (slice 3)
  30505. lane.target = lynx::AutomationTarget { lynx::AutomationTargetKind::channelVolume, 0 };
  30506. for (int e = 0; e < 16; ++e)
  30507. lane.events.push_back ({ e * lynx::ppq / 4, 0.3f + 0.6f * (float) e / 15.0f });
  30508. s.patterns[0].events = { lane };
  30509. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 3));
  30510. s.playlistTracks[1].name = "Bass";
  30511. }, false);
  30512. offline.dispatchPendingMessages();
  30513. write ("pattern"); // Pattern workflow: no detail view exists
  30514. ui.setClipLaunchWorkflow (true);
  30515. offline.editSong ([] (lynx::Song& s) {
  30516. lynx::Clip clip;
  30517. clip.pattern = 0;
  30518. clip.length = 4 * lynx::ppq;
  30519. lynx::launcher::setClip (s, 1, 0, clip);
  30520. }, false);
  30521. offline.dispatchPendingMessages();
  30522. juce::String counts;
  30523. if (auto* detail = ui.getDetailViewForSnapshot())
  30524. {
  30525. detail->showSelection (1, 0);
  30526. detail->setPage (lynx::DetailView::Page::devices);
  30527. write ("devices");
  30528. counts << "cards " << detail->cardCountForCheck() << ", insert " << detail->chainInsertForCheck() << ", channel " << detail->chainChannelForCheck() << "\n";
  30529. detail->toggleFoldForCheck (3); // the reverb (card 0 is the instrument)
  30530. write ("folded");
  30531. counts << "folded card 3: " << (detail->isFoldedForCheck (3) ? 1 : 0) << "\n";
  30532. detail->showSelection (2, 0); // an empty track
  30533. write ("empty-track");
  30534. detail->showSelection (1, 0);
  30535. detail->setPage (lynx::DetailView::Page::clip);
  30536. offline.dispatchPendingMessages();
  30537. ui.getPianoRollForSnapshot().scrollToNotes(); // (the app does it on the message loop, which this shot doesn't run)
  30538. write ("clip"); // slice 2: the Piano roll docked here
  30539. {
  30540. // round 190s: the Transform panel with each MIDI tool, then Arpeggiate applied (and undone again)
  30541. auto& tools = detail->midiToolsForSnapshot();
  30542. for (int t = 0; t < lynx::MidiToolsPanel::toolCount; ++t)
  30543. {
  30544. tools.setTool (t);
  30545. write (("clip-mt-" + juce::String (lynx::MidiToolsPanel::toolName (t)).toLowerCase()).toRawUTF8());
  30546. }
  30547. // round 190aa: the pages again with the settings of the Live shots they are compared with
  30548. tools.setAuto (false);
  30549. tools.setLiveShotSettingsForSnapshot();
  30550. for (int t : { (int) lynx::MidiToolsPanel::chop, (int) lynx::MidiToolsPanel::quantize, (int) lynx::MidiToolsPanel::timeWarp })
  30551. {
  30552. tools.setTool (t);
  30553. write (("clip-mt-" + juce::String (lynx::MidiToolsPanel::toolName (t)).toLowerCase() + "-set").toRawUTF8());
  30554. }
  30555. tools.setAuto (true);
  30556. tools.setTool (lynx::MidiToolsPanel::arpeggiate);
  30557. tools.transformNow();
  30558. offline.dispatchPendingMessages();
  30559. write ("clip-mt-applied");
  30560. counts << "midi tools: arpeggiate made " << (int) offline.getSong().patterns[0].notes.size() << " notes of 4\n";
  30561. offline.undo();
  30562. offline.dispatchPendingMessages();
  30563. counts << "midi tools: undo gives " << (int) offline.getSong().patterns[0].notes.size() << " notes\n";
  30564. }
  30565. counts << "piano roll docked: " << (ui.getPianoRollForSnapshot().getParentComponent() != nullptr
  30566. && ui.getPianoRollForSnapshot().getParentComponent()->getParentComponent() == detail ? 1 : 0) << "\n";
  30567. detail->setClipTab (true); // slice 3: the pattern's events in the Envelopes tab
  30568. offline.dispatchPendingMessages();
  30569. write ("envelopes");
  30570. detail->setClipTab (false);
  30571. detail->setPage (lynx::DetailView::Page::devices);
  30572. // round 183c-card: an Audio Effect Rack in the chain draws as its own card (the rack's view, Rand / Map in its
  30573. // title bar), as Live's Device View shows a rack
  30574. offline.editSong ([] (lynx::Song& s) { s.mixer[2].effects.insert (s.mixer[2].effects.begin() + 1, shotRack()); }, false);
  30575. offline.dispatchPendingMessages();
  30576. detail->showSelection (2, 0);
  30577. detail->showSelection (1, 0);
  30578. write ("devices-rack");
  30579. counts << "rack card: cards " << detail->cardCountForCheck() << "\n";
  30580. offline.editSong ([] (lynx::Song& s) { s.mixer[2].effects.erase (s.mixer[2].effects.begin() + 1); }, false);
  30581. offline.dispatchPendingMessages();
  30582. counts << "piano roll back in its panel: " << (ui.getPianoRollForSnapshot().getParentComponent() != nullptr
  30583. && ui.getPianoRollForSnapshot().getParentComponent()->getParentComponent() != detail ? 1 : 0) << "\n";
  30584. }
  30585. else
  30586. counts << "no detail view\n";
  30587. ui.setClipLaunchWorkflow (false);
  30588. offline.dispatchPendingMessages();
  30589. write ("pattern-after");
  30590. juce::File (prefix + "-counts.txt").replaceWithText (counts);
  30591. }
  30592. void runPerfShot (const juce::String& prefix, const juce::String& projectPath)
  30593. {
  30594. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  30595. lynx::AudioEngine offline (false);
  30596. {
  30597. lynx::MainComponent ui (offline, false);
  30598. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  30599. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  30600. if (projectPath.isNotEmpty())
  30601. ui.openFile (juce::File (projectPath));
  30602. offline.dispatchPendingMessages();
  30603. // LYNX_PERFSHOT_PREPARE=1: Tools › Macros › Prepare for performance mode first (16 one-bar columns)
  30604. if (juce::SystemStats::getEnvironmentVariable ("LYNX_PERFSHOT_PREPARE", {}) == "1")
  30605. offline.editSong ([] (lynx::Song& s) { lynx::perf::prepareForPerformance (s, 16, 4 * lynx::ppq); }, false);
  30606. offline.editSong ([] (lynx::Song& s) { s.performanceMode = true; s.mode = lynx::PlayMode::song; }, false);
  30607. offline.dispatchPendingMessages();
  30608. // what the Player would publish: on each of the first tracks with zone clips, one clip playing (part way)
  30609. // and on every other one the next clip waiting for its sync point
  30610. const auto& song = offline.getSong();
  30611. auto& live = offline.performanceStateForSnapshot();
  30612. const auto zone = lynx::perf::zoneClips (song);
  30613. int lastTrack = -1, launched = 0;
  30614. for (const auto index : zone)
  30615. {
  30616. const auto& c = song.playlist[(std::size_t) index];
  30617. if (c.track == lastTrack || c.track >= lynx::perf::maxTracks)
  30618. continue;
  30619. lastTrack = c.track;
  30620. std::int64_t clips[64];
  30621. const auto n = lynx::perf::trackZoneClips (song, zone, c.track, clips, 64);
  30622. auto& view = live.tracks[(std::size_t) c.track];
  30623. view.playing.store (clips[(std::size_t) ((launched % 3) % n)]);
  30624. view.progress.store (0.2f + 0.15f * (float) (launched % 5));
  30625. if (launched % 2 == 1 && n > 1)
  30626. view.pending.store (clips[(std::size_t) ((launched % 3 + 1) % n)]);
  30627. ++launched;
  30628. }
  30629. live.anyPlaying.store (launched > 0);
  30630. ui.selectTabForSnapshot (2);
  30631. offline.dispatchPendingMessages();
  30632. auto& playlist = ui.getPlaylistForSnapshot();
  30633. savePng (lynx::shot::snapshot (playlist), prefix + "-playlist-song.png");
  30634. playlist.runAction ("playlist.zoomPerformance"); // as FL opens these demos: the zone fills the view
  30635. offline.dispatchPendingMessages();
  30636. saveSnapshot (ui, prefix + "-playlist.png");
  30637. savePng (lynx::shot::snapshot (playlist), prefix + "-playlist-only.png");
  30638. // patcherize: the first insert with effects (all of them) and the first channel that can be
  30639. auto patched = offline.getSong();
  30640. for (int t = 0; t < (int) patched.mixer.size(); ++t)
  30641. if (lynx::patcherize::slotsForAll (patched, t).size() > 1)
  30642. {
  30643. lynx::patcherize::patcherizeSlots (patched, t, 0, true);
  30644. break;
  30645. }
  30646. for (int c = 0; c < (int) patched.channels.size(); ++c)
  30647. if (lynx::patcherize::patcherizeChannel (patched, c))
  30648. break;
  30649. juce::String error;
  30650. lynx::ProjectFile::save (patched, juce::File (prefix + "-patcherized.lynx"), error);
  30651. }
  30652. }
  30653. void runPatcherShot (const juce::String& prefix, const juce::String& projectPath)
  30654. {
  30655. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  30656. lynx::AudioEngine offline (false);
  30657. {
  30658. lynx::MainComponent ui (offline, false);
  30659. ui.setSize (1280, 720);
  30660. if (projectPath.isNotEmpty())
  30661. ui.openFile (juce::File (projectPath));
  30662. else
  30663. {
  30664. auto song = lynx::Song::makeDefault();
  30665. song.mixer.resize (4);
  30666. auto slot = lynx::makeEffectSlot (lynx::EffectKind::patcher);
  30667. slot.patcher.wires.clear();
  30668. for (auto [kind, x, y] : { std::tuple { lynx::EffectKind::frequencySplitter, 200.0f, 60.0f }, { lynx::EffectKind::reverb, 420.0f, 0.0f },
  30669. { lynx::EffectKind::fruityDelay3, 420.0f, 120.0f }, { lynx::EffectKind::peakController, 200.0f, 260.0f } })
  30670. {
  30671. lynx::PatchNode n;
  30672. n.effect = lynx::makeEffectSlot (kind);
  30673. n.x = x;
  30674. n.y = y;
  30675. slot.patcher.nodes.push_back (n);
  30676. }
  30677. { // round 165c: a Hardware Insert node (its editor opens from the node)
  30678. lynx::PatchNode n;
  30679. n.effect = lynx::makeEffectSlot (lynx::EffectKind::hardwareInsert);
  30680. n.x = 420.0f, n.y = 260.0f;
  30681. slot.patcher.nodes.push_back (n);
  30682. }
  30683. auto wire = [&] (int from, int fromPort, int to, int toPort, float gain = 1.0f, lynx::PatchWire::Kind kind = lynx::PatchWire::Kind::audio) {
  30684. lynx::PatchWire w;
  30685. w.kind = kind;
  30686. w.from = from, w.fromPort = fromPort, w.to = to, w.toPort = toPort, w.gain = gain;
  30687. slot.patcher.wires.push_back (w);
  30688. };
  30689. wire (lynx::patchFromHost, 0, 0, 0);
  30690. wire (0, 1, 1, 0);
  30691. wire (0, 3, 2, 0, 0.5f);
  30692. wire (1, 0, lynx::patchToHost, 0);
  30693. wire (2, 0, lynx::patchToHost, 0);
  30694. wire (lynx::patchFromHost, 1, 3, 0);
  30695. wire (3, 1, 2, 2, 1.0f, lynx::PatchWire::Kind::control);
  30696. wire (0, 2, lynx::patchToHost, 1, 0.7f);
  30697. // round 171b (issue #65): a Surface knob on the reverb's parameter input 1, the reverb's parameter 0 out to
  30698. // the delay's parameter input 2 (FL's Inputs / Outputs › Parameters)
  30699. {
  30700. lynx::SurfaceControl knob;
  30701. knob.name = "Knob 1";
  30702. knob.value = 0.6f;
  30703. slot.patcher.surface = { knob };
  30704. slot.patcher.surfaceX = 200.0f, slot.patcher.surfaceY = 380.0f;
  30705. lynx::patcher::setParamInput (slot.patcher, 1, 1, true, "Reverb - 2");
  30706. lynx::patcher::setParamOutput (slot.patcher, 1, 0, true);
  30707. lynx::patcher::setParamInput (slot.patcher, 2, 2, true, "Delay - 3");
  30708. wire (lynx::patchSurface, 0, 1, 1, 1.0f, lynx::PatchWire::Kind::control);
  30709. wire (1, lynx::patchParamOutput (0), 2, 2, 1.0f, lynx::PatchWire::Kind::control);
  30710. }
  30711. slot.patcher.outputTracks = { 3 };
  30712. slot.patcher.inputX = -20.0f;
  30713. slot.patcher.outputX = 660.0f;
  30714. song.mixer[1].effects = { slot };
  30715. lynx::ChannelDef ch;
  30716. ch.name = "Patcher";
  30717. ch.instrument = lynx::InstrumentKind::patcher;
  30718. lynx::PatchNode synth, chorus;
  30719. synth.generator = true;
  30720. synth.channel.instrument = lynx::InstrumentKind::synth;
  30721. synth.channel.name = "Synth";
  30722. synth.x = 220.0f;
  30723. chorus.effect = lynx::makeEffectSlot (lynx::EffectKind::chorus);
  30724. chorus.x = 420.0f;
  30725. // round 162: a MIDI Out node between the "MIDI port 5" pin and "To LYNX" MIDI port 3, an Envelope Controller
  30726. // on the notes moving the chorus
  30727. lynx::PatchNode midiOut, envelope;
  30728. midiOut.generator = envelope.generator = true;
  30729. midiOut.channel.instrument = lynx::InstrumentKind::midiOut;
  30730. midiOut.channel.name = "MIDI Out";
  30731. lynx::midictl::writeMidiOut (midiOut.channel.pluginState, { 3, 0, 0, -1, -1 });
  30732. midiOut.x = 220.0f, midiOut.y = 160.0f;
  30733. envelope.channel.instrument = lynx::InstrumentKind::controller;
  30734. envelope.channel.name = "Envelope Controller";
  30735. envelope.channel.controllerState = lynx::writeEnvelopeController (lynx::defaultEnvelopeController());
  30736. envelope.x = 220.0f, envelope.y = 260.0f;
  30737. lynx::PatchNode osc; // round 164f: an FL engine node (its editor opens from the node)
  30738. osc.generator = true;
  30739. osc.channel = lynx::natives::makeChannel (lynx::InstrumentKind::threeosc, lynx::flStudioAccess()).value_or (lynx::ChannelDef {});
  30740. osc.channel.instrument = lynx::InstrumentKind::threeosc;
  30741. osc.channel.name = "3x Osc";
  30742. osc.x = 420.0f, osc.y = 260.0f;
  30743. // round 165c: Keyboard Controller, SoundFont player, Granulizer and Dashboard nodes (their editors open from the node)
  30744. lynx::PatchNode keys, soundfont, granulizer, dashboard;
  30745. keys.generator = soundfont.generator = granulizer.generator = dashboard.generator = true;
  30746. keys.channel.instrument = lynx::InstrumentKind::controller;
  30747. keys.channel.name = "Keyboard Controller";
  30748. {
  30749. lynx::KeyboardControllerData ramp;
  30750. for (std::size_t k = 0; k < ramp.keys.size(); ++k)
  30751. ramp.keys[k] = (float) k / (float) (ramp.keys.size() - 1);
  30752. lynx::writeKeyboardController (ramp, keys.channel.controllerState);
  30753. }
  30754. soundfont.channel = lynx::sf::makeChannel();
  30755. granulizer.channel = lynx::natives::makeChannel (lynx::InstrumentKind::granulizer, lynx::flStudioAccess()).value_or (lynx::ChannelDef {});
  30756. granulizer.channel.instrument = lynx::InstrumentKind::granulizer;
  30757. granulizer.channel.name = "Fruity Granulizer";
  30758. dashboard.channel.instrument = lynx::InstrumentKind::dashboard;
  30759. dashboard.channel.name = "Dashboard";
  30760. dashboard.channel.patcher.surface = lynx::surface::starterControls();
  30761. keys.x = 20.0f, keys.y = 440.0f;
  30762. soundfont.x = 220.0f, soundfont.y = 440.0f;
  30763. granulizer.x = 420.0f, granulizer.y = 440.0f;
  30764. dashboard.x = 20.0f, dashboard.y = 540.0f;
  30765. // and a Layer node playing the SoundFont and Granulizer nodes on its Children pin (crossfaded)
  30766. lynx::PatchNode layerNode;
  30767. layerNode.generator = true;
  30768. layerNode.channel.instrument = lynx::InstrumentKind::layer;
  30769. layerNode.channel.name = "Layer";
  30770. layerNode.channel.layer.crossfade = true;
  30771. layerNode.channel.layer.fade = 0.35f;
  30772. layerNode.x = 220.0f, layerNode.y = 540.0f;
  30773. ch.patcher.nodes = { synth, chorus, midiOut, envelope, osc, keys, soundfont, granulizer, dashboard, layerNode };
  30774. lynx::PatchWire notes, a, b, portIn, portOut, envNotes, envControl;
  30775. notes.kind = lynx::PatchWire::Kind::midi, notes.to = 0;
  30776. a.from = 0, a.to = 1;
  30777. b.from = 1;
  30778. portIn.kind = lynx::PatchWire::Kind::midi, portIn.fromPort = lynx::patchMidiPortPin (5), portIn.to = 2;
  30779. portOut.kind = lynx::PatchWire::Kind::midi, portOut.from = 2, portOut.to = lynx::patchToHost, portOut.toPort = 3;
  30780. envNotes.kind = lynx::PatchWire::Kind::midi, envNotes.to = 3;
  30781. envControl.kind = lynx::PatchWire::Kind::control, envControl.from = 3, envControl.to = 1, envControl.toPort = 0;
  30782. lynx::PatchWire oscNotes, oscOut;
  30783. oscNotes.kind = lynx::PatchWire::Kind::midi, oscNotes.to = 4;
  30784. oscOut.from = 4;
  30785. lynx::PatchWire layerNotes, layerToFont, layerToGrains, fontOut, grainsOut;
  30786. layerNotes.kind = layerToFont.kind = layerToGrains.kind = lynx::PatchWire::Kind::midi;
  30787. layerNotes.to = 9;
  30788. layerToFont.from = 9, layerToFont.to = 6;
  30789. layerToGrains.from = 9, layerToGrains.to = 7;
  30790. fontOut.from = 6;
  30791. grainsOut.from = 7;
  30792. ch.patcher.wires = { notes, a, b, portIn, portOut, envNotes, envControl, oscNotes, oscOut, layerNotes, layerToFont, layerToGrains, fontOut, grainsOut };
  30793. ch.patcher.fromMidiPorts = { 1, 5 };
  30794. ch.patcher.toMidiPorts = { 3 };
  30795. ch.patcher.outputX = 640.0f;
  30796. song.channels.push_back (ch);
  30797. // LYNX_PATCHERSHOT_SAVE=file.lynx: the demo as a project (a GUI check of the same Patchers, round 164f)
  30798. if (const auto save = juce::SystemStats::getEnvironmentVariable ("LYNX_PATCHERSHOT_SAVE", {}); save.isNotEmpty())
  30799. {
  30800. if (! song.patterns.empty())
  30801. for (int k = 0; k < 4; ++k)
  30802. 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 });
  30803. juce::String error;
  30804. lynx::ProjectFile::save (song, juce::File (save), error);
  30805. // round 171b: the saved Patchers come back the same (parameter ports, event cables, published)
  30806. juce::String report;
  30807. if (const auto loaded = lynx::ProjectFile::load (juce::File (save), error))
  30808. {
  30809. const auto same = loaded->mixer.size() > 1 && ! loaded->mixer[1].effects.empty()
  30810. && loaded->mixer[1].effects[0].patcher == song.mixer[1].effects[0].patcher;
  30811. const auto& d = loaded->mixer.size() > 1 && ! loaded->mixer[1].effects.empty() ? loaded->mixer[1].effects[0].patcher : lynx::PatcherDoc {};
  30812. report << "patcher round trip: " << (same ? "OK" : "DIFFERENT") << "\n";
  30813. if (! same && loaded->mixer.size() > 1 && ! loaded->mixer[1].effects.empty())
  30814. {
  30815. const auto& a = song.mixer[1].effects[0].patcher;
  30816. report << "wires " << (a.wires == d.wires ? "same" : "differ") << ", published " << (a.published == d.published ? "same" : "differ")
  30817. << ", surface " << (a.surface == d.surface ? "same" : "differ") << "\n";
  30818. for (std::size_t n = 0; n < std::min (a.nodes.size(), d.nodes.size()); ++n)
  30819. if (! (a.nodes[n] == d.nodes[n]))
  30820. report << "node " << (int) n << " differs: ports " << (a.nodes[n].paramIns == d.nodes[n].paramIns && a.nodes[n].paramOuts == d.nodes[n].paramOuts ? "same" : "differ")
  30821. << ", effect " << (a.nodes[n].effect == d.nodes[n].effect ? "same" : "differ") << ", xy "
  30822. << (a.nodes[n].x == d.nodes[n].x && a.nodes[n].y == d.nodes[n].y ? "same" : "differ") << "\n";
  30823. }
  30824. for (int n = 0; n < (int) d.nodes.size(); ++n)
  30825. report << "node " << n << " paramIns " << (int) d.nodes[(std::size_t) n].paramIns.size() << " paramOuts "
  30826. << (int) d.nodes[(std::size_t) n].paramOuts.size() << "\n";
  30827. for (const auto& w : d.wires)
  30828. if (w.kind == lynx::PatchWire::Kind::control)
  30829. report << "control " << w.from << ":" << w.fromPort << " -> " << w.to << ":" << w.toPort << "\n";
  30830. for (const auto& p : d.published)
  30831. report << "published " << p.node << ":" << p.param << " " << juce::String::fromUTF8 (p.name.c_str()) << "\n";
  30832. }
  30833. else
  30834. report << "patcher round trip: load failed: " << error << "\n";
  30835. juce::File (prefix + "-roundtrip.txt").replaceWithText (report);
  30836. }
  30837. offline.setSong (std::move (song));
  30838. }
  30839. offline.dispatchPendingMessages();
  30840. const auto& song = offline.getSong();
  30841. auto shootOpen = [&] (const juce::String& name) {
  30842. for (int k = 0; k < juce::TopLevelWindow::getNumTopLevelWindows(); ++k)
  30843. if (auto* w = dynamic_cast<juce::DocumentWindow*> (juce::TopLevelWindow::getTopLevelWindow (k)))
  30844. if (w->getName().startsWith (lynx::tr ("Patcher")) && w->getContentComponent() != nullptr)
  30845. {
  30846. auto* c = w->getContentComponent();
  30847. savePng (lynx::shot::snapshot (*c), prefix + name);
  30848. delete w;
  30849. return;
  30850. }
  30851. };
  30852. int shots = 0;
  30853. for (int t = 0; t < (int) song.mixer.size() && shots < 12; ++t)
  30854. for (int s = 0; s < (int) song.mixer[(std::size_t) t].effects.size(); ++s)
  30855. if (song.mixer[(std::size_t) t].effects[(std::size_t) s].kind == lynx::EffectKind::patcher)
  30856. {
  30857. lynx::PatcherWindows::openSlot (offline, t, s);
  30858. shootOpen ("-insert" + juce::String (t) + "-slot" + juce::String (s) + ".png");
  30859. // each built-in node's editor, as a double-click opens it (round 165c)
  30860. lynx::PatcherWindows::shootNodeEditors (offline, false, t, s, [&] (const juce::Image& image, int n) {
  30861. savePng (image, prefix + "-insert" + juce::String (t) + "-slot" + juce::String (s) + "-node" + juce::String (n) + ".png");
  30862. });
  30863. ++shots;
  30864. if (shots == 1) // its menus (round 162)
  30865. lynx::PatcherWindows::shootMenus (offline, false, t, s, [&] (const juce::Image& image, const juce::String& name) {
  30866. savePng (image, prefix + "-menu-" + name + ".png");
  30867. });
  30868. }
  30869. for (int c = 0; c < (int) song.channels.size(); ++c)
  30870. if (song.channels[(std::size_t) c].instrument == lynx::InstrumentKind::patcher)
  30871. {
  30872. lynx::PatcherWindows::openChannel (offline, c);
  30873. shootOpen ("-channel" + juce::String (c) + ".png");
  30874. // each node's editor, as a double-click opens it (round 164f; every built-in node since round 165c)
  30875. lynx::PatcherWindows::shootNodeEditors (offline, true, c, 0, [&] (const juce::Image& image, int n) {
  30876. savePng (image, prefix + "-channel" + juce::String (c) + "-node" + juce::String (n) + ".png");
  30877. });
  30878. lynx::PatcherWindows::shootMenus (offline, true, c, 0, [&] (const juce::Image& image, const juce::String& name) {
  30879. savePng (image, prefix + "-channel" + juce::String (c) + "-menu-" + name + ".png");
  30880. });
  30881. }
  30882. }
  30883. }
  30884. // Issue #64: FL's letter keys in a plugin menu (quickpick::showMenu), checked on the real menu windows
  30885. struct TypeAheadTest final : private juce::Timer
  30886. {
  30887. juce::File out;
  30888. juce::StringArray log;
  30889. int step = 0, picked = 0;
  30890. bool ok = true, menuShown = false;
  30891. std::unique_ptr<juce::DocumentWindow> owner;
  30892. juce::PopupMenu pending;
  30893. static juce::String highlighted()
  30894. {
  30895. if (auto* window = juce::Component::getCurrentlyModalComponent())
  30896. for (auto* child : window->getChildren())
  30897. if (auto* h = child->getAccessibilityHandler(); h != nullptr && h->hasFocus (false))
  30898. return h->getTitle();
  30899. return "(none)";
  30900. }
  30901. static void press (const juce::KeyPress& key)
  30902. {
  30903. if (auto* window = juce::Component::getCurrentlyModalComponent())
  30904. if (auto* peer = window->getPeer())
  30905. peer->handleKeyPress (key);
  30906. }
  30907. void expect (const juce::String& what, const juce::String& got, const juce::String& wanted)
  30908. {
  30909. const auto good = got == wanted;
  30910. ok = ok && good;
  30911. log.add ((good ? "ok " : "FAIL ") + what + ": " + got + (good ? juce::String() : " (wanted " + wanted + ")"));
  30912. }
  30913. void start()
  30914. {
  30915. juce::PopupMenu menu, sub;
  30916. auto item = [this] (juce::PopupMenu& m, int id, const char* text, bool enabled = true) {
  30917. m.addItem (text, enabled, false, [this, id] { picked = id; });
  30918. };
  30919. menu.addSectionHeader ("LYNX SHARE");
  30920. item (menu, 1, "Echoform");
  30921. item (menu, 2, "EQ");
  30922. item (menu, 3, "Halo");
  30923. menu.addSectionHeader ("Misc");
  30924. item (menu, 4, "Effector");
  30925. item (menu, 5, "Exciter (unavailable)", false);
  30926. item (sub, 10, "Delay");
  30927. item (sub, 11, "Edison");
  30928. item (sub, 12, "Eventide");
  30929. menu.addSubMenu ("Tree", sub);
  30930. // the menu belongs to a window in the foreground, as when the user right-clicks a mixer slot (JUCE closes a
  30931. // menu of a background process at once)
  30932. owner = std::make_unique<juce::DocumentWindow> ("LYNX type-ahead test", juce::Colours::black, 0);
  30933. owner->setBounds (200, 200, 300, 200);
  30934. owner->setVisible (true);
  30935. lynx::forceForegroundForTest (*owner);
  30936. pending = menu; // shown once the window is up and active (X11 maps and activates it asynchronously)
  30937. startTimer (300);
  30938. }
  30939. void timerCallback() override
  30940. {
  30941. const auto e = juce::KeyPress ('e', {}, 'e');
  30942. if (step == 0 && owner != nullptr && ! menuShown)
  30943. {
  30944. menuShown = true;
  30945. lynx::forceForegroundForTest (*owner);
  30946. lynx::quickpick::showMenu (pending, juce::PopupMenu::Options().withTargetComponent (owner.get()), {});
  30947. return;
  30948. }
  30949. switch (step++)
  30950. {
  30951. case 0: expect ("menu open", juce::String ((int) (juce::Component::getCurrentlyModalComponent() != nullptr)), "1"); break;
  30952. case 1: press (e); expect ("e", highlighted(), "Echoform"); break;
  30953. case 2: press (e); expect ("e again", highlighted(), "EQ"); break;
  30954. case 3: press (juce::KeyPress ('E', juce::ModifierKeys::shiftModifier, 'E')); expect ("E (shift)", highlighted(), "Effector"); break;
  30955. case 4: press (e); expect ("e wraps (skips the disabled one)", highlighted(), "Echoform"); break;
  30956. case 5: press (juce::KeyPress ('m', {}, 'm')); expect ("m (only a heading starts with it: no move)", highlighted(), "Echoform"); break;
  30957. case 6: press (juce::KeyPress (juce::KeyPress::downKey)); expect ("down arrow", highlighted(), "EQ"); break;
  30958. case 7: press (e); expect ("e after the arrow", highlighted(), "Effector"); break;
  30959. case 8: press (juce::KeyPress ('t', {}, 't')); expect ("t", highlighted(), "Tree"); break;
  30960. case 9: press (juce::KeyPress (juce::KeyPress::rightKey)); break; // opens the submenu (it takes the keys)
  30961. case 10: press (e); expect ("e in the submenu", highlighted(), "Edison"); break;
  30962. case 11: press (e); expect ("e again in the submenu", highlighted(), "Eventide"); break;
  30963. case 12: expect ("nothing picked by the letters", juce::String (picked), "0"); press (juce::KeyPress (juce::KeyPress::returnKey)); break;
  30964. case 13: break;
  30965. default:
  30966. expect ("Enter closed the menu", juce::String ((int) (juce::Component::getCurrentlyModalComponent() == nullptr)), "1");
  30967. expect ("Enter picked", juce::String (picked), "12");
  30968. stopTimer();
  30969. owner.reset();
  30970. log.add (ok ? "result=OK" : "result=FAIL");
  30971. out.replaceWithText (log.joinIntoString ("\n") + "\n");
  30972. juce::JUCEApplication::getInstance()->setApplicationReturnValue (ok ? 0 : 1);
  30973. juce::JUCEApplication::quit();
  30974. return;
  30975. }
  30976. }
  30977. };
  30978. std::unique_ptr<TypeAheadTest> typeAheadTest;
  30979. struct ChooserTest final : private juce::Timer
  30980. {
  30981. juce::File out, file;
  30982. juce::StringArray log;
  30983. std::unique_ptr<juce::FileChooser> chooser;
  30984. double started = 0;
  30985. bool shot = false, done = false;
  30986. void start()
  30987. {
  30988. log.add ("LYNX_FILE_DIALOG=" + juce::SystemStats::getEnvironmentVariable ("LYNX_FILE_DIALOG", {}));
  30989. log.add ("native=" + juce::String ((int) lynx::ui::filechooser::nativeDialogs()));
  30990. chooser = lynx::ui::makeFileChooser ("Open audio file", file.getParentDirectory(), "*.wav;*.flac");
  30991. started = juce::Time::getMillisecondCounterHiRes();
  30992. lynx::ui::launchChooser (chooser, juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectFiles,
  30993. [this] (const juce::FileChooser& fc) { finish (fc.getResult()); });
  30994. startTimer (200);
  30995. }
  30996. static juce::FileChooserDialogBox* builtInDialog()
  30997. {
  30998. for (int i = 0; i < juce::Desktop::getInstance().getNumComponents(); ++i)
  30999. if (auto* box = dynamic_cast<juce::FileChooserDialogBox*> (juce::Desktop::getInstance().getComponent (i)); box != nullptr && box->isShowing())
  31000. return box;
  31001. return nullptr;
  31002. }
  31003. static juce::FileBrowserComponent* findBrowser (juce::Component& c)
  31004. {
  31005. if (auto* b = dynamic_cast<juce::FileBrowserComponent*> (&c))
  31006. return b;
  31007. for (auto* child : c.getChildren())
  31008. if (auto* b = findBrowser (*child))
  31009. return b;
  31010. return nullptr;
  31011. }
  31012. void timerCallback() override
  31013. {
  31014. if (done)
  31015. return;
  31016. if (auto* box = builtInDialog(); box != nullptr && ! shot)
  31017. {
  31018. shot = true;
  31019. log.add ("built-in dialog shown after " + juce::String (juce::roundToInt (juce::Time::getMillisecondCounterHiRes() - started)) + " ms");
  31020. const auto image = lynx::shot::snapshot (*box);
  31021. juce::FileOutputStream png (out.getSiblingFile (out.getFileName() + ".png"));
  31022. if (png.openedOk())
  31023. {
  31024. png.setPosition (0), png.truncate();
  31025. juce::PNGImageFormat().writeImageToStream (image, png);
  31026. }
  31027. if (auto* browser = findBrowser (*box))
  31028. {
  31029. browser->setRoot (file.getParentDirectory());
  31030. browser->setFileName (file.getFileName());
  31031. log.add ("typed " + file.getFileName());
  31032. box->exitModalState (1);
  31033. }
  31034. else
  31035. log.add ("no file browser in the dialog");
  31036. }
  31037. if (juce::Time::getMillisecondCounterHiRes() - started > 30000.0)
  31038. finish ({}, "timeout");
  31039. }
  31040. void finish (const juce::File& result, const juce::String& why = {})
  31041. {
  31042. if (done)
  31043. return;
  31044. done = true;
  31045. stopTimer();
  31046. log.add ("callback after " + juce::String (juce::roundToInt (juce::Time::getMillisecondCounterHiRes() - started)) + " ms: "
  31047. + (why.isNotEmpty() ? why : result.getFullPathName().isEmpty() ? juce::String ("(no file)") : result.getFullPathName()));
  31048. log.add ("native now=" + juce::String ((int) lynx::ui::filechooser::nativeDialogs()));
  31049. const auto ok = result == file && result.existsAsFile();
  31050. log.add (ok ? "result=OK" : "result=FAIL");
  31051. out.replaceWithText (log.joinIntoString ("\n") + "\n");
  31052. juce::JUCEApplication::getInstance()->setApplicationReturnValue (ok ? 0 : 1);
  31053. juce::MessageManager::callAsync ([] { juce::JUCEApplication::quit(); });
  31054. }
  31055. };
  31056. std::unique_ptr<ChooserTest> chooserTest;
  31057. void runChooserTest (const juce::File& out, const juce::File& file)
  31058. {
  31059. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  31060. chooserTest = std::make_unique<ChooserTest>();
  31061. chooserTest->out = out;
  31062. chooserTest->file = file;
  31063. chooserTest->start();
  31064. }
  31065. void runTypeAheadTest (const juce::File& out)
  31066. {
  31067. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  31068. typeAheadTest = std::make_unique<TypeAheadTest>();
  31069. typeAheadTest->out = out;
  31070. typeAheadTest->start();
  31071. }
  31072. void runStabilityShot (const juce::String& folder)
  31073. {
  31074. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  31075. const juce::File dir (folder);
  31076. dir.createDirectory();
  31077. {
  31078. lynx::AudioEngine offline (false);
  31079. const auto save = [&dir] (std::unique_ptr<juce::Component> c, const juce::String& name) {
  31080. juce::Component frame;
  31081. frame.setSize (c->getWidth(), c->getHeight());
  31082. frame.setOpaque (true);
  31083. if (c->isOnDesktop()) // (an AlertWindow: never shown, so it takes no foreground)
  31084. c->removeFromDesktop();
  31085. frame.addAndMakeVisible (*c);
  31086. c->setTopLeftPosition (0, 0);
  31087. const auto image = lynx::shot::paint (frame, lynx::theme::panel);
  31088. const auto file = dir.getChildFile (name);
  31089. file.deleteFile();
  31090. juce::PNGImageFormat png;
  31091. if (auto out = file.createOutputStream())
  31092. png.writeImageToStream (image, *out);
  31093. };
  31094. save (lynx::PluginWindows::makeCrashPromptPanel ("Serum", false), "crash-prompt.png");
  31095. save (lynx::PluginWindows::makeCrashPromptPanel ("Serum", true), "crash-prompt-onload.png");
  31096. save (lynx::PluginWindows::makeCrashNoticePanel ("Serum", true), "crash-notice.png");
  31097. save (lynx::makePluginManagerPanel (offline, false), "plugin-manager.png");
  31098. save (lynx::makePluginMonitorPanel (offline), "plugin-monitor.png");
  31099. }
  31100. setApplicationReturnValue (0);
  31101. quit();
  31102. }
  31103. void runDetails190ihShot (const juce::String& prefix)
  31104. {
  31105. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  31106. juce::String report;
  31107. auto line = [&report] (const juce::String& t) { report << t << "\n"; };
  31108. {
  31109. // R2: Gross Beat on Insert 1 — the first time slot and a half-beat volume gate, as in FL's capture ("Empty",
  31110. // "1/2 Bt Gate")
  31111. lynx::AudioEngine offline (false);
  31112. lynx::Song song;
  31113. song.mixer = lynx::Song::defaultMixer (2);
  31114. song.bpm = 150.0;
  31115. auto gb = lynx::makeEffectSlot (lynx::EffectKind::grossBeat);
  31116. const auto names = lynx::grossbeat::slotNames (gb.state, true);
  31117. int gate = 0;
  31118. for (int k = 0; k < (int) names.size(); ++k)
  31119. if (names[(std::size_t) k] == "Gate 1/2 beat") // (LYNX's factory slot for FL's "1/2 Bt Gate")
  31120. gate = k;
  31121. gb.params[0] = lynx::grossbeat::paramFromRaw (0, 0);
  31122. gb.params[1] = lynx::grossbeat::paramFromRaw (1, gate);
  31123. song.mixer[1].effects.push_back (gb);
  31124. offline.setSong (std::move (song));
  31125. offline.dispatchPendingMessages();
  31126. // the real effect played to beat 2.9 of its bar: its published outputs go where the rack writes them
  31127. auto run = lynx::makeEffect (gb);
  31128. run->prepare (48000.0);
  31129. const auto tps = 150.0 / 60.0 * lynx::ppq / 48000.0;
  31130. std::vector<float> l (480, 0.3f), r (480, 0.3f);
  31131. std::size_t done = 0;
  31132. auto block = [&] (lynx::EffectParams& params) {
  31133. run->setSongPosition ((double) done * tps);
  31134. run->process (l.data(), r.data(), 480, params, 150.0);
  31135. done += 480;
  31136. };
  31137. auto publish = [&] (bool playing) {
  31138. const auto key = (std::size_t) (1 * lynx::maxEffectSlots + 0) * lynx::ProcessTimes::meterOutputs;
  31139. if (auto* times = offline.getProcessTimes())
  31140. for (int k = 0; k < lynx::ProcessTimes::meterOutputs; ++k)
  31141. times->effectMeters[key + (std::size_t) k].store (run->controlOutput (k), std::memory_order_relaxed);
  31142. else
  31143. line ("no process times: the editor shows nothing live");
  31144. offline.getTransport().playing.store (playing);
  31145. juce::String values;
  31146. for (int k = 0; k < 7; ++k)
  31147. values << " " << juce::String (run->controlOutput (k), 3);
  31148. line ("gross beat outputs:" + values);
  31149. };
  31150. while ((double) done * tps / lynx::ppq < 2.9)
  31151. block (gb.params);
  31152. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f);
  31153. editor->setSize (editor->getWidth(), editor->getHeight());
  31154. for (const int view : { 1, 0 })
  31155. {
  31156. lynx::showGrossBeatEnvelopeForSnapshot (*editor, view);
  31157. publish (true);
  31158. lynx::tickNativeEffectEditor (*editor);
  31159. savePng (lynx::shot::snapshot (*editor), prefix + "-r2-grossbeat-playing-" + (view == 1 ? "volume" : "time") + ".png");
  31160. }
  31161. lynx::ui::motion::enabled() = false;
  31162. lynx::tickNativeEffectEditor (*editor);
  31163. editor->repaint();
  31164. savePng (lynx::shot::snapshot (*editor), prefix + "-r2-grossbeat-playing-noanim.png");
  31165. lynx::ui::motion::enabled() = true;
  31166. // a click on another time slot: queued until the next 4 beats
  31167. auto queued = gb.params;
  31168. queued[0] = lynx::grossbeat::paramFromRaw (0, 5);
  31169. block (queued);
  31170. publish (true);
  31171. lynx::tickNativeEffectEditor (*editor);
  31172. savePng (lynx::shot::snapshot (*editor), prefix + "-r2-grossbeat-queued.png");
  31173. publish (false); // stopped: no locator, no fill
  31174. lynx::tickNativeEffectEditor (*editor);
  31175. savePng (lynx::shot::snapshot (*editor), prefix + "-r2-grossbeat-stopped.png");
  31176. // round 190jd (live check 190iw Q7): the locator in FL's colours (the editor's Options menu) on the beat (cream,
  31177. // 3 px trail), a third into it (orange) and near its end (dusty red); LYNX's playhead colour stays the default
  31178. lynx::gblocator::setFlStyle (true);
  31179. lynx::showGrossBeatEnvelopeForSnapshot (*editor, 1);
  31180. for (const auto at : { 4.02, 4.35, 4.9 })
  31181. {
  31182. while ((double) done * tps / lynx::ppq < at)
  31183. block (queued);
  31184. publish (true);
  31185. juce::Thread::sleep (60); // (the editor's frame budget: ~21 frames a second in this style)
  31186. lynx::tickNativeEffectEditor (*editor);
  31187. savePng (lynx::shot::snapshot (*editor), prefix + "-r2-grossbeat-fl-colours-" + juce::String (at - 4.0, 2) + ".png");
  31188. }
  31189. lynx::gblocator::setFlStyle (false);
  31190. offline.getTransport().playing.store (false);
  31191. }
  31192. {
  31193. // R7: the Envelope Controller's Keyboard / Velocity mapping pages after a note (key 64, velocity 0.8)
  31194. lynx::AudioEngine offline (false);
  31195. lynx::Song song;
  31196. lynx::ChannelDef env;
  31197. env.name = "Envelope Controller";
  31198. env.instrument = lynx::InstrumentKind::controller;
  31199. auto ec = lynx::defaultEnvelopeController();
  31200. ec[0].maps[lynx::mapKeyboard].count = 2;
  31201. ec[0].maps[lynx::mapKeyboard].time = { 0.2f, 0.8f };
  31202. ec[0].maps[lynx::mapKeyboard].level = { 0.0f, 1.0f };
  31203. ec[0].maps[lynx::mapVelocity] = ec[0].maps[lynx::mapKeyboard];
  31204. env.controllerState = lynx::writeEnvelopeController (ec);
  31205. song.channels.push_back (env);
  31206. song.patterns.emplace_back();
  31207. offline.setSong (std::move (song));
  31208. offline.dispatchPendingMessages();
  31209. auto editor = lynx::makeEnvelopeControllerEditor (
  31210. offline, [] (lynx::Song& s) -> lynx::ChannelDef* { return s.channels.empty() ? nullptr : &s.channels[0]; }, 0,
  31211. [] (int k) { return k == 8 ? 64.0f : k == 9 ? 0.8f : 0.5f; });
  31212. for (const int part : { 2, 3 })
  31213. {
  31214. for (auto* child : editor->getChildren())
  31215. if (auto* box = dynamic_cast<juce::ComboBox*> (child))
  31216. box->setSelectedItemIndex (part, juce::sendNotificationSync);
  31217. savePng (lynx::shot::snapshot (*editor), prefix + "-r7-ec-" + (part == 2 ? "keyboard" : "velocity") + "-line.png");
  31218. }
  31219. }
  31220. {
  31221. lynx::AudioEngine offline (false);
  31222. lynx::MainComponent ui (offline, false);
  31223. ui.setSize (1920, 1080);
  31224. lynx::Song song;
  31225. song.mixer = lynx::Song::defaultMixer (4);
  31226. for (const auto* name : { "Grv Kick 27", "Snare", "Hat", "Bass (locked)" })
  31227. {
  31228. lynx::ChannelDef c;
  31229. c.name = name;
  31230. c.instrument = lynx::InstrumentKind::sampler;
  31231. song.channels.push_back (c);
  31232. }
  31233. song.channels[3].receiveFrom = "MIDI keyboard";
  31234. song.patterns.emplace_back();
  31235. offline.setSong (std::move (song));
  31236. offline.dispatchPendingMessages();
  31237. ui.showDesktopForSnapshot (false);
  31238. offline.dispatchPendingMessages();
  31239. // R4: the rack's activity light — before, at note-on, held, after the release; a locked channel lit (orange)
  31240. auto& rack = ui.getRackForSnapshot();
  31241. const std::pair<const char*, float> states[] { { "before", 0.0f }, { "noteon", 1.0f }, { "held", lynx::activity::held }, { "after", 0.0f } };
  31242. for (const auto& [name, level] : states)
  31243. {
  31244. rack.setActivityForSnapshot (0, level);
  31245. rack.setActivityForSnapshot (3, level);
  31246. savePng (lynx::shot::snapshot (rack), prefix + "-r4-rack-" + name + ".png");
  31247. }
  31248. rack.setActivityForSnapshot (0, 0.0f);
  31249. rack.setActivityForSnapshot (3, 0.0f);
  31250. // R3: the transport stopped, playing, recording (both blink phases), armed and stopped; the hint bar
  31251. const auto toolbar = ui.getToolbarBoundsForSnapshot();
  31252. auto& transport = offline.getTransport();
  31253. ui.transportForSnapshot (false, true);
  31254. saveArea (ui, toolbar, prefix + "-r3-toolbar-stopped.png");
  31255. transport.playing.store (true);
  31256. ui.transportForSnapshot (true, true);
  31257. saveArea (ui, toolbar, prefix + "-r3-toolbar-playing.png");
  31258. transport.recording.store (true);
  31259. ui.transportForSnapshot (true, true);
  31260. saveArea (ui, toolbar, prefix + "-r3-toolbar-recording-lit.png");
  31261. ui.transportForSnapshot (true, false);
  31262. saveArea (ui, toolbar, prefix + "-r3-toolbar-recording-dark.png");
  31263. lynx::ui::motion::enabled() = false;
  31264. ui.transportForSnapshot (true, false);
  31265. saveArea (ui, toolbar, prefix + "-r3-toolbar-recording-noanim.png");
  31266. lynx::ui::motion::enabled() = true;
  31267. transport.playing.store (false);
  31268. ui.transportForSnapshot (false, false);
  31269. saveArea (ui, toolbar, prefix + "-r3-toolbar-armed-stopped.png");
  31270. transport.recording.store (false);
  31271. ui.transportForSnapshot (false, true);
  31272. for (const bool on : { true, false })
  31273. {
  31274. offline.markLiveNote (60, 100, on);
  31275. const auto hint = ui.liveNoteHintForSnapshot();
  31276. line ("hint: " + hint);
  31277. ui.setHintForSnapshot ({ hint, {}, false, false });
  31278. saveArea (ui, toolbar, prefix + "-r3-hint-note" + (on ? "on" : "off") + ".png");
  31279. }
  31280. offline.editSong ([] (lynx::Song& s) { s.bpm = 128.0; }); // (a change: the project is modified)
  31281. offline.dispatchPendingMessages();
  31282. const auto reminder = ui.saveReminderForSnapshot();
  31283. line ("reminder: " + reminder);
  31284. ui.setHintForSnapshot ({ reminder, {}, false, false });
  31285. saveArea (ui, toolbar, prefix + "-r3-save-reminder.png");
  31286. // R14: the Simple dock's input level
  31287. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  31288. offline.dispatchPendingMessages();
  31289. if (auto* simple = ui.getSimpleWorkflowForSnapshot())
  31290. if (auto* dock = simple->dockForSnapshot())
  31291. {
  31292. dock->inputLevelForSnapshot (0.72f);
  31293. offline.dispatchPendingMessages();
  31294. savePng (lynx::shot::snapshot (*dock), prefix + "-r14-dock-input-level.png");
  31295. line ("dock: " + juce::String (dock->getWidth()) + "x" + juce::String (dock->getHeight()));
  31296. }
  31297. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
  31298. offline.dispatchPendingMessages();
  31299. }
  31300. juce::File (prefix + "-report.txt").replaceWithText (report);
  31301. }
  31302. void runSnapshot (const juce::String& prefix, const juce::String& projectPath)
  31303. {
  31304. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  31305. // LYNX_SNAPSHOT_THEME=file.lynxtheme: the pictures in that theme (round 162d)
  31306. if (const auto themeFile = juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_THEME", {}); themeFile.isNotEmpty())
  31307. if (const auto spec = lynx::themeui::loadFile (juce::File (themeFile)))
  31308. lynx::themeui::apply (*spec, false);
  31309. {
  31310. lynx::AudioEngine offline (false);
  31311. lynx::MainComponent ui (offline, false); // default layout and keys, nothing saved
  31312. // LYNX_SNAPSHOT_SIZE=WxH (default 1280x720)
  31313. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1280x720"), "x", "");
  31314. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  31315. if (projectPath.isNotEmpty())
  31316. ui.openFile (juce::File (projectPath));
  31317. offline.dispatchPendingMessages(); // change notifications are asynchronous
  31318. ui.waitForBrowserForSnapshot();
  31319. // the workspace desktop: the default layout, then with the Piano Roll and Mixer floating too
  31320. // (and a sample hint in the status strip, as when hovering a knob)
  31321. ui.showDesktopForSnapshot (false);
  31322. ui.setMetersForSnapshot (0.23, (std::int64_t) 412 << 20, 6);
  31323. offline.dispatchPendingMessages();
  31324. saveSnapshot (ui, prefix + "-desktop.png");
  31325. // the first start: the setup wizard over the main window (round 140), also on a small screen (it scrolls)
  31326. {
  31327. const auto size = ui.getBounds();
  31328. ui.showSetupWizard();
  31329. offline.dispatchPendingMessages();
  31330. saveSnapshot (ui, prefix + "-desktop-setup.png");
  31331. ui.setSize (1024, 600);
  31332. offline.dispatchPendingMessages();
  31333. saveSnapshot (ui, prefix + "-desktop-setup-small.png");
  31334. ui.closeSetupWizardForSnapshot();
  31335. ui.setBounds (size);
  31336. offline.dispatchPendingMessages();
  31337. }
  31338. // the start-up desktop and the toolbar at the usual window sizes: the untouched default layout
  31339. // follows the window (default rects, not scaled ones); panels drop from the toolbar by priority
  31340. {
  31341. const auto size = ui.getBounds();
  31342. for (const auto& [w, h] : std::vector<std::pair<int, int>> { { 1280, 720 }, { 1366, 768 }, { 1600, 900 }, { 1920, 1080 }, { 2560, 1440 }, { 3840, 2160 } })
  31343. {
  31344. ui.setSize (w, h);
  31345. offline.dispatchPendingMessages();
  31346. saveSnapshot (ui, prefix + "-desktop-" + juce::String (w) + ".png");
  31347. saveArea (ui, ui.getToolbarBoundsForSnapshot(), prefix + "-toolbar-" + juce::String (w) + ".png");
  31348. if (w == 1920) // the rack scrolled to its last steps: the controls column stays in view (round 90)
  31349. {
  31350. ui.scrollRackForSnapshot (100000);
  31351. offline.dispatchPendingMessages();
  31352. saveSnapshot (ui, prefix + "-desktop-rack-scrolled.png");
  31353. ui.scrollRackForSnapshot (0);
  31354. }
  31355. }
  31356. // the toolbar with small and large icons, and a customized one (groups hidden and reordered)
  31357. ui.setSize (1600, 900);
  31358. for (auto [iconSize, name] : { std::pair { lynx::toolbarlayout::IconSize::small, "small" }, { lynx::toolbarlayout::IconSize::large, "large" } })
  31359. {
  31360. auto layout = lynx::toolbarlayout::Layout::makeDefault();
  31361. layout.iconSize = iconSize;
  31362. ui.setToolbarLayoutForSnapshot (layout);
  31363. saveArea (ui, ui.getToolbarBoundsForSnapshot(), prefix + "-toolbar-" + name + "-1600.png");
  31364. }
  31365. {
  31366. auto layout = lynx::toolbarlayout::Layout::makeDefault();
  31367. layout.move (lynx::toolbarlayout::Group::windows, -3);
  31368. layout.setShown (lynx::toolbarlayout::Group::record, false);
  31369. layout.setShown (lynx::toolbarlayout::Group::meters, false);
  31370. ui.setToolbarLayoutForSnapshot (layout);
  31371. saveArea (ui, ui.getToolbarBoundsForSnapshot(), prefix + "-toolbar-custom-1600.png");
  31372. }
  31373. {
  31374. // round 170e: the toolbar after a knob was moved: the last tweaked read-out (its caption) and the snap magnet
  31375. ui.setSize (1920, 1080); // the read-out needs room beside the hint bar
  31376. ui.setToolbarLayoutForSnapshot (lynx::toolbarlayout::Layout::makeDefault());
  31377. lynx::AutomationTarget t;
  31378. t.kind = lynx::AutomationTargetKind::mixerVolume;
  31379. t.index = 0;
  31380. offline.noteTweaked (t);
  31381. ui.refreshTweakReadoutForSnapshot();
  31382. offline.dispatchPendingMessages();
  31383. saveArea (ui, ui.getToolbarBoundsForSnapshot(), prefix + "-toolbar-tweak-1920.png");
  31384. ui.setSize (1600, 900);
  31385. }
  31386. {
  31387. // the toolbar's edit mode (round 115): outlined panels and the tray of panels under it
  31388. ui.setToolbarLayoutForSnapshot (lynx::toolbarlayout::Layout::makeDefault());
  31389. auto layout = lynx::toolbarlayout::Layout::makeDefault();
  31390. layout.setShown (lynx::toolbarlayout::Group::meters, false);
  31391. ui.setToolbarLayoutForSnapshot (layout);
  31392. ui.setToolbarEditingForSnapshot (true);
  31393. offline.dispatchPendingMessages();
  31394. saveArea (ui, ui.getToolbarBoundsForSnapshot().withHeight (ui.getToolbarAndTrayHeightForSnapshot()), prefix + "-toolbar-edit-1600.png");
  31395. ui.setToolbarEditingForSnapshot (false);
  31396. // Ctrl+F11: only the menu and the hint bar
  31397. layout = lynx::toolbarlayout::Layout::makeDefault();
  31398. layout.visible = false;
  31399. ui.setToolbarLayoutForSnapshot (layout);
  31400. saveArea (ui, ui.getLocalBounds().withHeight (120), prefix + "-toolbar-hidden-1600.png");
  31401. }
  31402. ui.setToolbarLayoutForSnapshot (lynx::toolbarlayout::Layout::makeDefault());
  31403. // quick tips: the toolbar and title bars with a few name bubbles, and every tip on one sheet
  31404. offline.dispatchPendingMessages();
  31405. saveQuickTips (ui, prefix);
  31406. ui.setBounds (size);
  31407. offline.dispatchPendingMessages();
  31408. }
  31409. // the hint bar: a value control while it is dragged (live value), a gesture line with mouse and key
  31410. // glyphs, and a text too long for one line (two lines)
  31411. {
  31412. const auto toolbar = ui.getToolbarBoundsForSnapshot().withWidth (juce::jmin (ui.getWidth(), 900));
  31413. const lynx::ui::Hint hints[] = {
  31414. { lynx::tr ("Volume") + " - " + lynx::tr ("drag (Ctrl: fine), wheel, Alt+click resets"), "-3.2 dB", true, true },
  31415. { lynx::tr ("Piano Roll: [LMB] add a note, drag to move [RMB] delete [Ctrl][LMB] drag to select [Ctrl][Wheel] zoom"), {}, false, false },
  31416. { lynx::tr ("Global snap: the grid of the Piano Roll and Playlist (when they follow it) and the quantise of recorded notes "
  31417. "[LMB] choose [Wheel] step [RMB] length of new notes [Backspace] snap on/off [Alt] while dragging: no snap"), {}, false, true },
  31418. };
  31419. for (int i = 0; i < 3; ++i)
  31420. {
  31421. ui.setHintForSnapshot (hints[i], i == 0);
  31422. saveArea (ui, toolbar, prefix + "-hint-" + juce::String (i + 1) + ".png");
  31423. }
  31424. }
  31425. ui.showDesktopForSnapshot (true);
  31426. ui.setHintForSnapshot ({ lynx::tr ("Volume") + " - " + lynx::tr ("drag (Ctrl: fine), wheel, Alt+click resets"), "78%", true, true });
  31427. saveSnapshot (ui, prefix + "-desktop-all.png");
  31428. ui.selectTabForSnapshot (0);
  31429. saveSnapshot (ui, prefix + "-rack.png");
  31430. // round 190io (design190ia FM-10…14): steps on the first channels, audio clip channels included (they show
  31431. // their steps as in FL), a few selected rows, a muted channel; then the project as it was
  31432. {
  31433. const auto& kept = offline.getSong();
  31434. const auto keptSelection = offline.getSelectedChannels();
  31435. const auto keptPrimary = offline.getSelectedChannel();
  31436. const auto channels = (int) kept.channels.size();
  31437. offline.editSong ([channels] (lynx::Song& s) {
  31438. auto& p = s.activePattern();
  31439. for (int c = 0; c < juce::jmin (12, channels); ++c)
  31440. for (const auto step : { 0, 4 + (c % 3) * 2, 8, 12 + (c % 2) * 2 })
  31441. if (! p.hasStep (c, step))
  31442. p.toggleStep (c, step);
  31443. if (channels > 5)
  31444. s.channels[5].muted = true;
  31445. });
  31446. if (channels > 3)
  31447. offline.setChannelSelection ({ 1, 2, 3 }, 2);
  31448. offline.dispatchPendingMessages();
  31449. saveSnapshot (ui, prefix + "-rack190io-steps.png");
  31450. offline.undo(); // (one undo step: the project and its history as they were)
  31451. offline.setChannelSelection (keptSelection, keptPrimary);
  31452. offline.dispatchPendingMessages();
  31453. }
  31454. {
  31455. // a pattern with piano-roll notes: those rows show a miniature instead of steps (round 90)
  31456. int found = -1;
  31457. const auto before = offline.getSong().currentPattern;
  31458. {
  31459. const auto& song = offline.getSong();
  31460. for (int p = 0; p < (int) song.patterns.size() && found < 0; ++p)
  31461. for (int c = 0; c < (int) song.channels.size() && found < 0; ++c)
  31462. if (lynx::showsNotePreview (song.patterns[(std::size_t) p], c))
  31463. found = p;
  31464. }
  31465. if (found >= 0)
  31466. {
  31467. offline.editSong ([found] (lynx::Song& s) { s.currentPattern = found; }, false);
  31468. offline.dispatchPendingMessages();
  31469. saveSnapshot (ui, prefix + "-rack-preview.png");
  31470. offline.editSong ([before] (lynx::Song& s) { s.currentPattern = before; }, false);
  31471. offline.dispatchPendingMessages();
  31472. }
  31473. }
  31474. ui.selectTabForSnapshot (1);
  31475. saveSnapshot (ui, prefix + "-pianoroll.png");
  31476. {
  31477. // View › Keyboard style › Piano keys (round 190j, discussion #136), also with tall keys
  31478. auto& roll = ui.getPianoRollForSnapshot();
  31479. lynx::PianoRollComponent::keyStyle = lynx::pianokeys::Style::piano;
  31480. roll.repaint();
  31481. saveSnapshot (ui, prefix + "-pianoroll-pianokeys.png");
  31482. lynx::PianoRollComponent::keyStyle = lynx::pianokeys::Style::flat;
  31483. roll.repaint();
  31484. // round 190j (discussion #10): the toolbar in a narrow window: the chord stamp as an icon button, and
  31485. // the menu button still there
  31486. for (int narrower : { 150, 270, 330 })
  31487. {
  31488. roll.squeezeToolbarForSnapshot (narrower);
  31489. saveSnapshot (ui, prefix + "-pianoroll-narrow" + juce::String (narrower) + ".png");
  31490. roll.squeezeToolbarForSnapshot (-narrower);
  31491. }
  31492. }
  31493. if (const auto strip = ui.getToolStripAreaForSnapshot (false); ! strip.isEmpty())
  31494. saveArea (ui, strip, prefix + "-pianoroll-tools.png");
  31495. // the editors' mouse feel: the hovered note / clip edge (grip, outline) and its hint in the hint bar
  31496. ui.setHintForSnapshot (ui.getPianoRollForSnapshot().hoverForSnapshot());
  31497. saveSnapshot (ui, prefix + "-pianoroll-hover.png");
  31498. {
  31499. // a pattern with note Chance or a Velocity Range (round 187c): the Piano roll with those lanes
  31500. const auto& song = offline.getSong();
  31501. const auto& notes = song.patterns[(std::size_t) std::clamp (song.currentPattern, 0, (int) song.patterns.size() - 1)].notes;
  31502. if (std::any_of (notes.begin(), notes.end(), [] (const lynx::Note& n) { return n.hasChance(); }))
  31503. {
  31504. auto& roll = ui.getPianoRollForSnapshot();
  31505. ui.setHintForSnapshot ({});
  31506. for (const auto& [lane, name] : { std::pair { lynx::PianoRollComponent::laneChance, "chance" },
  31507. { lynx::PianoRollComponent::laneVelocityRange, "velrange" },
  31508. { lynx::PianoRollComponent::laneVelocity, "velocity" } })
  31509. {
  31510. roll.setLaneForSnapshot (lane);
  31511. offline.dispatchPendingMessages();
  31512. saveSnapshot (ui, prefix + "-pianoroll-" + name + ".png");
  31513. }
  31514. }
  31515. }
  31516. ui.selectTabForSnapshot (2);
  31517. saveSnapshot (ui, prefix + "-playlist.png");
  31518. if (const auto strip = ui.getToolStripAreaForSnapshot (true); ! strip.isEmpty())
  31519. saveArea (ui, strip, prefix + "-playlist-tools.png");
  31520. ui.setHintForSnapshot (ui.getPlaylistForSnapshot().hoverForSnapshot());
  31521. saveSnapshot (ui, prefix + "-playlist-hover.png");
  31522. ui.setHintForSnapshot ({ lynx::tr ("Volume") + " - " + lynx::tr ("drag (Ctrl: fine), wheel, Alt+click resets"), "78%", true, true });
  31523. // the Playlist with a time selection over bars 2-3 (it selects the clips it touches) and the Knife tool
  31524. ui.getPlaylistForSnapshot().setTimeSelectionForSnapshot (1, 3);
  31525. ui.getPlaylistForSnapshot().setToolForSnapshot (lynx::EditTool::knife);
  31526. offline.dispatchPendingMessages();
  31527. saveSnapshot (ui, prefix + "-playlist-timesel.png");
  31528. ui.getPlaylistForSnapshot().setToolForSnapshot (lynx::EditTool::pencil);
  31529. // round 177b: automation lanes on (two lanes under track 2: a volume ramp and a pan wobble)
  31530. {
  31531. const auto before = offline.getSong();
  31532. offline.editSong ([] (lynx::Song& s) {
  31533. s.loopStart = s.loopEnd = 0; // (no time selection in this one)
  31534. const auto bar = s.barTicks();
  31535. const auto vol = lynx::autolanes::addLane (s, 1, { lynx::AutomationTargetKind::mixerVolume, 1, 0, 0 }, "Insert 1 - Volume", 0.3f);
  31536. s.automations[(std::size_t) vol].points = { { 0, 0.3f, 0.0f }, { bar * 2, 0.8f, 0.4f }, { bar * 4, 0.6f, 0.0f } };
  31537. const auto pan = lynx::autolanes::addLane (s, 1, { lynx::AutomationTargetKind::mixerPan, 1, 0, 0 }, "Insert 1 - Pan", 0.5f);
  31538. 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 } };
  31539. }, false);
  31540. lynx::autolanes::setShown (true);
  31541. ui.getPlaylistForSnapshot().resized();
  31542. offline.dispatchPendingMessages();
  31543. saveSnapshot (ui, prefix + "-playlist-lanes.png");
  31544. lynx::autolanes::setShown (false);
  31545. offline.editSong ([before] (lynx::Song& s) { s = before; }, false);
  31546. offline.dispatchPendingMessages();
  31547. }
  31548. // round 104: a folded track group (FL's thin member rows) and the Picker's audio tab
  31549. {
  31550. int header = -1;
  31551. for (int t = 0; t < (int) offline.getSong().playlistTracks.size() && header < 0; ++t)
  31552. if (lynx::noteedit::isGroupHeader (offline.getSong(), t))
  31553. header = t;
  31554. if (header >= 0)
  31555. {
  31556. offline.editSong ([header] (lynx::Song& s) { lynx::noteedit::setGroupCollapsed (s, header, true); }, false);
  31557. offline.dispatchPendingMessages();
  31558. saveSnapshot (ui, prefix + "-playlist-group-folded.png");
  31559. offline.editSong ([header] (lynx::Song& s) { lynx::noteedit::setGroupCollapsed (s, header, false); }, false);
  31560. }
  31561. ui.getPickerForSnapshot().setView (1);
  31562. offline.dispatchPendingMessages();
  31563. saveSnapshot (ui, prefix + "-playlist-picker-audio.png");
  31564. ui.getPickerForSnapshot().setView (0);
  31565. }
  31566. // round 104: the Channel Rack filtered to its first filter group
  31567. if (! offline.getSong().channelGroups.empty())
  31568. {
  31569. ui.selectTabForSnapshot (0);
  31570. ui.getRackForSnapshot().setFilterGroup (0);
  31571. offline.dispatchPendingMessages();
  31572. saveSnapshot (ui, prefix + "-rack-filter.png");
  31573. ui.getRackForSnapshot().setFilterGroup (-1);
  31574. }
  31575. ui.selectTabForSnapshot (3);
  31576. // LYNX_SNAPSHOT_ARRANGE=1 (round 186c): Mixer menu › "Arrange inserts like the Playlist" first
  31577. if (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_ARRANGE", {}) == "1")
  31578. {
  31579. offline.editSong ([] (lynx::Song& s) { lynx::mixerops::arrangeLikePlaylist (s); });
  31580. offline.dispatchPendingMessages();
  31581. }
  31582. // LYNX_SNAPSHOT_TRACK=n: shows the effects of that mixer track
  31583. if (const auto track = juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_TRACK", {}); track.isNotEmpty())
  31584. {
  31585. ui.selectMixerTrackForSnapshot (track.getIntValue(),
  31586. juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SLOT", "-1").getIntValue());
  31587. offline.dispatchPendingMessages();
  31588. }
  31589. saveSnapshot (ui, prefix + "-mixer.png");
  31590. // round 190ir (Discord report, "it isnt picking up my audio input"): an armed insert without an input says so
  31591. // in its input box (record colour)
  31592. // (the first insert no channel plays into: armed without an input, it records silence)
  31593. {
  31594. const auto& song = offline.getSong();
  31595. auto target = -1;
  31596. for (int t = 1; t < (int) song.mixer.size() && target < 0; ++t)
  31597. if (song.mixer[(std::size_t) t].inputChannel < 0
  31598. && std::none_of (song.channels.begin(), song.channels.end(), [t] (const lynx::ChannelDef& c) { return c.mixerTrack == t; }))
  31599. target = t;
  31600. if (target > 0)
  31601. {
  31602. offline.setInsertArmed (target, true);
  31603. ui.selectMixerTrackForSnapshot (target, -1);
  31604. offline.dispatchPendingMessages();
  31605. saveSnapshot (ui, prefix + "-mixer190ir-armed-noinput.png");
  31606. offline.setInsertArmed (target, false);
  31607. offline.dispatchPendingMessages();
  31608. }
  31609. }
  31610. // round 190am: LYNX's two mixer extras, before and after (the demo project leaves most inserts unused). The
  31611. // loudness panel shows a real measurement of 12 s of a test tone (a 1 kHz sine at -14 dBFS after a quieter
  31612. // stretch, pushed through the Master's tap as the audio thread does)
  31613. {
  31614. auto& strips = ui.getMixerForSnapshot().getStripsForSnapshot();
  31615. saveSnapshot (ui, prefix + "-mixer190am-before.png");
  31616. strips.setShowUsedOnly (true);
  31617. offline.dispatchPendingMessages();
  31618. saveSnapshot (ui, prefix + "-mixer190am-usedonly.png");
  31619. strips.setShowUsedOnly (false);
  31620. strips.setShowLoudness (true);
  31621. {
  31622. const double sr = 48000.0;
  31623. std::vector<float> tone (480);
  31624. auto& tap = offline.getMeters().loudness;
  31625. for (int block = 0; block < 1200; ++block)
  31626. {
  31627. const auto gain = std::pow (10.0, (block < 400 ? -20.0 : -14.0) / 20.0);
  31628. for (int i = 0; i < 480; ++i)
  31629. tone[(std::size_t) i] = (float) (gain * std::sin (2.0 * juce::MathConstants<double>::pi * 1000.0 * (block * 480 + i) / sr));
  31630. tap.push (tone.data(), tone.data(), 480, sr);
  31631. }
  31632. }
  31633. strips.refreshLoudnessForSnapshot();
  31634. offline.dispatchPendingMessages();
  31635. saveSnapshot (ui, prefix + "-mixer190am-loudness.png");
  31636. for (const auto l : { lynx::mixerlayout::Layout::compact, lynx::mixerlayout::Layout::extraLarge })
  31637. {
  31638. const auto was = lynx::MixerStrips::layout;
  31639. strips.setLayout (l);
  31640. offline.dispatchPendingMessages();
  31641. saveSnapshot (ui, prefix + "-mixer190am-loudness-" + juce::String ((int) l) + ".png");
  31642. strips.setLayout (was);
  31643. }
  31644. strips.setShowUsedOnly (true);
  31645. offline.dispatchPendingMessages();
  31646. saveSnapshot (ui, prefix + "-mixer190am-both.png");
  31647. strips.setShowUsedOnly (false);
  31648. strips.setShowLoudness (false);
  31649. offline.dispatchPendingMessages();
  31650. }
  31651. // round 168h (issue #52): FL's 8 Mixer layouts
  31652. {
  31653. const auto before = lynx::MixerStrips::layout;
  31654. for (int l = 0; l < lynx::mixerlayout::layoutCount; ++l)
  31655. {
  31656. ui.getMixerForSnapshot().getStripsForSnapshot().setLayout ((lynx::mixerlayout::Layout) l);
  31657. offline.dispatchPendingMessages();
  31658. saveSnapshot (ui, prefix + "-mixer168h-" + juce::String (l) + ".png");
  31659. }
  31660. ui.getMixerForSnapshot().getStripsForSnapshot().setLayout (before);
  31661. offline.dispatchPendingMessages();
  31662. }
  31663. // round 163: the Mixer at short heights (UI zoom 150%+): the EQ folds, then the effects panel scrolls
  31664. {
  31665. const auto size = ui.getBounds();
  31666. for (auto h : { 450, 560, 680, 820 })
  31667. {
  31668. ui.setSize (size.getWidth(), h);
  31669. offline.dispatchPendingMessages();
  31670. saveSnapshot (ui, prefix + "-mixer163-" + juce::String (h) + ".png");
  31671. }
  31672. ui.setBounds (size);
  31673. offline.dispatchPendingMessages();
  31674. }
  31675. // round 170b (Busy Works Beats' review): inserts 1-3 selected and routed together to insert 4, a single effect
  31676. // moved down into slot 2 (FL's slot places), and the plugin menus grouped by category, LYNX SHARE first
  31677. {
  31678. const auto before = offline.getSong();
  31679. offline.editSong ([] (lynx::Song& s) {
  31680. if (s.mixer.size() < 5)
  31681. return;
  31682. s.mixer[1].effects.clear();
  31683. lynx::EffectSlot fx;
  31684. fx.kind = lynx::EffectKind::compressor;
  31685. s.mixer[1].effects.push_back (fx);
  31686. lynx::mixerops::moveEffectBy (s, 1, 0, 1);
  31687. lynx::mixerops::switchSelectedRoute (s, { 1, 2, 3 }, 4, true);
  31688. });
  31689. ui.selectMixerTrackForSnapshot (1);
  31690. ui.getMixerForSnapshot().getStripsForSnapshot().setSelection ({ 1, 2, 3 }, 1);
  31691. offline.dispatchPendingMessages();
  31692. saveSnapshot (ui, prefix + "-mixer170b.png");
  31693. juce::PopupMenu effects, generators;
  31694. lynx::quickpick::addFolderGroups (effects, offline, std::function<void (lynx::EffectSlot)> ([] (lynx::EffectSlot) {}));
  31695. lynx::quickpick::addFolderViewItems (effects, offline);
  31696. lynx::quickpick::addGeneratorMenu (generators, offline, [] (lynx::ChannelDef) {}, {}, nullptr, nullptr);
  31697. lynx::quickpick::addFolderViewItems (generators, offline);
  31698. saveMenus (juce::StringArray { "Mixer slot: add an effect", "Channel Rack: add" }, { effects, generators }, prefix + "-menus170b.png");
  31699. // round 190bf (fl190be Q3): the Channel Rack's "+" menu in FL's three views, with two root entries (plugins
  31700. // at the top of the database, in no folder) and the Categories / Simple / Tree switch at the end
  31701. {
  31702. auto& host = offline.getPluginHost();
  31703. const auto keep = host.databaseFolders();
  31704. auto folders = keep;
  31705. int added = 0;
  31706. for (const auto& e : lynx::quickpick::generatorEntries (offline))
  31707. if (e.folder == 3 && e.available && added < 2) // (installed plugins: FL's root entries are such)
  31708. {
  31709. folders.top.insert (e.key);
  31710. ++added;
  31711. }
  31712. for (const auto& e : lynx::quickpick::generatorEntries (offline))
  31713. if (e.folder != 3 && added < 2)
  31714. {
  31715. folders.top.insert (e.key);
  31716. ++added;
  31717. }
  31718. static const char* const views[] { "categories", "simple", "tree" };
  31719. for (int v = 0; v < 3; ++v)
  31720. {
  31721. folders.view = v;
  31722. host.setDatabaseFolders (folders);
  31723. juce::PopupMenu plus;
  31724. lynx::quickpick::addGeneratorMenu (plus, offline, [] (lynx::ChannelDef) {}, {}, nullptr, nullptr);
  31725. lynx::quickpick::addFolderViewItems (plus, offline);
  31726. saveMenus (juce::StringArray { juce::String ("Channel Rack +: ") + views[v] }, { plus }, prefix + "-menus190bf-" + views[v] + ".png");
  31727. }
  31728. host.setDatabaseFolders (keep);
  31729. }
  31730. offline.setSong (before);
  31731. offline.dispatchPendingMessages();
  31732. }
  31733. // standalone windows, with the theme background
  31734. auto saveWindow = [&prefix] (std::unique_ptr<juce::Component> c, const juce::String& name) {
  31735. juce::Component frame;
  31736. frame.setSize (c->getWidth(), c->getHeight());
  31737. frame.setOpaque (true);
  31738. // an AlertWindow is built on the desktop: shown there first, it would take the foreground from whoever has it
  31739. // (TopLevelWindow::visibilityChanged calls toFront (true)). Off the desktop, its control that showing it would
  31740. // have focused (what grabKeyboardFocus picks) is marked, so the picture keeps that control's focus ring
  31741. if (c->isOnDesktop())
  31742. {
  31743. c->removeFromDesktop();
  31744. auto* focus = c.get();
  31745. for (int depth = 0; focus != nullptr && depth < 32; ++depth)
  31746. {
  31747. if (focus->getWantsKeyboardFocus() && (focus->isEnabled() || focus == c.get()))
  31748. {
  31749. focus->getProperties().set ("lynxSnapshotFocus", true);
  31750. break;
  31751. }
  31752. auto traverser = focus->createKeyboardFocusTraverser();
  31753. focus = traverser != nullptr ? traverser->getDefaultComponent (focus) : nullptr;
  31754. }
  31755. }
  31756. frame.addAndMakeVisible (*c);
  31757. c->setTopLeftPosition (0, 0);
  31758. checkTextFit (*c, name.fromFirstOccurrenceOf ("-", false, false).upToLastOccurrenceOf (".", false, false));
  31759. auto image = lynx::shot::paint (frame, lynx::theme::panel);
  31760. const auto file = lynx::shot::file (juce::File (prefix + name));
  31761. file.deleteFile();
  31762. juce::PNGImageFormat png;
  31763. if (auto out = file.createOutputStream())
  31764. png.writeImageToStream (image, *out);
  31765. };
  31766. saveWindow (lynx::makeExportPanel (offline), "-export.png");
  31767. saveWindow (lynx::makeExportPanel (offline, 1), "-export-mp3.png");
  31768. saveWindow (lynx::makeExportPanel (offline, 3), "-export-flac-stems.png");
  31769. saveWindow (lynx::makeExportPanel (offline, 4), "-export-aiff.png"); // owner decision D5
  31770. if (lynx::aac::available())
  31771. saveWindow (lynx::makeExportPanel (offline, 5), "-export-m4a.png");
  31772. {
  31773. // REA round 165f-mixer: the mixer track's Track latency / routing submenus, Disk recording, PDC, and the
  31774. // Export window for "Render selected tracks to wave file(s)"
  31775. const auto before = offline.getSong();
  31776. offline.editSong ([] (lynx::Song& s) {
  31777. if (s.mixer.size() > 3)
  31778. {
  31779. s.mixer[1].latencyMs = 5.0f;
  31780. s.mixer[1].latencyBypass = lynx::LatencyBypass::whenRecordingOrStopped;
  31781. s.mixer[2].latencyMs = -1.5f;
  31782. }
  31783. });
  31784. offline.dispatchPendingMessages();
  31785. auto& strips = ui.getMixerForSnapshot().getStripsForSnapshot();
  31786. strips.setSelection ({ 1, 2, 3 }, 1);
  31787. const auto menu = strips.buildMenu (1);
  31788. juce::StringArray names { "Mixer track" };
  31789. std::vector<juce::PopupMenu> menus { menu };
  31790. const auto latencyPrefix = lynx::tr ("Track latency: {0}", { juce::String() });
  31791. const juce::String wanted[] = { lynx::tr ("Selected tracks ⇄ this track"), lynx::tr ("Disk recording"),
  31792. lynx::tr ("Plugin delay compensation") };
  31793. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  31794. {
  31795. const auto& item = it.getItem();
  31796. if (item.subMenu != nullptr && (item.text.startsWith (latencyPrefix) || std::find (std::begin (wanted), std::end (wanted), item.text) != std::end (wanted)))
  31797. {
  31798. names.add (item.text.upToFirstOccurrenceOf (":", false, false));
  31799. menus.push_back (*item.subMenu);
  31800. }
  31801. }
  31802. saveMenus (names, menus, prefix + "-menus165-mixer.png");
  31803. saveWindow (lynx::makeExportPanelForTracks (offline, { 1, 2, 3 }), "-export165-tracks.png");
  31804. offline.setSong (before);
  31805. offline.dispatchPendingMessages();
  31806. }
  31807. saveSplashFrames (prefix);
  31808. saveIconSheet (prefix + "-icons.png", 1.0f);
  31809. saveIconSheet (prefix + "-icons-150.png", 1.5f);
  31810. saveStateSheet (prefix + "-states190je.png", 1.0f); // round 190je: the one state rule, per button kind
  31811. saveStateSheet (prefix + "-states190je-z3.png", 3.0f);
  31812. saveWindow (lynx::MainComponent::makeHelpContent(), "-help.png");
  31813. saveWindow (lynx::ui::makeTrackIconGrid (5, {}), "-trackicons168h.png"); // round 168h: the icon picker
  31814. saveWindow (std::make_unique<lynx::toolbar::CustomizePanel> (lynx::toolbarlayout::Layout::makeDefault()), "-customize-toolbar.png");
  31815. // two moved controls: Tools › Last tweaked and Add › Automation for last tweaked parameter show them (REA round 143)
  31816. offline.noteTweaked ({ lynx::AutomationTargetKind::channelVolume, 0 });
  31817. offline.noteTweaked ({ lynx::AutomationTargetKind::mixerVolume, 0 });
  31818. saveMenus (ui, prefix + "-menus.png");
  31819. {
  31820. // the windows' own menus (title bars) and the toolbar's recording menu
  31821. juce::StringArray names;
  31822. std::vector<juce::PopupMenu> menus;
  31823. for (auto [panel, name] : { std::pair { lynx::workspace::Panel::playlist, "Playlist" }, { lynx::workspace::Panel::channelRack, "Channel Rack" },
  31824. { lynx::workspace::Panel::pianoRoll, "Piano Roll" }, { lynx::workspace::Panel::mixer, "Mixer" },
  31825. { lynx::workspace::Panel::browser, "Browser" } })
  31826. {
  31827. names.add (name);
  31828. menus.push_back (ui.getPanelMenuForSnapshot (panel));
  31829. }
  31830. names.add ("Recording");
  31831. menus.push_back (ui.getRecordMenuForSnapshot());
  31832. names.add ("Toolbar");
  31833. menus.push_back (ui.getToolbarMenuForSnapshot());
  31834. saveMenus (names, menus, prefix + "-panel-menus.png");
  31835. }
  31836. // round 189e: the Playlist menu's Edit and Select submenus (FL's items and order) and the header drop question
  31837. saveMenus (juce::StringArray { "Playlist: Edit", "Playlist: Select" },
  31838. std::vector<juce::PopupMenu> { ui.getPlaylistForSnapshot().editMenu(), ui.getPlaylistForSnapshot().selectMenu() },
  31839. prefix + "-playlist-edit189e.png");
  31840. saveWindow (lynx::PlaylistComponent::makeHeaderDropDialog(), "-header-drop189e.png");
  31841. {
  31842. // round 189i: FL's fade handle menu (right-click on an audio clip's fade handle), on the song's first audio
  31843. // clip, or on one added for the shot
  31844. const auto before = offline.getSong();
  31845. auto clipIndex = -1;
  31846. for (std::size_t i = 0; i < before.playlist.size() && clipIndex < 0; ++i)
  31847. if (before.playlist[i].kind == lynx::ClipKind::audio)
  31848. clipIndex = (int) i;
  31849. if (clipIndex < 0)
  31850. {
  31851. auto song = before;
  31852. lynx::ChannelDef channel;
  31853. channel.instrument = lynx::InstrumentKind::audioClip;
  31854. channel.name = "Audio clip";
  31855. song.channels.push_back (channel);
  31856. lynx::Clip clip;
  31857. clip.kind = lynx::ClipKind::audio;
  31858. clip.channel = (int) song.channels.size() - 1;
  31859. clip.length = lynx::ppq * 4;
  31860. song.playlist.push_back (clip);
  31861. clipIndex = (int) song.playlist.size() - 1;
  31862. offline.setSong (song);
  31863. offline.dispatchPendingMessages();
  31864. }
  31865. saveMenus (juce::StringArray { "Fade handle" },
  31866. std::vector<juce::PopupMenu> { ui.getPlaylistForSnapshot().fadeHandleMenu (clipIndex, 1) },
  31867. prefix + "-fade-handle189i.png");
  31868. if (offline.getSong().playlist.size() != before.playlist.size())
  31869. {
  31870. offline.setSong (before);
  31871. offline.dispatchPendingMessages();
  31872. }
  31873. }
  31874. {
  31875. // round 189n: FL's gain handle menu with two overlapping clips selected (Normalize selection individually / as a
  31876. // group) and the later clip's fade in menu (Create crossfade enabled); FL shots in /mnt/e/lynx-work/flgap189n
  31877. const auto before = offline.getSong();
  31878. auto song = before;
  31879. lynx::ChannelDef channel;
  31880. channel.instrument = lynx::InstrumentKind::audioClip;
  31881. channel.name = "Audio clip";
  31882. song.channels.push_back (channel);
  31883. int lane = 0;
  31884. for (const auto& c : song.playlist)
  31885. lane = std::max (lane, c.track + 1);
  31886. for (int k = 0; k < 2; ++k)
  31887. {
  31888. lynx::Clip clip;
  31889. clip.kind = lynx::ClipKind::audio;
  31890. clip.channel = (int) song.channels.size() - 1;
  31891. clip.track = lane;
  31892. clip.start = k * lynx::ppq * 3;
  31893. clip.length = lynx::ppq * 4;
  31894. song.playlist.push_back (clip);
  31895. }
  31896. const auto second = (int) song.playlist.size() - 1;
  31897. song.autoCrossfades = true; // FL's capture: Thief has Automatic crossfades on
  31898. offline.setSong (song);
  31899. offline.dispatchPendingMessages();
  31900. auto& playlist = ui.getPlaylistForSnapshot();
  31901. playlist.selectForSnapshot ({ second - 1, second });
  31902. auto gain = playlist.gainMenu (second);
  31903. auto fadeIn = playlist.fadeHandleMenu (second, 0); // (both selected, as in FL's capture)
  31904. playlist.selectForSnapshot ({});
  31905. saveMenus (juce::StringArray { "Gain handle, 2 selected", "Fade in, overlapping" },
  31906. std::vector<juce::PopupMenu> { gain, fadeIn }, prefix + "-fade-gain189n.png");
  31907. // round 189o: the audio clip menu with both overlapping clips selected (FL's Fades › Crossfade selected
  31908. // shown) and with none selected (hidden)
  31909. playlist.selectForSnapshot ({ second - 1, second });
  31910. auto clipSelected = playlist.getClipMenuForSnapshot (second);
  31911. playlist.selectForSnapshot ({});
  31912. auto clipAlone = playlist.getClipMenuForSnapshot (second);
  31913. saveMenus (juce::StringArray { "Audio clip, 2 selected", "Audio clip, none selected" },
  31914. std::vector<juce::PopupMenu> { clipSelected, clipAlone }, prefix + "-xfadesel189o.png");
  31915. offline.setSong (before);
  31916. offline.dispatchPendingMessages();
  31917. }
  31918. {
  31919. // REA round 143: the piano roll Tools menu, a Playlist track menu and a mixer insert menu (FL's layouts)
  31920. std::vector<juce::PopupMenu> menus { ui.getPianoRollForSnapshot().getToolsMenuForSnapshot(),
  31921. ui.getPlaylistForSnapshot().getTrackMenuForSnapshot (0),
  31922. ui.getMixerForSnapshot().getStripsForSnapshot().buildMenu (1) };
  31923. saveMenus (juce::StringArray { "Piano roll tools", "Playlist track", "Mixer track" }, menus, prefix + "-menus143.png");
  31924. // round 190as: the Piano roll's scripts (FL's Tools › Scripts column) and a script's form
  31925. saveMenus (juce::StringArray { "Piano roll scripts" }, std::vector<juce::PopupMenu> { ui.getPianoRollForSnapshot().getScriptsMenuForSnapshot() },
  31926. prefix + "-prscripts-menu.png");
  31927. {
  31928. lynx::prscript::Score score;
  31929. const auto out = lynx::prscript::run (lynx::prscript::builtins().front().source, score, {});
  31930. if (out.status == lynx::prscript::Outcome::Status::needsForm)
  31931. {
  31932. lynx::ScriptPanel::Options options;
  31933. options.acceptText = lynx::tr ("Accept");
  31934. saveWindow (std::make_unique<lynx::ScriptPanel> (out.form, [] (const lynx::scriptform::Form&) {}, [] (const lynx::scriptform::Form&) {},
  31935. nullptr, options),
  31936. "-prscript-form.png");
  31937. }
  31938. }
  31939. // round 190j (discussion #10): the Piano roll menu's Chord stamp list
  31940. saveMenus (juce::StringArray { "Chord stamp" }, std::vector<juce::PopupMenu> { ui.getPianoRollForSnapshot().getStampMenuForSnapshot() },
  31941. prefix + "-stamp-menu.png");
  31942. // round 167l: the channel menu ("Lock active/mute state")
  31943. if (! offline.getSong().channels.empty())
  31944. saveMenus (juce::StringArray { "Channel" }, std::vector<juce::PopupMenu> { ui.getRackForSnapshot().getChannelMenuForSnapshot (0) }, prefix + "-channel-menu.png");
  31945. // round 163: menu density, compact (default) and comfortable, on a Browser folder menu
  31946. {
  31947. juce::PopupMenu folder;
  31948. folder.addSectionHeader ("Documents");
  31949. folder.addItem (1, "Expand all");
  31950. folder.addItem (2, "Collapse all");
  31951. folder.addSeparator();
  31952. folder.addItem (3, "Refresh");
  31953. folder.addSectionHeader ("System");
  31954. folder.addItem (4, "Open");
  31955. folder.addItem (5, "Copy the file path");
  31956. folder.addSectionHeader ("Tags");
  31957. folder.addItem (6, "Starred", true, true);
  31958. folder.addSeparator();
  31959. folder.addItem (7, "Add folder...");
  31960. const auto wasCompact = lynx::theme::menus::compact();
  31961. lynx::theme::menus::setCompact (true);
  31962. saveMenus (juce::StringArray { "Compact" }, { folder }, prefix + "-menu163-compact.png");
  31963. lynx::theme::menus::setCompact (false);
  31964. saveMenus (juce::StringArray { "Comfortable" }, { folder }, prefix + "-menu163-comfortable.png");
  31965. lynx::theme::menus::setCompact (wasCompact);
  31966. }
  31967. // and the clip menus of the first pattern, audio and automation clips of the project
  31968. juce::StringArray clipNames;
  31969. std::vector<juce::PopupMenu> clipMenus;
  31970. for (auto [kind, name] : { std::pair { lynx::ClipKind::pattern, "Pattern clip" }, { lynx::ClipKind::audio, "Audio clip" },
  31971. { lynx::ClipKind::automation, "Automation clip" } })
  31972. for (int c = 0; c < (int) offline.getSong().playlist.size(); ++c)
  31973. if (offline.getSong().playlist[(std::size_t) c].kind == kind)
  31974. {
  31975. clipNames.add (name);
  31976. clipMenus.push_back (ui.getPlaylistForSnapshot().getClipMenuForSnapshot (c));
  31977. break;
  31978. }
  31979. if (! clipMenus.empty())
  31980. saveMenus (clipNames, clipMenus, prefix + "-menus143-clips.png");
  31981. }
  31982. auto saveAlert = [&] (std::unique_ptr<juce::AlertWindow> alert, const juce::String& name) {
  31983. alert->setOpaque (true);
  31984. saveWindow (std::move (alert), name);
  31985. };
  31986. saveAlert (ui.makeConfirmDiscardWindow(), "-confirm.png");
  31987. saveAlert (lynx::MainComponent::makeAboutWindow(), "-about.png");
  31988. saveAlert (lynx::support::makeSupportWindow(), "-support.png"); // round 190fq: Help › Support LYNX SHARE...
  31989. saveAlert (lynx::makeNameAndColourDialog (lynx::tr ("Rename pattern"), "Pattern 2", lynx::lynxPalette()[6]), "-rename.png");
  31990. saveAlert (lynx::makeRecordChoiceDialog(), "-record-dialog.png");
  31991. // round 190ah: Online Sessions — a guest's "go back in?" at start-up, the host's question at a guest's file limit
  31992. saveAlert (lynx::liveui::makeRejoinDialog ("Ana", juce::Time (2026, 10, 10, 21, 40).toString (true, true, false, true)), "-live-rejoin.png");
  31993. saveAlert (lynx::liveui::makeMediaLimitDialog ("Pedro", (juce::int64) 1010 << 20, (juce::int64) 1 << 30), "-live-media-limit.png");
  31994. saveAlert (lynx::makeSamplePitchDialog (7.25f, true, true), "-sample-pitch.png"); // round 163c
  31995. saveAlert (lynx::makeGradientColourDialog (juce::Colour (0xffe5383b), juce::Colour (0xff3a7bd5), 8), "-gradient.png"); // round 177a
  31996. saveAlert (lynx::makeMidiImportDialog(), "-midi-import-dialog.png"); // File › Import › MIDI file (REA round 143)
  31997. // round 186c: FL's mixer "Delete" questions and its Settings › General › Manage messages menu
  31998. saveAlert (lynx::makeFlMessageDialog ({ lynx::tr ("Delete tracks"), lynx::tr ("This will |delete| {0} selected mixer track(s). Are you sure?", { "1" }),
  31999. { lynx::tr ("Yes"), lynx::tr ("No") }, true }),
  32000. "-delete-tracks.png");
  32001. saveAlert (lynx::makeFlMessageDialog ({ lynx::tr ("Playlist tracks"),
  32002. lynx::tr ("One or more mixer tracks that will be deleted are connected to instrument/audio tracks.") + "\n"
  32003. + lynx::tr ("Do you want to unlink the tracks and channels or delete them?"),
  32004. { lynx::tr ("Delete tracks and channels"), lynx::tr ("Unlink tracks and channels"), lynx::tr ("Cancel") }, false }),
  32005. "-delete-tracks-linked.png");
  32006. saveMenus (juce::StringArray { "Manage messages" }, std::vector<juce::PopupMenu> { lynx::messages::manageMenu() }, prefix + "-manage-messages.png");
  32007. saveWindow (lynx::makeSetupWizardContent (offline, {}, {}), "-setup.png");
  32008. saveWindow (lynx::crashreporter::makeDialogForSnapshot (false), "-crash-report.png"); // round 159
  32009. saveWindow (lynx::crashreporter::makeDialogForSnapshot (true), "-report-problem.png");
  32010. // round 166b: the update bar in its states (available, downloading, failed, ready) and the release notes window
  32011. {
  32012. struct Bars final : juce::Component
  32013. {
  32014. Bars()
  32015. {
  32016. constexpr int h = lynx::updater::UpdateBar::height;
  32017. setSize (1100, 6 * (h + 6));
  32018. for (int state = 0; state < 6; ++state) // (round 190gh: 4 going back, 5 went back)
  32019. {
  32020. bars[state].setBounds (0, state * (h + 6), getWidth(), h);
  32021. bars[state].showForSnapshot (state);
  32022. addAndMakeVisible (bars[state]);
  32023. }
  32024. }
  32025. lynx::updater::UpdateBar bars[6];
  32026. };
  32027. saveWindow (std::make_unique<Bars>(), "-update-bar.png");
  32028. saveWindow (lynx::updater::makeReleaseNotesForSnapshot(), "-update-notes.png");
  32029. // round 190gh (B23): Help › Test audio output... in its states
  32030. for (int state = 0; state < 5; ++state)
  32031. saveWindow (lynx::makeAudioCheckForSnapshot (offline, state), "-audio-check-" + juce::String (state) + ".png");
  32032. }
  32033. saveWindow (lynx::makeMissingFilesPanel (lynx::missingFilesSnapshotInfo(), 0, 1), "-missing-files.png");
  32034. saveWindow (lynx::makeMissingFilesPanel (lynx::missingFilesSnapshotInfo(), 1), "-missing-plugins.png");
  32035. saveWindow (lynx::makeMissingFilesPanel (lynx::missingFilesSnapshotInfo(), 2), "-missing-found.png");
  32036. {
  32037. // the Settings pages, with credits like a project imported from FL would carry
  32038. offline.editSong ([] (lynx::Song& s) {
  32039. s.info = { "Night Drive", "LYNX SHARE demo", "Synthwave", "https://lynx-share.com",
  32040. "Made with LYNX SHARE.\nDrums and bass from the Channel Rack, pads from the Browser.", false };
  32041. }, false);
  32042. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::project), "-settings-project.png");
  32043. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::info), "-settings-info.png");
  32044. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::files), "-settings-files.png");
  32045. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::general), "-settings-general.png");
  32046. {
  32047. // round 189o: the whole General page (the Editing and Plugins sections hold FL's "Monophonic painting in
  32048. // piano roll" and "Limit the number of open plugin editors")
  32049. auto tall = lynx::makeSettingsPanel (offline, lynx::SettingsPage::general);
  32050. tall->setSize (tall->getWidth(), 3200);
  32051. saveWindow (std::move (tall), "-settings-general-tall189o.png");
  32052. }
  32053. {
  32054. // the whole General page (round 186a: the Startup section is below the first screen)
  32055. auto tall = lynx::makeSettingsPanel (offline, lynx::SettingsPage::general);
  32056. tall->setSize (tall->getWidth(), 1500);
  32057. saveWindow (std::move (tall), "-settings-general-tall.png");
  32058. }
  32059. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::theme), "-settings-theme.png");
  32060. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::extras), "-settings-extras.png"); // round 190am
  32061. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::audio), "-settings-audio.png");
  32062. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::midi), "-settings-midi.png");
  32063. {
  32064. // round 190bj (QA): the MIDI page in a small window keeps each row's switch and device name
  32065. auto small = lynx::makeSettingsPanel (offline, lynx::SettingsPage::midi);
  32066. small->setSize (390, 390);
  32067. saveWindow (std::move (small), "-settings-midi-small.png");
  32068. }
  32069. {
  32070. // round 190bj (QA): the Apex Limiter's window content at its default size, as sized before (JUCE's ratio
  32071. // on the whole window: the status row cut off) and now
  32072. lynx::AudioEngine apexEngine (false);
  32073. lynx::Song song;
  32074. song.mixer.resize (2);
  32075. song.mixer[0].name = "Master";
  32076. song.mixer[1].name = "Insert 1";
  32077. song.mixer[1].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::apexLimiter));
  32078. apexEngine.setSong (std::move (song));
  32079. apexEngine.dispatchPendingMessages();
  32080. savePng (lynx::ProEditorWindows::windowContentForSnapshot (apexEngine, 1, 0, true), prefix + "-apex-window-before190bj.png");
  32081. savePng (lynx::ProEditorWindows::windowContentForSnapshot (apexEngine, 1, 0, false), prefix + "-apex-window.png");
  32082. }
  32083. saveWindow (lynx::makePluginManagerPanel (offline, false), "-plugin-manager.png");
  32084. // round 190gg: the crash prompt and a plugin window's crash notice, with "Always run ... in a separate process"
  32085. saveWindow (lynx::PluginWindows::makeCrashPromptPanel ("Serum", false), "-plugin-crash-prompt.png");
  32086. saveWindow (lynx::PluginWindows::makeCrashNoticePanel ("Serum", true), "-plugin-crash-notice.png");
  32087. saveWindow (lynx::makeShortcutManagerPanel (false), "-shortcuts.png");
  32088. }
  32089. {
  32090. // round 84: New project, Clip properties, Arrangements, Plugin performance monitor, Touch keyboard
  32091. saveWindow (lynx::makeNewProjectPanel(), "-new-project.png");
  32092. const auto& clips = offline.getSong().playlist;
  32093. for (int i = 0; i < (int) clips.size(); ++i)
  32094. if (clips[(std::size_t) i].kind == lynx::ClipKind::pattern)
  32095. {
  32096. saveWindow (lynx::makeClipPropertiesPanel (offline, i, { i, (i + 1) % (int) clips.size() }), "-clip-properties.png");
  32097. break;
  32098. }
  32099. for (int i = 0; i < (int) clips.size(); ++i)
  32100. if (clips[(std::size_t) i].kind == lynx::ClipKind::audio)
  32101. {
  32102. saveWindow (lynx::makeClipPropertiesPanel (offline, i, { i }), "-clip-properties-audio.png");
  32103. break;
  32104. }
  32105. if (offline.getSong().arrangements.size() < 2)
  32106. offline.editSong ([] (lynx::Song& s) {
  32107. const auto current = s.currentArrangement;
  32108. s.addArrangement ("Radio edit", true);
  32109. s.addArrangement ("Intro loop");
  32110. s.selectArrangement (current);
  32111. }, false);
  32112. saveWindow (lynx::makeArrangementsPanel (offline), "-arrangements.png");
  32113. saveWindow (lynx::makePluginMonitorPanel (offline), "-plugin-monitor.png");
  32114. saveWindow (lynx::makeTouchKeyboardPanel (offline), "-touch-keyboard.png");
  32115. }
  32116. {
  32117. // round 142: the Newtone / Newtime editors on a synthetic sung line (A3 B3 C4 · E4), one note moved
  32118. const auto wav = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-snapshot-newtone.wav");
  32119. {
  32120. juce::AudioBuffer<float> line (1, 44100 * 2);
  32121. const double hz[] = { 220.0, 246.94, 261.63, 0.0, 329.63 };
  32122. double ph = 0.0;
  32123. for (int i = 0; i < line.getNumSamples(); ++i)
  32124. {
  32125. const auto f0 = hz[std::min (4, i / 17640)];
  32126. 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;
  32127. float v = 0.0f;
  32128. for (int h = 1; f0 > 0.0 && h < 8; ++h)
  32129. v += (float) (0.3 / h * std::sin (h * ph));
  32130. line.setSample (0, i, v);
  32131. }
  32132. wav.deleteFile();
  32133. juce::WavAudioFormat format;
  32134. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  32135. if (auto* w = out != nullptr ? format.createWriterFor (out.get(), 44100.0, 1, 16, {}, 0) : nullptr)
  32136. {
  32137. out.release();
  32138. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  32139. writer->writeFromAudioSampleBuffer (line, 0, line.getNumSamples());
  32140. }
  32141. }
  32142. if (const auto sample = offline.getSampleLibrary().load (wav.getFullPathName()))
  32143. {
  32144. auto notes = lynx::newtonefx::analyseNotes (*sample);
  32145. if (notes.pitches.size() > 1)
  32146. notes.pitches[1].shift = 2.0;
  32147. lynx::newtonefx::WarpMap warp;
  32148. warp.frames = (std::int64_t) sample->frames();
  32149. warp.markers = { { 22050, 33075 } };
  32150. int at = 0;
  32151. offline.editSong ([&] (lynx::Song& song) {
  32152. if (song.mixer.size() < 2)
  32153. song.mixer.resize (2);
  32154. auto& fx = song.mixer[1].effects;
  32155. auto tone = lynx::makeEffectSlot (lynx::EffectKind::newtone);
  32156. tone.samplePath = wav.getFullPathName().toStdString();
  32157. tone.state = lynx::newtonefx::writeNative (notes);
  32158. auto time = lynx::makeEffectSlot (lynx::EffectKind::newtime);
  32159. time.samplePath = tone.samplePath;
  32160. time.state = lynx::newtonefx::writeWarp (warp);
  32161. at = (int) fx.size();
  32162. fx.push_back (tone);
  32163. fx.push_back (time);
  32164. }, false);
  32165. saveWindow (lynx::makeNewtoneEditor (offline, 1, at), "-newtone.png");
  32166. saveWindow (lynx::makeNewtoneEditor (offline, 1, at + 1), "-newtime.png");
  32167. offline.editSong ([at] (lynx::Song& song) {
  32168. auto& fx = song.mixer[1].effects;
  32169. fx.erase (fx.begin() + at, fx.begin() + at + 2);
  32170. }, false);
  32171. }
  32172. }
  32173. if (! offline.getSong().automations.empty())
  32174. {
  32175. auto editor = lynx::makeAutomationEditor (offline, 0);
  32176. editor->setSize (760, 300);
  32177. saveWindow (std::move (editor), "-automation.png");
  32178. // round 177b: the same clip in FL's LFO mode: FL's defaults, then one shaped state (the UI gate pairs)
  32179. const auto before = offline.getSong().automations[0].lfo;
  32180. const auto lfoShot = [&offline, &saveWindow] (std::function<void (lynx::AutomationLfo&)> set, const char* suffix) {
  32181. offline.editSong ([&set] (lynx::Song& song) {
  32182. auto& lfo = song.automations[0].lfo;
  32183. lfo = lynx::AutomationLfo {};
  32184. lfo.on = true;
  32185. set (lfo);
  32186. }, false);
  32187. auto lfoEditor = lynx::makeAutomationEditor (offline, 0);
  32188. lfoEditor->setSize (760, 346);
  32189. saveWindow (std::move (lfoEditor), suffix);
  32190. };
  32191. lfoShot ([] (lynx::AutomationLfo&) {}, "-automation-lfo.png");
  32192. lfoShot ([] (lynx::AutomationLfo& lfo) {
  32193. // the state set through FL's own UI for the UI gate (TNS 50 %, SKEW 25 %, PW 25 %, two points), as FL saved it
  32194. lfo.tension = 64;
  32195. lfo.skew = 32;
  32196. lfo.pulseWidth = 28;
  32197. lfo.amp = { { 0, 0.6716f, 0.0f }, { (std::int64_t) (lynx::ppq * 1.4128), 0.9204f, 0.0f } };
  32198. }, "-automation-lfo-shape.png");
  32199. offline.editSong ([before] (lynx::Song& song) { song.automations[0].lfo = before; }, false);
  32200. }
  32201. // round 177b: LYNX's modulators window, with one routed modulator
  32202. {
  32203. offline.editSong ([] (lynx::Song& song) {
  32204. lynx::Modulator m;
  32205. m.name = "LFO 1";
  32206. m.shape = lynx::ModShape::triangle;
  32207. m.routes = { { { lynx::AutomationTargetKind::mixerVolume, 1, 0, 0 }, 0.25f }, { { lynx::AutomationTargetKind::mixerPan, 1, 0, 0 }, -0.5f } };
  32208. song.modulators.push_back (m);
  32209. lynx::Modulator r;
  32210. r.name = "LFO 2";
  32211. r.shape = lynx::ModShape::smoothRandom;
  32212. r.sync = false;
  32213. r.hz = 0.5;
  32214. song.modulators.push_back (r);
  32215. }, false);
  32216. auto mods = lynx::makeModulatorsPanel (offline);
  32217. mods->setSize (720, 360);
  32218. saveWindow (std::move (mods), "-modulators.png");
  32219. offline.editSong ([] (lynx::Song& song) { song.modulators.clear(); }, false);
  32220. }
  32221. saveWindow (lynx::makeChannelSettingsPanel (offline, 0), "-sampler.png");
  32222. // the channel window frame (REA round 143b): header strip + tabs; the Misc tab of the first channel and of a synth
  32223. saveWindow (lynx::makeChannelFrame (offline, 0), "-channel-frame.png");
  32224. saveWindow (lynx::makeChannelFrame (offline, 0, -1), "-channel-misc.png");
  32225. for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
  32226. if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::synth)
  32227. {
  32228. saveWindow (lynx::makeChannelSettingsPanel (offline, c), "-synth.png");
  32229. saveWindow (lynx::makeChannelModulationPanel (offline, c), "-modulation.png");
  32230. break;
  32231. }
  32232. for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
  32233. if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::controller)
  32234. {
  32235. saveWindow (lynx::makeChannelSettingsPanel (offline, c), "-controller.png");
  32236. break;
  32237. }
  32238. for (const auto kind : { lynx::InstrumentKind::sakura, lynx::InstrumentKind::drumpad })
  32239. for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
  32240. if (offline.getSong().channels[(std::size_t) c].instrument == kind)
  32241. {
  32242. saveWindow (lynx::makeChannelSettingsPanel (offline, c), kind == lynx::InstrumentKind::sakura ? "-sakura.png" : "-drumpad.png");
  32243. break;
  32244. }
  32245. // round 180c: Fruity Slicer's editor
  32246. for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
  32247. if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::fruityslicer)
  32248. {
  32249. saveWindow (lynx::makeChannelSettingsPanel (offline, c), "-fruityslicer.png");
  32250. // rounds 190f / 190m: its Envelope / instrument page, one picture per target
  32251. saveWindow (lynx::makeChannelFrame (offline, c, 1), "-fruityslicer-envelope.png");
  32252. for (const auto& [target, name] : std::vector<std::pair<int, const char*>> { { 0, "panning" }, { 2, "modx" }, { 3, "mody" }, { 4, "pitch" } })
  32253. {
  32254. auto frame = lynx::makeChannelFrame (offline, c, 1);
  32255. lynx::showFlVoiceTarget (*frame, target);
  32256. saveWindow (std::move (frame), juce::String ("-fruityslicer-envelope-") + name + ".png");
  32257. }
  32258. break;
  32259. }
  32260. // round 190r: Slicex's editor
  32261. for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
  32262. if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::slicex)
  32263. {
  32264. saveWindow (lynx::makeChannelSettingsPanel (offline, c), "-slicex.png");
  32265. break;
  32266. }
  32267. // round 190q: FPC's editor
  32268. for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
  32269. if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::fpc)
  32270. {
  32271. saveWindow (lynx::makeChannelSettingsPanel (offline, c), "-fpc.png");
  32272. break;
  32273. }
  32274. // round 190hz: DirectWave's editor
  32275. for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
  32276. if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::directwave)
  32277. {
  32278. saveWindow (lynx::makeChannelSettingsPanel (offline, c), "-directwave.png");
  32279. break;
  32280. }
  32281. // parametric EQ: the one with the most pronounced curve (in an imported .flp, with FL's settings)
  32282. {
  32283. int bestTrack = -1, bestSlot = -1;
  32284. double bestShape = -1.0;
  32285. const auto& mixer = offline.getSong().mixer;
  32286. for (int t = 0; t < (int) mixer.size(); ++t)
  32287. for (int s = 0; s < (int) mixer[(std::size_t) t].effects.size(); ++s)
  32288. if (const auto& fx = mixer[(std::size_t) t].effects[(std::size_t) s]; fx.kind == lynx::EffectKind::parametricEq)
  32289. {
  32290. double shape = 0.0;
  32291. for (double hz = 30.0; hz < 18000.0; hz *= 1.5)
  32292. shape += std::abs (lynx::peq::responseDb (fx.params, 48000.0, hz));
  32293. if (shape > bestShape)
  32294. {
  32295. bestShape = shape;
  32296. bestTrack = t;
  32297. bestSlot = s;
  32298. }
  32299. }
  32300. if (bestTrack >= 0)
  32301. saveWindow (lynx::makeParametricEqEditor (offline, bestTrack, bestSlot), "-peq.png");
  32302. }
  32303. // Note inspector for the Piano Roll's notes (its selection, or all of the channel's notes)
  32304. if (auto inspector = ui.getPianoRollForSnapshot().makeNoteInspectorForSnapshot())
  32305. saveWindow (std::move (inspector), "-noteinspector.png");
  32306. if (auto inspector = ui.getPianoRollForSnapshot().makeNoteInspectorForSnapshot (true))
  32307. saveWindow (std::move (inspector), "-noteinspector-one.png");
  32308. // workflow P2: note tool dialogs (they preview on the pattern; each one puts the notes back when destroyed)
  32309. {
  32310. auto& roll = ui.getPianoRollForSnapshot();
  32311. const std::pair<lynx::NoteTool, const char*> tools[] = { { lynx::NoteTool::strum, "-tool-strum.png" },
  32312. { lynx::NoteTool::arpeggiate, "-tool-arpeggiate.png" },
  32313. { lynx::NoteTool::flip, "-tool-flip.png" },
  32314. { lynx::NoteTool::randomise, "-tool-randomise.png" },
  32315. { lynx::NoteTool::scaleLevels, "-tool-scalelevels.png" },
  32316. { lynx::NoteTool::limit, "-tool-limit.png" },
  32317. { lynx::NoteTool::quantize, "-tool-quantize.png" },
  32318. { lynx::NoteTool::chop, "-tool-chop.png" },
  32319. { lynx::NoteTool::flam, "-tool-flam.png" },
  32320. { lynx::NoteTool::lfo, "-tool-lfo.png" },
  32321. { lynx::NoteTool::claw, "-tool-claw.png" },
  32322. { lynx::NoteTool::articulate, "-tool-articulate.png" },
  32323. { lynx::NoteTool::riffMachine, "-tool-riff.png" },
  32324. { lynx::NoteTool::chordProgression, "-tool-chords.png" } };
  32325. for (const auto& [tool, name] : tools)
  32326. saveWindow (lynx::makeNoteToolPanel (offline, tool, roll.noteIndicesForSnapshot(), roll.gridForSnapshot()), name);
  32327. }
  32328. // round 83: the event editor, with sample events on the selected channel's volume (removed afterwards)
  32329. {
  32330. const lynx::AutomationTarget volume { lynx::AutomationTargetKind::channelVolume, offline.getSelectedChannel() };
  32331. const auto before = offline.getSong().patterns[(std::size_t) offline.getSong().currentPattern].events;
  32332. offline.editSong ([&] (lynx::Song& s) {
  32333. auto& lane = lynx::eventedit::laneFor (s.patterns[(std::size_t) s.currentPattern], volume);
  32334. lynx::eventedit::line (lane, 0, lynx::ppq * 2, 0.2f, 0.9f, lynx::ticksPerStep);
  32335. lynx::prtools::LfoOptions lfo;
  32336. lfo.startSpeed = 7 * 4096; // one beat
  32337. lynx::eventedit::applyLfo (lane, lynx::ppq * 2, lynx::ppq * 4, lfo, lynx::ticksPerStep);
  32338. }, false);
  32339. saveWindow (lynx::makeEventEditor (offline, volume), "-eventeditor.png");
  32340. offline.editSong ([&] (lynx::Song& s) { s.patterns[(std::size_t) s.currentPattern].events = before; }, false);
  32341. // issue #86: the same editor on the Tempo target, with the project's own Tempo events (a sample ramp if none)
  32342. const lynx::AutomationTarget tempo { lynx::AutomationTargetKind::tempo, 0 };
  32343. offline.editSong ([&] (lynx::Song& s) {
  32344. auto& lane = lynx::eventedit::laneFor (s.patterns[(std::size_t) s.currentPattern], tempo);
  32345. if (lane.events.empty())
  32346. lynx::eventedit::line (lane, 0, lynx::ppq * 2, 0.05f, 0.11f, lynx::ticksPerStep);
  32347. }, false);
  32348. saveWindow (lynx::makeEventEditor (offline, tempo), "-eventeditor-tempo.png");
  32349. {
  32350. auto compact = lynx::makeEventEditor (offline, tempo); // the toolbar in a small window
  32351. compact->setSize (640, 300);
  32352. saveWindow (std::move (compact), "-eventeditor-tempo-small.png");
  32353. auto narrowest = lynx::makeEventEditor (offline, tempo); // the tool window's lower limit
  32354. narrowest->setSize (400, 300);
  32355. saveWindow (std::move (narrowest), "-eventeditor-tempo-narrowest.png");
  32356. }
  32357. offline.editSong ([&] (lynx::Song& s) { s.patterns[(std::size_t) s.currentPattern].events = before; }, false);
  32358. }
  32359. // round 86: the audio editor with a synthetic drum loop (markers, a region, a loop), waveform and spectrogram,
  32360. // and its menu items (-audioeditor-menu.txt)
  32361. {
  32362. namespace ae = lynx::audioedit;
  32363. ae::Document d;
  32364. d.title = "Drum loop";
  32365. d.audio.sampleRate = 44100.0;
  32366. const auto frames = (std::size_t) (44100 * 2);
  32367. d.audio.channels.assign (2, std::vector<float> (frames, 0.0f));
  32368. std::uint32_t seed = 7;
  32369. for (int hit = 0; hit < 8; ++hit)
  32370. {
  32371. const auto at = (std::size_t) hit * frames / 8;
  32372. const auto kick = hit % 2 == 0;
  32373. double phase = 0.0;
  32374. for (std::size_t i = 0; i < 12000 && at + i < frames; ++i)
  32375. {
  32376. seed = seed * 1664525u + 1013904223u;
  32377. const auto noise = (float) (seed >> 8) / 16777216.0f - 0.5f;
  32378. const auto t = (double) i / 44100.0;
  32379. phase += 2.0 * 3.141592653589793 * (kick ? 45.0 + 160.0 * std::exp (-t * 30.0) : 190.0) / 44100.0;
  32380. const auto body = (float) std::sin (phase) * (float) std::exp (-t * (kick ? 9.0 : 22.0));
  32381. const auto v = kick ? 0.85f * body : 0.35f * body + 0.6f * noise * (float) std::exp (-t * 18.0);
  32382. d.audio.channels[0][at + i] += v;
  32383. d.audio.channels[1][at + i] += kick ? v : v * 0.8f + 0.1f * noise * (float) std::exp (-t * 30.0);
  32384. }
  32385. }
  32386. ae::addMarker (d, (std::int64_t) frames / 8, "Snare");
  32387. ae::addRegion (d, { (std::int64_t) frames / 2, (std::int64_t) frames * 3 / 4 }, "Fill");
  32388. ae::setLoop (d, { 0, (std::int64_t) frames });
  32389. auto wave = lynx::makeAudioEditorForSnapshot (offline, d, false);
  32390. juce::File (prefix + "-audioeditor-menu.txt").replaceWithText (lynx::audioEditorMenuForSnapshot (*wave).joinIntoString ("\n") + "\n");
  32391. saveWindow (std::move (wave), "-audioeditor.png");
  32392. saveWindow (lynx::makeAudioEditorForSnapshot (offline, d, true), "-audioeditor-spectrum.png");
  32393. }
  32394. // warp markers (round 175a, M3): the audio editor of the first audio clip whose channel has warp markers,
  32395. // opened as the Playlist opens it, with its warp lane
  32396. {
  32397. const auto& song = offline.getSong();
  32398. for (int i = 0; i < (int) song.playlist.size(); ++i)
  32399. {
  32400. const auto& c = song.playlist[(std::size_t) i];
  32401. if (c.kind == lynx::ClipKind::audio && juce::isPositiveAndBelow (c.channel, (int) song.channels.size())
  32402. && song.channels[(std::size_t) c.channel].sampler.warp.size() >= 3)
  32403. {
  32404. if (auto panel = lynx::makeAudioEditorPanel (offline, c.channel, i, true))
  32405. saveWindow (std::move (panel), "-audioeditor-warp.png");
  32406. break;
  32407. }
  32408. }
  32409. }
  32410. // the tempo tapper after five steady taps (round 132)
  32411. saveWindow (lynx::makeTempoTapperForSnapshot (offline, 5, 128.0), "-tempotapper.png");
  32412. // the Channel Rack's piano-roll view (round 132)
  32413. ui.selectTabForSnapshot (0);
  32414. ui.getRackForSnapshot().setPianoRollView (true);
  32415. offline.dispatchPendingMessages();
  32416. saveSnapshot (ui, prefix + "-rack-pianoroll-view.png");
  32417. ui.getRackForSnapshot().setPianoRollView (false);
  32418. // the Channel Rack with the step graph lane (velocity), and the Euclidean fill window
  32419. ui.selectTabForSnapshot (0);
  32420. ui.getRackForSnapshot().setGraphLevelForSnapshot (0);
  32421. offline.dispatchPendingMessages();
  32422. saveSnapshot (ui, prefix + "-rack-graph.png");
  32423. ui.getRackForSnapshot().setGraphLevelForSnapshot (1);
  32424. saveSnapshot (ui, prefix + "-rack-graph-pan.png");
  32425. ui.getRackForSnapshot().toggleGraphLanes();
  32426. saveWindow (ui.getRackForSnapshot().makeEuclideanPanel (0), "-euclidean.png");
  32427. // the Mixer with three inserts selected and one armed for recording
  32428. ui.selectTabForSnapshot (3);
  32429. if (offline.getSong().mixer.size() > 4)
  32430. {
  32431. ui.getMixerForSnapshot().getStripsForSnapshot().setSelection ({ 1, 2, 3 }, 2);
  32432. offline.setInsertArmed (3, true);
  32433. offline.dispatchPendingMessages();
  32434. saveSnapshot (ui, prefix + "-mixer-multi.png");
  32435. // the armed insert with an audio input (its input row in the side panel, the level bar on the strip)
  32436. offline.editSong ([] (lynx::Song& s) { s.mixer[3].inputChannel = 0; });
  32437. ui.getMixerForSnapshot().selectTrack (3);
  32438. offline.dispatchPendingMessages();
  32439. saveSnapshot (ui, prefix + "-mixer-input.png");
  32440. offline.undo();
  32441. offline.setInsertArmed (3, false);
  32442. ui.getMixerForSnapshot().getStripsForSnapshot().setSelection ({}, 0);
  32443. }
  32444. // the Mixer's routing lane: an insert with sends selected (send knobs and wires)
  32445. if (offline.getSong().mixer.size() > 6)
  32446. {
  32447. int source = -1;
  32448. for (int t = 1; t < (int) offline.getSong().mixer.size() && source < 0; ++t)
  32449. if (! offline.getSong().mixer[(std::size_t) t].sends.empty())
  32450. source = t;
  32451. const auto temporary = source < 0;
  32452. if (temporary) // the demo has no sends: add two for the picture
  32453. {
  32454. source = 1;
  32455. 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); });
  32456. }
  32457. ui.getMixerForSnapshot().selectTrack (source);
  32458. offline.dispatchPendingMessages();
  32459. saveSnapshot (ui, prefix + "-mixer-sends.png");
  32460. if (temporary)
  32461. offline.editSong ([] (lynx::Song& s) { s.setRoute (1, 5, false); s.setRoute (1, 6, false); s.setRoute (4, 1, false); });
  32462. ui.getMixerForSnapshot().selectTrack (0);
  32463. }
  32464. // round 190io (issue #154 part 2): the Mixer view that lists each strip's insert effects (a LYNX view, off by
  32465. // default), with an insert selected whose sends light the route arrows
  32466. {
  32467. auto& strips = ui.getMixerForSnapshot().getStripsForSnapshot();
  32468. strips.setShowStripInserts (true);
  32469. offline.dispatchPendingMessages();
  32470. saveSnapshot (ui, prefix + "-mixer190io-inserts.png");
  32471. strips.setShowStripInserts (false);
  32472. offline.dispatchPendingMessages();
  32473. }
  32474. // the Playlist with ripple editing on
  32475. ui.selectTabForSnapshot (2);
  32476. ui.getPlaylistForSnapshot().setRipple (true);
  32477. saveSnapshot (ui, prefix + "-playlist-ripple.png");
  32478. ui.getPlaylistForSnapshot().setRipple (false);
  32479. // FL's legacy Pattern Blocks (round 170f, issue #60): the section under the clip tracks, a row per pattern
  32480. {
  32481. const auto saved = offline.getSong();
  32482. offline.editSong ([] (lynx::Song& s) {
  32483. s.patternBlocksOn = true;
  32484. while (s.patterns.size() < 5) // a few rows to show (Drums, Bass...: copies of the demo's pattern)
  32485. lynx::clonePattern (s, (int) s.patterns.size() - 1);
  32486. const auto rows = juce::jmin (6, (int) s.patterns.size());
  32487. for (int r = 0; r < rows; ++r)
  32488. lynx::patternblocks::paintRange (s, r, (std::int64_t) (r % 3) * 4 * lynx::ppq * 2,
  32489. (std::int64_t) (8 + r * 2) * 4 * lynx::ppq);
  32490. }, false);
  32491. offline.dispatchPendingMessages();
  32492. saveSnapshot (ui, prefix + "-playlist-blocks.png");
  32493. // issue #127 (PR #132 and our follow-up): the Playlist's pencil, brush and eraser on the blocks, driven
  32494. // with real mouse events on the view. One picture per tool, and the gestures' results in
  32495. // <prefix>-playlist-blocks-tools.txt ("OK", or the checks that failed).
  32496. if (auto* blocks = ui.getPlaylistForSnapshot().getBlocksViewForSnapshot())
  32497. {
  32498. juce::StringArray failed;
  32499. const auto expect = [&failed] (bool ok, const char* what) { if (! ok) failed.add (what); };
  32500. const auto bar = offline.getSong().barTicks();
  32501. offline.editSong ([bar] (lynx::Song& s) {
  32502. s.blocks.clear();
  32503. for (std::size_t r = 0; r < 4 && r < s.patterns.size(); ++r)
  32504. s.patterns[r].lengthTicks = r == 1 ? 2 * bar : bar; // row 2 holds a 2-bar pattern
  32505. }, false);
  32506. offline.dispatchPendingMessages();
  32507. const auto source = juce::Desktop::getInstance().getMainMouseSource();
  32508. const juce::ModifierKeys left (juce::ModifierKeys::leftButtonModifier), right (juce::ModifierKeys::rightButtonModifier);
  32509. juce::Point<float> pressedAt;
  32510. const auto event = [&] (int row, std::int64_t tick, juce::ModifierKeys mods) {
  32511. const auto at = blocks->pointForSnapshot (row, tick).toFloat();
  32512. const auto now = juce::Time::getCurrentTime();
  32513. return juce::MouseEvent (source, at, mods, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, blocks, blocks, now, pressedAt, now, 1, false);
  32514. };
  32515. const auto press = [&] (int row, std::int64_t tick, juce::ModifierKeys mods) {
  32516. pressedAt = blocks->pointForSnapshot (row, tick).toFloat();
  32517. blocks->mouseDown (event (row, tick, mods));
  32518. };
  32519. const auto dragTo = [&] (int row, std::int64_t tick, juce::ModifierKeys mods) { blocks->mouseDrag (event (row, tick, mods)); };
  32520. const auto release = [&] (int row, std::int64_t tick) { blocks->mouseUp (event (row, tick, {})); };
  32521. // the starts of row `row`'s blocks, as "0,2,5" (bars from 0)
  32522. const auto rowBars = [&] (int row) {
  32523. juce::StringArray bars;
  32524. for (const auto& b : offline.getSong().blocks)
  32525. if (b.pattern == row)
  32526. bars.add (juce::String (b.start / bar) + (b.start % bar != 0 ? "+" : ""));
  32527. return bars.joinIntoString (",");
  32528. };
  32529. auto& tools = ui.getPlaylistForSnapshot();
  32530. // Pencil: a press on empty space places one block that follows the mouse along its row
  32531. tools.setToolForSnapshot (lynx::EditTool::pencil);
  32532. press (0, 2 * bar + 40, left);
  32533. expect (rowBars (0) == "2", "pencil: a press places one block");
  32534. dragTo (2, 5 * bar + 40, left); // (over another row: the block stays in its own)
  32535. release (2, 5 * bar + 40);
  32536. expect (rowBars (0) == "5" && rowBars (2).isEmpty(), "pencil: the placed block follows the drag in its row");
  32537. // a 2-bar block grabbed by its second bar keeps that bar under the mouse (it used to jump a bar)
  32538. press (1, 1 * bar + 40, left);
  32539. release (1, 1 * bar + 40);
  32540. expect (rowBars (1) == "1", "pencil: a click places the 2-bar block");
  32541. press (1, 2 * bar + 40, left);
  32542. dragTo (1, 2 * bar + bar / 2, left);
  32543. expect (rowBars (1) == "1", "move: a small move on the grabbed bar leaves the block in place");
  32544. dragTo (1, 4 * bar + 40, left);
  32545. release (1, 4 * bar + 40);
  32546. expect (rowBars (1) == "3", "move: the grabbed bar stays under the mouse");
  32547. offline.dispatchPendingMessages();
  32548. saveSnapshot (ui, prefix + "-playlist-blocks-pencil.png");
  32549. // Brush: a drag over empty space paints a run; a press on a block moves it
  32550. tools.setToolForSnapshot (lynx::EditTool::brush);
  32551. press (2, 0, left);
  32552. dragTo (2, 3 * bar + 40, left);
  32553. release (2, 3 * bar + 40);
  32554. expect (rowBars (2) == "0,1,2,3", "brush: a drag paints a run");
  32555. press (2, 3 * bar + 40, left);
  32556. dragTo (2, 6 * bar + 40, left);
  32557. release (2, 6 * bar + 40);
  32558. expect (rowBars (2) == "0,1,2,6", "brush: a press on a block moves it");
  32559. offline.dispatchPendingMessages();
  32560. saveSnapshot (ui, prefix + "-playlist-blocks-brush.png");
  32561. // Eraser, and the right button with any tool: only the blocks under the mouse, row by row
  32562. offline.editSong ([bar] (lynx::Song& s) {
  32563. for (int r = 0; r < 4 && r < (int) s.patterns.size(); ++r)
  32564. lynx::patternblocks::place (s, r, 8 * bar);
  32565. }, false);
  32566. offline.dispatchPendingMessages();
  32567. expect (rowBars (0) == "5,8" && rowBars (3) == "8", "eraser: the column is set up");
  32568. saveSnapshot (ui, prefix + "-playlist-blocks-eraser-before.png");
  32569. tools.setToolForSnapshot (lynx::EditTool::eraser);
  32570. press (0, 8 * bar + 40, left);
  32571. expect (rowBars (0) == "5" && rowBars (1) == "3,8" && rowBars (2) == "0,1,2,6,8" && rowBars (3) == "8",
  32572. "eraser: a click takes only the block under the mouse");
  32573. dragTo (1, 8 * bar + 60, left); // down one row: that row's block goes too, the rows below stay
  32574. release (1, 8 * bar + 60);
  32575. expect (rowBars (1) == "3" && rowBars (2) == "0,1,2,6,8" && rowBars (3) == "8", "eraser: the drag erases the rows it crosses, no others");
  32576. tools.setToolForSnapshot (lynx::EditTool::pencil);
  32577. press (3, 8 * bar + 40, right);
  32578. release (3, 8 * bar + 40);
  32579. expect (rowBars (3).isEmpty() && rowBars (2) == "0,1,2,6,8", "right click: erases only the block under the mouse");
  32580. offline.dispatchPendingMessages();
  32581. saveSnapshot (ui, prefix + "-playlist-blocks-eraser.png");
  32582. juce::File (prefix + "-playlist-blocks-tools.txt").replaceWithText (failed.isEmpty() ? juce::String ("OK\n") : "ERROR\n" + failed.joinIntoString ("\n") + "\n");
  32583. }
  32584. offline.editSong ([saved] (lynx::Song& s) { s = saved; }, false);
  32585. offline.dispatchPendingMessages();
  32586. }
  32587. // quick-add palette, and the Browser searching
  32588. saveWindow (ui.makeQuickAddForSnapshot(), "-quickadd.png");
  32589. ui.showDesktopForSnapshot (false);
  32590. ui.getBrowserForSnapshot().setSearchForSnapshot ("kick");
  32591. offline.dispatchPendingMessages();
  32592. saveSnapshot (ui, prefix + "-browser-search.png");
  32593. ui.getBrowserForSnapshot().setSearchForSnapshot ({});
  32594. ui.getBrowserForSnapshot().selectFirstSampleForSnapshot(); // the tree with a sample selected and its waveform
  32595. offline.dispatchPendingMessages();
  32596. saveSnapshot (ui, prefix + "-browser-tree.png");
  32597. // the Browser's PROJECT tab: the patterns, generators and audio files of the project in their colours
  32598. ui.getBrowserForSnapshot().showProjectForSnapshot();
  32599. offline.dispatchPendingMessages();
  32600. saveSnapshot (ui, prefix + "-browser-project.png");
  32601. ui.getBrowserForSnapshot().showPluginDatabaseForSnapshot(); // round 142: the Plugin database's FL engines
  32602. offline.dispatchPendingMessages();
  32603. saveSnapshot (ui, prefix + "-browser-plugins.png");
  32604. // round 190bf (fl190be Q1): the Plugin database's right-click menus, a folder's and an entry's (FL's System group)
  32605. saveMenus (juce::StringArray { "Plugin database: folder", "Plugin database: entry" }, ui.getBrowserForSnapshot().pluginDatabaseMenusForSnapshot(),
  32606. prefix + "-browser190bf-menus.png");
  32607. ui.getBrowserForSnapshot().setTab (lynx::BrowserComponent::allTab);
  32608. saveWindow (ui.getBrowserForSnapshot().makeFoldersPanelForSnapshot(), "-browser-folders.png"); // round 164
  32609. {
  32610. // round 164: the content filter leaves out the folders with nothing to list (a small library)
  32611. const auto lib = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-snapshot-library");
  32612. lib.deleteRecursively();
  32613. for (const auto* path : { "Drums/Kicks/kick 1.wav", "Drums/Kicks/kick 2.wav", "Drums/snare.wav", "Keys/pad.sf2", "Presets/Synth/lead.fst",
  32614. "Projects/beat.flp", "Projects/MIDI/chords.mid", "Notes/readme.txt", "Empty/Nothing/.keep" })
  32615. lib.getChildFile (path).create();
  32616. ui.showDesktopForSnapshot (false);
  32617. ui.getBrowserForSnapshot().showFilterForSnapshot (lib, lynx::browserview::ContentFilter::all);
  32618. offline.dispatchPendingMessages();
  32619. saveSnapshot (ui, prefix + "-browser164-all.png");
  32620. ui.getBrowserForSnapshot().showFilterForSnapshot (lib, lynx::browserview::ContentFilter::samples);
  32621. offline.dispatchPendingMessages();
  32622. saveSnapshot (ui, prefix + "-browser164-samples.png");
  32623. ui.getBrowserForSnapshot().showFilterForSnapshot (lib, lynx::browserview::ContentFilter::projects);
  32624. offline.dispatchPendingMessages();
  32625. saveSnapshot (ui, prefix + "-browser164-projects.png");
  32626. lib.deleteRecursively();
  32627. ui.getBrowserForSnapshot().resetViewForSnapshot();
  32628. }
  32629. {
  32630. // round 190as: "Find similar samples" on a small library of kicks, hats and pads (LYNX_SNAPSHOT_SIMILAR =
  32631. // "<folder>|<file>" lists a real folder instead)
  32632. auto lib = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-snapshot-similar");
  32633. auto query = lib.getChildFile ("Drums/Kicks/Kick 2.wav");
  32634. const auto real = juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIMILAR", {});
  32635. const auto made = real.isEmpty();
  32636. if (made)
  32637. {
  32638. lib.deleteRecursively();
  32639. juce::Random random (190);
  32640. const auto write = [&] (const juce::String& path, char kind, int v) {
  32641. const auto rate = 44100.0;
  32642. const auto frames = (int) (rate * (kind == 'k' ? 0.35 : kind == 'h' ? 0.09 : 2.5));
  32643. juce::AudioBuffer<float> audio (1, frames);
  32644. double phase = 0.0;
  32645. float last = 0.0f;
  32646. for (int i = 0; i < frames; ++i)
  32647. {
  32648. const auto t = i / rate;
  32649. float x = 0.0f;
  32650. if (kind == 'k')
  32651. {
  32652. phase += juce::MathConstants<double>::twoPi * ((46.0 + 3.0 * v) + 150.0 * std::exp (-t * 35.0)) / rate;
  32653. x = (float) (std::sin (phase) * std::exp (-t * (8.0 + v)));
  32654. }
  32655. else if (kind == 'h')
  32656. {
  32657. const auto n = random.nextFloat() * 2.0f - 1.0f;
  32658. x = (n - last) * 0.5f * (float) std::exp (-t * (50.0 + 12.0 * v));
  32659. last = n;
  32660. }
  32661. else
  32662. {
  32663. const auto base = 220.0 * std::pow (2.0, v / 12.0);
  32664. x = (float) (0.25 * std::min (1.0, t / 0.4) * std::min (1.0, (2.5 - t) / 0.5)
  32665. * (std::sin (juce::MathConstants<double>::twoPi * base * t) + std::sin (juce::MathConstants<double>::twoPi * base * 1.5 * t)));
  32666. }
  32667. audio.setSample (0, i, 0.8f * x);
  32668. }
  32669. const auto file = lib.getChildFile (path);
  32670. file.getParentDirectory().createDirectory();
  32671. juce::WavAudioFormat wav;
  32672. if (auto out = file.createOutputStream())
  32673. if (auto writer = std::unique_ptr<juce::AudioFormatWriter> (wav.createWriterFor (out.release(), rate, 1, 16, {}, 0)))
  32674. writer->writeFromAudioSampleBuffer (audio, 0, frames);
  32675. };
  32676. for (int v = 1; v <= 5; ++v)
  32677. {
  32678. write ("Drums/Kicks/Kick " + juce::String (v) + ".wav", 'k', v);
  32679. write ("Drums/Hats/Hat " + juce::String (v) + ".wav", 'h', v);
  32680. write ("Keys/Pad " + juce::String (v) + ".wav", 'p', v);
  32681. }
  32682. }
  32683. else
  32684. {
  32685. lib = juce::File (real.upToFirstOccurrenceOf ("|", false, false));
  32686. query = juce::File (real.fromFirstOccurrenceOf ("|", false, false));
  32687. }
  32688. ui.showDesktopForSnapshot (false);
  32689. ui.getBrowserForSnapshot().showFilterForSnapshot (lib, lynx::browserview::ContentFilter::all);
  32690. ui.getBrowserForSnapshot().findSimilarForSnapshot (query, lib);
  32691. offline.dispatchPendingMessages();
  32692. saveSnapshot (ui, prefix + "-browser-similar.png");
  32693. ui.getBrowserForSnapshot().setSearchForSnapshot ({});
  32694. if (made)
  32695. lib.deleteRecursively();
  32696. ui.getBrowserForSnapshot().resetViewForSnapshot();
  32697. }
  32698. // the undo history after a few edits
  32699. offline.editSong ([] (lynx::Song& s) { s.bpm += 1.0; });
  32700. offline.editSong ([] (lynx::Song& s) { if (! s.channels.empty()) s.channels[0].muted = ! s.channels[0].muted; });
  32701. offline.editSong ([] (lynx::Song& s) { if (! s.patterns.empty()) s.patterns[(std::size_t) s.currentPattern].notes.push_back ({}); });
  32702. offline.undo();
  32703. saveWindow (lynx::makeHistoryPanel (offline), "-history.png");
  32704. // spectral waveforms: a synthetic beat (kick, hats, a chord, a noise riser) as audio clips in spectral
  32705. // colours, zoomed in, classic and stereo; the same file in the Sampler editor and the Browser preview
  32706. {
  32707. const juce::File wav (prefix + "-wavedemo.wav");
  32708. writeWaveDemo (wav, offline.getSong().bpm);
  32709. const auto path = wav.getFullPathName();
  32710. const auto pathUtf8 = path.toStdString();
  32711. int samplerChannel = -1, firstTrack = 0;
  32712. offline.editSong ([&] (lynx::Song& s) {
  32713. for (const auto& clip : s.playlist)
  32714. firstTrack = std::max (firstTrack, clip.track + 1);
  32715. lynx::ChannelDef audio;
  32716. audio.name = "Beat (audio)";
  32717. audio.instrument = lynx::InstrumentKind::audioClip;
  32718. audio.samplePath = pathUtf8;
  32719. s.channels.push_back (audio);
  32720. const auto audioChannel = (int) s.channels.size() - 1;
  32721. lynx::ChannelDef sampler = audio;
  32722. sampler.name = "Beat (sampler)";
  32723. sampler.instrument = lynx::InstrumentKind::sampler;
  32724. sampler.sampler.regionStart = 0.06f;
  32725. sampler.sampler.regionEnd = 0.94f;
  32726. s.channels.push_back (sampler);
  32727. samplerChannel = (int) s.channels.size() - 1;
  32728. const auto bar = s.barTicks();
  32729. const auto whole = (std::int64_t) std::llround (8.0 * s.bpm / 60.0 * lynx::ppq);
  32730. lynx::Clip clip;
  32731. clip.kind = lynx::ClipKind::audio;
  32732. clip.channel = audioChannel;
  32733. clip.track = firstTrack;
  32734. clip.length = whole;
  32735. s.playlist.push_back (clip);
  32736. clip.track = firstTrack + 1; // a slice of it, later in the song
  32737. clip.start = bar;
  32738. clip.offset = bar;
  32739. clip.length = 2 * bar;
  32740. s.playlist.push_back (clip);
  32741. // taller rows for the audio (tracks can be resized: P18)
  32742. if ((int) s.playlistTracks.size() < firstTrack + 2)
  32743. s.playlistTracks.resize ((std::size_t) firstTrack + 2);
  32744. s.playlistTracks[(std::size_t) firstTrack].height = 80;
  32745. s.playlistTracks[(std::size_t) firstTrack + 1].height = 60;
  32746. });
  32747. offline.dispatchPendingMessages();
  32748. auto& cache = *lynx::ui::WaveformCache::getInstance();
  32749. cache.find (path, [&offline, path] { return offline.getSampleLibrary().load (path); });
  32750. cache.waitUntilIdle (30000);
  32751. ui.selectTabForSnapshot (2);
  32752. auto& playlist = ui.getPlaylistForSnapshot();
  32753. playlist.setTimeSelectionForSnapshot (0, 0);
  32754. {
  32755. // the Playlist alone (the floating Channel Rack would cover the clips)
  32756. auto saveSnapshot = [&playlist] (juce::Component&, const juce::String& file) { saveArea (playlist, playlist.getLocalBounds(), file); };
  32757. playlist.setViewForSnapshot (180.0, 0, std::max (0, firstTrack - 3));
  32758. saveSnapshot (ui, prefix + "-playlist-audio.png");
  32759. playlist.setViewForSnapshot (1400.0, 0, std::max (0, firstTrack - 3));
  32760. saveSnapshot (ui, prefix + "-playlist-audio-zoom.png");
  32761. lynx::ui::WaveformCache::stereo = true;
  32762. saveSnapshot (ui, prefix + "-playlist-audio-stereo.png");
  32763. lynx::ui::WaveformCache::stereo = false;
  32764. lynx::ui::WaveformCache::spectral = true;
  32765. playlist.setViewForSnapshot (180.0, 0, std::max (0, firstTrack - 3));
  32766. saveSnapshot (ui, prefix + "-playlist-audio-spectral.png");
  32767. lynx::ui::WaveformCache::spectral = false;
  32768. playlist.setViewForSnapshot (40.0, 0, 0);
  32769. saveSnapshot (ui, prefix + "-playlist-audio-far.png");
  32770. // LYNX_SNAPSHOT_AUDIO=a.wav;b.wav...: real audio as clips (default-height tracks, one tall,
  32771. // a fade, a reversed copy), at three zoom levels
  32772. if (const auto files = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_AUDIO", {}), ";", "");
  32773. ! files.isEmpty())
  32774. {
  32775. const auto realTrack = firstTrack + 2;
  32776. std::vector<juce::String> paths;
  32777. for (const auto& f : files)
  32778. if (juce::File (f.trim()).existsAsFile())
  32779. paths.push_back (f.trim());
  32780. offline.editSong ([&] (lynx::Song& s) {
  32781. const auto bar = s.barTicks();
  32782. const std::uint32_t colours[] = { 0, 0xffd9a441, 0xff6fb36a, 0xffb06fd0, 0xff5fb7c9, 0xffd06f6f };
  32783. for (std::size_t i = 0; i < paths.size(); ++i)
  32784. {
  32785. lynx::ChannelDef audio;
  32786. audio.name = juce::File (paths[i]).getFileNameWithoutExtension().toStdString();
  32787. audio.instrument = lynx::InstrumentKind::audioClip;
  32788. audio.samplePath = paths[i].toStdString();
  32789. audio.colour = colours[i % 6];
  32790. audio.sampler.stretchBeats = i % 2 == 0 ? 16.0f : 0.0f; // fitted to 4 bars, or as recorded
  32791. audio.sampler.keepPitch = true;
  32792. s.channels.push_back (audio);
  32793. lynx::Clip clip;
  32794. clip.kind = lynx::ClipKind::audio;
  32795. clip.channel = (int) s.channels.size() - 1;
  32796. clip.track = realTrack + (int) i;
  32797. clip.length = 4 * bar;
  32798. clip.fadeIn = i == 1 ? bar / 2 : 0;
  32799. s.playlist.push_back (clip);
  32800. clip.start = 4 * bar;
  32801. clip.fadeIn = 0;
  32802. clip.fadeOut = i == 0 ? bar : 0;
  32803. s.playlist.push_back (clip);
  32804. }
  32805. if ((int) s.playlistTracks.size() < realTrack + (int) paths.size())
  32806. s.playlistTracks.resize ((std::size_t) realTrack + paths.size());
  32807. if (! paths.empty())
  32808. s.playlistTracks[(std::size_t) realTrack].height = 90;
  32809. });
  32810. offline.dispatchPendingMessages();
  32811. for (const auto& path2 : paths)
  32812. cache.find (path2, [&offline, path2] { return offline.getSampleLibrary().load (path2); });
  32813. cache.waitUntilIdle (60000);
  32814. playlist.setViewForSnapshot (160.0, 0, std::max (0, realTrack - 4));
  32815. saveSnapshot (ui, prefix + "-playlist-real.png");
  32816. playlist.setViewForSnapshot (700.0, 0, std::max (0, realTrack - 1));
  32817. saveSnapshot (ui, prefix + "-playlist-real-zoom.png");
  32818. playlist.setViewForSnapshot (2400.0, 0, std::max (0, realTrack - 1));
  32819. saveSnapshot (ui, prefix + "-playlist-real-close.png");
  32820. playlist.setViewForSnapshot (50.0, 0, std::max (0, realTrack - 4));
  32821. saveSnapshot (ui, prefix + "-playlist-real-far.png");
  32822. // the clip menu of the first real clip
  32823. if (const auto menu = playlist.getClipMenuForSnapshot ((int) offline.getSong().playlist.size() - (int) paths.size() * 2); menu.getNumItems() > 0)
  32824. saveMenus (juce::StringArray { "Audio clip" }, std::vector<juce::PopupMenu> { menu }, prefix + "-clip-menu-audio.png");
  32825. if (const auto menu = playlist.getClipMenuForSnapshot (0); menu.getNumItems() > 0)
  32826. saveMenus (juce::StringArray { "Pattern clip" }, std::vector<juce::PopupMenu> { menu }, prefix + "-clip-menu-pattern.png");
  32827. // the clip menu's actions, run through the menu itself; results in -clip-actions.txt
  32828. {
  32829. juce::StringArray log;
  32830. auto clipOf = [&offline] (const std::string& channelName, int nth) {
  32831. const auto& sg = offline.getSong();
  32832. for (int i = 0; i < (int) sg.playlist.size(); ++i)
  32833. {
  32834. const auto& c = sg.playlist[(std::size_t) i];
  32835. if (c.kind == lynx::ClipKind::audio && c.channel >= 0 && sg.channels[(std::size_t) c.channel].name == channelName && nth-- == 0)
  32836. return i;
  32837. }
  32838. return -1;
  32839. };
  32840. std::function<bool (const juce::PopupMenu&, const juce::String&)> run = [&run] (const juce::PopupMenu& m, const juce::String& text) {
  32841. for (juce::PopupMenu::MenuItemIterator it (m); it.next();)
  32842. {
  32843. auto& item = it.getItem();
  32844. if (item.subMenu != nullptr && run (*item.subMenu, text))
  32845. return true;
  32846. // (without the menu mnemonic's mark: FL's underlined letters, round 190dz)
  32847. if (item.text.removeCharacters (juce::String::charToString (1)).startsWith (text) && item.isEnabled && item.action)
  32848. {
  32849. item.action();
  32850. return true;
  32851. }
  32852. }
  32853. return false;
  32854. };
  32855. auto act = [&] (const std::string& name, int nth, const juce::String& text) {
  32856. const auto clip = clipOf (name, nth);
  32857. const auto ok = clip >= 0 && run (playlist.getClipMenuForSnapshot (clip), text);
  32858. offline.dispatchPendingMessages();
  32859. return ok;
  32860. };
  32861. auto channelOf = [&] (const std::string& name) -> const lynx::ChannelDef* {
  32862. for (const auto& c : offline.getSong().channels)
  32863. if (c.name == name)
  32864. return &c;
  32865. return nullptr;
  32866. };
  32867. auto check = [&log] (const juce::String& what, bool ok) { log.add ((ok ? "OK " : "FAIL ") + what); };
  32868. const auto names = [&] { std::vector<std::string> n; for (auto& p2 : paths) n.push_back (juce::File (p2).getFileNameWithoutExtension().toStdString()); return n; }();
  32869. if (names.size() >= 4)
  32870. {
  32871. const auto channelsBefore = offline.getSong().channels.size();
  32872. check ("Reverse", act (names[2], 0, lynx::tr ("Reverse")) && channelOf (names[2])->sampler.reverse);
  32873. offline.undo();
  32874. offline.dispatchPendingMessages();
  32875. check ("Reverse undone", ! channelOf (names[2])->sampler.reverse);
  32876. act (names[2], 0, lynx::tr ("Reverse"));
  32877. check ("Make unique", act (names[3], 1, lynx::tr ("Make unique")) && offline.getSong().channels.size() == channelsBefore + 1
  32878. && channelOf (names[3] + " #2") != nullptr);
  32879. check ("Fit to tempo, resample", act (names[1], 0, lynx::tr ("Fit to tempo, resample ({0})", { juce::String() }).upToFirstOccurrenceOf ("(", false, false))
  32880. && channelOf (names[1])->sampler.stretchBeats > 0.0f && ! channelOf (names[1])->sampler.keepPitch);
  32881. const auto gainBefore = offline.getSong().playlist[(std::size_t) clipOf (names[0], 1)].gain;
  32882. check ("Normalize", act (names[0], 1, lynx::tr ("Normalize"))
  32883. && offline.getSong().playlist[(std::size_t) clipOf (names[0], 1)].gain != gainBefore);
  32884. const auto clipsBefore = offline.getSong().playlist.size();
  32885. check ("Split here", act (names[3], 0, lynx::tr ("Split here")) && offline.getSong().playlist.size() == clipsBefore + 1);
  32886. check ("Mute", act (names[0], 0, lynx::tr ("Mute")) && offline.getSong().playlist[(std::size_t) clipOf (names[0], 0)].muted);
  32887. check ("Copy + Paste here", act (names[0], 0, lynx::tr ("Copy")) && act (names[0], 1, lynx::tr ("Paste here"))
  32888. && offline.getSong().playlist.size() == clipsBefore + 2);
  32889. check ("Delete", act (names[0], 2, lynx::tr ("Delete")) && offline.getSong().playlist.size() == clipsBefore + 1);
  32890. check ("Chop to grid", act (names[3], 0, lynx::tr ("Chop to grid")) && offline.getSong().playlist.size() > clipsBefore + 1);
  32891. }
  32892. playlist.setViewForSnapshot (160.0, 0, std::max (0, realTrack - 4));
  32893. saveSnapshot (ui, prefix + "-playlist-real-actions.png");
  32894. juce::File (prefix + "-clip-actions.txt").replaceWithText (log.joinIntoString ("\n") + "\n");
  32895. }
  32896. }
  32897. }
  32898. saveWindow (lynx::makeChannelSettingsPanel (offline, samplerChannel), "-sampler-wave.png");
  32899. ui.showDesktopForSnapshot (false);
  32900. ui.getBrowserForSnapshot().showPreviewForSnapshot (wav);
  32901. saveSnapshot (ui, prefix + "-browser-preview.png");
  32902. }
  32903. }
  32904. // round 165o: every Label / button / tick box whose text the drawing squeezes below its minimum scale or cuts
  32905. // (an ellipsis), per language: `LYNX --lang de --snapshot shots/de` -> shots/de-textfit.txt
  32906. juce::File (prefix + "-textfit.txt").replaceWithText (textFitLog().joinIntoString ("\n") + "\n");
  32907. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  32908. quit();
  32909. }
  32910. // --snapshot: 8 s of a synthetic stereo beat whose parts sit in different bands (kick = low, chord = mid,
  32911. // hats and the noise riser = high), to show the spectral waveform colours
  32912. #include "BrowserShot190iz.inc" // round 190iz
  32913. #include "UndoGesture190jv.inc" // round 190jv
  32914. #include "TrimShot190jv.inc" // round 190jv
  32915. #include "PrChordShot190kd.inc" // round 190kd
  32916. #include "PrShot190jv.inc" // round 190jv
  32917. #include "SimpleGbShot190ke.inc" // round 190ke
  32918. #include "LoopShot190kf.inc" // round gaps190kf
  32919. static void writeWaveDemo (const juce::File& file, double bpm)
  32920. {
  32921. constexpr double rate = 44100.0;
  32922. const auto frames = (int) (8.0 * rate);
  32923. juce::AudioBuffer<float> buffer (2, frames);
  32924. buffer.clear();
  32925. auto* l = buffer.getWritePointer (0);
  32926. auto* r = buffer.getWritePointer (1);
  32927. const auto beat = 60.0 / juce::jlimit (40.0, 300.0, bpm);
  32928. std::uint32_t noise = 0x9e3779b9u;
  32929. auto white = [&noise] {
  32930. noise ^= noise << 13;
  32931. noise ^= noise >> 17;
  32932. noise ^= noise << 5;
  32933. return (float) (noise & 0xffffff) / (float) 0x800000 - 1.0f;
  32934. };
  32935. float previous = 0.0f;
  32936. for (int i = 0; i < frames; ++i)
  32937. {
  32938. const auto t = i / rate;
  32939. const auto inBeat = std::fmod (t, beat);
  32940. const auto bar = (int) (t / (beat * 4.0));
  32941. float left = 0.0f, right = 0.0f;
  32942. // kick on every beat: a falling sine
  32943. {
  32944. const auto phase = 2.0 * juce::MathConstants<double>::pi * (48.0 * inBeat + 4.0 * (1.0 - std::exp (-inBeat * 30.0)));
  32945. const auto k = (float) (std::sin (phase) * std::exp (-inBeat * 7.0)) * 0.85f;
  32946. left += k;
  32947. right += k;
  32948. }
  32949. // hats on the off-beats: high-passed noise bursts, a little to the right
  32950. {
  32951. const auto h = std::fmod (t + beat * 0.5, beat);
  32952. const auto n = white();
  32953. const auto hp = (n - previous) * 0.5f;
  32954. previous = n;
  32955. const auto hat = hp * (float) std::exp (-h * 45.0) * 0.55f;
  32956. left += hat * 0.6f;
  32957. right += hat;
  32958. }
  32959. // a chord in the second and third bars (mid band)
  32960. if (bar == 1 || bar == 2)
  32961. {
  32962. const auto env = (float) std::min (1.0, std::min (t - beat * 4.0, beat * 12.0 - t) * 8.0);
  32963. float chord = 0.0f;
  32964. for (const auto hz : { 523.25, 659.25, 783.99 })
  32965. chord += (float) (std::sin (2.0 * juce::MathConstants<double>::pi * hz * t) + 0.3 * std::sin (4.0 * juce::MathConstants<double>::pi * hz * t));
  32966. left += chord * 0.09f * std::max (0.0f, env);
  32967. right += chord * 0.09f * std::max (0.0f, env);
  32968. }
  32969. // a white-noise riser over the last two seconds (high band)
  32970. if (t > 6.0)
  32971. {
  32972. const auto rise = (float) ((t - 6.0) / 2.0);
  32973. left += white() * 0.4f * rise * rise;
  32974. right += white() * 0.4f * rise * rise;
  32975. }
  32976. l[i] = left;
  32977. r[i] = right;
  32978. }
  32979. buffer.applyGain (0.9f / juce::jmax (1.0e-6f, buffer.getMagnitude (0, frames)));
  32980. file.deleteFile();
  32981. juce::WavAudioFormat wav;
  32982. if (std::unique_ptr<juce::AudioFormatWriter> writer { wav.createWriterFor (file.createOutputStream().release(), rate, 2, 24, {}, 0) })
  32983. writer->writeFromAudioSampleBuffer (buffer, 0, frames);
  32984. }
  32985. // the menu bar's menus side by side, drawn with the LookAndFeel as they appear when opened
  32986. static void saveMenus (lynx::MainComponent& ui, const juce::String& path)
  32987. {
  32988. const auto names = ui.getMenuNamesForSnapshot();
  32989. std::vector<juce::PopupMenu> source;
  32990. for (int m = 0; m < names.size(); ++m)
  32991. source.push_back (ui.getMenuForSnapshot (m));
  32992. saveMenus (names, source, path);
  32993. }
  32994. // menus side by side, each under its name, in the columns JUCE shows them in: its own column breaks, or (round 190je,
  32995. // cmake/LynxPatchJuce.cmake fix 40) the split of a menu taller than 70 % of a 1080 px screen
  32996. static void saveMenus (const juce::StringArray& names, const std::vector<juce::PopupMenu>& source, const juce::String& path)
  32997. {
  32998. auto& lf = juce::LookAndFeel::getDefaultLookAndFeel();
  32999. struct Row
  33000. {
  33001. const juce::PopupMenu::Item* item;
  33002. int height;
  33003. };
  33004. struct Laid
  33005. {
  33006. juce::PopupMenu menu;
  33007. std::vector<std::vector<Row>> columns;
  33008. std::vector<int> widths;
  33009. int width = 0, height = 0;
  33010. };
  33011. std::vector<Laid> menus;
  33012. menus.reserve ((std::size_t) names.size());
  33013. const auto border = lf.getPopupMenuBorderSize();
  33014. const auto separatorWidth = lf.getPopupMenuColumnSeparatorWidthWithOptions (juce::PopupMenu::Options());
  33015. for (int m = 0; m < names.size(); ++m)
  33016. {
  33017. menus.push_back (Laid { source[(std::size_t) m] });
  33018. auto& laid = menus.back();
  33019. std::vector<Row> rows;
  33020. std::vector<lynx::themes::MenuRow> shape;
  33021. std::vector<int> breaks;
  33022. for (juce::PopupMenu::MenuItemIterator it (laid.menu); it.next();)
  33023. {
  33024. const auto& item = it.getItem();
  33025. int w = 0, h = 0;
  33026. if (item.customComponent != nullptr)
  33027. item.customComponent->getIdealSize (w, h); // (a title band: its own height, as JUCE asks it)
  33028. else
  33029. lf.getIdealPopupMenuItemSize (item.text, item.isSeparator, item.isSectionHeader ? -1 : 0, w, h);
  33030. if (item.isSectionHeader) h += h / 2; // as JUCE does
  33031. rows.push_back ({ &item, h });
  33032. shape.push_back ({ h, item.isSeparator, item.isSectionHeader });
  33033. if (item.shouldBreakAfter)
  33034. breaks.push_back ((int) rows.size() - 1);
  33035. }
  33036. if (breaks.empty())
  33037. if (const auto at = lynx::themes::tallMenuBreak (shape, 1080 * 7 / 10); at >= 0)
  33038. breaks.push_back (at);
  33039. laid.columns.emplace_back();
  33040. laid.widths.push_back (160);
  33041. for (int i = 0; i < (int) rows.size(); ++i)
  33042. {
  33043. const auto& item = *rows[(std::size_t) i].item;
  33044. int w = 0, h = 0;
  33045. if (item.customComponent != nullptr)
  33046. item.customComponent->getIdealSize (w, h);
  33047. else
  33048. lf.getIdealPopupMenuItemSize (item.text, item.isSeparator, item.isSectionHeader ? -1 : 0, w, h);
  33049. if (item.shortcutKeyDescription.isNotEmpty() || item.text.containsChar ('\t'))
  33050. w += 90;
  33051. laid.columns.back().push_back (rows[(std::size_t) i]);
  33052. laid.widths.back() = juce::jmax (laid.widths.back(), w + 10);
  33053. if (std::find (breaks.begin(), breaks.end(), i) != breaks.end() && i + 1 < (int) rows.size())
  33054. {
  33055. laid.columns.emplace_back();
  33056. laid.widths.push_back (160);
  33057. }
  33058. }
  33059. laid.width = (int) (laid.columns.size() - 1) * separatorWidth;
  33060. for (std::size_t c = 0; c < laid.columns.size(); ++c)
  33061. {
  33062. laid.width += laid.widths[c];
  33063. int h = 2 * border;
  33064. for (const auto& row : laid.columns[c])
  33065. h += row.height;
  33066. laid.height = juce::jmax (laid.height, h);
  33067. }
  33068. }
  33069. int totalWidth = 16, totalHeight = 0;
  33070. for (const auto& l : menus)
  33071. {
  33072. totalWidth += l.width + 16;
  33073. totalHeight = juce::jmax (totalHeight, l.height + 32);
  33074. }
  33075. auto image = lynx::shot::canvas (totalWidth, totalHeight);
  33076. {
  33077. juce::Graphics g (image);
  33078. lynx::shot::logical (g);
  33079. g.fillAll (lynx::theme::colour::bg1);
  33080. int x = 16;
  33081. bool first = true;
  33082. for (int m = 0; m < (int) menus.size(); ++m)
  33083. {
  33084. const auto& l = menus[(std::size_t) m];
  33085. g.setColour (lynx::theme::colour::textSecondary);
  33086. g.setFont (lynx::theme::font (lynx::theme::type::small, true));
  33087. g.drawText (names[m], x, 0, l.width, 24, juce::Justification::centredLeft);
  33088. {
  33089. juce::Graphics::ScopedSaveState state (g);
  33090. g.reduceClipRegion (x, 24, l.width, l.height);
  33091. g.setOrigin (x, 24);
  33092. lf.drawPopupMenuBackground (g, l.width, l.height);
  33093. int columnX = 0;
  33094. for (std::size_t c = 0; c < l.columns.size(); ++c)
  33095. {
  33096. int y = border;
  33097. for (const auto& row : l.columns[c])
  33098. {
  33099. const auto& item = *row.item;
  33100. const juce::Rectangle<int> r (columnX + (c == 0 ? border : 0), y, l.widths[c] - (c == 0 ? border : 0) - (c + 1 == l.columns.size() ? border : 0),
  33101. row.height);
  33102. auto text = item.text, shortcut = item.shortcutKeyDescription;
  33103. if (text.containsChar ('\t'))
  33104. {
  33105. shortcut = text.fromFirstOccurrenceOf ("\t", false, false);
  33106. text = text.upToFirstOccurrenceOf ("\t", false, false);
  33107. }
  33108. if (item.isSectionHeader)
  33109. lf.drawPopupMenuSectionHeader (g, r, text);
  33110. else if (item.customComponent != nullptr)
  33111. {
  33112. juce::Graphics::ScopedSaveState itemState (g);
  33113. g.setOrigin (r.getPosition());
  33114. item.customComponent->setSize (r.getWidth(), r.getHeight());
  33115. item.customComponent->paintEntireComponent (g, false);
  33116. }
  33117. else
  33118. lf.drawPopupMenuItem (g, r, item.isSeparator, item.isEnabled, first && ! item.isSeparator && m == 0, item.isTicked,
  33119. item.subMenu != nullptr, text, shortcut, item.image.get(), nullptr);
  33120. first = false;
  33121. y += row.height;
  33122. }
  33123. columnX += l.widths[c];
  33124. if (c + 1 < l.columns.size())
  33125. {
  33126. lf.drawPopupMenuColumnSeparatorWithOptions (g, juce::Rectangle<int> (columnX, border, separatorWidth, l.height - 2 * border),
  33127. juce::PopupMenu::Options());
  33128. columnX += separatorWidth;
  33129. }
  33130. }
  33131. }
  33132. x += l.width + 16;
  33133. }
  33134. }
  33135. const auto file = lynx::shot::file (juce::File (path));
  33136. file.deleteFile();
  33137. juce::PNGImageFormat png;
  33138. if (auto out = file.createOutputStream())
  33139. png.writeImageToStream (image, *out);
  33140. }
  33141. static void writePng (const juce::Image& image, const juce::String& path)
  33142. {
  33143. const auto file = lynx::shot::file (juce::File (path));
  33144. file.deleteFile();
  33145. juce::PNGImageFormat png;
  33146. if (auto out = file.createOutputStream())
  33147. png.writeImageToStream (image, *out);
  33148. }
  33149. // the splash screen: one settled frame, and a strip of frames through its animation
  33150. static void saveSplashFrames (const juce::String& prefix)
  33151. {
  33152. lynx::SplashScreen splash;
  33153. splash.setStatus (lynx::tr ("Loading the workspace..."));
  33154. splash.setTimeForSnapshot (1.6);
  33155. writePng (lynx::shot::snapshot (splash), prefix + "-splash.png");
  33156. const double times[] = { 0.10, 0.22, 0.29, 0.40, 0.58, 0.75, 1.00, 1.30 };
  33157. const auto w = lynx::SplashScreen::width / 2, h = lynx::SplashScreen::height / 2;
  33158. auto strip = lynx::shot::canvas (4 * (w + 8) + 8, 2 * (h + 8) + 8);
  33159. {
  33160. juce::Graphics g (strip);
  33161. lynx::shot::logical (g);
  33162. g.fillAll (lynx::theme::colour::bg1);
  33163. for (int i = 0; i < 8; ++i)
  33164. {
  33165. splash.setTimeForSnapshot (times[i]);
  33166. const auto frame = lynx::shot::snapshot (splash);
  33167. g.drawImage (frame, 8 + (i % 4) * (w + 8), 8 + (i / 4) * (h + 8), w, h, 0, 0, frame.getWidth(), frame.getHeight());
  33168. }
  33169. }
  33170. writePng (strip, prefix + "-splash-frames.png");
  33171. }
  33172. // every icon at 16, 20 and 24 px (at `scale`, e.g. 1.5 for a 150% display), in the toolbar's
  33173. // colours: at rest, hovered and switched on
  33174. // round 190je (design190ia G1): one state sheet per button kind: idle, hover, pressed, on, disabled, as the one state rule
  33175. // draws them (core/ThemePalette.h buttonLook); the menu rows in both menu styles
  33176. static void saveStateSheet (const juce::String& path, float scale)
  33177. {
  33178. using namespace lynx;
  33179. scale *= shot::scale();
  33180. auto& lf = juce::LookAndFeel::getDefaultLookAndFeel();
  33181. const int labelWidth = 220, cellW = 120, cellH = 40, columns = 5;
  33182. const juce::String heads[] = { "idle", "hover", "pressed", "on", "disabled" };
  33183. enum Kind { text, iconFilled, iconOnce, iconSwitch, iconSwitchOwn, tick, radio, combo, tab, menuDark, menuFl, kinds };
  33184. const char* names[] = { "Text button", "Icon button (filled)", "Toolbar icon (acts once)", "Toolbar switch", "Toolbar switch (own colours)",
  33185. "Tick box", "Radio choice", "Combo box", "Tab", "Menu item (LYNX dark)", "Menu item (FL classic)" };
  33186. const auto w = labelWidth + columns * cellW + 16, h = 30 + kinds * cellH + 16;
  33187. juce::Image image (juce::Image::ARGB, juce::roundToInt ((float) w * scale), juce::roundToInt ((float) h * scale), true);
  33188. {
  33189. juce::Graphics g (image);
  33190. g.addTransform (juce::AffineTransform::scale (scale));
  33191. g.fillAll (theme::colour::bg3);
  33192. g.setFont (theme::font (theme::type::small, true));
  33193. g.setColour (theme::colour::textSecondary);
  33194. for (int c = 0; c < columns; ++c)
  33195. g.drawText (heads[c], labelWidth + c * cellW, 6, cellW, 20, juce::Justification::centred);
  33196. const auto styleBefore = theme::menus::style();
  33197. for (int k = 0; k < kinds; ++k)
  33198. {
  33199. const auto y = 30 + k * cellH;
  33200. g.setFont (theme::font (theme::type::small));
  33201. g.setColour (theme::colour::textPrimary);
  33202. g.drawText (names[k], 8, y, labelWidth - 12, cellH, juce::Justification::centredLeft);
  33203. for (int c = 0; c < columns; ++c)
  33204. {
  33205. const auto hover = c == 1, down = c == 2, on = c == 3, disabled = c == 4;
  33206. const juce::Rectangle<int> cell (labelWidth + c * cellW, y, cellW, cellH);
  33207. juce::Graphics::ScopedSaveState state (g);
  33208. g.reduceClipRegion (cell);
  33209. switch (k)
  33210. {
  33211. case text:
  33212. {
  33213. juce::TextButton b ("Export");
  33214. b.setSize (96, 26);
  33215. b.setToggleState (on, juce::dontSendNotification);
  33216. b.setEnabled (! disabled);
  33217. g.setOrigin (cell.getX() + 12, cell.getY() + 7);
  33218. lf.drawButtonBackground (g, b, b.findColour (on ? juce::TextButton::buttonOnColourId : juce::TextButton::buttonColourId), hover, down);
  33219. lf.drawButtonText (g, b, hover, down);
  33220. break;
  33221. }
  33222. case iconFilled:
  33223. case iconOnce:
  33224. case iconSwitch:
  33225. case iconSwitchOwn:
  33226. {
  33227. IconButton b ("state", k == iconFilled ? Icon::plus : k == iconOnce ? Icon::save : Icon::metronome);
  33228. b.setFlat (k != iconFilled);
  33229. if (k == iconSwitch)
  33230. b.setToggleLook (true);
  33231. if (k == iconSwitchOwn)
  33232. {
  33233. b.setOnColour (theme::colour::bg6);
  33234. b.setIconColourWhenOn (theme::colour::accent);
  33235. }
  33236. b.setSize (k == iconFilled ? 34 : 30, 30);
  33237. b.setToggleState (on, juce::dontSendNotification);
  33238. b.setEnabled (! disabled);
  33239. g.setOrigin (cell.getX() + 12, cell.getY() + 5);
  33240. b.paintButton (g, hover, down);
  33241. break;
  33242. }
  33243. case tick:
  33244. case radio:
  33245. {
  33246. juce::ToggleButton b (k == tick ? "Snap to grid" : "Pattern");
  33247. if (k == radio)
  33248. b.getProperties().set ("lynxRadio", true);
  33249. b.setSize (110, 24);
  33250. b.setToggleState (on, juce::dontSendNotification);
  33251. b.setEnabled (! disabled);
  33252. g.setOrigin (cell.getX() + 6, cell.getY() + 8);
  33253. lf.drawToggleButton (g, b, hover, down);
  33254. break;
  33255. }
  33256. case combo:
  33257. {
  33258. if (hover || down || on) // (a combo box's hover comes from the mouse itself: --uitest covers it)
  33259. break;
  33260. juce::ComboBox b;
  33261. b.setSize (100, 24);
  33262. b.setEnabled (! disabled);
  33263. g.setOrigin (cell.getX() + 10, cell.getY() + 8);
  33264. lf.drawComboBox (g, 100, 24, false, 0, 0, 0, 0, b);
  33265. g.setColour (disabled ? theme::colour::textDisabled : theme::colour::textPrimary);
  33266. g.setFont (lf.getComboBoxFont (b));
  33267. g.drawText ("1/16 step", 6, 0, 70, 24, juce::Justification::centredLeft);
  33268. break;
  33269. }
  33270. case tab:
  33271. {
  33272. if (disabled)
  33273. break;
  33274. juce::TabbedButtonBar bar (juce::TabbedButtonBar::TabsAtTop);
  33275. bar.setSize (220, 32);
  33276. bar.addTab ("Audio", theme::colour::bg2, -1);
  33277. bar.addTab ("MIDI", theme::colour::bg2, -1);
  33278. bar.setCurrentTabIndex (on ? 1 : 0, false);
  33279. auto* tabButton = bar.getTabButton (1);
  33280. tabButton->setBounds (0, 0, 100, 32);
  33281. g.setOrigin (cell.getX() + 10, cell.getY() + 4);
  33282. g.setColour (theme::colour::bg1);
  33283. g.fillRect (0, 0, 100, 32);
  33284. lf.drawTabButton (*tabButton, g, hover, down);
  33285. break;
  33286. }
  33287. case menuDark:
  33288. case menuFl:
  33289. {
  33290. if (down)
  33291. break;
  33292. theme::menus::setStyle (k == menuFl ? themes::MenuStyle::flClassic : themes::MenuStyle::lynxDark);
  33293. g.setOrigin (cell.getX() + 4, cell.getY() + 8);
  33294. lf.drawPopupMenuBackground (g, 112, 25);
  33295. lf.drawPopupMenuItem (g, { 2, 2, 108, 21 }, false, ! disabled, hover, on, false, theme::mnemonic ("Open", 'O'), "Ctrl+O", nullptr, nullptr);
  33296. theme::menus::setStyle (styleBefore);
  33297. break;
  33298. }
  33299. default:
  33300. break;
  33301. }
  33302. }
  33303. }
  33304. }
  33305. writePng (image, path);
  33306. }
  33307. static void saveIconSheet (const juce::String& path, float scale)
  33308. {
  33309. scale *= lynx::shot::scale();
  33310. const int sizes[] = { 16, 20, 24 };
  33311. const int cell = 34, columns = 3 * 3, labelWidth = 110;
  33312. const auto w = labelWidth + columns * cell + 16, h = lynx::iconCount * cell + 16;
  33313. juce::Image image (juce::Image::ARGB, juce::roundToInt ((float) w * scale), juce::roundToInt ((float) h * scale), true);
  33314. {
  33315. juce::Graphics g (image); // (drawing is flushed when it goes out of scope)
  33316. g.addTransform (juce::AffineTransform::scale (scale));
  33317. g.fillAll (lynx::theme::colour::bg3);
  33318. g.setFont (lynx::theme::font (lynx::theme::type::small));
  33319. for (int i = 1; i < lynx::iconCount; ++i)
  33320. {
  33321. const auto y = 8 + (i - 1) * cell;
  33322. g.setColour (lynx::theme::colour::textDisabled);
  33323. g.drawText (juce::String (i), 8, y, labelWidth - 8, cell, juce::Justification::centredLeft);
  33324. for (int v = 0; v < 3; ++v)
  33325. for (int s = 0; s < 3; ++s)
  33326. {
  33327. const juce::Rectangle<float> box ((float) (labelWidth + (v * 3 + s) * cell), (float) y, (float) cell, (float) cell);
  33328. const auto bg = v == 2 ? lynx::theme::colour::accent : v == 1 ? lynx::theme::colour::bg5 : lynx::theme::colour::bg3;
  33329. g.setColour (bg);
  33330. g.fillRoundedRectangle (box.reduced (2.0f), 4.0f);
  33331. const auto fg = v == 2 ? lynx::theme::colour::onAccent : v == 1 ? lynx::theme::colour::textPrimary
  33332. : lynx::theme::colour::textSecondary.brighter (0.25f);
  33333. lynx::icons::draw (g, (lynx::Icon) i, box.withSizeKeepingCentre ((float) sizes[s], (float) sizes[s]), fg);
  33334. }
  33335. }
  33336. }
  33337. writePng (image, path);
  33338. }
  33339. // a part of a component (e.g. the main toolbar)
  33340. static void saveArea (juce::Component& c, juce::Rectangle<int> area, const juce::String& path)
  33341. {
  33342. const auto file = lynx::shot::file (juce::File (path));
  33343. file.deleteFile();
  33344. juce::PNGImageFormat png;
  33345. if (auto out = file.createOutputStream())
  33346. png.writeImageToStream (lynx::shot::snapshot (c, area), *out);
  33347. }
  33348. static void savePng (const juce::Image& image, const juce::String& path)
  33349. {
  33350. const auto file = lynx::shot::file (juce::File (path));
  33351. file.deleteFile();
  33352. juce::PNGImageFormat png;
  33353. if (auto out = file.createOutputStream())
  33354. png.writeImageToStream (image, *out);
  33355. }
  33356. // -toolbar-tips.png: the top of the window with the bubbles of a few controls as they appear under the
  33357. // mouse; -tips-sheet.png: every quick tip of the window, to check names, shortcuts and translations
  33358. static void saveQuickTips (lynx::MainComponent& ui, const juce::String& prefix)
  33359. {
  33360. const auto tips = ui.getQuickTipsForSnapshot();
  33361. const auto top = juce::Rectangle<int> (0, 0, ui.getWidth(), juce::jmin (ui.getHeight(), ui.getToolbarBoundsForSnapshot().getHeight() + 72));
  33362. auto image = lynx::shot::snapshot (ui, top);
  33363. {
  33364. juce::Graphics g (image);
  33365. lynx::shot::logical (g);
  33366. const juce::String shown[] = { lynx::tr ("Pattern mode"), lynx::tr ("Play"), lynx::tr ("Metronome"), lynx::tr ("Mixer"), lynx::tr ("Save project"),
  33367. lynx::tr ("Window options"), lynx::tr ("Close") };
  33368. std::vector<juce::Rectangle<int>> used;
  33369. for (const auto& [area, tip] : tips)
  33370. {
  33371. const auto name = tip.upToFirstOccurrenceOf ("\t", false, false);
  33372. if (std::find (std::begin (shown), std::end (shown), name) == std::end (shown))
  33373. continue;
  33374. const auto bubble = lynx::ui::quickTipBounds (tip, area, top);
  33375. if (std::any_of (used.begin(), used.end(), [&] (const auto& r) { return r.intersects (bubble); }))
  33376. continue;
  33377. used.push_back (bubble);
  33378. g.setColour (juce::Colours::white.withAlpha (0.075f)); // the hovered control
  33379. g.fillRoundedRectangle (area.toFloat().reduced (0.5f), lynx::theme::radius::md);
  33380. lynx::ui::paintQuickTip (g, bubble.toFloat(), tip);
  33381. }
  33382. }
  33383. savePng (image, prefix + "-toolbar-tips.png");
  33384. // the sheet: bubbles in rows
  33385. const int width = 900;
  33386. int x = 12, y = 12;
  33387. std::vector<std::pair<juce::Rectangle<int>, juce::String>> placed;
  33388. for (const auto& [area, tip] : tips)
  33389. {
  33390. auto r = lynx::ui::quickTipSize (tip);
  33391. if (x + r.getWidth() > width - 12)
  33392. {
  33393. x = 12;
  33394. y += r.getHeight() + 10;
  33395. }
  33396. placed.emplace_back (r.withPosition (x, y), tip);
  33397. x += r.getWidth() + 10;
  33398. }
  33399. auto sheet = lynx::shot::canvas (width, y + 20 + 12);
  33400. {
  33401. juce::Graphics g (sheet);
  33402. lynx::shot::logical (g);
  33403. g.fillAll (lynx::theme::colour::bg3);
  33404. for (const auto& [r, tip] : placed)
  33405. lynx::ui::paintQuickTip (g, r.toFloat(), tip);
  33406. }
  33407. savePng (sheet, prefix + "-tips-sheet.png");
  33408. }
  33409. static juce::StringArray& textFitLog()
  33410. {
  33411. static juce::StringArray log;
  33412. return log;
  33413. }
  33414. // drawFittedText would shrink `text` below `minScale` or cut it: fewer visible glyphs than the text has
  33415. static bool textIsCut (const juce::Font& font, const juce::String& text, juce::Rectangle<int> area, int maxLines, float minScale)
  33416. {
  33417. if (text.trim().isEmpty() || area.getWidth() <= 4 || area.getHeight() <= 4)
  33418. return false;
  33419. auto visible = [] (juce::GlyphArrangement& ga) {
  33420. int n = 0;
  33421. for (int i = 0; i < ga.getNumGlyphs(); ++i)
  33422. n += ga.getGlyph (i).isWhitespace() ? 0 : 1;
  33423. return n;
  33424. };
  33425. juce::GlyphArrangement fitted, full;
  33426. fitted.addFittedText (font, text, 0.0f, 0.0f, (float) area.getWidth(), (float) area.getHeight(), juce::Justification::centredLeft,
  33427. juce::jmax (1, maxLines), minScale);
  33428. full.addLineOfText (font, text, 0.0f, 0.0f);
  33429. return visible (fitted) < visible (full);
  33430. }
  33431. // walks the visible components under `root` and logs the texts that don't fit (labels, text buttons, tick boxes)
  33432. static void checkTextFit (juce::Component& root, const juce::String& where)
  33433. {
  33434. std::function<void (juce::Component&)> visit = [&] (juce::Component& c) {
  33435. if (! c.isVisible() || c.getWidth() <= 0 || c.getHeight() <= 0)
  33436. return;
  33437. juce::String text;
  33438. bool cut = false;
  33439. if (auto* label = dynamic_cast<juce::Label*> (&c); label != nullptr && ! label->isBeingEdited())
  33440. {
  33441. const auto font = label->getLookAndFeel().getLabelFont (*label);
  33442. const auto area = label->getBorderSize().subtractedFrom (label->getLocalBounds());
  33443. text = label->getText();
  33444. cut = textIsCut (font, text, area, juce::jmax (1, (int) ((float) area.getHeight() / font.getHeight())),
  33445. label->getMinimumHorizontalScale());
  33446. }
  33447. else if (auto* toggle = dynamic_cast<juce::ToggleButton*> (&c))
  33448. {
  33449. const auto tick = juce::jmin (16.0f, (float) c.getHeight() - 4.0f);
  33450. text = toggle->getButtonText();
  33451. cut = textIsCut (juce::Font (lynx::theme::font (juce::jmin ((float) lynx::theme::type::body, (float) c.getHeight() * 0.75f))), text,
  33452. c.getLocalBounds().withTrimmedLeft (juce::roundToInt (tick) + 8).withTrimmedRight (2), 2, 0.85f);
  33453. }
  33454. else if (auto* button = dynamic_cast<juce::TextButton*> (&c);
  33455. button != nullptr && (int) button->getProperties().getWithDefault (lynx::theme::LookAndFeel::iconProperty, 0) == 0)
  33456. {
  33457. text = button->getButtonText();
  33458. cut = textIsCut (button->getLookAndFeel().getTextButtonFont (*button, button->getHeight()), text,
  33459. button->getLocalBounds().reduced (juce::jmin (8, button->getWidth() / 6), 0), 2, 0.85f);
  33460. }
  33461. if (cut)
  33462. {
  33463. juce::String path;
  33464. for (auto* p = &c; p != nullptr && p != &root; p = p->getParentComponent())
  33465. if (p->getName().isNotEmpty())
  33466. path = p->getName() + (path.isEmpty() ? "" : "/") + path;
  33467. const auto line = where + " | " + juce::String (c.getWidth()) + "x" + juce::String (c.getHeight()) + " | " + text.replace ("\n", "\\n")
  33468. + (path.isEmpty() ? juce::String() : " | " + path);
  33469. textFitLog().addIfNotAlreadyThere (line);
  33470. }
  33471. for (auto* child : c.getChildren())
  33472. visit (*child);
  33473. };
  33474. visit (root);
  33475. }
  33476. static void saveSnapshot (juce::Component& c, const juce::String& path)
  33477. {
  33478. checkTextFit (c, juce::File (path).getFileNameWithoutExtension());
  33479. const auto file = lynx::shot::file (juce::File (path));
  33480. file.deleteFile();
  33481. juce::PNGImageFormat png;
  33482. if (auto out = file.createOutputStream())
  33483. png.writeImageToStream (lynx::shot::snapshot (c), *out);
  33484. }
  33485. class MainWindow final : public juce::DocumentWindow
  33486. {
  33487. public:
  33488. MainWindow (const juce::String& name, lynx::AudioEngine& engine)
  33489. : DocumentWindow (name, lynx::theme::window, DocumentWindow::allButtons, false)
  33490. {
  33491. probeEngine = &engine;
  33492. // (round 190hd) one desktop window, made with the native title bar: before, JUCE made one with its own title
  33493. // bar and setUsingNativeTitleBar made it again (~20-35 ms each, the Direct2D context included)
  33494. setUsingNativeTitleBar (true);
  33495. addToDesktop();
  33496. setIcon (lynx::logoImage());
  33497. startupTrace.mark (" window: its desktop window (native title bar), icon");
  33498. content = new lynx::MainComponent (engine);
  33499. setContentOwned (content, true);
  33500. startupTrace.mark (" window: content set");
  33501. setResizable (true, true);
  33502. setResizeLimits (800, 400, 10000, 10000);
  33503. // ~88% of the main display's usable area (at least the UI's design size, but never larger than the
  33504. // display: the AppImage catalog test runs on an 800x600 screen)
  33505. if (const auto* display = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay())
  33506. {
  33507. const auto area = display->userArea;
  33508. const auto fit = [] (int design, int available) {
  33509. return juce::jmin (available, juce::jmax (design, (int) (available * 0.88)));
  33510. };
  33511. setSize (fit (getWidth(), area.getWidth()), fit (getHeight(), area.getHeight()));
  33512. }
  33513. centreWithSize (getWidth(), getHeight());
  33514. // where it was last time (round 167v); the first start opens maximized, the Playlist filling the screen
  33515. // with the Browser at the left and the Channel Rack above it, like FL Studio's first start
  33516. const auto saved = stateFile().loadFileAsString().trim();
  33517. // (LYNX_TEST_MODE keeps the fixed-size window scripted checks expect, unless LYNX_TEST_MAXIMIZE=1)
  33518. const auto firstStart = saved.isEmpty()
  33519. && (! lynx::platform::testMode() || juce::SystemStats::getEnvironmentVariable ("LYNX_TEST_MAXIMIZE", {}) == "1");
  33520. maximiseOnReveal = firstStart || saved.startsWithIgnoreCase ("fs");
  33521. if (saved.isNotEmpty())
  33522. restoreWindowStateFromString (saved.startsWithIgnoreCase ("fs") ? saved.substring (2).trim() : saved);
  33523. }
  33524. // Shows the window (built hidden while the splash screen is up).
  33525. void reveal()
  33526. {
  33527. if (lynx::uitrace::enabled()) // LYNX_TRACE_UI: the frames per second and the longest gap in ui.log (round 173f)
  33528. watchFrames ({});
  33529. setVisible (true);
  33530. // LYNX_LOCATOR_PROBE=1 (round 190ip, measurements): a floating window with a locator moving 30 times a second
  33531. if (juce::SystemStats::getEnvironmentVariable ("LYNX_LOCATOR_PROBE", {}) == "1")
  33532. juce::Timer::callAfterDelay (1500, [e = probeEngine] {
  33533. lynx::ui::openLocatorProbe ([e] {
  33534. const auto& transport = e->getTransport();
  33535. const auto bar = (double) juce::jmax<std::int64_t> (1, e->getSong().barTicks());
  33536. return transport.playing.load() ? std::fmod (transport.positionTicks.load(), bar) / bar : -1.0;
  33537. });
  33538. });
  33539. lynx::applyWindowChrome (*this);
  33540. lynx::fitWindowOnScreen (*this); // a size saved at another UI zoom still fits (round 163)
  33541. if (maximiseOnReveal)
  33542. setFullScreen (true); // (a title-bar window: maximized, the taskbar stays)
  33543. toFront (true);
  33544. content->grabKeyboardFocus();
  33545. // issue #62: the detached panels restored with the layout (built before this window was shown): their saved
  33546. // place and above it, once the window manager has placed this one
  33547. juce::Timer::callAfterDelay (250, [safe = juce::Component::SafePointer<MainWindow> (this)] {
  33548. if (safe != nullptr)
  33549. safe->content->restoreDetachedWindows();
  33550. });
  33551. }
  33552. // Runs `then` once, right after the window's next frame (round 190go: the audio device opens behind the
  33553. // window's first frame, not before it); at the latest after 300 ms (a window that paints nothing: minimised).
  33554. void whenPainted (std::function<void()> then)
  33555. {
  33556. afterPaint = std::move (then);
  33557. afterPaintPosted = false;
  33558. repaint();
  33559. juce::Timer::callAfterDelay (300, [safe = juce::Component::SafePointer<MainWindow> (this)] {
  33560. if (safe != nullptr)
  33561. safe->runAfterPaint();
  33562. });
  33563. }
  33564. void runAfterPaint()
  33565. {
  33566. if (auto then = std::exchange (afterPaint, nullptr))
  33567. then();
  33568. }
  33569. // The window's place and maximized state for the next start (main-window.txt in the settings folder).
  33570. void saveState() { stateFile().replaceWithText (getWindowStateAsString()); }
  33571. static juce::File stateFile() { return lynx::PluginHost::settingsFolder().getChildFile ("main-window.txt"); }
  33572. void openFile (const juce::File& file) { content->openFile (file); }
  33573. lynx::MainComponent& getContent() { return *content; }
  33574. void showSetupWizard() { content->showSetupWizard(); }
  33575. void confirmDiscard (std::function<void()> then) { content->confirmDiscard (std::move (then)); }
  33576. void closeButtonPressed() override { JUCEApplication::getInstance()->systemRequestedQuit(); }
  33577. // Every frame the window paints, with its dirty area (ui/FrameProbe.h; --uiperf, LYNX_TRACE_UI). The trace keeps
  33578. // counting when --uiperf watches too.
  33579. void watchFrames (std::function<void (double, juce::Rectangle<int>)> callback)
  33580. {
  33581. if (probe == nullptr)
  33582. {
  33583. probe = std::make_unique<lynx::ui::FrameProbe>();
  33584. Component::addAndMakeVisible (*probe); // (ResizableWindow hides the plain overload)
  33585. probe->setBounds (getLocalBounds());
  33586. }
  33587. probe->onFrame = [callback = std::move (callback)] (double now, juce::Rectangle<int> area) {
  33588. if (lynx::uitrace::enabled())
  33589. lynx::uitrace::frame (now);
  33590. if (callback)
  33591. callback (now, area);
  33592. };
  33593. }
  33594. void resized() override
  33595. {
  33596. DocumentWindow::resized();
  33597. if (probe != nullptr)
  33598. probe->setBounds (getLocalBounds());
  33599. }
  33600. // --uiperf: the time of each frame the window paints (its own paint, then every child's, up to the last)
  33601. std::function<void (double)> onFrame;
  33602. void paint (juce::Graphics& g) override
  33603. {
  33604. if (onFrame)
  33605. frameStart = juce::Time::getMillisecondCounterHiRes();
  33606. DocumentWindow::paint (g);
  33607. }
  33608. void paintOverChildren (juce::Graphics& g) override
  33609. {
  33610. DocumentWindow::paintOverChildren (g);
  33611. if (afterPaint != nullptr && ! std::exchange (afterPaintPosted, true)) // (the frame is presented first)
  33612. juce::MessageManager::callAsync ([safe = juce::Component::SafePointer<MainWindow> (this)] {
  33613. if (safe != nullptr)
  33614. safe->runAfterPaint();
  33615. });
  33616. if (onFrame && frameStart > 0.0)
  33617. onFrame (juce::Time::getMillisecondCounterHiRes() - frameStart);
  33618. frameStart = 0.0;
  33619. }
  33620. private:
  33621. lynx::MainComponent* content = nullptr; // owned by the window
  33622. std::unique_ptr<lynx::ui::FrameProbe> probe; // (on top of the content; see watchFrames)
  33623. double frameStart = 0.0;
  33624. bool maximiseOnReveal = false;
  33625. std::function<void()> afterPaint; // (whenPainted)
  33626. lynx::AudioEngine* probeEngine = nullptr; // (LYNX_LOCATOR_PROBE)
  33627. bool afterPaintPosted = false;
  33628. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MainWindow)
  33629. };
  33630. lynx::theme::LookAndFeel lookAndFeel;
  33631. std::unique_ptr<lynx::AudioEngine> engine;
  33632. std::unique_ptr<lynx::RemoteControl> remoteControl;
  33633. std::unique_ptr<juce::XmlElement> savedDeviceState; // --rtstress: the user's device before this run's --type/--buffer
  33634. // Hidden test mode --asiodll "<driver.dll>[|{CLSID}]" (REA round 97): an ASIO driver loaded straight from its file,
  33635. // without registering it, listed as the driver type "ASIO driver file". True when one was added.
  33636. bool addDriverFileDeviceType()
  33637. {
  33638. const auto args = juce::JUCEApplication::getCommandLineParameterArray();
  33639. const auto i = args.indexOf ("--asiodll");
  33640. if (i < 0 || i + 1 >= args.size() || engine == nullptr)
  33641. return false;
  33642. auto& devices = engine->getDeviceManager();
  33643. devices.getAvailableDeviceTypes(); // creates the standard types first
  33644. for (auto* t : devices.getAvailableDeviceTypes())
  33645. if (t->getTypeName() == lynx::dllAsioTypeName)
  33646. return true;
  33647. auto type = lynx::makeDllAsioDeviceType (args[i + 1].unquoted());
  33648. if (type == nullptr)
  33649. return false;
  33650. devices.addAudioDeviceType (std::move (type));
  33651. return true;
  33652. }
  33653. void restoreSavedDeviceState()
  33654. {
  33655. if (engine != nullptr)
  33656. engine->restoreAudioDeviceState (savedDeviceState.get());
  33657. }
  33658. std::unique_ptr<MainWindow> mainWindow;
  33659. std::unique_ptr<juce::Timer> perf; // --uiperf
  33660. std::unique_ptr<lynx::StartupSplash> splash;
  33661. static constexpr double landingSeconds = 1.05; // the logo's drop (SplashScreen::remainingDuration's `landing`)
  33662. std::shared_future<std::pair<juce::Image, double>> graphicsDeviceJob; // (round 190hd) holds the graphics device
  33663. bool graphicsDeviceMarked = false, windowRevealed = false;
  33664. std::future<std::shared_ptr<const lynx::SampleData>> startupSampleJob; // (round 190go: the built-in start-up sound)
  33665. bool startedAfterWindow = false, startupSoundPlayed = false;
  33666. double splashDuration = lynx::SplashScreen::minimumDuration; // seconds of its clock (round 121: from the process start)
  33667. lynx::StartupOptions startupOptions;
  33668. juce::File fileToOpen;
  33669. bool startupFileHandled = false;
  33670. bool startWithoutPlugins = false; // --no-plugins project.lynx (round 190ap)
  33671. juce::File openTimeReport; // --opentime
  33672. int openTimeIdleSeconds = 10;
  33673. };
  33674. START_JUCE_APPLICATION (LynxApplication)