| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522 |
- #include <juce_gui_basics/juce_gui_basics.h>
- #include "engine/FileSort.h"
- #include "platform/Paths.h"
- #include "core/PlaylistOps.h"
- #include "core/Drumaxx.h"
- #include "core/PatternBlocks.h"
- #include "core/LoadTrace.h"
- #include "core/Patcher.h"
- #include "core/Patcherize.h"
- #include "core/Performance.h"
- #include "core/VideoPlayer.h"
- #include "core/Effects.h"
- #include "core/MixSuite.h"
- #include "core/HardwareInsert.h"
- #include "core/EchoSuite.h"
- #include "core/LynxTune.h"
- #include "core/FlEffects.h"
- #include "core/FlpImport.h"
- #include "core/NoteEdit.h"
- #include "core/MaximusFx.h"
- #include "core/Harmor.h"
- #include "flp/Flp.h"
- #include "core/SynthPresets.h"
- #include "core/FlWrapper.h"
- #include "engine/AudioEngine.h"
- #include "engine/Metronome.h"
- #include "engine/AudioLogger.h"
- #include "engine/DllAsioDevice.h"
- #include "engine/PipeWireDevice.h"
- #include "platform/LinuxRealtime.h"
- #include "engine/Exporter.h"
- #include "engine/FlStudioExport.h"
- #include "engine/MidiFileIo.h"
- #include "engine/PluginHost.h"
- #include "engine/PluginSandbox.h"
- #include "engine/Bridge32Test.h"
- #include "engine/ProjectFile.h"
- #include "core/Sha256.h"
- #include "engine/SessionPack.h"
- #include "engine/LiveTest.h"
- #include "core/SessionIds.h"
- #include "core/SessionParts.h"
- #include "engine/SampleLibrary.h"
- #include "engine/Text.h"
- #include "platform/FileTypes.h"
- #include "platform/Package.h"
- #include "ui/VideoPlayerView.h"
- #include "ui/PatcherEditor.h"
- #include "ui/VisualEditors.h"
- #include "ui/FlExtraEditors.h"
- #include "ui/VisualGl.h"
- #include "ui/DanceView.h"
- #include "ui/PluginPresetMenu.h"
- #include "ui/PluginWindow.h"
- #include "ui/PluginThumbs.h"
- #include "ui/ClipProperties.h"
- #include "ui/NewProjectDialog.h"
- #include "ui/PluginMonitorWindow.h"
- #include "ui/TouchKeyboard.h"
- #include "ui/AutomationUi.h"
- #include "ui/PluginSkin.h"
- #include "ui/ChannelSettings.h"
- #include "core/LynxBanks.h"
- #include "core/NativeEngines.h"
- #include "ui/ControllerEditors.h"
- #include "ui/NewtoneEditor.h"
- #include "core/NewtoneFx.h"
- #include "core/FormulaController.h"
- #include "core/MidiControls.h"
- #include "core/FlSynths.h"
- #include "core/SoundFont.h"
- #include "core/Sfz.h"
- #include "ui/Dialogs.h"
- #include "ui/FileChoosers.h"
- #include "ui/TrackIcons.h"
- #include "core/RackOps.h"
- #include "core/Layer.h"
- #include "core/XyController.h"
- #include "core/FlCurve.h"
- #include "core/ControlSurface.h"
- #include "core/VoltageController.h"
- #include "ui/Controllers164.h"
- #include "ui/ExportDialog.h"
- #include "ui/QuickAddPalette.h"
- #include "ui/I18n.h"
- #include "ui/MainComponent.h"
- #include "ui/FrameProbe.h"
- #include "ui/UiTrace.h"
- #include "core/MixerOps.h"
- #include "ui/QuickPick.h"
- #include "core/NoteTools.h"
- #include "engine/ProjectPackage.h"
- #include "ui/SetupWizard.h"
- #include "engine/FlStudio.h"
- #include "ui/HistoryPanel.h"
- #include "ui/MissingFilesDialog.h"
- #include "ui/SettingsDialog.h"
- #include "ui/PluginManager.h"
- #include "ui/ShortcutManager.h"
- #include "ui/NoteToolDialogs.h"
- #include "ui/EventEditor.h"
- #include "ui/AudioEditor.h"
- #include "ui/TempoTapper.h"
- #include "core/EventEdit.h"
- #include "core/FacetEq.h"
- #include "ui/FacetEqEditor.h"
- #include "core/RackRenderer.h"
- #include "ui/ProEditors.h"
- #include "ui/ParametricEqEditor.h"
- #include "ui/PluginEditors.h"
- #include "core/PluginLayout.h"
- #include "core/EffectPresets.h"
- #include "core/Vfx.h"
- #include "ui/Splash.h"
- #include "ui/Theme.h"
- #include "ui/ThemeSettings.h"
- #include "ui/WaveformView.h"
- #include "ui/WindowOwner.h"
- #include "ui/Toolbar.h"
- #include "ui/ToolWindow.h"
- #include "platform/CrashGuard.h"
- #include "ui/CrashReporter.h"
- #include "ui/Updater.h"
- #include "ui/StemExtract.h"
- #include <atomic>
- #include <chrono>
- #include <cstdio>
- #include <cstdlib>
- #include <mutex>
- #include <thread>
- namespace
- {
- lynx::AudioEngine* crashEngine = nullptr;
- // Startup trace (REA round 116): with LYNX_TRACE_STARTUP set, the time of each startup step since the C++ runtime
- // started is written to %APPDATA%\LYNX\startup.log (the loader's own time before that is not included).
- struct StartupTrace
- {
- using clock = std::chrono::steady_clock;
- const clock::time_point t0 = clock::now(); // static initialisation: no JUCE yet, standard library only
- const bool on = std::getenv ("LYNX_TRACE_STARTUP") != nullptr;
- juce::String text;
- clock::time_point last = t0;
- double seconds() const { return std::chrono::duration<double> (clock::now() - t0).count(); } // since the process started
- void mark (const char* step)
- {
- if (! on)
- return;
- const auto now = clock::now();
- const auto ms = [] (clock::duration d) { return std::chrono::duration<double, std::milli> (d).count(); };
- text << juce::String (ms (now - t0), 1).paddedLeft (' ', 8) << " ms +" << juce::String (ms (now - last), 1).paddedLeft (' ', 7) << " " << step << "\n";
- last = now;
- lynx::platform::settingsFile ("startup.log").replaceWithText (text);
- }
- };
- StartupTrace startupTrace;
- void startupMarkHook (const char* step) { startupTrace.mark (step); }
- // Crashed: try to save the project and write the backtrace (like FL's "emergency save").
- void onCrash (void* exceptionPointers)
- {
- const auto folder = lynx::platform::settingsFile ("autosave");
- folder.createDirectory();
- const auto stamp = juce::Time::getCurrentTime().formatted ("%Y-%m-%d %H-%M-%S");
- // JUCE's backtrace (named frames only), then every frame of the faulting thread as module+offset (round 157a: a
- // release LYNX.exe has no symbols, so its own frames were missing from the file)
- folder.getChildFile ("crash " + stamp + ".txt").replaceWithText (juce::SystemStats::getStackBacktrace() + "\n--- frames (module+offset)\n"
- + juce::String::fromUTF8 (lynx::crashguard::exceptionBacktrace (exceptionPointers).c_str()));
- lynx::crashguard::note (("crashed: backtrace in autosave\\crash " + stamp + ".txt").toStdString());
- if (crashEngine != nullptr)
- {
- juce::String error;
- lynx::ProjectFile::save (crashEngine->getSong(), folder.getChildFile ("recovered " + stamp + lynx::ProjectFile::extension), error);
- }
- }
- juce::File sessionsFolder()
- {
- return lynx::PluginHost::settingsFolder().getChildFile ("sessions");
- }
- // Sessions of earlier runs whose process is gone without closing (a fail-fast, a crash, a forced end): each is appended
- // to %APPDATA%\LYNX\crash-history.log and its file removed. Returns the last step of the newest one ("" when none).
- juce::StringArray uncleanSteps; // the newest unclean session's steps (without their times)
- juce::String uncleanSessionText; // the newest unclean session's whole file (round 159: the crash report reads it)
- // What the newest unclean session tells (round 157a): the plugin whose editor was opening / shown when it ended, and
- // whether its crash file blames a graphics driver
- struct UncleanCause
- {
- juce::String editorPlugin; // the last steps were that plugin's editor
- bool gpuDriver = false; // the crash file's top frames are in a GPU driver / Direct3D / Direct2D module
- juce::String driverModule;
- };
- UncleanCause uncleanCause()
- {
- UncleanCause cause;
- juce::File crashFile;
- for (int i = uncleanSteps.size(); --i >= 0 && i >= uncleanSteps.size() - 4;)
- {
- const auto& step = uncleanSteps[i];
- if (step.startsWith ("crashed: backtrace in "))
- crashFile = lynx::platform::settingsFolder().getChildFile (step.fromFirstOccurrenceOf ("backtrace in ", false, false).replaceCharacter ('\\', '/'));
- for (const auto* prefix : { "opening the editor of ", "editor open: ", "editor shown: " })
- if (cause.editorPlugin.isEmpty() && step.startsWith (prefix))
- cause.editorPlugin = step.fromFirstOccurrenceOf (prefix, false, false).trim();
- if (step.startsWith ("closing the editor of ") || step.startsWith ("loaded plugin") || step.startsWith ("opening project"))
- break; // older steps than these did not end the session
- }
- // issue #32 (round 174a): a plugin whose editor already faulted in this session (caught, LYNX went on) is the
- // likely cause when the session then ended without a word: offer it a separate process too
- for (int i = uncleanSteps.size(); --i >= 0 && cause.editorPlugin.isEmpty();)
- if (const auto editor = lynx::crashreport::parseEditorCrashStep (uncleanSteps[i].toStdString()); ! editor.plugin.empty())
- cause.editorPlugin = juce::String::fromUTF8 (editor.plugin.c_str());
- if (crashFile.existsAsFile())
- {
- // the first frames after the crash handler's own (the "--- frames" part lists the faulting thread)
- auto text = crashFile.loadFileAsString();
- if (text.contains ("--- frames"))
- text = text.fromFirstOccurrenceOf ("--- frames", false, false);
- auto lines = juce::StringArray::fromLines (text);
- int looked = 0;
- for (const auto& line : lines)
- {
- const auto module = line.fromFirstOccurrenceOf (": ", false, false).upToFirstOccurrenceOf ("+", false, false).trim().toLowerCase();
- if (module.isEmpty() || ! module.endsWith (".dll"))
- continue;
- if (++looked > 12)
- break;
- for (const auto* driver : { "igd", "ig9icd", "ig7icd", "igxelp", "nvwgf2um", "nvoglv", "nvd3dum", "atidxx", "atio6axx", "amdxx", "aticfx",
- "d3d11.dll", "d3d10warp", "dxgi.dll", "d2d1.dll", "opengl32.dll", "dcomp.dll" })
- if (module.startsWith (driver))
- {
- cause.gpuDriver = true;
- cause.driverModule = module;
- break;
- }
- if (cause.gpuDriver)
- break;
- }
- }
- return cause;
- }
- juce::String collectUncleanSessions()
- {
- juce::String lastStep;
- juce::Time newest;
- for (const auto& file : sessionsFolder().findChildFiles (juce::File::findFiles, false, "session-*.txt"))
- {
- const auto text = file.loadFileAsString();
- juce::StringPairArray values;
- juce::StringArray steps;
- for (const auto& line : juce::StringArray::fromLines (text))
- {
- if (line.startsWith ("step="))
- steps.add (line.fromFirstOccurrenceOf ("=", false, false));
- else if (line.contains ("="))
- values.set (line.upToFirstOccurrenceOf ("=", false, false), line.fromFirstOccurrenceOf ("=", false, false));
- }
- const auto pid = (std::uint32_t) values["pid"].getLargeIntValue();
- const auto start = (std::uint64_t) values["start"].getLargeIntValue();
- if (pid == lynx::crashguard::processId() || lynx::crashguard::processRunning (pid, start))
- continue; // this run, or another LYNX window still open
- lynx::PluginHost::settingsFolder().getChildFile ("crash-history.log")
- .appendText (juce::Time::getCurrentTime().toISO8601 (true) + " previous session ended without closing\n" + text + "\n");
- file.deleteFile();
- if (const auto modified = file.getLastModificationTime(); lastStep.isEmpty() || modified > newest)
- {
- newest = modified;
- lastStep = steps.isEmpty() ? juce::String ("start-up") : steps[steps.size() - 1].fromFirstOccurrenceOf (" ", false, false);
- uncleanSessionText = text;
- uncleanSteps.clear();
- for (const auto& step : steps)
- uncleanSteps.add (step.fromFirstOccurrenceOf (" ", false, false));
- }
- }
- return lastStep;
- }
- } // namespace
- // --uiperf (round 173f, discussion #10): a mixer fader dragged up and down with the mouse while the pattern plays. A
- // high-resolution timer delivers 125 moves a second to the message thread through the window's own mouse path
- // (ComponentPeer::handleMouseEvent), at most one waiting at a time as Windows does with WM_MOUSEMOVE; every frame the
- // window paints tells whether it covered the fader. Measured: how long a move waited for the message thread, the time
- // from a move to the first frame that shows the fader after it (input → paint), and whether the value stays put when
- // the mouse is released.
- struct UiPerfDrag final : public std::enable_shared_from_this<UiPerfDrag>,
- private juce::HighResolutionTimer
- {
- ~UiPerfDrag() override { stopTimer(); }
- void start (juce::Component& windowIn, juce::Component& strips, juce::Rectangle<int> rail, lynx::AudioEngine* engineIn, int trackIn)
- {
- window = &windowIn;
- engine = engineIn;
- track = trackIn;
- railInWindow = window->getLocalArea (&strips, rail);
- watch = railInWindow.expanded (6, 40); // the cap, its tip above and the dB read-out below
- visible = strips.isShowing() && window->getLocalArea (&strips, strips.getLocalBounds()).contains (railInWindow.getCentre());
- const auto volume = engine->getSong().mixer[(std::size_t) track].volume;
- x = (float) railInWindow.getCentreX();
- startY = (float) railInWindow.getBottom() - volume * (float) railInWindow.getHeight(); // on the cap: no jump
- amplitude = 0.4f * (float) railInWindow.getHeight();
- centreY = juce::jlimit ((float) railInWindow.getY() + amplitude, (float) railInWindow.getBottom() - amplitude, startY);
- t0 = juce::Time::getMillisecondCounterHiRes();
- inject (x, startY, false);
- juce::ModifierKeys::currentModifiers = juce::ModifierKeys (juce::ModifierKeys::leftButtonModifier);
- inject (x, startY, true);
- active = true;
- startTimer (8);
- }
- // message thread
- void framePainted (double now, juce::Rectangle<int> area)
- {
- if (pending.empty() || ! area.intersects (watch))
- return;
- for (const auto t : pending)
- latencies.push_back (now - t);
- pending.clear();
- ++framesOverFader;
- }
- // the moves end; as in the reporter's clip, the song is stopped while the button is still down
- juce::String stop()
- {
- stopTimer();
- active = false;
- valueAtRelease = engine->getSong().mixer[(std::size_t) track].volume;
- engine->stop();
- juce::String text;
- text << " drag of insert " << track << "'s fader" << (visible ? "" : " (NOT VISIBLE)") << ": " << moves << " moves handled, " << dropped
- << " folded into the next (the message thread still busy with the previous one)\n"
- << " move waited for the message thread: " << describe (queueDelays) << "\n"
- << " input -> paint (move to the first frame over the fader): " << describe (latencies) << ", " << framesOverFader
- << " frames over the fader\n";
- return text;
- }
- juce::String release()
- {
- const auto now = engine->getSong().mixer[(std::size_t) track].volume;
- juce::ModifierKeys::currentModifiers = {};
- inject (x, lastY, false);
- return " song stopped, button still down: fader " + juce::String (now, 4) + " (" + juce::String (valueAtRelease, 4) + " at the last move) "
- + (std::abs (now - valueAtRelease) < 1.0e-4f ? "kept" : "CHANGED") + "\n";
- }
- juce::String released() const
- {
- const auto now = engine->getSong().mixer[(std::size_t) track].volume;
- return " after the release: fader " + juce::String (now, 4) + " (" + juce::String (valueAtRelease, 4) + " when released) "
- + (std::abs (now - valueAtRelease) < 1.0e-4f ? "kept" : "CHANGED") + "\n";
- }
- private:
- juce::Component* window = nullptr;
- lynx::AudioEngine* engine = nullptr;
- int track = 1;
- juce::Rectangle<int> railInWindow, watch;
- bool visible = false;
- float x = 0.0f, startY = 0.0f, centreY = 0.0f, amplitude = 0.0f, lastY = 0.0f;
- double t0 = 0.0;
- std::atomic<bool> active { false }, posted { false };
- std::atomic<int> dropped { 0 };
- int moves = 0, framesOverFader = 0;
- float valueAtRelease = 0.0f;
- std::vector<double> pending, latencies, queueDelays;
- static juce::String describe (std::vector<double> v)
- {
- if (v.empty())
- return "none";
- std::sort (v.begin(), v.end());
- const auto at = [&v] (double q) { return v[std::min (v.size() - 1, (std::size_t) (q * (double) v.size()))]; };
- return "p50 " + juce::String (at (0.5), 1) + " / p95 " + juce::String (at (0.95), 1) + " / p99 " + juce::String (at (0.99), 1) + " / max "
- + juce::String (v.back(), 1) + " ms";
- }
- void inject (float px, float py, bool down)
- {
- lastY = py;
- if (auto* peer = window != nullptr ? window->getPeer() : nullptr)
- {
- const auto local = peer->globalToLocal (window->localPointToGlobal (juce::Point<float> (px, py)));
- peer->handleMouseEvent (juce::MouseInputSource::InputSourceType::mouse, local,
- down ? juce::ModifierKeys (juce::ModifierKeys::leftButtonModifier) : juce::ModifierKeys(),
- juce::MouseInputSource::defaultPressure, juce::MouseInputSource::defaultOrientation,
- juce::Time::currentTimeMillis());
- }
- }
- void hiResTimerCallback() override
- {
- if (! active.load())
- return;
- if (posted.exchange (true))
- {
- ++dropped;
- return;
- }
- const auto postedAt = juce::Time::getMillisecondCounterHiRes();
- juce::MessageManager::callAsync ([self = shared_from_this(), postedAt] {
- self->posted = false;
- if (! self->active.load())
- return;
- const auto now = juce::Time::getMillisecondCounterHiRes();
- self->queueDelays.push_back (now - postedAt);
- // up and down ~1.3 times a second, like the reporter's hand
- const auto y = self->centreY + self->amplitude * (float) std::sin (2.0 * juce::MathConstants<double>::pi * 1.3 * (now - self->t0) / 1000.0);
- self->inject (self->x, y, true);
- self->pending.push_back (postedAt);
- ++self->moves;
- });
- }
- };
- class LynxApplication final : public juce::JUCEApplication
- {
- public:
- const juce::String getApplicationName() override { return JUCE_APPLICATION_NAME_STRING; }
- const juce::String getApplicationVersion() override { return JUCE_APPLICATION_VERSION_STRING; }
- // the plugin scan runs copies of LYNX as child processes
- bool moreThanOneInstanceAllowed() override { return true; }
- void initialise (const juce::String& commandLine) override
- {
- // round 166b: the copy of LYNX.exe that installs an update (ui/Updater.h) waits, installs, starts LYNX again
- if (commandLine.contains ("--apply-update") && lynx::updater::runApplyHelper (juce::StringArray::fromTokens (commandLine, true)))
- {
- updateHelper = true;
- quit();
- return;
- }
- // Windows, LYNX.exe in a folder with accents: run again from its ASCII short path (Waves editors crash otherwise)
- if (int code = 0; lynx::platform::relaunchFromAsciiPath (code))
- {
- relaunched = true;
- setApplicationReturnValue (code);
- quit();
- return;
- }
- // a crash in any mode (UI, command line) writes its backtrace to %APPDATA%\LYNX\autosave
- juce::SystemStats::setApplicationCrashHandler (onCrash);
- // SFZ instruments (round 167o): their FLAC / OGG / AIFF / MP3 samples through JUCE's readers
- lynx::sfz::setDecoder ([] (const std::string& path, lynx::sfz::Audio& out) {
- juce::AudioFormatManager formats;
- formats.registerBasicFormats();
- std::unique_ptr<juce::AudioFormatReader> reader (formats.createReaderFor (juce::File (juce::String::fromUTF8 (path.c_str()))));
- if (reader == nullptr || reader->lengthInSamples <= 0 || reader->lengthInSamples > (1 << 28) || reader->numChannels == 0)
- return false;
- const auto frames = (int) reader->lengthInSamples;
- juce::AudioBuffer<float> buffer ((int) std::min (2u, reader->numChannels), frames);
- if (! reader->read (&buffer, 0, frames, 0, true, buffer.getNumChannels() > 1))
- return false;
- out.channels.clear();
- for (int ch = 0; ch < buffer.getNumChannels(); ++ch)
- out.channels.emplace_back (buffer.getReadPointer (ch), buffer.getReadPointer (ch) + frames);
- out.sampleRate = reader->sampleRate;
- out.loopStart = out.loopEnd = -1;
- return true;
- });
- // child process of a sandboxed plugin: no window or audio of its own
- if (lynx::runPluginSandboxWorker (commandLine))
- {
- lynx::crashguard::quietCrashReports();
- sandboxChild = true;
- return;
- }
- const auto args = juce::StringArray::fromTokens (commandLine, true);
- // interface language: saved in %APPDATA%\LYNX\language.txt; --lang pt-BR overrides it for this run
- lynx::i18n::initialise (args);
- lookAndFeel.applyLanguageFont (lynx::i18n::current());
- if (args.contains ("--showcase"))
- {
- // LYNX's own demo project (README screenshots): --showcase output.lynx [pattern]
- const auto i = args.indexOf ("--showcase");
- runShowcase (args[i + 1].unquoted(), args[i + 2].getIntValue());
- return;
- }
- if (args.contains ("--sandboxtest"))
- {
- const auto i = args.indexOf ("--sandboxtest");
- runSandboxTest (args[i + 1].unquoted(), args[i + 2].unquoted());
- return;
- }
- if (args.contains ("--bridge32test"))
- {
- // LYNX.exe --bridge32test "LYNX Test Synth 32.dll" report.txt [--compare "LYNX Test Synth.dll"] (round 176a):
- // the 32-bit plugin bridge (engine/Bridge32Test.cpp)
- const auto i = args.indexOf ("--bridge32test");
- const auto compare = args.contains ("--compare") ? args[args.indexOf ("--compare") + 1].unquoted() : juce::String();
- setApplicationReturnValue (lynx::runBridge32Test (args[i + 1].unquoted(), args[i + 2].unquoted(), compare));
- quit();
- return;
- }
- if (args.contains ("--rtstress"))
- {
- // LYNX.exe --rtstress project.(flp|lynx) report.txt [seconds] [--buffer N] [--type "driver type"] [--device "output"]
- // [--no-window] [--record take.wav]: the real app (window, audio device) plays the project and reports the callbacks
- // that missed their deadline (REA round 87); --type/--device pick another driver for this run only (round 97);
- // --record also records the input during the run, like Rec + Play, and moves the take to take.wav (round 106)
- const auto i = args.indexOf ("--rtstress");
- const auto seconds = args[i + 3].getDoubleValue();
- const auto buffer = args.contains ("--buffer") ? args[args.indexOf ("--buffer") + 1].getIntValue() : 0;
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- const auto option = [&args] (const char* name) { return args.contains (name) ? args[args.indexOf (name) + 1].unquoted() : juce::String(); };
- runRealtimeStress (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()), seconds > 0.0 ? seconds : 30.0, buffer,
- option ("--type"), option ("--device"), option ("--record"));
- return;
- }
- if (args.contains ("--cliplooptest"))
- {
- // LYNX --cliplooptest report.txt [export.wav] (round 167q, issue #25: 0.1.21 drew the repeats of a stretched
- // pattern clip but played the pattern once). The real engine's device callback (a stand-in device, driven
- // block by block) plays a synth's 1-bar pattern in a 4-bar clip: every repeat must sound as bar 1, also
- // starting inside a repeat, after a jump mid-clip and in a loop region; the WAV export (written to
- // export.wav and read back) the same. With the LYNX extra off, bars 2-4 must be silent (FL's behaviour).
- const auto i = args.indexOf ("--cliplooptest");
- runClipLoopTest (juce::File (args[i + 1].unquoted()), args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? juce::File (args[i + 2].unquoted()) : juce::File());
- return;
- }
- if (args.contains ("--countinrectest"))
- {
- // LYNX --countinrectest report.txt (round 170d, the Busy Works video: the chord on the downbeat after the
- // pre-count was lost). The real engine's device callback (a stand-in device: 48 kHz, blocks of 512, 256
- // samples of output latency) records a Song-mode take from bar 3 with a 1-bar count-in. Pass 1 finds where
- // the metronome's bar-3 click is heard; pass 2 plays MIDI notes stamped at the times they are heard around
- // 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
- // LYNX's MIDI input. Every note must land on the tick it was heard at (the chord on bar 3).
- const auto i = args.indexOf ("--countinrectest");
- runCountInRecordTest (juce::File (args[i + 1].unquoted()));
- return;
- }
- if (args.contains ("--bendrectest"))
- {
- // LYNX --bendrectest report.txt [song|pattern] (round 167a, issue #12): pitch bend recording end to end. A
- // controller's pitch wheel is injected into LYNX's MIDI input (as a device would send it) while recording
- // plays: a held note and a wheel sweep 0 → full up → full down → centre. The recorded lane (pattern mode) or
- // automation clip (song mode) of the channel's pitch bend must follow the sweep.
- const auto i = args.indexOf ("--bendrectest");
- const auto songMode = args.size() > i + 2 && args[i + 2] == "song";
- runBendRecordTest (juce::File (args[i + 1].unquoted()), songMode);
- return;
- }
- if (args.contains ("--rectest"))
- {
- // LYNX --rectest report.txt [seconds] [--type T] [--device D] [--input I] [--loop] [--buffer N]
- // (round 163): records a click track through a loopback (cable, interface loopback or PipeWire's
- // pw-loopback): pings the round trip, plays a click on every beat from an audio clip, records it on Insert 1,
- // stops, and checks every recorded click's song position on the Playlist against its beat (samples).
- // --loop: loop recording over bars 2-4 (take lanes). --punch: punch in/out on bars 3-4 with 1 bar of pre-roll
- // and 1 of post-roll (playback stops by itself after the post-roll).
- const auto i = args.indexOf ("--rectest");
- const auto option = [&args] (const char* name) { return args.contains (name) ? args[args.indexOf (name) + 1].unquoted() : juce::String(); };
- const auto seconds = args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? args[i + 2].getDoubleValue() : 20.0;
- runRecordTest (juce::File (args[i + 1].unquoted()), seconds > 0.0 ? seconds : 20.0, option ("--type"), option ("--device"), option ("--input"),
- args.contains ("--loop") ? 1 : args.contains ("--punch") ? 2 : 0, option ("--pdc").getIntValue(), option ("--buffer").getIntValue());
- return;
- }
- if (args.contains ("--hwinserttest"))
- {
- // LYNX --hwinserttest report.txt [seconds] [--type T] [--device D] [--input I] [--buffer N] (round 164d): a
- // hardware insert through a loopback cable (output pair 1-2 -> input pair 1-2; the Master plays nowhere, so
- // the cable carries the send only). The same click track plays on two inserts: Insert 1 through the
- // hardware insert (panned left), Insert 2 dry (panned right). The insert's own ping measures the round
- // trip, PDC delays the dry path by it, and every click of the Master's left side must sit on the same
- // sample as the right side's.
- const auto i = args.indexOf ("--hwinserttest");
- const auto option = [&args] (const char* name) { return args.contains (name) ? args[args.indexOf (name) + 1].unquoted() : juce::String(); };
- const auto seconds = args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? args[i + 2].getDoubleValue() : 10.0;
- // round 165c: --patcher puts the insert inside a Patcher on Insert 1; --bounce file.wav then exports the song in real
- // time through the device (Export › "Render through the hardware in real time") and offline, and compares them
- runHwInsertTest (juce::File (args[i + 1].unquoted()), seconds > 0.0 ? seconds : 10.0, option ("--type"), option ("--device"), option ("--input"),
- option ("--buffer").getIntValue(), args.contains ("--patcher"),
- args.contains ("--bounce") ? juce::File (option ("--bounce")) : juce::File());
- return;
- }
- if (args.contains ("--uiperf"))
- {
- // LYNX --uiperf project.(flp|lynx) report.txt: the heavy UI cases in the real window, every frame timed (round 161)
- const auto i = args.indexOf ("--uiperf");
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- runUiPerf (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()));
- return;
- }
- if (args.contains ("--livetest"))
- {
- // LYNX --livetest report.txt [--relay URL]: a live session of four peers over the relay (round 169b)
- setApplicationReturnValue (lynx::livetest::run (args));
- quit();
- return;
- }
- if (args.contains ("--selftest"))
- {
- const auto i = args.indexOf ("--selftest");
- runSelfTest (args[i + 1].unquoted(), args[i + 2].unquoted());
- return;
- }
- if (args.contains ("--scan-one"))
- {
- // child process of the plugin scan (see PluginHost::scan)
- const auto i = args.indexOf ("--scan-one");
- // no crash dialogs from the plugin being examined; and once the result is written, the process ends without
- // unloading it: a Waves shell crashed in its own teardown at exit (Intel GPU driver fail-fast, 0xC0000409),
- // which showed Windows' crash dialog and made the scan reject the whole shell (round 111)
- lynx::crashguard::quietCrashReports();
- lynx::PluginHost::scanOneFile (args[i + 1].unquoted(), args[i + 2].unquoted(), juce::File (args[i + 3].unquoted()));
- lynx::crashguard::exitNow (0);
- }
- if (args.contains ("--packageinfo"))
- {
- // round 165n: the Microsoft Store (MSIX) build's identity and folders (platform/Package.h); the release
- // workflow runs it inside the installed test package
- juce::File (args[args.indexOf ("--packageinfo") + 1].unquoted()).replaceWithText (lynx::platform::packageReport());
- quit();
- return;
- }
- if (args.contains ("--paths"))
- {
- // diagnostics: folders LYNX searches
- const auto programs = juce::File::getSpecialLocation (juce::File::globalApplicationsDirectory);
- juce::String report;
- report << "programs=" << programs.getFullPathName() << "\n";
- for (const auto& dir : programs.getChildFile ("Image-Line").findChildFiles (juce::File::findDirectories, false, "FL Studio*"))
- report << "fl=" << dir.getFullPathName() << " packs=" << (int) dir.getChildFile ("Data").getChildFile ("Patches").getChildFile ("Packs").isDirectory() << "\n";
- juce::File (args[args.indexOf ("--paths") + 1].unquoted()).replaceWithText (report);
- quit();
- return;
- }
- if (args.contains ("--fldb"))
- {
- // diagnostics: LYNX.exe --fldb report.txt [project.flp]: the FL Studio installation, its plugin database,
- // the suggested plugin folders and, for a project, how each of its plugins resolves (read-only)
- const auto i = args.indexOf ("--fldb");
- const auto fl = lynx::findFlStudio();
- lynx::PluginHost host (false);
- juce::String report;
- report << "install=" << fl.installDir.getFullPathName() << "\nuserdata=" << fl.userData.getFullPathName() << "\n";
- for (const auto& f : fl.vstFolders)
- report << "flvstfolder=" << f << "\n";
- report << "dbfiles=" << host.flPluginDatabaseFiles() << " entries=" << (int) host.flPluginDatabase().entries().size() << "\n";
- for (const auto& e : host.flPluginDatabase().entries())
- report << " entry: " << juce::String::fromUTF8 (e.name.c_str()) << " | " << juce::String::fromUTF8 (e.path.c_str()) << " | role=" << e.role << "\n";
- const auto suggested = host.suggestedFolders();
- for (int k = 0; k < suggested.getNumPaths(); ++k)
- report << "folder=" << suggested[k].getFullPathName() << "\n";
- if (const juce::File project (args[i + 2].unquoted()); project.existsAsFile())
- {
- juce::MemoryBlock data;
- project.loadFileAsData (data);
- try
- {
- for (const auto& use : lynx::flpForeignPlugins (flp::parseProject ({ static_cast<const std::uint8_t*> (data.getData()), data.getSize() })))
- {
- juce::String how;
- const auto d = host.findForeign (use.plugin, use.instrument, &how);
- const auto* entry = host.flPluginDatabase().match (use.plugin, use.instrument);
- report << "plugin: " << juce::String::fromUTF8 (use.plugin.name.c_str()) << " -> "
- << (d ? d->fileOrIdentifier + " (" + how + ")" : juce::String ("not known"))
- << (entry != nullptr ? " | fl db: " + juce::String::fromUTF8 (entry->path.c_str()) : juce::String()) << "\n";
- }
- const auto uses = lynx::flpForeignPlugins (flp::parseProject ({ static_cast<const std::uint8_t*> (data.getData()), data.getSize() }));
- const auto candidates = host.filesToScanFor (uses);
- report << "scan_candidates=" << candidates.joinIntoString (";") << "\n";
- if (args.contains ("--scan"))
- {
- // the targeted scan an open would run (child processes; the user's plugin list is not touched)
- report << "scanned_new=" << host.scanFiles (candidates, {}) << "\n";
- for (const auto& use : uses)
- {
- juce::String how;
- const auto d = host.findForeign (use.plugin, use.instrument, &how);
- report << "after_scan: " << juce::String::fromUTF8 (use.plugin.name.c_str()) << " -> "
- << (d ? d->fileOrIdentifier + " (" + how + ")" : juce::String ("not known")) << "\n";
- }
- }
- }
- catch (const flp::Error& e)
- {
- report << "error=" << e.what() << "\n";
- }
- }
- juce::File (args[i + 1].unquoted()).replaceWithText (report);
- quit();
- return;
- }
- if (args.contains ("--midisync-test"))
- {
- // LYNX --midisync-test report.txt ["output device"] ["input device"] (round 165f): MIDI clock timing
- const auto i = args.indexOf ("--midisync-test");
- const auto out = args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
- const auto in = args.size() > i + 3 && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
- juce::File (args[i + 1].unquoted()).replaceWithText (lynx::MidiSyncIo::selfTest (out, in));
- quit();
- return;
- }
- if (args.contains ("--devices") || args.contains ("--dispositivos")) // --dispositivos: legacy alias
- {
- // diagnostics: driver types and output devices JUCE offers (without opening any)
- juce::AudioDeviceManager manager;
- juce::String report;
- manager.getAvailableDeviceTypes();
- if (auto pipeWire = lynx::makePipeWireDeviceType()) // Linux: LYNX's own PipeWire client (round 161)
- manager.addAudioDeviceType (std::move (pipeWire));
- #if JUCE_LINUX
- report << lynx::describePipeWire() << "\n";
- #endif
- for (auto* type : manager.getAvailableDeviceTypes())
- {
- type->scanForDevices();
- report << "type=" << type->getTypeName() << "\n";
- for (const auto& name : type->getDeviceNames (false))
- report << " output=" << name << "\n";
- for (const auto& name : type->getDeviceNames (true))
- report << " input=" << name << "\n";
- }
- for (const auto& d : juce::MidiInput::getAvailableDevices())
- report << "midi-in=" << d.name << "\n";
- for (const auto& d : juce::MidiOutput::getAvailableDevices())
- report << "midi-out=" << d.name << "\n";
- const auto flag = args.contains ("--devices") ? args.indexOf ("--devices") : args.indexOf ("--dispositivos");
- juce::File (args[flag + 1].unquoted()).replaceWithText (report);
- quit();
- return;
- }
- if (args.contains ("--devicetest"))
- {
- // LYNX.exe --devicetest "type" "device" report.txt ["input device"] [--buffer N] [--roundtrip]: opens that output device (and, with the
- // 4th argument, an input: "*" = the same device / the driver's default input), receives 1 s of callbacks
- // writing silence, closes it and reports rate, block size, latency, callbacks and the input channels with
- // their peak level (driver check, no sound). --roundtrip: clicks out, found again on input 1 through a loopback
- // cable / PipeWire link: the round-trip latency (3 s)
- const auto i = args.indexOf ("--devicetest");
- const auto typeName = args[i + 1].unquoted(), deviceName = args[i + 2].unquoted();
- auto inputName = args.size() > i + 4 && ! args[i + 4].startsWith ("--") ? args[i + 4].unquoted() : juce::String();
- const auto wantInput = inputName.isNotEmpty();
- juce::String report;
- const juce::File reportFile (args[i + 3].unquoted());
- auto step = [&] (const juce::String& line) { report << line << "\n"; reportFile.replaceWithText (report); }; // progress survives a driver that ends the process
- step ("step=start");
- juce::AudioDeviceManager manager;
- manager.getAvailableDeviceTypes();
- if (auto pipeWire = lynx::makePipeWireDeviceType())
- manager.addAudioDeviceType (std::move (pipeWire));
- std::unique_ptr<juce::AudioIODevice> device;
- for (auto* type : manager.getAvailableDeviceTypes())
- if (type->getTypeName() == typeName)
- {
- type->scanForDevices();
- if (wantInput && type->hasSeparateInputsAndOutputs())
- {
- const auto inputs = type->getDeviceNames (true);
- if (inputName == "*" || ! inputs.contains (inputName))
- {
- const auto index = type->getDefaultDeviceIndex (true);
- inputName = juce::isPositiveAndBelow (index, inputs.size()) ? inputs[index] : juce::String();
- }
- for (const auto& n : inputs)
- step ("input_device=" + n);
- step ("input_chosen=" + inputName);
- }
- else if (wantInput)
- inputName = deviceName;
- step ("step=create");
- device.reset (type->createDevice (deviceName, type->hasSeparateInputsAndOutputs() ? inputName : juce::String()));
- step ("step=created");
- }
- struct Silence final : juce::AudioIODeviceCallback
- {
- std::atomic<int> calls { 0 }, inputs { 0 };
- std::array<std::atomic<float>, 64> peaks {};
- // --roundtrip (round 161): a click every quarter second on the outputs, found again on input 1 through a
- // loopback; the delays in samples
- bool roundtrip = false;
- int period = 12000;
- std::int64_t position = 0, lastClick = -1;
- std::vector<int> delays;
- void audioDeviceIOCallbackWithContext (const float* const* in, int numIn, float* const* out, int channels, int n,
- const juce::AudioIODeviceCallbackContext&) override
- {
- for (int c = 0; c < channels; ++c)
- if (out[c] != nullptr)
- juce::FloatVectorOperations::clear (out[c], n);
- if (roundtrip)
- {
- for (int i = 0; i < n; ++i)
- {
- if (numIn > 0 && in[0] != nullptr && lastClick >= 0 && std::abs (in[0][i]) > 0.5f)
- {
- if (delays.size() < delays.capacity())
- delays.push_back ((int) (position + i - lastClick));
- lastClick = -1;
- }
- if ((position + i) % period == 0 && position + i > 0)
- {
- for (int c = 0; c < channels; ++c)
- if (out[c] != nullptr)
- out[c][i] = 0.9f;
- lastClick = position + i;
- }
- }
- position += n;
- }
- inputs.store (numIn);
- for (int c = 0; c < juce::jmin (numIn, 64); ++c)
- if (in[c] != nullptr)
- {
- const auto range = juce::FloatVectorOperations::findMinAndMax (in[c], n);
- const auto peak = juce::jmax (std::abs (range.getStart()), std::abs (range.getEnd()));
- if (peak > peaks[(std::size_t) c].load())
- peaks[(std::size_t) c].store (peak);
- }
- ++calls;
- }
- void audioDeviceAboutToStart (juce::AudioIODevice*) override {}
- void audioDeviceStopped() override {}
- } silence;
- bool ok = false;
- if (device == nullptr)
- step ("error=device not found");
- else
- {
- step ("step=open");
- juce::BigInteger outputs;
- outputs.setRange (0, 2, true);
- const auto rates = device->getAvailableSampleRates();
- const auto rate = device->getCurrentSampleRate() > 0 ? device->getCurrentSampleRate()
- : rates.contains (48000.0) ? 48000.0 : rates.isEmpty() ? 44100.0 : rates[0];
- step ("rates=" + juce::String (rates.size()) + " chosen=" + juce::String (rate) + " default_block=" + juce::String (device->getDefaultBufferSize()));
- juce::BigInteger inputs;
- if (wantInput)
- {
- const auto names = device->getInputChannelNames();
- step ("input_channels=" + juce::String (names.size()));
- for (int c = 0; c < names.size(); ++c)
- step (" in" + juce::String (c + 1) + "=" + names[c]);
- inputs.setRange (0, juce::jmin (64, names.size()), true);
- }
- // --buffer N: ask for that block size (REA round 97 latency survey); default: the driver's default
- const auto wantedBlock = args.contains ("--buffer") ? args[args.indexOf ("--buffer") + 1].getIntValue() : 0;
- const auto error = device->open (inputs, outputs, rate, wantedBlock > 0 ? wantedBlock : device->getDefaultBufferSize());
- if (error.isNotEmpty())
- step ("error=" + error);
- else
- {
- step ("step=start_callbacks");
- silence.roundtrip = args.contains ("--roundtrip");
- silence.period = juce::jmax (1, (int) (rate / 4));
- silence.delays.reserve (64);
- device->start (&silence);
- juce::Thread::sleep (silence.roundtrip ? 3000 : 1000);
- device->stop();
- if (silence.roundtrip)
- {
- auto d = silence.delays;
- std::sort (d.begin(), d.end());
- report << "roundtrip_clicks=" << (int) d.size() << "\n";
- if (! d.empty())
- report << "roundtrip_samples=min " << d.front() << " median " << d[d.size() / 2] << " max " << d.back() << "\n"
- << "roundtrip_ms=" << juce::String (1000.0 * d[d.size() / 2] / device->getCurrentSampleRate(), 2) << "\n";
- }
- report << "rate=" << device->getCurrentSampleRate() << "\n"
- << "block=" << device->getCurrentBufferSizeSamples() << "\n"
- << "output_latency=" << device->getOutputLatencyInSamples() << "\n"
- << "callbacks=" << silence.calls.load() << "\n";
- if (wantInput)
- {
- report << "input_latency=" << device->getInputLatencyInSamples() << "\n"
- << "active_inputs=" << device->getActiveInputChannels().countNumberOfSetBits() << "\n"
- << "callback_inputs=" << silence.inputs.load() << "\n";
- for (int c = 0; c < juce::jmin (64, silence.inputs.load()); ++c)
- report << " peak_in" << (c + 1) << "=" << juce::Decibels::gainToDecibels (silence.peaks[(std::size_t) c].load(), -150.0f) << " dB\n";
- }
- ok = silence.calls.load() > 0 && (! wantInput || silence.inputs.load() > 0);
- device->close();
- }
- }
- step (juce::String ("result=") + (ok ? "OK" : "FAILED"));
- setApplicationReturnValue (ok ? 0 : 1);
- quit();
- return;
- }
- if (args.contains ("--scantest"))
- {
- // LYNX.exe --scantest folder report.txt: scan (in child processes) without touching the user's list
- const auto i = args.indexOf ("--scantest");
- lynx::PluginHost host (false);
- const auto found = host.scan (juce::FileSearchPath (args[i + 1].unquoted()), {});
- juce::String report;
- report << "found=" << found << "\n";
- for (const auto& t : host.getKnownPlugins().getTypes())
- report << " " << (t.isInstrument ? "instrument: " : "effect: ") << t.name << "\n";
- for (const auto& f : host.getKnownPlugins().getBlacklistedFiles())
- report << " blacklisted: " << f << "\n";
- juce::File (args[i + 2].unquoted()).replaceWithText (report);
- setApplicationReturnValue (found > 0 ? 0 : 1);
- quit();
- return;
- }
- if (args.contains ("--vst2test"))
- {
- const auto i = args.indexOf ("--vst2test");
- runVst2Test (args[i + 1].unquoted(), args[i + 2].unquoted());
- return;
- }
- if (args.contains ("--wrappertest"))
- {
- const auto i = args.indexOf ("--wrappertest");
- runWrapperTest (args[i + 1].unquoted(), args[i + 2].unquoted());
- return;
- }
- if (args.contains ("--plugintest"))
- {
- const auto i = args.indexOf ("--plugintest");
- // optional 3rd argument: the plugin's name inside a shell (e.g. "CLA-2A Stereo" in a WaveShell)
- const auto only = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
- runPluginTest (args[i + 1].unquoted(), args[i + 2].unquoted(), only);
- return;
- }
- if (args.contains ("--claprestarttest"))
- {
- // LYNX.exe --claprestarttest "LYNX Test Restart.clap" report.txt (tools/testplugin/lynx_test_restart.c)
- const auto i = args.indexOf ("--claprestarttest");
- runClapRestartTest (args[i + 1].unquoted(), args[i + 2].unquoted());
- return;
- }
- if (args.contains ("--editortest"))
- {
- // LYNX.exe --editortest plugin.vst3 report.txt ["name"]: opens the plugin's own editor in a window for a few
- // seconds, then closes it (a plugin whose UI crashes the host ends the process before the report says OK)
- const auto i = args.indexOf ("--editortest");
- const auto only = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
- runEditorTest (args[i + 1].unquoted(), args[i + 2].unquoted(), only);
- return;
- }
- if (args.contains ("--editorcrashtest"))
- {
- // LYNX.exe --editorcrashtest "LYNX Test Crash.clap" report.txt (issue #32, round 174a; Windows): the test
- // plugin's editor faults in its own window procedure (LYNX_TEST_CRASH=editor). LYNX must catch it, close
- // that editor, record the trace and keep running its message loop.
- const auto i = args.indexOf ("--editorcrashtest");
- runEditorCrashTest (args[i + 1].unquoted(), args[i + 2].unquoted());
- return;
- }
- if (args.contains ("--plugwintest"))
- {
- // LYNX --plugwintest plugin report.txt ["name"] [seconds]: round 162d. Puts the plugin in a channel (an
- // instrument) or on insert 1 (an effect) of an offline engine, opens its plugin window (wrapper header,
- // presets), checks a preset round trip, keeps the window `seconds` on screen (default 15: time for xdotool /
- // screenshots), then removes the plugin from the song and reports whether its window closed by itself.
- const auto i = args.indexOf ("--plugwintest");
- const auto only = i + 3 < args.size() && ! args[i + 3].startsWith ("--") && ! args[i + 3].containsOnly ("0123456789") ? args[i + 3].unquoted() : juce::String();
- auto seconds = 15;
- for (int k = i + 3; k < juce::jmin (args.size(), i + 5); ++k)
- if (args[k].containsOnly ("0123456789"))
- seconds = args[k].getIntValue();
- runPlugWinTest (args[i + 1].unquoted(), args[i + 2].unquoted(), only, seconds);
- return;
- }
- if (args.contains ("--fittest"))
- {
- // LYNX.exe --fittest report.txt [percent]: round 163 — at that UI zoom (default 150) a window taller than
- // the screen and a big resizable window that grows with a zoom change keep their title bar and close
- // button on the screen. The windows show for about two seconds.
- const auto i = args.indexOf ("--fittest");
- runFitTest (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].getIntValue() : 150);
- return;
- }
- if (args.contains ("--windowtest"))
- {
- // LYNX.exe --windowtest report.txt: opens the Quick-add palette, the Audio editor, a plugin-like window and a name dialog
- // over the main window and checks that each one stays in front, owned by the main window, with the
- // keyboard focus (issue #4). The windows appear on screen for a few seconds.
- runWindowTest (args[args.indexOf ("--windowtest") + 1].unquoted());
- return;
- }
- if (args.contains ("--pluginstyle")) // round 126: force one style for this run (glow, neon, hardware, vivid; auto = per plugin)
- {
- const auto i = args.indexOf ("--pluginstyle");
- if (i + 1 < args.size())
- {
- const auto name = args[i + 1].unquoted();
- lynx::skin::setForcedStyle (name.equalsIgnoreCase ("auto") ? -1 : (int) lynx::skin::styleFromName (name));
- }
- }
- if (args.contains ("--gfxprobe"))
- {
- // LYNX.exe --gfxprobe report.txt (round 170c, issue #11): renderer checks on this platform's native images —
- // text drawn with a gradient fill (a word with a space in it) and an empty path filled with a gradient must
- // stay inside their shapes. JUCE 8.0.4's CoreGraphics renderer (macOS) clipped to an empty glyph or path as
- // "no clip" and flooded the whole component (Facet EQ's blank pink window).
- const auto i = args.indexOf ("--gfxprobe");
- juce::File (args[i + 1].unquoted()).replaceWithText (lynx::skin::rendererProbeReport());
- quit();
- return;
- }
- if (args.contains ("--steppertest"))
- {
- // LYNX.exe --steppertest <report.txt>: round 170c (#14) — every value stepper of every generated effect editor
- // driven by synthetic input (arrows, click on the value, drag, wheel, trackpad); ends with result=OK / FAIL
- const auto i = args.indexOf ("--steppertest");
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- juce::String report;
- int fails = 0, count = 0, skips = 0;
- {
- lynx::AudioEngine offline (false);
- auto kinds = lynx::plugui::flLayoutKinds();
- for (const auto own : lynx::plugui::ownLayoutKinds())
- kinds.push_back (own);
- // FL's Default preset when the installation has one (the state-backed controls need FL's state)
- const auto roots = lynx::findFlStudioRoots();
- const auto presets = juce::File (juce::String::fromUTF8 (roots.data.c_str())).getChildFile ("Patches/Plugin presets/Effects");
- for (const auto kind : kinds)
- {
- auto fx = lynx::makeEffectSlot (kind);
- for (const auto& plugin : lynx::flPluginsForEffect (kind))
- {
- juce::MemoryBlock data;
- const auto file = presets.getChildFile (juce::String::fromUTF8 (plugin.c_str())).getChildFile ("Default.fst");
- if (file.existsAsFile() && file.loadFileAsData (data))
- {
- const auto* bytes = static_cast<const std::uint8_t*> (data.getData());
- if (auto loaded = lynx::effectFromFlPreset (std::vector<std::uint8_t> (bytes, bytes + data.getSize()), 130.0); loaded && loaded->kind == kind)
- fx = *loaded;
- }
- break;
- }
- lynx::Song song;
- song.mixer.resize (2);
- song.mixer[0].name = "Master";
- song.mixer[1].name = "Insert 1";
- song.mixer[1].effects.push_back (fx);
- offline.setSong (std::move (song));
- offline.dispatchPendingMessages();
- const auto lines = lynx::stepperSelfTest (offline, 1, 0, (int) lynx::plugui::layoutFor (kind).pages.size());
- for (const auto& line : juce::StringArray::fromLines (lines))
- if (line.isNotEmpty())
- {
- ++count;
- fails += line.contains (": FAIL") ? 1 : 0;
- skips += line.contains (": SKIP") ? 1 : 0;
- }
- report << lines;
- juce::PopupMenu::dismissAllActiveMenus();
- offline.dispatchPendingMessages();
- }
- }
- report << "steppers=" << count << " failures=" << fails << " skipped=" << skips << "\nresult=" << (fails == 0 && count > 0 ? "OK" : "FAIL") << "\n";
- juce::File (args[i + 1].unquoted()).replaceWithText (report);
- quit();
- return;
- }
- if (args.contains ("--plugui"))
- {
- // LYNX.exe --plugui <folder>: the native effect editors at FL's size (one PNG per editor and page), each
- // loaded with the FL plugin's Default preset when the FL installation has one
- const auto i = args.indexOf ("--plugui");
- runPluginEditorSnapshots (args[i + 1].unquoted());
- return;
- }
- if (args.contains ("--parityshot"))
- {
- // LYNX.exe --parityshot <out.png> <effect name> [<params file>]: one built-in effect's editor with the given
- // parameters ("index value" lines, tools/fxrender --dump), its displays fed by the demo song — the LYNX side
- // of the third-party parity pictures (round tp172b)
- const auto i = args.indexOf ("--parityshot");
- runParityShot (args[i + 1].unquoted(), args[i + 2].unquoted(), i + 3 < args.size() ? args[i + 3].unquoted() : juce::String());
- quit();
- return;
- }
- if (args.contains ("--design168rshot"))
- {
- // LYNX.exe --design168rshot <folder>: round 168r's editors (FL effects that had a generated page and LYNX's own
- // simple built-ins) at 100 % and 200 %, with their default settings and, when they have one, the first
- // preset of LYNX's own bank. "--design168rshot <folder> generated": the generated pages they had before
- const auto i = args.indexOf ("--design168rshot");
- if (i + 2 < args.size() && args[i + 2] == "generated")
- lynx::plugui::showGeneratedLayoutsOnly (true);
- runDesign168rShots (args[i + 1].unquoted());
- quit();
- return;
- }
- if (args.contains ("--eq166fshot"))
- {
- // LYNX.exe --eq166fshot <folder>: round 166f's pictures (issue #16) — Parametric EQ 2's spectrum and heatmap
- // (flat, a +12 dB band, a -12 dB band, Top position) and Facet EQ's comparative EQ (listening to the target,
- // its spectrum over the source's), each fed by the demo song rendered offline
- const auto i = args.indexOf ("--eq166fshot");
- runEq166fShots (args[i + 1].unquoted());
- quit();
- return;
- }
- if (args.contains ("--editorcpu"))
- {
- // LYNX.exe --editorcpu report.txt: opens built-in plugin editors one at a time in a small window (no audio
- // device: a silent, idle editor) and writes the process CPU each costs while idle and while its display
- // animates (demo signal) — round 122's check that an idle editor burns no CPU
- const auto i = args.indexOf ("--editorcpu");
- runEditorCpu (args[i + 1].unquoted());
- return;
- }
- if (args.contains ("--precomputeshot"))
- {
- // LYNX.exe --precomputeshot project.(flp|lynx) <prefix>: round 167h — <prefix>-precompute.png (channel 1's
- // Precomputed effects panel) and <prefix>-project.png (Options › Project with "Fast declick for cut groups")
- const auto i = args.indexOf ("--precomputeshot");
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- lynx::AudioEngine shotEngine (false);
- const juce::File input (args[i + 1].unquoted());
- const auto prefix = args[i + 2].unquoted();
- juce::String error;
- bool ok = false;
- if (input.hasFileExtension ("flp"))
- ok = shotEngine.importFlpFile (input, error);
- else if (auto song = lynx::ProjectFile::load (input, error))
- shotEngine.setSong (std::move (*song)), ok = true;
- shotEngine.dispatchPendingMessages();
- auto shoot = [&] (std::unique_ptr<juce::Component> c, const juce::String& name) {
- if (c == nullptr)
- return false;
- if (c->getWidth() <= 0)
- c->setSize (520, 600);
- savePng (c->createComponentSnapshot (c->getLocalBounds()), prefix + name);
- return true;
- };
- ok = ok && shoot (lynx::makeChannelPrecomputePanel (shotEngine, 0), "-precompute.png");
- ok = ok && shoot (lynx::makeSettingsPanel (shotEngine, lynx::SettingsPage::project), "-project.png");
- setApplicationReturnValue (ok ? 0 : 1);
- quit();
- return;
- }
- if (args.contains ("--pluginthumbs"))
- {
- // LYNX.exe --pluginthumbs <folder> [key,key...]: the Plugin picker's pictures of LYNX's own plugins (round 171c,
- // ui/PluginThumbs.h), each editor drawn off-screen and kept as <folder>/<name>.png; the picker starts this in
- // the background when pictures are missing. One line per plugin on stdout.
- const auto i = args.indexOf ("--pluginthumbs");
- lynx::crashguard::quietCrashReports();
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- juce::StringArray only;
- if (i + 2 < args.size() && ! args[i + 2].startsWith ("--"))
- only.addTokens (args[i + 2].unquoted(), ",", "");
- const auto t0 = juce::Time::getMillisecondCounterHiRes();
- const auto drawn = lynx::pluginthumbs::renderNative (juce::File (args[i + 1].unquoted()), only, [] (const juce::String& line) {
- std::printf ("%s\n", line.toRawUTF8());
- std::fflush (stdout);
- });
- std::printf ("drawn %d in %.0f ms\n", drawn, juce::Time::getMillisecondCounterHiRes() - t0);
- setApplicationReturnValue (0);
- quit();
- return;
- }
- if (args.contains ("--artshot"))
- {
- // LYNX.exe --artshot <folder> [before|after] [name,name...]: every editor with art of its own (round 170j/170k: the
- // Themed style; or only the named ones, e.g. "sakura,facet-eq") drawn off-screen at 100 % and 200 % as
- // <folder>/<plugin>-<before|after>-<scale>.png. "before" draws each in the style it had before the Themed style
- const auto i = args.indexOf ("--artshot");
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- const auto mode = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String ("after");
- if (i + 3 < args.size() && ! args[i + 3].startsWith ("--")) // [name,name...]: only these arts
- artOnly().addTokens (args[i + 3].unquoted(), ",", "");
- setApplicationReturnValue (runArtShots (juce::File (args[i + 1].unquoted()), mode == "before") ? 0 : 1);
- quit();
- return;
- }
- if (args.contains ("--artgui"))
- {
- // LYNX.exe --artgui <folder> [before|after|still] [name,name...]: the same editors in REAL windows on the desktop, one at a
- // time (always on top, no focus taken), each held while an outside script screenshots it (it writes
- // <folder>/<plugin>.ready with the window's bounds and waits up to 10 s for <folder>/<plugin>.done), then the
- // process CPU it costs over 6 s is written to <folder>/cpu-<mode>.txt. "still": Themed with the motion off
- const auto i = args.indexOf ("--artgui");
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- const auto mode = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String ("after");
- if (i + 3 < args.size() && ! args[i + 3].startsWith ("--")) // [name,name...]: only these arts
- artOnly().addTokens (args[i + 3].unquoted(), ",", "");
- runArtGui (juce::File (args[i + 1].unquoted()), mode);
- return;
- }
- if (args.contains ("--instrumentshot"))
- {
- // LYNX.exe --instrumentshot <folder> <engine,engine...|banks> [lynx|fl]: round 168n — the channel window of
- // each engine (its Plugin tab) at 100 %, 150 % and 200 %, as <folder>/<engine>-<source>-<scale>.png. Source
- // "lynx" starts from the engine's LYNX bank (what a PC without FL gets), "fl" from FL's Default preset.
- const auto i = args.indexOf ("--instrumentshot");
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- const auto source = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String ("lynx");
- setApplicationReturnValue (runInstrumentShots (juce::File (args[i + 1].unquoted()), args[i + 2].unquoted(), source) ? 0 : 1);
- quit();
- return;
- }
- if (args.contains ("--flextrashot"))
- {
- // LYNX.exe --flextrashot <folder>: pictures of the editors of round 165g (Big Clock, Tuner, HTML NoteBook, Mute 2, Scratcher, Transmitter) + round 167n Transporter
- const auto i = args.indexOf ("--flextrashot");
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- lynx::AudioEngine shotEngine (false);
- const auto ok = lynx::runFlExtraShots (shotEngine, juce::File (args[i + 1].unquoted()));
- setApplicationReturnValue (ok ? 0 : 1);
- quit();
- return;
- }
- if (args.contains ("--visualtest"))
- {
- // LYNX.exe --visualtest <folder> [project.flp]: the visual plugins (round 164c) — the audio path's CPU, every
- // Wave Candy mode and Visualizer scene drawn from a test signal (PNG + the editor's CPU each), and the video
- // export of a project (default: FL's first ZGameEditor demo) with ffmpeg and as images. Writes report.txt.
- const auto i = args.indexOf ("--visualtest");
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- const auto project = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? juce::File (args[i + 2].unquoted()) : juce::File();
- lynx::runVisualTest (juce::File (args[i + 1].unquoted()), project, [this] (bool ok) {
- setApplicationReturnValue (ok ? 0 : 1);
- quit();
- });
- return;
- }
- if (args.contains ("--menu-entry"))
- {
- // LYNX.AppImage --menu-entry on|off: puts the AppImage in the applications menu (and .lynx files on it) or
- // takes it out again, without opening a window; the same as the switch in Options › General (round 161)
- const auto i = args.indexOf ("--menu-entry");
- const auto on = args[i + 1].unquoted() != "off";
- const auto ok = lynx::runningAsAppImage() && lynx::setAppImageMenuEntry (on);
- std::fprintf (ok ? stdout : stderr, "%s\n", ok ? (on ? "LYNX SHARE added to the applications menu" : "LYNX SHARE removed from the applications menu")
- : "only the LYNX SHARE AppImage on Linux can do this");
- setApplicationReturnValue (ok ? 0 : 1);
- quit();
- return;
- }
- if (args.contains ("--send-test-report"))
- {
- // LYNX.exe --send-test-report out.txt [--dry]: builds a crash report marked "test" from the newest crash /
- // hang file and this computer's facts, writes its JSON to out.txt.json and (without --dry) sends it to
- // lynx-share.com (LYNX_CRASH_ENDPOINT overrides); out.txt gets "id=…" and "result=OK" or the error (round 159)
- const auto i = args.indexOf ("--send-test-report");
- const juce::File out (args[i + 1].unquoted());
- lynx::crashreporter::Session session;
- session.version = getApplicationVersion();
- for (const auto* pattern : { "crash *.txt", "hang *.txt" })
- {
- auto files = lynx::platform::settingsFile ("autosave").findChildFiles (juce::File::findFiles, false, pattern);
- lynx::filesort::byTime (files, lynx::filesort::By::modificationTime, true);
- if (! files.isEmpty())
- (juce::String (pattern).startsWith ("crash") ? session.crashFile : session.hangFile) = files[0];
- }
- session.steps = { "00:00:01 test report (LYNX.exe --send-test-report)", "00:00:02 opening project " + out.getFileName() };
- auto input = lynx::crashreporter::makeInput (session, session.crashFile.existsAsFile() ? "crash" : "manual", nullptr);
- input.test = true;
- const auto json = lynx::crashreporter::buildJson (input, false);
- out.withFileExtension (out.getFileExtension() + ".json").replaceWithText (json);
- const auto error = args.contains ("--dry") ? juce::String() : lynx::crashreporter::sendNow (json);
- out.replaceWithText ("id=" + juce::String::fromUTF8 (input.id.c_str()) + "\nendpoint=" + lynx::crashreporter::endpoint() + "\nbytes="
- + juce::String (json.getNumBytesAsUTF8()) + "\nresult=" + (error.isEmpty() ? juce::String ("OK") : error) + "\n");
- setApplicationReturnValue (error.isEmpty() ? 0 : 1);
- quit();
- return;
- }
- if (args.contains ("--symbolize"))
- {
- // LYNX.exe --symbolize "crash … .txt" out.txt: names the LYNX.exe+offset frames of a user's crash / hang file
- // (needs this build's LYNX.pdb next to LYNX.exe — the release's "LYNX-symbols" CI artifact; round 157a)
- const auto i = args.indexOf ("--symbolize");
- const auto text = juce::File (args[i + 1].unquoted()).loadFileAsString();
- juce::File (args[i + 2].unquoted()).replaceWithText (juce::String::fromUTF8 (lynx::crashguard::symbolizeOwnFrames (text.toStdString()).c_str()));
- quit();
- return;
- }
- if (args.contains ("--opentest"))
- {
- // LYNX.exe --opentest report.txt [--visible]: every built-in effect and instrument window opened as the mixer /
- // Channel rack open them, with default, extreme, random and old-project states; a watchdog fails the test on
- // a hang (round 157a: opening the Parametric EQ froze LYNX). Windows stay off-screen without --visible.
- const auto i = args.indexOf ("--opentest");
- runOpenTest (args[i + 1].unquoted(), args.contains ("--visible"), [this] (bool ok) {
- setApplicationReturnValue (ok ? 0 : 1);
- quit();
- });
- return;
- }
- if (args.contains ("--fxfuzz"))
- {
- // LYNX.exe --fxfuzz report.txt [rounds] [--drags]: every built-in effect in its editor, parameters swept (and
- // dragged with the mouse), audio rendered at several rates; a crash ends the process (round 111)
- const auto i = args.indexOf ("--fxfuzz");
- const auto rounds = args.size() > i + 2 ? juce::jmax (1, args[i + 2].getIntValue()) : 6;
- // --drags: also mouse drags over the editors (their menus may flash on screen: not for the selftest)
- const auto ok = runEffectFuzz (rounds, args[i + 1].unquoted(), args.contains ("--drags"));
- setApplicationReturnValue (ok ? 0 : 1);
- quit();
- return;
- }
- if (args.contains ("--controllershot"))
- {
- // LYNX.exe --controllershot prefix: the built-in controllers' editors (round 133) as PNGs
- const auto i = args.indexOf ("--controllershot");
- runControllerShot (args[i + 1].unquoted());
- quit();
- return;
- }
- if (args.contains ("--edisonshot"))
- {
- // LYNX.exe --edisonshot prefix [audio.wav]: the audio editor's Edison tool windows (round 165l) and the
- // editor before / after some of them, as PNGs (a synthetic drum loop without a file)
- const auto i = args.indexOf ("--edisonshot");
- runEdisonShot (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String());
- quit();
- return;
- }
- if (args.contains ("--danceshot"))
- {
- // LYNX.exe --danceshot prefix: LYNX Dance (round 165e) — every move as a contact sheet, the channel's editor,
- // and a demo project with two dance channels (for --snapshot)
- const auto i = args.indexOf ("--danceshot");
- runDanceShot (args[i + 1].unquoted());
- quit();
- return;
- }
- if (args.contains ("--videoshot") && args.indexOf ("--videoshot") + 2 < args.size())
- {
- // LYNX.exe --videoshot prefix video: the Video Player's editor (round 165g) at a few song positions, with
- // the user's ffmpeg, as PNGs + report.txt (frames decoded, the sound track)
- const auto i = args.indexOf ("--videoshot");
- runVideoShot (args[i + 1].unquoted(), args[i + 2].unquoted());
- return;
- }
- if (args.contains ("--vfxshot"))
- {
- // LYNX.exe --vfxshot prefix: the VFX note effects' editors (round 164b), on channels and in a Patcher, as PNGs
- const auto i = args.indexOf ("--vfxshot");
- runVfxShot (args[i + 1].unquoted());
- quit();
- return;
- }
- if (args.contains ("--patchershot"))
- {
- // LYNX.exe --patchershot prefix [project]: every Patcher's editor (round 141) as PNGs (a demo one without a project)
- const auto i = args.indexOf ("--patchershot");
- runPatcherShot (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String());
- quit();
- return;
- }
- if (args.contains ("--feat166shot"))
- {
- // LYNX.exe --feat166shot prefix [project]: round 166d (issue #14) — the Piano Roll with a scale, folded to
- // it, with one ghost channel, the ghost channels menu, and the Mixer filled to 500 inserts (its start and
- // its end, and the time a full repaint takes)
- const auto i = args.indexOf ("--feat166shot");
- runFeat166Shot (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String());
- quit();
- return;
- }
- if (args.contains ("--perfshot"))
- {
- // LYNX.exe --perfshot prefix project: the Playlist in Performance mode with a few clips launched and waiting,
- // then the project patcherized (every insert's effects, the first channels) saved as prefix-patcherized.lynx
- // for --patchershot (round 165m)
- const auto i = args.indexOf ("--perfshot");
- runPerfShot (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String());
- quit();
- return;
- }
- if (args.contains ("--typeaheadtest"))
- {
- // LYNX.exe --typeaheadtest out.txt: issue #64 — a real popup menu (headings, a submenu) driven by key presses
- // through its window's peer, as the OS delivers them; writes what got the highlight and what was picked
- const auto i = args.indexOf ("--typeaheadtest");
- runTypeAheadTest (juce::File (args[i + 1].unquoted()));
- return;
- }
- if (args.contains ("--choosertest"))
- {
- // LYNX --choosertest out.txt file: issue #72 — opens LYNX's file chooser as the UI does (makeFileChooser +
- // launchChooser) and reports which dialog came up and what reached the callback. A built-in dialog is shot
- // (out.txt.png), `file` typed into it and confirmed; a native one (zenity / kdialog) is left to answer.
- const auto i = args.indexOf ("--choosertest");
- runChooserTest (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()));
- return;
- }
- if (args.contains ("--snapshot"))
- {
- const auto i = args.indexOf ("--snapshot");
- runSnapshot (args[i + 1].unquoted(), args[i + 2].unquoted());
- return;
- }
- if (args.contains ("--stemsplit"))
- {
- // LYNX.exe --stemsplit input.wav folder: the stem separation of the clip menu, without the window
- const auto i = args.indexOf ("--stemsplit");
- lynx::AudioEngine loader (false);
- const auto error = lynx::extractStemsToFolder (loader, juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()));
- juce::File (args[i + 2].unquoted()).getSiblingFile ("stemsplit.txt").replaceWithText (error.isEmpty() ? "result=OK\n" : "result=FAIL " + error + "\n");
- setApplicationReturnValue (error.isEmpty() ? 0 : 1);
- quit();
- return;
- }
- if (args.contains ("--stems"))
- {
- // LYNX.exe --stems project base.wav: one WAV per insert that has sound (like "Export stems")
- const auto i = args.indexOf ("--stems");
- juce::String error, report;
- int written = 0;
- {
- lynx::AudioEngine loader (false);
- const juce::File input (args[i + 1].unquoted()), base (args[i + 2].unquoted());
- auto ok = input.hasFileExtension ("flp") ? loader.importFlpFile (input, error) : false;
- if (! input.hasFileExtension ("flp"))
- if (auto song = lynx::ProjectFile::load (input, error))
- {
- loader.setSong (std::move (*song));
- ok = true;
- }
- const auto& song = loader.getSong();
- for (int t = 1; ok && t < (int) song.mixer.size(); ++t)
- {
- if (std::none_of (song.channels.begin(), song.channels.end(), [t] (const lynx::ChannelDef& c) { return c.mixerTrack == t; }))
- continue;
- const auto file = base.getSiblingFile (base.getFileNameWithoutExtension() + " - " + juce::String (t) + ".wav");
- lynx::ExportSettings settings;
- lynx::ExportJob job (lynx::makeBounceSong (song, t), settings, file);
- if (job.run ({}, error))
- {
- ++written;
- report << file.getFileName() << " peak=" << job.getPeak() << "\n";
- }
- }
- }
- report << "stems=" << written << "\n";
- juce::File (args[i + 2].unquoted() + ".txt").replaceWithText (report);
- setApplicationReturnValue (written > 0 ? 0 : 1);
- quit();
- return;
- }
- if (args.contains ("--export-flp"))
- {
- const auto i = args.indexOf ("--export-flp");
- runFlExport (args[i + 1].unquoted(), args[i + 2].unquoted(), args.contains ("--substitute"));
- return;
- }
- if (args.contains ("--export"))
- {
- const auto i = args.indexOf ("--export");
- const auto insert = args.contains ("--insert") ? args[args.indexOf ("--insert") + 1].getIntValue() : 0;
- runExport (args[i + 1].unquoted(), args[i + 2].unquoted(), args.contains ("--pattern"), insert);
- return;
- }
- if (args.contains ("--render"))
- {
- const auto i = args.indexOf ("--render");
- runRender (args[i + 1].unquoted(), args[i + 2].unquoted(), args[i + 3].getDoubleValue());
- return;
- }
- // session breadcrumb: a fail-fast (no crash handler runs) still leaves the last steps behind (round 111)
- uncleanLastStep = collectUncleanSessions();
- sessionsFolder().createDirectory();
- lynx::crashguard::beginSession (
- sessionsFolder().getChildFile ("session-" + juce::String (lynx::crashguard::processId()) + ".txt").getFullPathName().toStdString(),
- ("LYNX session\nversion=" + getApplicationVersion() + "\npid=" + juce::String (lynx::crashguard::processId())
- + "\nstart=" + juce::String ((juce::int64) lynx::crashguard::processStartTime())
- + "\nstarted=" + juce::Time::getCurrentTime().toISO8601 (true) + "\n").toStdString());
- startHangWatch();
- startupTrace.mark ("initialise (normal start)");
- if (startupTrace.on)
- lynx::startupMark = startupMarkHook;
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- lynx::themeui::loadSaved(); // the user's theme (Options › Theme, round 162d)
- startupOptions = lynx::StartupOptions::load();
- lynx::registerFileTypes();
- startupTrace.mark ("options + file types");
- // Double-clicking a .lynx/.flp opens LYNX with the file as an argument.
- if (args.size() > 0 && juce::File::isAbsolutePath (args[0].unquoted()))
- fileToOpen = juce::File (args[0].unquoted());
- // LYNX --opentime project.(flp|lynx)|- report.txt [idle seconds] (round 165i): the normal start-up (splash, audio
- // device, window) opens the project, waits until it is loaded and LYNX has gone quiet, measures the idle CPU and
- // memory, writes the times and quits normally (a benchmark that killed LYNX left "closed unexpectedly" behind)
- if (args.contains ("--opentime"))
- {
- const auto i = args.indexOf ("--opentime");
- const auto project = args[i + 1].unquoted();
- fileToOpen = project != "-" && juce::File::isAbsolutePath (project) ? juce::File (project) : juce::File();
- openTimeReport = juce::File (args[i + 2].unquoted());
- if (args.size() > i + 3 && ! args[i + 3].startsWith ("--"))
- openTimeIdleSeconds = juce::jlimit (1, 120, args[i + 3].getIntValue());
- }
- if (! startupOptions.splash)
- {
- startEngine();
- createMainWindow();
- mainWindow->reveal();
- showUncleanNotice();
- startupTrace.mark ("window revealed");
- openStartupFile();
- startupTrace.mark ("startup file opened");
- startOpenTimeProbe();
- startUpdateCheck();
- juce::MessageManager::callAsync ([] { startupTrace.mark ("first message loop turn"); });
- return;
- }
- // the splash first, so it is on screen while the audio device opens; the main window is built
- // once the pepper has landed (the scene is still for a moment then) and shown when the splash ends
- splash = std::make_unique<lynx::SplashScreen>();
- startupTrace.mark ("splash made");
- splash->showOnDesktop();
- startupTrace.mark ("splash on the desktop");
- juce::Timer::callAfterDelay (40, [this] {
- startEngine();
- if (splash == nullptr) // quit meanwhile
- return;
- splash->setStatus (lynx::tr ("Loading the workspace..."));
- splash->startClock();
- // the minimum counts from the process start (the audio device took part of it already)
- splashDuration = lynx::SplashScreen::remainingDuration (startupTrace.seconds());
- splash->setBarDuration (splashDuration);
- juce::Timer::callAfterDelay (1050, [this] {
- if (splash == nullptr || engine == nullptr)
- return;
- createMainWindow();
- const auto wait = juce::jmax (0.0, splashDuration - splash->getElapsed());
- juce::Timer::callAfterDelay ((int) (wait * 1000.0), [this] {
- if (splash == nullptr || mainWindow == nullptr)
- return;
- mainWindow->reveal();
- startupTrace.mark ("window revealed (after the splash)");
- splash->toFront (false);
- splash->finish ([this] { splash = nullptr; });
- showUncleanNotice();
- openStartupFile();
- startupTrace.mark ("startup file opened");
- startOpenTimeProbe();
- startUpdateCheck();
- juce::MessageManager::callAsync ([] { startupTrace.mark ("first message loop turn"); });
- // first run: language, audio, plugin folders (FL Studio's included) and a background scan
- if (! lynx::setupWizardDone() && lynx::platform::testMode())
- lynx::platform::testModeLog ("setup wizard");
- else if (! lynx::setupWizardDone())
- mainWindow->showSetupWizard();
- });
- });
- });
- }
- void startEngine()
- {
- startupTrace.mark ("before the audio engine");
- engine = std::make_unique<lynx::AudioEngine>();
- lynx::videoview::install (*engine); // (Fruity Video Player channels: their sound tracks)
- startupTrace.mark ("audio engine + device");
- crashEngine = engine.get();
- lynx::crashreporter::watchAudioDevice (engine->getDeviceManager()); // (the session file names the device: crash reports)
- addDriverFileDeviceType();
- if (startupOptions.sound)
- {
- // Options › Theme › Startup sound (issue #12): the user's file, else (or when it can't be read) LYNX's own
- std::shared_ptr<const lynx::SampleData> sound;
- if (const auto& own = lynx::themeui::current().startupSound; ! own.empty() && juce::File (juce::String::fromUTF8 (own.c_str())).existsAsFile())
- sound = engine->getSampleLibrary().load (juce::String::fromUTF8 (own.c_str()));
- engine->previewSample (sound != nullptr ? sound : lynx::makeStartupSample());
- }
- startupTrace.mark ("startup sound");
- // a project given on the command line: its slow plugin modules (a Waves shell) start now, on their own
- // thread, while the splash and the main window come up (round 121)
- if (fileToOpen.hasFileExtension ("flp"))
- if (juce::MemoryBlock data; fileToOpen.loadFileAsData (data))
- try
- {
- engine->getPluginHost().startModulesFor (lynx::flpForeignPlugins (flp::parseProject ({ static_cast<const std::uint8_t*> (data.getData()), data.getSize() })));
- startupTrace.mark ("plugin modules started ahead");
- }
- catch (const flp::Error&)
- {
- }
- }
- void createMainWindow()
- {
- mainWindow = std::make_unique<MainWindow> ("LYNX SHARE", *engine); // the brand; getApplicationName() stays "LYNX" (an id: instance lock, X11 WM_CLASS, ALSA client)
- lynx::setMainWindowForOwnership (mainWindow.get());
- lynx::applyRenderingChoice (*mainWindow); // (GPU rendering off: GDI; round 157a)
- lynx::startRenderingWatch();
- startupTrace.mark ("main window built");
- }
- // the previous run ended without closing (see collectUncleanSessions): say so once, with its last step — and, as
- // Settings › General › "Crash reports" says (round 159), ask whether to send a report, send it unasked, or not
- void showUncleanNotice()
- {
- if (lynx::platform::testMode()) // LYNX_TEST_MODE: no prompt, no report sent (written to test-mode.log)
- {
- if (uncleanLastStep.isNotEmpty())
- lynx::platform::testModeLog ("\"closed unexpectedly\" notice (last step: " + uncleanLastStep + ")");
- return;
- }
- if (uncleanLastStep.isEmpty())
- {
- lynx::crashreporter::retryPending(); // (reports an earlier run could not send: once more)
- return;
- }
- auto message = lynx::tr ("The last session ended without closing normally. Last step: {0}. Backup copies of your project are in "
- "LYNX SHARE's autosave folder; details in crash-history.log.",
- { uncleanLastStep });
- uncleanLastStep.clear();
- const auto cause = uncleanCause();
- // round 157a: a plugin's editor was opening — it crashed (often in the graphics driver, inside the plugin's own
- // OpenGL window): offer to keep that plugin in its own process, where a crash takes only the plugin down
- juce::String separatePlugin;
- if (cause.editorPlugin.isNotEmpty() && ! lynx::pluginSandboxEnabled() && ! lynx::pluginAlwaysSeparate (cause.editorPlugin))
- separatePlugin = cause.editorPlugin;
- // LYNX's own drawing crashed in the graphics driver (Direct2D / Direct3D): draw with the CPU from now on
- else if (cause.gpuDriver && lynx::gpuRenderingEnabled())
- {
- lynx::setGpuRenderingEnabled (false);
- message << "\n\n"
- << lynx::tr ("The crash was in the graphics driver ({0}). LYNX SHARE now draws its windows without the GPU; you can turn GPU "
- "rendering back on in Options > General settings (after a driver update, for example).",
- { cause.driverModule });
- }
- // round 165e: the Visualizer's GPU view was drawing when the session ended (a driver crash, a hang, the machine
- // going down): the Visualizer draws with the 2D renderer from now on (its GPU button turns it back on)
- for (int i = uncleanSteps.size(); --i >= 0;)
- {
- if (uncleanSteps[i].contains (lynx::visualgl::stopNote))
- break;
- if (uncleanSteps[i].contains (lynx::visualgl::startNote))
- {
- if (lynx::visualgl::enabled())
- {
- lynx::visualgl::setEnabled (false);
- message << "\n\n"
- << lynx::tr ("The Visualizer was drawing with the GPU (OpenGL) when it happened. It now draws without the GPU; its GPU "
- "button turns it back on.");
- }
- break;
- }
- }
- const auto session = lynx::crashreporter::parseSession (uncleanSessionText);
- auto* devices = engine != nullptr ? &engine->getDeviceManager() : nullptr;
- const auto action = lynx::crashreport::actionFor (lynx::crashreporter::consent());
- lynx::crashreporter::retryPending();
- if (action == lynx::crashreport::Action::askUser)
- {
- if (separatePlugin.isNotEmpty())
- message << "\n\n"
- << lynx::tr ("It happened while the window of {0} was opening{1}.",
- { separatePlugin, cause.gpuDriver ? lynx::tr (" (in the graphics driver, {0})", { cause.driverModule }) : juce::String() });
- lynx::crashreporter::showStartupDialog (session, message, separatePlugin, [separatePlugin] { lynx::setPluginAlwaysSeparate (separatePlugin, true); },
- devices);
- return;
- }
- if (action == lynx::crashreport::Action::sendSilently)
- {
- const auto input = lynx::crashreporter::makeInput (session, session.kind(), devices);
- lynx::crashreporter::send (lynx::crashreporter::buildJson (input, false), juce::String::fromUTF8 (input.id.c_str()));
- message << "\n\n" << lynx::tr ("A crash report is being sent to help fix it (Options > General settings > Crash reports).");
- }
- if (separatePlugin.isNotEmpty())
- {
- juce::AlertWindow::showOkCancelBox (
- juce::MessageBoxIconType::WarningIcon, lynx::tr ("LYNX SHARE closed unexpectedly"),
- message + "\n\n"
- + lynx::tr ("It happened while the window of {0} was opening{1}. Run {0} in a separate process from now on? If it "
- "crashes again, only the plugin stops and LYNX SHARE keeps running (Plugin wrapper menu: \"Always run in a "
- "separate process\").",
- { separatePlugin, cause.gpuDriver ? lynx::tr (" (in the graphics driver, {0})", { cause.driverModule }) : juce::String() }),
- lynx::tr ("Run separately"), lynx::tr ("No"), nullptr,
- juce::ModalCallbackFunction::create ([separatePlugin] (int result) {
- if (result != 0)
- lynx::setPluginAlwaysSeparate (separatePlugin, true);
- }));
- return;
- }
- juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, lynx::tr ("LYNX SHARE closed unexpectedly"), message);
- }
- // --opentime: after the start-up file was handed to the window
- void startOpenTimeProbe()
- {
- if (openTimeReport == juce::File())
- return;
- struct Probe final : juce::Timer
- {
- LynxApplication& app;
- juce::File report, project;
- int idleSeconds;
- int phase = 0; // 0 loading, 1 settling, 2 idle measurement
- double revealedS = 0.0, loadedS = -1.0, settledS = -1.0, cpuAtLoaded = 0.0;
- double lastCpu = 0.0, lastT = 0.0, quietSince = -1.0, idleCpu0 = 0.0, idleT0 = 0.0;
- Probe (LynxApplication& a, juce::File r, juce::File p, int idle)
- : app (a), report (std::move (r)), project (std::move (p)), idleSeconds (idle)
- {
- revealedS = startupTrace.seconds();
- startTimer (250);
- }
- bool loaded() const
- {
- if (project == juce::File())
- return true;
- return app.mainWindow != nullptr
- && app.mainWindow->getName().containsIgnoreCase (project.getFileNameWithoutExtension());
- }
- void finish (const juce::String& result)
- {
- stopTimer();
- const auto now = startupTrace.seconds();
- const auto cpu = lynx::processCpuSeconds();
- juce::String text;
- text << "project=" << (project == juce::File() ? juce::String ("-") : project.getFullPathName()) << "\n"
- << "window_s=" << juce::String (revealedS, 3) << "\n"
- << "loaded_s=" << juce::String (loadedS, 3) << "\n"
- << "settled_s=" << juce::String (settledS, 3) << "\n"
- << "cpu_at_loaded_s=" << juce::String (cpuAtLoaded, 3) << "\n"
- << "idle_s=" << juce::String (now - idleT0, 2) << "\n"
- << "idle_cpu_pct=" << juce::String (phase == 2 && now > idleT0 ? 100.0 * (cpu - idleCpu0) / (now - idleT0) : -1.0, 1) << "\n"
- << "working_set_mb=" << juce::String ((double) lynx::toolbar::PerformanceMeter::processMemoryBytes() / 1048576.0, 0) << "\n"
- << "cpu_total_s=" << juce::String (cpu, 3) << "\n"
- << "result=" << result << "\n";
- report.replaceWithText (text);
- app.setApplicationReturnValue (result == "OK" ? 0 : 1);
- app.quit();
- }
- void timerCallback() override
- {
- const auto now = startupTrace.seconds();
- const auto cpu = lynx::processCpuSeconds();
- if (phase == 0)
- {
- if (loaded())
- {
- loadedS = now;
- cpuAtLoaded = cpu;
- phase = 1;
- lastCpu = cpu;
- lastT = now;
- }
- else if (now - revealedS > 240.0)
- finish ("TIMEOUT loading");
- return;
- }
- if (phase == 1)
- {
- // quiet = under 10 % of one core for 1.5 s (the harness's rule), at most 30 s after loading
- const auto use = now > lastT ? 100.0 * (cpu - lastCpu) / (now - lastT) : 0.0;
- lastCpu = cpu;
- lastT = now;
- if (use < 10.0)
- {
- if (quietSince < 0.0)
- quietSince = now - 0.25;
- if (now - quietSince >= 1.5)
- settledS = quietSince;
- }
- else
- quietSince = -1.0;
- if (settledS >= 0.0 || now - loadedS > 30.0)
- {
- phase = 2;
- idleCpu0 = cpu;
- idleT0 = now;
- }
- return;
- }
- if (now - idleT0 >= (double) idleSeconds)
- finish ("OK");
- }
- };
- perf = std::make_unique<Probe> (*this, openTimeReport, fileToOpen, openTimeIdleSeconds);
- }
- // round 166b: the update check of a normal start (never in --opentime and the other command-line modes), a few
- // seconds after the window is up so it never competes with the start-up; and the result of an update just installed
- void startUpdateCheck()
- {
- if (openTimeReport != juce::File())
- return;
- lynx::updater::afterStart();
- juce::Timer::callAfterDelay (3000, [] { lynx::updater::startAutomaticCheck(); });
- }
- void openStartupFile()
- {
- if (fileToOpen != juce::File() && mainWindow != nullptr)
- mainWindow->openFile (fileToOpen);
- }
- void shutdown() override
- {
- if (relaunched || updateHelper)
- return; // the copy that ran owns the session (its crash notes stay for the next start)
- lynx::crashguard::note ("closing");
- lynx::shutdownPluginSandboxWorker();
- splash = nullptr;
- lynx::shutdownStemExtraction(); // (a separation in flight stops before its window and the engine go)
- if (mainWindow != nullptr && mainWindow->isVisible())
- mainWindow->saveState();
- mainWindow = nullptr; // the UI goes before the engine
- lynx::updater::shutdown(); // (a check or download in flight stops)
- crashEngine = nullptr;
- engine = nullptr;
- juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
- heartbeat.stopTimer();
- lynx::crashreporter::shutdown(); // (an upload in flight gets a moment, never long)
- lynx::crashguard::stopHangWatch();
- lynx::crashguard::endSession(); // a clean exit: no breadcrumb left behind
- // everything is saved and closed: a process that loaded third-party plugins ends here, before the DLLs' own
- // teardown runs (some crash in it at exit, round 111)
- if (sandboxChild || lynx::PluginHost::pluginsWereLoaded())
- lynx::crashguard::exitNow (getApplicationReturnValue());
- }
- void systemRequestedQuit() override
- {
- if (mainWindow != nullptr)
- mainWindow->confirmDiscard ([] { juce::JUCEApplication::quit(); });
- else
- quit();
- }
- private:
- // round 157a: a frozen UI (Windows' "not responding") writes the message thread's stack to autosave\hang <time>.txt
- // and a session step, so a freeze can be told apart from a crash and located. The timer is the heartbeat.
- struct Heartbeat final : juce::Timer
- {
- void timerCallback() override { lynx::crashguard::heartbeat(); }
- } heartbeat;
- void startHangWatch()
- {
- const auto folder = lynx::platform::settingsFile ("autosave");
- folder.createDirectory();
- // keep the newest hang files only
- auto old = folder.findChildFiles (juce::File::findFiles, false, "hang *.txt");
- lynx::filesort::byTime (old, lynx::filesort::By::modificationTime, true);
- for (int i = 20; i < old.size(); ++i)
- old.getReference (i).deleteFile();
- lynx::crashguard::startHangWatch (folder.getFullPathName().replaceCharacter ('\\', '/').toStdString());
- heartbeat.startTimerHz (5);
- }
- bool sandboxChild = false;
- bool relaunched = false; // relaunchFromAsciiPath ran LYNX from its short path: this process only waited
- bool updateHelper = false; // --apply-update (round 166b)
- juce::String uncleanLastStep; // last step of a previous run that ended without closing
- // LYNX.exe --selftest report.txt: renders 2 s without a sound card and writes the result.
- // Exit code 0 = audio came out, 1 = silence.
- void runSelfTest (const juce::String& reportPath, const juce::String& demoProjectPath)
- {
- lynx::AudioEngine offline (false);
- const auto peak = offline.renderOffline (2.0, 48000.0);
- const auto audioOk = peak > 0.01f && peak < 10.0f;
- // project format round trip, with accents in the name
- auto original = lynx::Song::makeDefault();
- original.channels[0].name = "Bumbo ação";
- original.playlist.push_back ({ 0, 2, 3840, 1920, 960 });
- original.mode = lynx::PlayMode::song;
- original.mixer[3].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::delay));
- original.mixer[3].effects[0].params[1] = 0.25f;
- lynx::Automation automation;
- automation.name = "Pan";
- automation.target = { lynx::AutomationTargetKind::effectParam, 3, 0, 1 };
- automation.points = { { 0, 0.25f, 0.5f }, { 3840, 1.0f, 0.0f } };
- original.automations.push_back (automation);
- lynx::Clip automationClip;
- automationClip.kind = lynx::ClipKind::automation;
- automationClip.automation = 0;
- automationClip.track = 4;
- automationClip.length = 3840;
- original.playlist.push_back (automationClip);
- original.loopStart = 960;
- original.loopEnd = 7680;
- original.playlistTracks.resize (3);
- original.playlistTracks[2].colour = 0xFF2A6FDB; // a track colour (round 90)
- original.playlistTracks[2].grouped = true; // track groups and rack filter groups (round 104)
- original.playlistTracks[1].collapsed = true;
- original.channelGroups = { "Drums", "Keys" };
- original.channels[1].group = 1;
- juce::String error;
- if (demoProjectPath.isNotEmpty()) // sample project for checking the UI with --snapshot
- lynx::ProjectFile::save (original, juce::File (demoProjectPath), error);
- const auto reloaded = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (original), error);
- const auto projectOk = reloaded && reloaded->channels.size() == original.channels.size()
- && reloaded->channels[0].name == original.channels[0].name
- && reloaded->patterns[0].notes.size() == original.patterns[0].notes.size()
- && reloaded->patterns[0].notes[3].start == original.patterns[0].notes[3].start
- && reloaded->mode == lynx::PlayMode::song && reloaded->playlist.size() == 2
- && reloaded->playlist[1].kind == lynx::ClipKind::automation && reloaded->playlist[1].automation == 0
- && reloaded->automations.size() == 1 && reloaded->automations[0].target == automation.target
- && reloaded->automations[0].points.size() == 2 && reloaded->automations[0].points[0].tension == 0.5f
- && reloaded->automations[0].points[1].tick == 3840
- && reloaded->loopStart == 960 && reloaded->loopEnd == 7680
- && reloaded->playlistTracks.size() == 3 && reloaded->playlistTracks[2].colour == 0xFF2A6FDB
- && reloaded->playlistTracks[1].colour == 0
- && reloaded->playlistTracks[2].grouped && reloaded->playlistTracks[1].collapsed && ! reloaded->playlistTracks[1].grouped
- && reloaded->channelGroups == original.channelGroups && reloaded->channels[1].group == 1 && reloaded->channels[0].group == -1
- && reloaded->playlist[0].offset == 960 && reloaded->playlist[0].track == 2
- && reloaded->mixer[3].effects.size() == 1
- && reloaded->mixer[3].effects[0].kind == lynx::EffectKind::delay
- && reloaded->mixer[3].effects[0].params[1] == 0.25f;
- // round trip of the newer features: synth/sampler with modulation, EQs, utility, markers
- auto rich = lynx::Song::makeDefault();
- auto& synth = rich.channels[4].synth;
- synth.osc[1] = { lynx::Waveform::square, -1, 7.0f, 0.4f, 5, -0.25f };
- synth.filterType = 2;
- synth.mono = true;
- synth.portaBeats = 0.125f;
- synth.am = true;
- synth.filterEnv = { 3.0f, 0.01f, 0.02f, 0.3f, 0.25f, 0.4f };
- synth.lfo[lynx::lfoPitch] = { 0.5f, 0.25f, true, 1, 0.1f, 0.2f };
- auto& sampler = rich.channels[0].sampler;
- sampler.cutoff = 1200.0f;
- sampler.resonance = 0.3f;
- sampler.filterType = 1;
- sampler.pitchEnv = { -12.0f, 0.0f, 0.0f, 0.05f, 0.0f, 0.1f };
- sampler.lfo[lynx::lfoVolume] = { 0.5f, 0.5f, false, 2, 0.0f, 0.0f };
- rich.mixer[2].eq.gainDb = { 3.0f, -2.5f, 1.0f };
- rich.mixer[2].eq.hz[1] = 2200.0f;
- auto peqSlot = lynx::makeEffectSlot (lynx::EffectKind::parametricEq);
- peqSlot.params[(std::size_t) lynx::peq::param (2, 2)] = lynx::peq::gainValue (6.0);
- peqSlot.params[(std::size_t) (lynx::peq::slopeParam + 0)] = lynx::peq::slopeValue (3);
- rich.mixer[2].effects.push_back (peqSlot);
- auto utilitySlot = lynx::makeEffectSlot (lynx::EffectKind::utility);
- utilitySlot.params[1] = 0.2f;
- rich.mixer[2].effects.push_back (utilitySlot);
- auto vocodexSlot = lynx::makeEffectSlot (lynx::EffectKind::vocodex); // FL's raw state travels as base64
- for (int i = 0; i < 300; ++i)
- vocodexSlot.state.push_back ((std::uint8_t) (i * 37));
- vocodexSlot.sidechain = 1;
- vocodexSlot.sidechain2 = 2;
- rich.mixer[3].effects.push_back (vocodexSlot);
- rich.addMarker ({ 3840, "Refrão", 0, 4 });
- rich.addMarker ({ 7680, {}, 7, 8 });
- const auto richBack = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (rich), error);
- auto paramsClose = [] (const lynx::EffectParams& a, const lynx::EffectParams& b) {
- for (std::size_t i = 0; i < a.size(); ++i)
- if (std::abs (a[i] - b[i]) > 1.0e-3f)
- return false;
- return true;
- };
- const auto richOk = richBack && richBack->channels[4].synth == synth && richBack->channels[0].sampler == sampler
- && richBack->mixer[2].eq == rich.mixer[2].eq && richBack->mixer[2].effects.size() == 2
- && richBack->mixer[2].effects[0].kind == lynx::EffectKind::parametricEq
- && paramsClose (richBack->mixer[2].effects[0].params, peqSlot.params)
- && richBack->mixer[2].effects[1].kind == lynx::EffectKind::utility
- && paramsClose (richBack->mixer[2].effects[1].params, utilitySlot.params)
- && richBack->mixer[3].effects.size() == 1 && richBack->mixer[3].effects[0].kind == lynx::EffectKind::vocodex
- && richBack->mixer[3].effects[0].state == vocodexSlot.state && richBack->mixer[3].effects[0].sidechain2 == 2
- && richBack->markers() == rich.markers();
- // hardware output targets (REA round 156): saved only when set; old projects (no field) keep the defaults
- bool hwOutOk = false;
- {
- auto song = lynx::Song::makeDefault();
- const auto plain = lynx::ProjectFile::toJson (song);
- song.mixer[0].outputChannel = lynx::outputNone;
- song.mixer[1].outputChannel = 2;
- song.mixer[1].outputMode = lynx::OutputMode::monoRight;
- song.mixer[2].outputChannel = 6;
- song.mixer[3].outputChannel = 4;
- song.mixer[3].outputMode = lynx::OutputMode::monoSum;
- const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
- const auto plainBack = lynx::ProjectFile::fromJson (plain, error);
- hwOutOk = back && back->mixer[0].outputChannel == lynx::outputNone && back->mixer[1].outputChannel == 2
- && back->mixer[1].outputMode == lynx::OutputMode::monoRight && back->mixer[2].outputChannel == 6
- && back->mixer[2].outputMode == lynx::OutputMode::stereo && back->mixer[3].outputMode == lynx::OutputMode::monoSum
- && back->mixer[4].outputChannel == lynx::outputDefault && ! plain.contains ("\"output\"") && plainBack
- && plainBack->mixer[0].outputChannel == lynx::outputDefault && plainBack->mixer[1].outputChannel == lynx::outputDefault;
- }
- // round 168j: FL's icons (channel / mixer track / playlist track), PDC Automatic / Compensate automations, Time
- // settings, scale highlighting and data folder — saved only when set, old projects load with FL's defaults
- bool flp168jOk = false;
- {
- auto song = lynx::Song::makeDefault();
- const auto plain = lynx::ProjectFile::toJson (song);
- song.channels[0].icon = 75;
- song.mixer[2].icon = 71;
- song.playlistTracks.resize (3);
- song.playlistTracks[2].icon = 30;
- song.autoPdc = false;
- song.compensateAutomations = false;
- song.timeSignatureMode = true;
- song.scaleHighlight = { 10, 5 };
- song.dataFolder = "D:\\Projects\\data";
- const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
- const auto plainBack = lynx::ProjectFile::fromJson (plain, error);
- flp168jOk = back && back->channels[0].icon == 75 && back->mixer[2].icon == 71 && back->playlistTracks.size() >= 3
- && back->playlistTracks[2].icon == 30 && ! back->autoPdc && ! back->compensateAutomations && back->timeSignatureMode
- && back->scaleHighlight == song.scaleHighlight && back->dataFolder == song.dataFolder && plainBack && plainBack->autoPdc
- && plainBack->compensateAutomations && ! plainBack->timeSignatureMode && plainBack->scaleHighlight == lynx::Song::ScaleHighlight {}
- && plainBack->dataFolder.empty() && plainBack->channels[0].icon == 0 && ! plain.contains ("\"icon\"")
- && ! plain.contains ("autoPdc") && ! plain.contains ("scaleHighlight");
- }
- // FL's legacy Pattern Blocks (round 170f): the option and every arrangement's blocks are saved; a project without
- // them has neither in its file and loads with the option off
- bool blocksOk = false;
- {
- auto song = lynx::Song::makeDefault();
- const auto plain = lynx::ProjectFile::toJson (song);
- song.patternBlocksOn = true;
- lynx::patternblocks::place (song, 0, 0);
- lynx::patternblocks::place (song, 0, 4 * 4 * lynx::ppq);
- song.addArrangement ("Second");
- lynx::patternblocks::place (song, 0, 2 * 4 * lynx::ppq);
- song.selectArrangement (0);
- const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
- const auto plainBack = lynx::ProjectFile::fromJson (plain, error);
- blocksOk = back && back->patternBlocksOn && back->blocks == song.blocks && song.blocks.size() == 2
- && back->arrangements.size() == 2 && back->arrangements[1].blocks == song.arrangements[1].blocks
- && song.arrangements[1].blocks.size() == 1 && back->songLength() == song.songLength() && plainBack
- && ! plainBack->patternBlocksOn && plainBack->blocks.empty() && ! plain.contains ("blocks")
- && ! plain.contains ("patternBlocks");
- }
- // Misc › Mono / Porta / Slide on every generator (round 168l): kept in the file; a project saved before (an
- // imported engine's flags in its synth settings) gets them back, a Max polyphony of 1 is not Mono
- bool polyOk = false;
- {
- auto song = lynx::Song::makeDefault();
- lynx::ChannelDef osc;
- osc.instrument = lynx::InstrumentKind::threeosc;
- osc.misc.mono = osc.misc.porta = true;
- osc.misc.portaBeats = 0.25f;
- song.channels.push_back (osc);
- auto old = osc;
- old.misc = {};
- old.synth.mono = old.synth.porta = true;
- old.synth.portaBeats = 0.5f;
- song.channels.push_back (old);
- old.maxPolyphony = 1;
- song.channels.push_back (old);
- const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
- const auto n = song.channels.size();
- polyOk = back && back->channels.size() == n && back->channels[n - 3].misc.mono && back->channels[n - 3].misc.porta
- && std::abs (back->channels[n - 3].misc.portaBeats - 0.25f) < 1e-6f && back->channels[n - 2].misc.mono
- && back->channels[n - 2].misc.porta && std::abs (back->channels[n - 2].misc.portaBeats - 0.5f) < 1e-6f
- && ! back->channels[n - 1].misc.mono && back->channels[n - 1].maxPolyphony == 1
- && ! back->channels[4].misc.mono; // (the LYNX Synth keeps its own flags)
- }
- // FL's track latency (REA round 165f-mixer): manual ms, bypass mode and master compensation saved only when set
- bool latencyOk = false;
- {
- auto song = lynx::Song::makeDefault();
- const auto plain = lynx::ProjectFile::toJson (song);
- song.mixer[1].latencyMs = -20.0f;
- song.mixer[2].latencyMs = 12.5f;
- song.mixer[2].latencyBypass = lynx::LatencyBypass::always;
- song.mixer[3].latencyBypass = lynx::LatencyBypass::whenRecordingOrStopped;
- song.mixer[3].compensateMasterLatency = false;
- const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
- latencyOk = back && back->mixer[1].latencyMs == -20.0f && back->mixer[2].latencyMs == 12.5f
- && back->mixer[2].latencyBypass == lynx::LatencyBypass::always
- && back->mixer[3].latencyBypass == lynx::LatencyBypass::whenRecordingOrStopped && ! back->mixer[3].compensateMasterLatency
- && back->mixer[4].latencyMs == 0.0f && back->mixer[4].compensateMasterLatency
- && ! plain.contains ("latencyMs") && ! plain.contains ("latencyBypass") && ! plain.contains ("compensateMaster");
- }
- // LYNX substitutes (round 98): a missing plugin's slot plays a built-in equivalent and the project keeps the
- // original reference byte for byte (.flp record and LYNX plugin state)
- bool substituteOk = false;
- {
- auto song = lynx::Song::makeDefault();
- lynx::ForeignPlugin vv; // an .flp VST3 record (ValhallaVintageVerb's class ID), opaque state
- vv.format = lynx::ForeignPlugin::Format::vst3;
- const std::uint8_t cid[] = { 0x76, 0x54, 0x53, 0x56, 0x65, 0x65, 0x76, 0x33, 0x61, 0x6c, 0x68, 0x61, 0x6c, 0x6c, 0x61, 0x76 };
- std::copy (std::begin (cid), std::end (cid), vv.classId.begin());
- vv.hasClassId = true;
- vv.name = "ValhallaVintageVerb";
- vv.path = "C:\\x\\ValhallaVintageVerb.vst3";
- for (int i = 0; i < 777; ++i)
- vv.state.push_back ((std::uint8_t) (i * 13 + 1));
- lynx::EffectSlot fromFlp;
- fromFlp.kind = lynx::EffectKind::plugin;
- fromFlp.plugin.foreign = vv;
- lynx::EffectSlot fromLynx; // a LYNX reference whose plugin isn't installed here
- fromLynx.kind = lynx::EffectKind::plugin;
- fromLynx.plugin.id = "VST3-FabFilter Pro-Q 3-1a2b3c4d-5e6f7a8b";
- fromLynx.plugin.name = "FabFilter Pro-Q 3";
- fromLynx.plugin.state = "AAECAwQFBgcICQ==";
- const auto flpRef = fromFlp.plugin, lynxRef = fromLynx.plugin;
- song.mixer[1].effects = { fromFlp, fromLynx };
- const auto substitutesOn = lynx::pluginSubstitutesEnabled();
- const auto changed = offline.getPluginHost().applySubstitutes (song);
- auto& fx = song.mixer[1].effects;
- // only the LYNX reference is substituted here (an .flp record is the import's job); do the .flp one directly
- const auto flpSubstituted = lynx::substituteEffectSlot (fx[0], lynx::pluginIdentity (vv));
- const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
- substituteOk = flpSubstituted && fx[0].kind == lynx::EffectKind::epochVerb
- && (! substitutesOn || (changed == 1 && fx[1].kind == lynx::EffectKind::facetEq && fx[1].substituteFor == lynxRef))
- && back && back->mixer[1].effects.size() == 2 && back->mixer[1].effects[0].kind == lynx::EffectKind::epochVerb
- && back->mixer[1].effects[0].substituteFor == flpRef && back->mixer[1].effects[0].substituteFor.foreign.state == vv.state
- && back->mixer[1].effects[1].kind == fx[1].kind && back->mixer[1].effects[1].substituteFor == fx[1].substituteFor;
- }
- // undo/redo
- offline.editSong ([] (lynx::Song& s) { s.bpm = 99.0; });
- offline.editSong ([] (lynx::Song& s) { s.bpm = 101.0; });
- offline.undo();
- const auto afterUndo = offline.getSong().bpm;
- offline.redo();
- const auto undoOk = afterUndo == 99.0 && offline.getSong().bpm == 101.0 && offline.canUndo() && ! offline.canRedo()
- && offline.isModified();
- // recording from the PC keyboard: a one-beat note lands in the pattern, in a single undo step
- const auto notesBefore = offline.getSong().patterns[0].notes.size();
- offline.setRecording (true);
- offline.play();
- offline.getTransport().positionTicks.store (960.0);
- offline.sendLiveNote (2, 72, 0.9f, true, true);
- offline.getTransport().positionTicks.store (1920.0);
- offline.sendLiveNote (2, 72, 0.0f, false, true);
- offline.setRecording (false);
- offline.stop();
- const auto& recorded = offline.getSong().patterns[0].notes;
- const auto recordOk = recorded.size() == notesBefore + 1
- && std::any_of (recorded.begin(), recorded.end(), [] (const lynx::Note& n) {
- return n.key == 72 && n.channel == 2 && n.length == 960 && n.start >= 960 && n.start < 3840;
- });
- offline.undo();
- const auto recordUndoOk = offline.getSong().patterns[0].notes.size() == notesBefore;
- // MIDI: exporting the pattern and importing it back gives the same notes
- bool midiOk = false;
- {
- auto source = lynx::Song::makeDefault();
- source.patterns[0].notes.push_back ({ 1000, 480, 4, 67, 0.5f });
- source.patterns[0].sortNotes();
- const auto midiFile = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest.mid");
- juce::String midiError;
- const auto saved = lynx::MidiFileIo::savePattern (source, 0, midiFile, midiError);
- const auto song = saved ? lynx::MidiFileIo::loadSong (midiFile, midiError) : std::nullopt;
- midiFile.deleteFile();
- if (song && song->patterns.size() == 1 && song->patterns[0].notes.size() == source.patterns[0].notes.size()
- && std::abs (song->bpm - source.bpm) < 0.01)
- {
- midiOk = true;
- const auto& a = source.patterns[0].notes;
- const auto& b = song->patterns[0].notes;
- for (std::size_t i = 0; i < a.size(); ++i)
- midiOk = midiOk && a[i].start == b[i].start && a[i].key == b[i].key && a[i].length == b[i].length;
- }
- }
- // project package (REA round 118): a project with a sample exported as .zip, extracted and opened again,
- // finds its sample inside the extracted folder
- bool packageOk = false;
- {
- const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest-package");
- dir.deleteRecursively();
- dir.getChildFile ("src").createDirectory();
- const auto wav = dir.getChildFile ("src/hit.wav");
- {
- juce::WavAudioFormat format;
- juce::AudioBuffer<float> hit (1, 480);
- for (int i = 0; i < 480; ++i)
- hit.setSample (0, i, 0.5f * std::sin (0.1f * (float) i));
- std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
- if (auto* w = format.createWriterFor (out.get(), 48000.0, 1, 16, {}, 0))
- {
- out.release();
- std::unique_ptr<juce::AudioFormatWriter> writer (w);
- writer->writeFromAudioSampleBuffer (hit, 0, 480);
- }
- }
- auto source = lynx::Song::makeDefault();
- lynx::ChannelDef c;
- c.name = "Hit";
- c.instrument = lynx::InstrumentKind::sampler;
- c.samplePath = wav.getFullPathName().toStdString();
- source.channels.push_back (c);
- lynx::ProjectPackage::Result packed;
- juce::String packageError;
- const auto zip = dir.getChildFile ("Beat.zip");
- if (wav.existsAsFile() && lynx::ProjectPackage::exportZip (source, "Beat", zip, packed, packageError) && packed.files == 1)
- {
- const auto project = lynx::ProjectPackage::extractZip (zip, dir.getChildFile ("out"), packageError);
- const auto song = project.existsAsFile() ? lynx::ProjectFile::load (project, packageError) : std::nullopt;
- if (song && ! song->channels.empty())
- {
- const juce::File back (juce::String::fromUTF8 (song->channels.back().samplePath.c_str()));
- packageOk = back.existsAsFile() && back.isAChildOf (project.getParentDirectory()) && back.getSize() == wav.getSize();
- }
- }
- dir.deleteRecursively();
- }
- // Online Sessions (round 168a): a project sent as a .lynxpack (one sample used twice is stored once, the uids
- // survive), a stand-in rendered through an ExportJob, the guest's part sent back and merged by the host
- juce::String sessionResult = "ERROR";
- {
- const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest-session");
- dir.deleteRecursively();
- dir.getChildFile ("src").createDirectory();
- const auto wav = dir.getChildFile ("src/hit.wav");
- {
- juce::WavAudioFormat format;
- juce::AudioBuffer<float> hit (1, 4800);
- for (int i = 0; i < 4800; ++i)
- hit.setSample (0, i, 0.5f * std::sin (0.05f * (float) i) * (1.0f - (float) i / 4800.0f));
- std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
- if (auto* w = format.createWriterFor (out.get(), 48000.0, 1, 16, {}, 0))
- {
- out.release();
- std::unique_ptr<juce::AudioFormatWriter> writer (w);
- writer->writeFromAudioSampleBuffer (hit, 0, 4800);
- }
- }
- auto host = lynx::Song::makeDefault();
- host.mode = lynx::PlayMode::song;
- const auto copyOfWav = dir.getChildFile ("src/hit copy.wav"); // the same bytes under another name: stored once
- wav.copyFileTo (copyOfWav);
- for (const auto& [name, file] : { std::pair<const char*, juce::File> { "Hit", wav }, { "Hit 2", copyOfWav } })
- {
- lynx::ChannelDef c;
- c.name = name;
- c.instrument = lynx::InstrumentKind::sampler;
- c.samplePath = file.getFullPathName().toStdString();
- host.channels.push_back (c);
- }
- const auto hitChannel = (int) host.channels.size() - 2;
- lynx::Note hitNote;
- hitNote.channel = hitChannel;
- hitNote.length = 480;
- host.patterns[0].notes.push_back (hitNote);
- host.playlist.push_back ({ 0, 0, 0, host.patterns[0].effectiveLength (host.beatsPerBar), 0 });
- lynx::uids::normalize (host);
- const auto* guest = lynx::parts::invite (host, "Host", "Ana", 0xFF3D9BE9, false);
- juce::String e;
- std::vector<lynx::sessionpack::Rendered> rendered;
- // (a sampler stands in for a plugin channel here: render() renders whatever it is given)
- const std::vector<lynx::sessionpack::RenderItem> items { { false, hitChannel, false, "Hit", "Test" } };
- const auto renderedOk = guest != nullptr && lynx::sessionpack::render (host, items, 44100.0, dir.getChildFile ("stems"), "Host", rendered, {}, e)
- && rendered.size() == 1 && rendered[0].standIns.size() == 2
- && juce::File (juce::String::fromUTF8 (rendered[0].standIns[0].path.c_str())).getSize() > 1000;
- if (renderedOk)
- lynx::sessionpack::apply (host, rendered);
- lynx::sessionpack::Manifest m;
- m.projectName = "Selftest";
- m.from = *host.session.find (lynx::session::hostTag);
- m.to = *host.session.find (2);
- lynx::sessionpack::WriteResult written;
- const auto pack = dir.getChildFile (juce::String ("Selftest") + lynx::sessionpack::extension);
- const auto packOk = renderedOk && lynx::sessionpack::write (lynx::parts::guestCopy (host, 2), m, offline.getPluginHost(), pack, written, e)
- && written.media == 3 && written.duplicates == 1; // the sample once (used twice), the stand-in pair
- auto opened = packOk ? lynx::sessionpack::open (pack, dir.getChildFile ("received"), e) : std::nullopt;
- bool openOk = false, mergeOk = false;
- if (opened && opened->corrupt.isEmpty())
- {
- const auto& g = opened->song;
- const juce::File sample (juce::String::fromUTF8 (g.channels[(std::size_t) hitChannel].samplePath.c_str()));
- openOk = g.session.me == 2 && g.projectId == host.projectId && g.channels[(std::size_t) hitChannel].uid == host.channels[(std::size_t) hitChannel].uid
- && sample.existsAsFile() && sample.isAChildOf (opened->folder) && g.channels[(std::size_t) hitChannel].standIns.size() == 2
- && juce::File (juce::String::fromUTF8 (g.channels[(std::size_t) hitChannel].standIns[1].path.c_str())).existsAsFile();
- // the guest adds a channel and a pattern of his own, sends his part back
- auto copy = g;
- lynx::ChannelDef mine;
- mine.name = "Ana's hit";
- mine.instrument = lynx::InstrumentKind::sampler;
- mine.samplePath = sample.getFullPathName().toStdString();
- copy.channels.push_back (mine);
- lynx::Pattern p;
- p.name = "Ana";
- lynx::Note note;
- note.channel = (int) copy.channels.size() - 1;
- note.length = 240;
- note.key = 64;
- p.notes.push_back (note);
- copy.patterns.push_back (p);
- lynx::uids::normalize (copy);
- // its uids survive a save and a load
- const auto saved = dir.getChildFile ("guest.lynx");
- auto reloaded = lynx::ProjectFile::save (copy, saved, e) ? lynx::ProjectFile::load (saved, e) : std::nullopt;
- lynx::sessionpack::Manifest back;
- back.part = true;
- back.from = *copy.session.self();
- const auto partFile = dir.getChildFile (juce::String ("Ana part") + lynx::sessionpack::extension);
- lynx::sessionpack::WriteResult partWritten;
- auto part = reloaded && reloaded->channels.back().uid == copy.channels.back().uid && lynx::uids::tagOf (reloaded->channels.back().uid) == 2
- ? lynx::sessionpack::write (lynx::parts::extract (*reloaded, 2), back, offline.getPluginHost(), partFile, partWritten, e)
- : false;
- auto partOpened = part ? lynx::sessionpack::open (partFile, dir.getChildFile ("parts"), e) : std::nullopt;
- if (partOpened && partOpened->manifest.part && lynx::sessionpack::adoptMedia (partOpened->song, dir.getChildFile ("Session media/Ana"), e))
- {
- const auto report = lynx::parts::merge (host, partOpened->song, 2);
- const auto& added = host.channels.back();
- mergeOk = report.ok && report.channels >= 1 && added.name == "Ana's hit" && lynx::uids::tagOf (added.uid) == 2
- && juce::File (juce::String::fromUTF8 (added.samplePath.c_str())).isAChildOf (dir.getChildFile ("Session media/Ana"))
- && host.channels[(std::size_t) hitChannel].name == "Hit";
- }
- }
- // a crafted package whose project points at a file elsewhere on this computer: opening it must not
- // reach that file, or merging would copy it into the project and the next package would send it on
- if (mergeOk)
- {
- const auto secret = dir.getChildFile ("secret.wav");
- wav.copyFileTo (secret);
- auto evil = lynx::Song::makeDefault();
- lynx::ChannelDef c;
- c.instrument = lynx::InstrumentKind::sampler;
- c.samplePath = secret.getFullPathName().toStdString();
- evil.channels.push_back (c);
- lynx::ChannelDef keys; // (FL Keys' zones are read by the engine but are not in the media list)
- keys.instrument = lynx::InstrumentKind::flkeys;
- keys.zones.push_back ({});
- keys.zones.back().path = c.samplePath;
- evil.channels.push_back (keys);
- lynx::ChannelDef patch; // (a Patcher's nodes are not in the media list either)
- patch.instrument = lynx::InstrumentKind::patcher;
- patch.patcher.nodes.resize (2);
- patch.patcher.nodes[0].generator = true;
- patch.patcher.nodes[0].channel = c;
- patch.patcher.nodes[1].effect.samplePath = c.samplePath;
- evil.channels.push_back (patch);
- evil.mixer[1].recordTo = dir.getChildFile ("overwritten.wav").getFullPathName().toStdString();
- const auto evilProject = dir.getChildFile ("evil.lynx");
- lynx::sessionpack::Manifest em;
- em.part = true;
- juce::ZipFile::Builder b;
- const auto json = lynx::sessionpack::manifestToJson (em);
- b.addEntry (new juce::MemoryInputStream (json.toRawUTF8(), json.getNumBytesAsUTF8(), true), 0, "manifest.json", {});
- const auto evilPack = dir.getChildFile (juce::String ("Evil") + lynx::sessionpack::extension);
- bool zipped = false;
- if (lynx::ProjectFile::save (evil, evilProject, e))
- {
- b.addFile (evilProject, 0, "project.lynx");
- juce::FileOutputStream out (evilPack);
- zipped = out.openedOk() && b.writeToStream (out, nullptr);
- }
- auto evilOpened = zipped ? lynx::sessionpack::open (evilPack, dir.getChildFile ("evil"), e) : std::nullopt;
- const auto media = dir.getChildFile ("Session media/Evil");
- mergeOk = evilOpened && lynx::sessionpack::adoptMedia (evilOpened->song, media, e)
- && std::none_of (evilOpened->song.channels.begin(), evilOpened->song.channels.end(), [&] (const lynx::ChannelDef& ch) {
- return juce::File (juce::String::fromUTF8 (ch.samplePath.c_str())) == secret
- || std::any_of (ch.zones.begin(), ch.zones.end(), [&] (const lynx::SampleZone& z) { return juce::File (juce::String::fromUTF8 (z.path.c_str())) == secret; });
- })
- && evilOpened->song.channels.back().patcher.nodes.size() == 2
- && juce::File (juce::String::fromUTF8 (evilOpened->song.channels.back().patcher.nodes[0].channel.samplePath.c_str())) != secret
- && juce::File (juce::String::fromUTF8 (evilOpened->song.channels.back().patcher.nodes[1].effect.samplePath.c_str())) != secret
- && evilOpened->song.mixer[1].recordTo.empty()
- && media.findChildFiles (juce::File::findFiles, true).isEmpty();
- if (! mergeOk && e.isEmpty())
- e = "a received package reached a file outside it";
- }
- // ... nor through its own folder: "..", Windows' dotted names (". ." climbs like ".." there), and a manifest
- // media entry outside the package (it must not even be read: "/dev/zero" would never end)
- if (mergeOk)
- {
- const auto secret = dir.getChildFile ("secret.wav");
- const auto folder = dir.getChildFile ("evil2").getChildFile ("Evil2"); // (where open() will unpack it)
- const auto climb = folder.getFullPathName() + "/media/../../../secret.wav";
- const auto dotted = folder.getFullPathName() + "/. ./.. ./secret.wav";
- auto evil = lynx::Song::makeDefault();
- for (const auto& path : { climb, dotted })
- {
- lynx::ChannelDef c;
- c.instrument = lynx::InstrumentKind::sampler;
- c.samplePath = path.toStdString();
- evil.channels.push_back (c);
- }
- juce::MemoryBlock secretBytes;
- secret.loadFileAsData (secretBytes);
- lynx::sessionpack::Manifest em;
- em.part = true;
- em.media.push_back ({ "sha256-" + juce::String (lynx::sha256Hex ((const std::uint8_t*) secretBytes.getData(), secretBytes.getSize())),
- "secret.wav", (juce::int64) secretBytes.getSize(), "../../secret.wav" });
- const auto evilProject = dir.getChildFile ("evil2.lynx");
- juce::ZipFile::Builder b;
- const auto json = lynx::sessionpack::manifestToJson (em);
- b.addEntry (new juce::MemoryInputStream (json.toRawUTF8(), json.getNumBytesAsUTF8(), true), 0, "manifest.json", {});
- const auto evilPack = dir.getChildFile (juce::String ("Evil2") + lynx::sessionpack::extension);
- bool zipped = false;
- if (lynx::ProjectFile::save (evil, evilProject, e))
- {
- b.addFile (evilProject, 0, "project.lynx");
- juce::FileOutputStream out (evilPack);
- zipped = out.openedOk() && b.writeToStream (out, nullptr);
- }
- auto evilOpened = zipped ? lynx::sessionpack::open (evilPack, dir.getChildFile ("evil2"), e) : std::nullopt;
- const auto media = dir.getChildFile ("Session media/Evil2");
- mergeOk = evilOpened && evilOpened->folder == folder && evilOpened->corrupt.contains ("secret.wav")
- && lynx::sessionpack::adoptMedia (evilOpened->song, media, e) && evilOpened->song.channels.size() >= 2
- && std::none_of (evilOpened->song.channels.begin(), evilOpened->song.channels.end(), [&] (const lynx::ChannelDef& ch) {
- const auto p = juce::String::fromUTF8 (ch.samplePath.c_str());
- return p == climb || p == dotted || (juce::File::isAbsolutePath (p) && juce::File (p) == secret);
- })
- && media.findChildFiles (juce::File::findFiles, true).isEmpty();
- if (! mergeOk && e.isEmpty())
- e = "a received package climbed out of its folder";
- }
- if (! packOk && e.isEmpty())
- e = "media " + juce::String (written.media) + ", duplicates " + juce::String (written.duplicates) + ", missing "
- + written.missing.joinIntoString (";");
- sessionResult = mergeOk ? juce::String ("OK")
- : "ERROR (" + juce::String (renderedOk ? packOk ? openOk ? "merge" : "open" : "pack" : "render") + (e.isEmpty() ? "" : ": " + e) + ")";
- dir.deleteRecursively();
- }
- // WavPack: a .wv from the FL packs (if installed) opens through the sample loader
- juce::String wavpack = "NO_FL";
- {
- const auto roots = lynx::findFlStudioRoots();
- const auto packs = juce::File (juce::String::fromUTF8 (roots.data.c_str())).getChildFile ("Patches/Packs");
- const auto found = packs.isDirectory() ? packs.findChildFiles (juce::File::findFiles, true, "*.wv") : juce::Array<juce::File> {};
- if (! found.isEmpty())
- {
- lynx::SampleLibrary library;
- const auto sample = library.load (found.getFirst().getFullPathName());
- float peakWv = 0.0f;
- if (sample != nullptr)
- for (std::size_t i = 0; i < sample->frames(); ++i)
- peakWv = std::max (peakWv, std::abs (sample->leftData()[i]));
- wavpack = sample != nullptr && sample->frames() > 0 && peakWv > 1e-4f ? "OK" : "ERROR";
- }
- }
- // every built-in effect's editor and engine with extreme settings (round 111): a crash or NaN output fails here
- const auto effectsOk = runEffectFuzz (4, {}); // (no mouse drags: nothing may open on screen)
- // FL's Patcher (round 141): a mixer slot and a generator channel with their graphs survive save / load, and the
- // generator one plays through the rack
- bool patcherOk = false;
- {
- auto song = lynx::Song::makeDefault();
- song.mixer.resize (4);
- auto slot = lynx::makeEffectSlot (lynx::EffectKind::patcher);
- lynx::PatchNode reverb, gain;
- reverb.effect = lynx::makeEffectSlot (lynx::EffectKind::utility); // (exact defaults: params are saved to 4 decimals)
- reverb.label = "Room";
- reverb.x = 120.5f;
- reverb.y = 40.0f;
- gain.effect = lynx::makeEffectSlot (lynx::EffectKind::utility);
- gain.effect.enabled = false;
- slot.patcher.nodes = { reverb, gain };
- lynx::PatchWire a, b, c, control;
- a.to = 0;
- b.from = 0, b.to = 1, b.gain = 0.5f;
- c.from = 1;
- control.kind = lynx::PatchWire::Kind::control, control.from = 0, control.to = 1, control.toPort = 0, control.curve = { 0.0f, 0.25f, 1.0f };
- slot.patcher.wires = { a, b, c, control };
- slot.patcher.outputTracks = { 3 };
- song.mixer[1].effects = { slot };
- lynx::ChannelDef ch;
- ch.name = "Patched";
- ch.instrument = lynx::InstrumentKind::patcher;
- lynx::PatchNode synth;
- synth.generator = true;
- synth.channel.instrument = lynx::InstrumentKind::synth;
- synth.channel.name = "Synth";
- ch.patcher.nodes = { synth };
- lynx::PatchWire notes, out;
- notes.kind = lynx::PatchWire::Kind::midi, notes.to = 0;
- out.from = 0;
- ch.patcher.wires = { notes, out };
- // round 162: the I/O nodes' MIDI pins and a MIDI Out node between them
- lynx::PatchNode midiOutNode;
- midiOutNode.generator = true;
- midiOutNode.channel.instrument = lynx::InstrumentKind::midiOut;
- lynx::midictl::writeMidiOut (midiOutNode.channel.pluginState, { 4, 0, 0, -1, -1 });
- ch.patcher.nodes.push_back (midiOutNode);
- lynx::PatchWire portIn, portOut;
- portIn.kind = portOut.kind = lynx::PatchWire::Kind::midi;
- portIn.fromPort = lynx::patchMidiPortPin (7), portIn.to = 1;
- portOut.from = 1, portOut.to = lynx::patchToHost, portOut.toPort = 9;
- ch.patcher.wires.push_back (portIn);
- ch.patcher.wires.push_back (portOut);
- ch.patcher.fromMidiPorts = { 2, 7 };
- ch.patcher.toMidiPorts = { 9, 11 };
- ch.patcher.fromNotesHidden = true;
- song.channels.push_back (ch);
- const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
- patcherOk = back && back->mixer.size() >= 2 && back->mixer[1].effects.size() == 1
- && back->mixer[1].effects[0].kind == lynx::EffectKind::patcher && back->mixer[1].effects[0].patcher == slot.patcher
- && back->channels.back().instrument == lynx::InstrumentKind::patcher && back->channels.back().patcher.nodes.size() == 2
- && back->channels.back().patcher.fromMidiPorts == ch.patcher.fromMidiPorts
- && back->channels.back().patcher.toMidiPorts == ch.patcher.toMidiPorts && back->channels.back().patcher.fromNotesHidden
- && back->channels.back().patcher.nodes[1].channel.pluginState == midiOutNode.channel.pluginState
- && back->channels.back().patcher.nodes[0].generator
- && back->channels.back().patcher.nodes[0].channel.instrument == lynx::InstrumentKind::synth
- && back->channels.back().patcher.wires == ch.patcher.wires;
- }
- // FL engines in a native project (round 142, issue #5): every engine this PC can make survives save / load and
- // the instruments play through the rack
- juce::String nativesResult = "OK";
- int nativesMade = 0, nativesSilent = 0;
- {
- auto song = lynx::Song::makeDefault();
- song.channels.clear();
- song.patterns[0].notes.clear();
- song.mixer.resize (3);
- const auto& fl = lynx::flStudioAccess();
- for (const auto& e : lynx::natives::instrumentEngines())
- if (lynx::natives::available (e, fl))
- if (auto c = lynx::natives::makeChannel (e.kind, fl))
- {
- c->mixerTrack = 1;
- song.channels.push_back (*c);
- }
- for (const auto& e : lynx::natives::effectEngines())
- if (auto fx = lynx::natives::makeSlot (e.kind, fl))
- song.mixer[2].effects.push_back (*fx);
- nativesMade = (int) (song.channels.size() + song.mixer[2].effects.size());
- const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
- auto same = back && back->channels.size() == song.channels.size() && back->mixer.size() >= 3
- && back->mixer[2].effects.size() == song.mixer[2].effects.size();
- for (std::size_t i = 0; same && i < song.channels.size(); ++i)
- {
- const auto& a = song.channels[i];
- const auto& b = back->channels[i];
- same = a.instrument == b.instrument && a.pluginState == b.pluginState && a.samplePath == b.samplePath && a.zones.size() == b.zones.size()
- && a.modelParams.size() == b.modelParams.size();
- if (! same)
- nativesResult = "ERROR channel " + juce::String::fromUTF8 (a.name.c_str());
- }
- for (std::size_t i = 0; same && i < song.mixer[2].effects.size(); ++i)
- {
- const auto& a = song.mixer[2].effects[i];
- const auto& b = back->mixer[2].effects[i];
- same = a.kind == b.kind && a.state == b.state;
- for (std::size_t p = 0; same && p < a.params.size(); ++p)
- same = std::abs (a.params[p] - b.params[p]) < 1.0e-3f;
- if (! same)
- nativesResult = juce::String ("ERROR effect ") + lynx::effectInfo (a.kind).name;
- }
- if (! back)
- nativesResult = "ERROR " + error;
- // each instrument plays a note alone. The Granulizer and Wave Traveller play the channel's sample, and a new
- // one has none (a PC without FL Studio, macOS / Linux: FL's presets are not there either), so they get a
- // generated one: a second of a 220 Hz tone (round 167m, PR #19: Wave Traveller was "SILENT 1" on macOS)
- const auto toneWav = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest-natives.wav");
- {
- juce::WavAudioFormat format;
- juce::AudioBuffer<float> tone (1, 48000);
- for (int i = 0; i < 48000; ++i)
- tone.setSample (0, i, 0.5f * std::sin (juce::MathConstants<float>::twoPi * 220.0f * (float) i / 48000.0f));
- toneWav.deleteFile();
- std::unique_ptr<juce::OutputStream> out (toneWav.createOutputStream().release());
- if (auto* w = format.createWriterFor (out.get(), 48000.0, 1, 16, {}, 0))
- {
- out.release();
- std::unique_ptr<juce::AudioFormatWriter> writer (w);
- writer->writeFromAudioSampleBuffer (tone, 0, 48000);
- }
- }
- juce::StringArray silentNames;
- for (std::size_t i = 0; same && i < song.channels.size(); ++i)
- {
- auto one = song;
- one.channels = { song.channels[i] };
- one.channels[0].mixerTrack = 1;
- const auto kind = song.channels[i].instrument;
- if ((kind == lynx::InstrumentKind::granulizer || kind == lynx::InstrumentKind::wavetraveller) && one.channels[0].samplePath.empty())
- one.channels[0].samplePath = toneWav.getFullPathName().toStdString();
- one.mixer[2].effects.clear();
- // Drumaxx plays pad 1's key: FL's default kit has a pad at 48, LYNX's own bank kits (a PC without FL,
- // macOS / Linux; round 168p) start at 36 (round 169d: "SILENT 1 [Drumaxx]" on the Linux / macOS CI)
- auto key = 60;
- if (kind == lynx::InstrumentKind::drumaxx)
- {
- const auto padKey = lynx::drumaxxParam (one.channels[0].pluginState, 4);
- key = std::isfinite (padKey) && padKey >= 0.0f && padKey <= 127.0f ? (int) padKey : 48;
- }
- one.patterns[0].notes = { { 0, 1920, 0, key, 0.8f } };
- lynx::AudioEngine player (false);
- player.setSong (std::move (one));
- player.dispatchPendingMessages();
- if (! (player.renderOffline (1.0, 48000.0) > 1.0e-4f))
- {
- ++nativesSilent;
- silentNames.add (juce::String::fromUTF8 (song.channels[i].name.c_str()));
- }
- }
- toneWav.deleteFile();
- if (nativesSilent > 0 && nativesResult == "OK")
- nativesResult = "SILENT " + juce::String (nativesSilent) + " [" + silentNames.joinIntoString (", ") + "]";
- }
- const auto nativesOk = nativesResult == "OK";
- // The metronome as FL 2026 plays it (round 165z-a2): FL's five sounds from its install, the downbeat at
- // 0.9404 × the Tick two semitones up, into the Master ("---") by default; insert 2 as its track plays it through
- // insert 2 (muted: silent); never in an export
- juce::String metronomeResult = "OK";
- int metronomeFlSounds = 0;
- float metronomeMaster = 0.0f;
- {
- const auto& flData = lynx::flStudioAccess().roots.data;
- const auto sounds = lynx::Metronome::loadSounds (flData.empty() ? juce::File() : lynx::platform::localFile (flData));
- for (const auto& s : sounds)
- metronomeFlSounds += s.fromFl ? 1 : 0;
- auto renderClick = [] (int track, bool muteInsert, bool include) {
- auto song = lynx::Song::makeDefault();
- song.channels.clear();
- song.playlist.clear();
- for (auto& p : song.patterns)
- p.notes.clear();
- song.mixer[0].effects.clear(); // (the default Master limiter)
- song.mixer[2].muted = muteInsert;
- lynx::AudioEngine player (false);
- player.setSong (std::move (song));
- player.dispatchPendingMessages();
- auto& t = player.getTransport();
- t.metronome = true;
- t.metronomeSound = 1; // Tick
- t.metronomeTrack = track;
- lynx::AudioEngine::RenderOptions o;
- o.seconds = 0.25;
- o.sampleRate = 44100.0;
- o.pluginWarmUp = false;
- o.includeMetronome = include;
- return player.renderOffline (o);
- };
- metronomeMaster = renderClick (0, false, true);
- const auto insert = renderClick (2, false, true);
- const auto muted = renderClick (2, true, true);
- const auto exported = renderClick (0, false, false);
- // FL's Tick peaks at 1.0: its downbeat at most 0.9404 (the interpolation may land between peaks)
- const auto expectHigh = metronomeFlSounds == lynx::metronome::soundCount ? lynx::metronome::downbeatGain + 1.0e-3f : 1.0f;
- if (! (metronomeMaster > 0.5f && metronomeMaster < expectHigh))
- metronomeResult = "ERROR master " + juce::String (metronomeMaster, 4);
- else if (std::abs (insert - metronomeMaster) > 2.0e-3f)
- metronomeResult = "ERROR insert " + juce::String (insert, 4);
- else if (muted > 1.0e-4f)
- metronomeResult = "ERROR muted insert " + juce::String (muted, 4);
- else if (exported > 1.0e-4f)
- metronomeResult = "ERROR in export " + juce::String (exported, 4);
- }
- const auto metronomeOk = metronomeResult == "OK";
- // Settings › Audio "Driver settings…" with a fake driver panel (issue #13's crash, the panel's buffer kept)
- const auto driverPanel = lynx::AudioEngine::driverPanelSelfTest();
- // Online Sessions P2 (round 169b): live sessions without a network (the JSON round trip of every entity, replicas
- // through it, the invite code's keys)
- const auto liveResult = lynx::livetest::selfTest (&rich);
- // issue #67: every built-in effect's parameters, named and hidden (the Parametric EQ's FL law, processing, band
- // mask...), at odd values, through a project save and reload: the same floats back
- juce::String effectParamsResult = "OK";
- {
- auto song = lynx::Song::makeDefault();
- song.mixer.resize (1);
- for (int k = 0; k <= (int) lynx::lastEffectKind; ++k)
- {
- const auto kind = (lynx::EffectKind) k;
- if (kind == lynx::EffectKind::plugin || kind == lynx::EffectKind::parallel)
- continue;
- auto fx = lynx::makeEffectSlot (kind);
- for (std::size_t i = 0; i < fx.params.size(); ++i)
- {
- auto v = (float) ((double) ((i * 7919 + (std::size_t) k * 104729) % 65521) / 65521.0);
- fx.params[i] = v == fx.params[i] ? 1.0f - v : v;
- }
- if (kind == lynx::EffectKind::fruitySend) // ("Send to" is written over the insert span)
- fx.params[3] = 0.0f;
- song.mixer.emplace_back();
- song.mixer.back().name = "Insert " + std::to_string (song.mixer.size() - 1);
- song.mixer.back().effects.push_back (fx);
- }
- // round 171b's Patcher round trip (coordinator): the Frequency Splitter, Fruity Delay 3 and Peak Controller
- // nodes came back different (their FL defaults, e.g. the LFO speed 32750 / 65336, lost to 4 decimals)
- {
- auto patch = lynx::makeEffectSlot (lynx::EffectKind::patcher);
- for (const auto kind : { lynx::EffectKind::frequencySplitter, lynx::EffectKind::fruityDelay3, lynx::EffectKind::peakController,
- lynx::EffectKind::reverb, lynx::EffectKind::hardwareInsert })
- {
- lynx::PatchNode node;
- node.effect = lynx::natives::newEffect (kind, lynx::flStudioAccess()).value_or (lynx::makeEffectSlot (kind));
- if (kind == lynx::EffectKind::peakController)
- node.effect.params[7] = 32750.0f / 65336.0f;
- node.x = 200.0f, node.y = 60.0f * (float) patch.patcher.nodes.size();
- patch.patcher.nodes.push_back (node);
- }
- song.mixer.emplace_back();
- song.mixer.back().name = "Patcher";
- song.mixer.back().effects.push_back (patch);
- }
- juce::String why;
- const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
- if (back && back->mixer.size() == song.mixer.size())
- {
- const auto& a = song.mixer.back().effects[0].patcher.nodes;
- const auto& b = back->mixer.back().effects[0].patcher.nodes;
- for (std::size_t n = 0; n < a.size(); ++n)
- if (n >= b.size() || ! (a[n].effect == b[n].effect))
- effectParamsResult = juce::String ("ERROR Patcher node ") + lynx::effectInfo (a[n].effect.kind).name;
- }
- if (! back || back->mixer.size() != song.mixer.size())
- effectParamsResult = "ERROR load " + why;
- else
- for (std::size_t t = 1; t + 1 < song.mixer.size() && effectParamsResult == "OK"; ++t)
- if (back->mixer[t].effects.size() != 1 || back->mixer[t].effects[0].params != song.mixer[t].effects[0].params)
- {
- effectParamsResult = juce::String ("ERROR ") + lynx::effectInfo (song.mixer[t].effects[0].kind).name;
- break;
- }
- }
- // round 170j: the Themed plugin style (its resolution with and without art; every art draws)
- const auto artResult = lynx::skin::artSelfTest();
- // round 177b: a plugin's sidechain bus gets the slot's sidechain (one-click sidechain)
- const auto sidechainResult = lynx::pluginSidechainSelfTest();
- // round 177b: automation lanes come back from a project (track, automation, height, folded)
- juce::String lanesResult = "OK";
- {
- auto song = lynx::Song::makeDefault();
- const auto lane = lynx::autolanes::addLane (song, 3, { lynx::AutomationTargetKind::mixerVolume, 1, 0, 0 }, "Vol", 0.4f);
- song.playlistTracks[3].lanes[0].height = 72;
- song.playlistTracks[3].lanesFolded = true;
- // (the same round's clip LFO and modulators ride along)
- auto& lfo = song.automations[(std::size_t) lane].lfo;
- lfo.on = true;
- lfo.level = -40;
- lfo.speed = 30000;
- lfo.flags = 1 | 4;
- lfo.phase = 123456789u;
- lfo.amp = { { 0, 0.5f, 0.0f }, { 960, 1.0f, 0.0f } };
- lynx::Modulator mod;
- mod.name = "LFO 1";
- mod.shape = lynx::ModShape::square;
- mod.sync = false;
- mod.hz = 2.5;
- mod.routes = { { { lynx::AutomationTargetKind::mixerPan, 1, 0, 0 }, -0.5f } };
- song.modulators.push_back (mod);
- juce::String why;
- const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
- if (! back || back->playlistTracks.size() < 4 || ! (back->playlistTracks[3].lanes == song.playlistTracks[3].lanes)
- || ! back->playlistTracks[3].lanesFolded || back->automations.size() != song.automations.size()
- || ! (back->automations[(std::size_t) lane].points == song.automations[(std::size_t) lane].points)
- || ! (back->automations[(std::size_t) lane].lfo == lfo) || ! (back->modulators == song.modulators))
- lanesResult = "ERROR " + why;
- }
- const auto ok = audioOk && projectOk && richOk && hwOutOk && flp168jOk && blocksOk && polyOk && latencyOk && substituteOk && patcherOk && nativesOk && undoOk && recordOk && recordUndoOk && midiOk && packageOk
- && sessionResult == "OK" && liveResult.startsWith ("OK")
- && wavpack != "ERROR" && effectsOk && driverPanel == "OK" && metronomeOk && artResult == "OK" && effectParamsResult == "OK"
- && sidechainResult == "OK" && lanesResult == "OK";
- juce::String report;
- report << "connections=" << offline.getNumGraphConnections() << "\n"
- << "peak=" << peak << "\n"
- << "project=" << (projectOk ? "OK" : "ERROR " + error) << "\n"
- << "project_features=" << (richOk ? "OK" : "ERROR") << "\n"
- << "hardware_outputs=" << (hwOutOk ? "OK" : "ERROR") << "\n"
- << "flp168j_fields=" << (flp168jOk ? "OK" : "ERROR") << "\n"
- << "pattern_blocks=" << (blocksOk ? "OK" : "ERROR") << "\n"
- << "channel_polyphony=" << (polyOk ? "OK" : "ERROR") << "\n"
- << "track_latency=" << (latencyOk ? "OK" : "ERROR") << "\n"
- << "plugin_substitutes=" << (substituteOk ? "OK" : "ERROR") << "\n"
- << "patcher=" << (patcherOk ? "OK" : "ERROR") << "\n"
- << "native_engines=" << nativesResult << " (" << nativesMade << " made)\n"
- << "undo=" << (undoOk ? "OK" : "ERROR") << "\n"
- << "recording=" << (recordOk && recordUndoOk ? "OK" : "ERROR") << "\n"
- << "midi=" << (midiOk ? "OK" : "ERROR") << "\n"
- << "package=" << (packageOk ? "OK" : "ERROR") << "\n"
- << "online_session=" << sessionResult << "\n"
- << "live_session=" << liveResult << "\n"
- << "wavpack=" << wavpack << "\n"
- << "effects=" << (effectsOk ? "OK" : "NONFINITE") << "\n"
- << "effect_params_saved=" << effectParamsResult << "\n"
- << "driver_panel=" << driverPanel << "\n"
- << "plugin_art=" << artResult << "\n"
- << "plugin_sidechain=" << sidechainResult << "\n"
- << "lanes_saved=" << lanesResult << "\n"
- << "metronome=" << metronomeResult << " (FL sounds " << metronomeFlSounds << "/" << lynx::metronome::soundCount
- << ", downbeat peak " << juce::String (metronomeMaster, 4) << ")\n"
- << "result=" << (ok ? "OK" : "FAILED") << "\n";
- if (reportPath.isNotEmpty())
- juce::File (reportPath).replaceWithText (report);
- setApplicationReturnValue (ok ? 0 : 1);
- quit();
- }
- // Every built-in effect in its native editor: random / extreme parameters, mouse drags over the editor, the editor
- // painted, audio rendered at 44.1 / 48 / 96 kHz. Returns false when an effect output NaN / inf (muted by the
- // renderer's guard). The report lists each effect. Used by --fxfuzz and (a short run) by --selftest.
- bool runEffectFuzz (int rounds, const juce::String& reportPath, bool drags = false)
- {
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- lynx::setNativeEditorDemo (true);
- juce::String report;
- auto allFinite = true;
- {
- lynx::AudioEngine offline (false);
- juce::Random random (111);
- const auto value = [&] { const auto r = random.nextInt (6); return r == 0 ? 0.0f : r == 1 ? 1.0f : random.nextFloat(); };
- for (int k = 0; k <= (int) lynx::lastEffectKind; ++k)
- {
- const auto kind = (lynx::EffectKind) k;
- if (! lynx::NativeEffectWindows::canOpen (kind) || kind == lynx::EffectKind::patcher) // (the Patcher's editor is a graph window)
- continue;
- const auto before = lynx::RackRenderer::nonFiniteEffectBlocks();
- const auto& info = lynx::effectInfo (kind);
- // (FL engines: a fresh instance as the menus make it, from the user's FL installation; round 142)
- auto fx = lynx::natives::newEffect (kind, lynx::flStudioAccess()).value_or (lynx::makeEffectSlot (kind));
- int dragged = 0; // parameter changes made by the mouse drags
- for (int round = 0; round < rounds; ++round)
- {
- if (round > 0)
- for (std::size_t p = 0; p < info.params.size(); ++p)
- fx.params[p] = round == 1 ? 0.0f : round == 2 ? 1.0f : value();
- auto song = lynx::Song::makeDefault(); // its demo beat feeds the effect
- song.mixer.resize (2);
- song.mixer[0].name = "Master";
- song.mixer[1].name = "Insert 1";
- song.mixer[1].effects.assign (1, fx);
- for (auto& channel : song.channels)
- channel.mixerTrack = 1;
- offline.setSong (std::move (song));
- offline.dispatchPendingMessages();
- const auto pages = juce::jmax (1, (int) lynx::plugui::layoutFor (kind).pages.size());
- for (int page = 0; page < pages; ++page)
- {
- auto editor = kind == lynx::EffectKind::facetEq ? lynx::makeFacetEqEditor (offline, 1, 0, false)
- : lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, page);
- if (editor == nullptr || editor->getWidth() <= 0 || editor->getHeight() <= 0)
- continue;
- juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
- const auto paint = [&] {
- juce::Graphics g (image);
- editor->paintEntireComponent (g, false);
- };
- paint();
- // drags from a grid of points, as a user moving every control (plain left button)
- if (round >= 3 && drags)
- {
- const auto source = juce::Desktop::getInstance().getMainMouseSource();
- const auto step = juce::jmax (12, juce::jmin (editor->getWidth(), editor->getHeight()) / 8);
- for (int y = step / 2; y < editor->getHeight(); y += step)
- for (int x = step / 2; x < editor->getWidth(); x += step)
- {
- auto* target = editor->getComponentAt (x, y);
- if (target == nullptr)
- continue;
- const auto at = target->getLocalPoint (editor.get(), juce::Point<float> ((float) x, (float) y));
- const auto now = juce::Time::getCurrentTime();
- const auto event = [&] (juce::Point<float> p, juce::ModifierKeys mods) {
- return juce::MouseEvent (source, p, mods, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, target, target, now, at, now, 1, false);
- };
- const auto down = juce::ModifierKeys (juce::ModifierKeys::leftButtonModifier);
- const juce::Component::SafePointer<juce::Component> alive (target);
- target->mouseDown (event (at, down));
- const auto dy = (float) (random.nextBool() ? 400 : -400), dx = (float) (random.nextInt (401) - 200);
- if (alive != nullptr)
- target->mouseDrag (event (at + juce::Point<float> (dx * 0.5f, dy * 0.5f), down));
- if (alive != nullptr)
- target->mouseDrag (event (at + juce::Point<float> (dx, dy), down));
- if (alive != nullptr)
- target->mouseUp (event (at + juce::Point<float> (dx, dy), juce::ModifierKeys()));
- juce::PopupMenu::dismissAllActiveMenus();
- offline.dispatchPendingMessages();
- }
- paint();
- }
- }
- for (const auto rate : { 44100.0, 48000.0, 96000.0 })
- offline.renderOffline (0.05, rate);
- if (round == 0 || round >= 3) // keep what the drags set for the next round
- if (offline.getSong().mixer.size() > 1 && ! offline.getSong().mixer[1].effects.empty())
- {
- const auto& now = offline.getSong().mixer[1].effects[0];
- for (std::size_t p = 0; p < fx.params.size(); ++p)
- dragged += now.params[p] != fx.params[p] ? 1 : 0;
- dragged += now.state != fx.state ? 1 : 0;
- fx = now;
- }
- }
- const auto broken = lynx::RackRenderer::nonFiniteEffectBlocks() - before;
- allFinite = allFinite && broken == 0;
- report << info.name << ": " << (broken == 0 ? juce::String ("OK") : "non-finite output in " + juce::String ((juce::int64) broken) + " blocks")
- << " (" << dragged << " changes by mouse)\n";
- if (reportPath.isNotEmpty())
- juce::File (reportPath).replaceWithText (report + "(running)\n"); // what was reached, if it crashes
- }
- }
- lynx::setNativeEditorDemo (false);
- juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
- report << "result=" << (allFinite ? "OK" : "NONFINITE") << "\n";
- if (reportPath.isNotEmpty())
- juce::File (reportPath).replaceWithText (report);
- return allFinite;
- }
- // --opentest (round 157a): see the command line. Runs on the message loop (the editors' timers, animations and
- // native windows are real); one step per timer tick.
- void runOpenTest (const juce::String& reportPath, bool visible, std::function<void (bool)> done)
- {
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- struct OpenTest final : juce::Timer
- {
- juce::String reportPath, report;
- bool visible = false, ok = true;
- std::function<void (bool)> done;
- std::unique_ptr<lynx::AudioEngine> engine;
- std::vector<std::pair<juce::String, std::function<void()>>> steps;
- std::size_t next = 0;
- std::atomic<std::int64_t> lastStep { 0 };
- std::atomic<bool> finished { false };
- std::thread watchdog;
- juce::String current;
- std::mutex currentLock;
- int opened = 0, painted = 0;
- // LYNX_OPENTEST_TIMEOUT (seconds): longer for sanitizer builds
- const std::int64_t timeoutMs = 1000 * juce::jmax (5, juce::SystemStats::getEnvironmentVariable ("LYNX_OPENTEST_TIMEOUT", "20").getIntValue());
- static std::int64_t now() { return (std::int64_t) juce::Time::getMillisecondCounter(); }
- void write (const juce::String& tail = {}) { juce::File (reportPath).replaceWithText (report + tail); }
- ~OpenTest() override
- {
- finished = true;
- if (watchdog.joinable())
- watchdog.join();
- }
- void start()
- {
- lastStep = now();
- // the UI hang watch runs during the whole test (5 s): a slow step leaves its stack next to the report
- const auto folder = juce::File (reportPath).getParentDirectory().getChildFile ("opentest-hang");
- folder.deleteRecursively();
- folder.createDirectory();
- lynx::crashguard::startHangWatch (folder.getFullPathName().replaceCharacter ('\\', '/').toStdString(), 5000);
- watchdog = std::thread ([this] {
- while (! finished)
- {
- std::this_thread::sleep_for (std::chrono::milliseconds (200));
- if (now() - lastStep.load() > timeoutMs)
- {
- juce::String at;
- {
- const std::lock_guard<std::mutex> l (currentLock);
- at = current;
- }
- juce::File (reportPath).replaceWithText (report + "HANG at " + at + " (no progress for " + juce::String (timeoutMs / 1000) + " s; stack in opentest-hang)\nresult=HANG\n");
- lynx::crashguard::exitNow (3);
- }
- }
- });
- startTimer (30);
- }
- // every LYNX window but none of the main one (there is none here): moved off-screen, painted once into an image
- void touchWindows (bool resize, bool large)
- {
- auto& desktop = juce::Desktop::getInstance();
- for (int i = desktop.getNumComponents(); --i >= 0;)
- if (auto* c = desktop.getComponent (i); c != nullptr && c->isVisible())
- {
- if (! visible && c->getScreenX() > -3000)
- c->setTopLeftPosition (-6000, -6000);
- if (resize)
- if (auto* w = dynamic_cast<juce::ResizableWindow*> (c))
- {
- const auto b = w->getBounds();
- w->setSize (large ? b.getWidth() * 2 : juce::jmax (40, b.getWidth() / 3), large ? b.getHeight() * 2 : juce::jmax (40, b.getHeight() / 3));
- }
- if (c->getWidth() > 0 && c->getHeight() > 0 && c->getWidth() < 8000 && c->getHeight() < 8000)
- {
- juce::Image image (juce::Image::ARGB, c->getWidth(), c->getHeight(), true);
- juce::Graphics g (image);
- c->paintEntireComponent (g, false);
- ++painted;
- // LYNX_OPENTEST_SHOTS=folder: each window as first painted (before the resizes), for a look
- if (const auto shots = juce::SystemStats::getEnvironmentVariable ("LYNX_OPENTEST_SHOTS", {}); shots.isNotEmpty() && ! resize)
- {
- juce::FileOutputStream out (juce::File (shots).getChildFile (juce::String (painted).paddedLeft ('0', 4) + ".png"));
- if (out.openedOk())
- {
- out.setPosition (0), out.truncate();
- juce::PNGImageFormat().writeImageToStream (c->createComponentSnapshot (c->getLocalBounds()), out);
- }
- }
- }
- }
- }
- void timerCallback() override
- {
- if (next >= steps.size())
- {
- stopTimer();
- lynx::NativeEffectWindows::closeAll();
- lynx::closeChannelSettings();
- // the UI hang watch itself: the message thread spins past the stall time; the watcher must write the stack
- {
- const auto before = lynx::crashguard::lastHangFile();
- for (const auto until = now() + 7000; now() < until;)
- lastStep = now(); // (busy: no heartbeat; the test's own watchdog stays quiet)
- for (const auto until = now() + 1500; now() < until && lynx::crashguard::lastHangFile() == before;)
- std::this_thread::sleep_for (std::chrono::milliseconds (20));
- lynx::crashguard::stopHangWatch();
- const juce::File hang (juce::String::fromUTF8 (lynx::crashguard::lastHangFile().c_str()));
- const auto text = hang.loadFileAsString();
- const auto frames = juce::StringArray::fromLines (text).size() - 2;
- #if JUCE_WINDOWS
- const auto hangOk = lynx::crashguard::lastHangFile() != before && hang.existsAsFile() && text.contains ("LYNX.exe+0x") && frames >= 3;
- #else
- const auto hangOk = lynx::crashguard::lastHangFile() != before && hang.existsAsFile() && frames >= 3;
- #endif
- report << "hang watch: " << (hangOk ? "OK" : "FAIL") << " (" << hang.getFileName() << ", " << frames << " lines"
- << (before.empty() ? juce::String() : "; a step stalled > 5 s earlier: " + juce::String::fromUTF8 (before.c_str())) << ")\n";
- ok = ok && hangOk;
- }
- report << "windows opened: " << opened << ", paints: " << painted << "\nresult=" << (ok ? "OK" : "FAIL") << "\n";
- write();
- finished = true;
- if (done)
- done (ok);
- return;
- }
- auto& [label, fn] = steps[next++];
- {
- const std::lock_guard<std::mutex> l (currentLock);
- current = label;
- }
- fn();
- lastStep = now();
- lynx::crashguard::heartbeat();
- }
- };
- auto* test = new OpenTest();
- test->reportPath = reportPath;
- test->visible = visible;
- test->engine = std::make_unique<lynx::AudioEngine> (false);
- test->done = [test, done] (bool ok) {
- juce::MessageManager::callAsync ([test, done, ok] {
- delete test;
- juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
- done (ok);
- });
- };
- auto& engine = *test->engine;
- lynx::setNativeEditorDemo (true); // live displays animate without an audio device
- const auto songWith = [] (const lynx::EffectSlot& fx) {
- auto song = lynx::Song::makeDefault();
- song.mixer.resize (2);
- song.mixer[0].name = "Master";
- song.mixer[1].name = "Insert 1";
- song.mixer[1].effects.assign (1, fx);
- for (auto& channel : song.channels)
- channel.mixerTrack = 1;
- return song;
- };
- // an older project's slot: its parameter list cut to `count` and read back by the project reader (the
- // parameters a newer LYNX added after them take their defaults)
- const auto oldState = [songWith] (const lynx::EffectSlot& fx, std::size_t count) -> std::optional<lynx::Song> {
- auto json = juce::JSON::parse (lynx::ProjectFile::toJson (songWith (fx)));
- if (auto* mixer = json["mixer"].getArray(); mixer != nullptr && mixer->size() > 1)
- if (auto* effects = (*mixer)[1]["effects"].getArray(); effects != nullptr && ! effects->isEmpty())
- if (auto* params = (*effects)[0]["params"].getArray())
- params->removeRange ((int) count, params->size());
- juce::String error;
- return lynx::ProjectFile::fromJson (juce::JSON::toString (json), error);
- };
- auto& steps = test->steps;
- juce::Random random (157);
- for (int k = 0; k <= (int) lynx::lastEffectKind; ++k)
- {
- const auto kind = (lynx::EffectKind) k;
- if (! lynx::NativeEffectWindows::canOpen (kind) || kind == lynx::EffectKind::patcher)
- continue;
- const auto& info = lynx::effectInfo (kind);
- const auto base = lynx::natives::newEffect (kind, lynx::flStudioAccess()).value_or (lynx::makeEffectSlot (kind));
- const auto n = info.params.size();
- std::vector<std::pair<juce::String, std::function<std::optional<lynx::Song>()>>> variants;
- variants.push_back ({ "default", [=] { return std::optional<lynx::Song> (songWith (base)); } });
- for (const auto value : { 0.0f, 1.0f })
- variants.push_back ({ value == 0.0f ? "all 0" : "all 1", [=] {
- auto fx = base;
- for (std::size_t p = 0; p < n; ++p) fx.params[p] = value;
- return std::optional<lynx::Song> (songWith (fx));
- } });
- const auto seed = random.nextInt64();
- variants.push_back ({ "random", [=] {
- juce::Random r (seed);
- auto fx = base;
- for (std::size_t p = 0; p < n; ++p) fx.params[p] = r.nextFloat();
- return std::optional<lynx::Song> (songWith (fx));
- } });
- std::vector<std::size_t> cuts { n / 2 };
- 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)
- if (c < n) cuts.push_back (c);
- for (const auto c : cuts)
- variants.push_back ({ "old project (" + juce::String ((int) c) + " of " + juce::String ((int) n) + " params)", [=] { return oldState (base, c); } });
- for (const auto& [variant, makeSong] : variants)
- {
- const auto label = juce::String::fromUTF8 (info.name) + " / " + variant;
- steps.push_back ({ label + ": open", [test, &engine, label, makeSong = makeSong] {
- auto song = makeSong();
- if (! song)
- {
- test->report << "FAIL " << label << ": project reader refused the state\n";
- test->ok = false;
- return;
- }
- engine.setSong (std::move (*song));
- engine.dispatchPendingMessages();
- lynx::NativeEffectWindows::open (engine, 1, 0);
- ++test->opened;
- test->touchWindows (false, false);
- } });
- steps.push_back ({ label + ": run", [test, &engine] {
- for (const auto rate : { 44100.0, 48000.0, 96000.0 })
- engine.renderOffline (0.03, rate);
- test->touchWindows (false, false);
- } });
- steps.push_back ({ label + ": small", [test] { test->touchWindows (true, false); } });
- steps.push_back ({ label + ": large", [test] { test->touchWindows (true, true); } });
- steps.push_back ({ label + ": close", [test, label] {
- lynx::NativeEffectWindows::closeAll();
- test->report << label << ": OK\n";
- test->write ("(running)\n");
- } });
- }
- }
- // instruments: the channel window the Channel rack opens (Patcher: its graph window, not here)
- for (int k = 0; k <= (int) lynx::InstrumentKind::soundfont; ++k)
- {
- const auto kind = (lynx::InstrumentKind) k;
- if (kind == lynx::InstrumentKind::plugin || kind == lynx::InstrumentKind::patcher)
- continue;
- for (const auto* variant : { "default", "old project (saved and read back)", "odd settings" })
- {
- if (juce::String (variant) == "odd settings" && kind != lynx::InstrumentKind::soundfont)
- continue;
- const auto label = "instrument " + juce::String (k) + " / " + variant;
- steps.push_back ({ label + ": open", [test, &engine, kind, label, variant = juce::String (variant), old = juce::String (variant) != "default"] {
- auto song = lynx::Song::makeDefault();
- auto channel = lynx::natives::makeChannel (kind, lynx::flStudioAccess());
- lynx::ChannelDef def;
- def.instrument = kind;
- def.name = "Test";
- song.channels.push_back (channel ? *channel : def);
- if (kind == lynx::InstrumentKind::soundfont && variant != "default")
- {
- // a real font when FL's is there; NaN / huge / truncated settings
- const auto& roots = lynx::flStudioAccess().roots;
- if (! roots.data.empty())
- song.channels.back().samplePath = (juce::File (juce::String::fromUTF8 (roots.data.c_str()))
- .getChildFile ("Patches/Soundfonts/STR_Ensemble.sf2"))
- .getFullPathName().toStdString();
- if (variant == "odd settings")
- song.channels.back().modelParams = { NAN, 1.0e9f, -1.0e9f, 0.5f, 7.0f };
- }
- if (old)
- {
- juce::String error;
- if (auto again = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error))
- song = std::move (*again);
- }
- const auto index = (int) song.channels.size() - 1;
- engine.setSong (std::move (song));
- engine.dispatchPendingMessages();
- lynx::openChannelSettings (engine, index);
- ++test->opened;
- test->touchWindows (false, false);
- } });
- steps.push_back ({ label + ": run", [test, &engine] {
- engine.renderOffline (0.03, 48000.0);
- test->touchWindows (false, false);
- } });
- steps.push_back ({ label + ": small", [test] { test->touchWindows (true, false); } });
- steps.push_back ({ label + ": large", [test] { test->touchWindows (true, true); } });
- steps.push_back ({ label + ": close", [test, label] {
- lynx::closeChannelSettings();
- test->report << label << ": OK\n";
- test->write ("(running)\n");
- } });
- }
- }
- test->start();
- }
- void runPlugWinTest (const juce::String& pluginPath, const juce::String& reportPath, const juce::String& only, int seconds)
- {
- struct Test final : juce::Timer
- {
- juce::String reportPath, report;
- std::unique_ptr<lynx::AudioEngine> engine;
- bool instrument = false;
- int phase = 0, ticks = 0, seconds = 15;
- juce::AudioPluginInstance* instance = nullptr;
- juce::AudioProcessorParameter* checked = nullptr;
- std::unique_ptr<juce::DocumentWindow> mainWindow; // stands for LYNX's main window (window ownership)
- std::function<void (bool)> done;
- void step (const juce::String& line)
- {
- report << line << "\n";
- juce::File (reportPath).replaceWithText (report);
- }
- juce::AudioPluginInstance* find()
- {
- if (instrument)
- {
- if (auto* p = dynamic_cast<lynx::PluginInstrument*> (engine->getChannelInstrument (0).get()))
- return &p->getInstance();
- }
- else if (auto* p = dynamic_cast<lynx::PluginEffect*> (engine->getEffect (1, 0).get()))
- return &p->getInstance();
- return nullptr;
- }
- void timerCallback() override
- {
- ++ticks;
- if (phase == 0) // waiting for the engine to host the plugin
- {
- instance = find();
- if (instance == nullptr)
- {
- if (ticks > 200)
- {
- step ("result=FAILED (not hosted)");
- stopTimer();
- done (false);
- }
- return;
- }
- step ("hosted=" + instance->getName() + " format=" + instance->getPluginDescription().pluginFormatName);
- step ("programs=" + juce::String (instance->getNumPrograms()));
- for (int p = 0; p < juce::jmin (5, instance->getNumPrograms()); ++p)
- step ("program" + juce::String (p) + "=" + instance->getProgramName (p));
- step ("save_formats=" + lynx::pluginpresetui::saveWildcard (*instance));
- // preset round trip: save, change the first parameter, load, compare
- juce::AudioProcessorParameter* param = nullptr;
- for (auto* candidate : instance->getParameters())
- if (candidate->isAutomatable() && ! candidate->isMetaParameter() && candidate != instance->getBypassParameter())
- {
- param = candidate;
- break;
- }
- if (param != nullptr)
- {
- step ("param=" + param->getName (64));
- checked = param;
- const auto file = lynx::pluginpresetui::folderFor (instance->getName()).getChildFile ("plugwintest.lynxpreset");
- juce::String error;
- const auto before = param->getValue();
- const auto saved = lynx::pluginpresetui::save (*instance, file, "plugwintest", error);
- param->setValueNotifyingHost (before > 0.5f ? 0.1f : 0.9f);
- const auto changed = param->getValue();
- const auto loaded = saved && lynx::pluginpresetui::load (*instance, file, error);
- step ("preset_roundtrip saved=" + juce::String ((int) saved) + " loaded=" + juce::String ((int) loaded) + " param0 before="
- + juce::String (before, 4) + " changed=" + juce::String (changed, 4) + " after=" + juce::String (param->getValue(), 4)
- + (error.isNotEmpty() ? " error=" + error : juce::String()));
- for (const auto* ext : { "fxp", "fxb", "vstpreset" })
- {
- juce::String e2;
- const auto f2 = file.withFileExtension (ext);
- const auto ok2 = lynx::pluginpresetui::save (*instance, f2, "plugwintest", e2) && lynx::pluginpresetui::load (*instance, f2, e2);
- step (juce::String ("preset_") + ext + "=" + juce::String ((int) ok2) + (e2.isNotEmpty() ? " (" + e2 + ")" : juce::String()));
- f2.deleteFile();
- }
- step ("browser_lists=" + juce::String (lynx::pluginpresetui::userPresets (instance->getName()).size()));
- }
- std::shared_ptr<void> owner = instrument ? std::shared_ptr<void> (engine->getChannelInstrument (0))
- : std::shared_ptr<void> (engine->getEffect (1, 0));
- lynx::PluginWindows::open (owner, *instance, instance->getName(),
- { engine.get(), [this] (lynx::Song& song) -> lynx::PluginRef* {
- if (instrument)
- return song.channels.empty() ? nullptr : &song.channels[0].plugin;
- return song.mixer.size() < 2 || song.mixer[1].effects.empty() ? nullptr : &song.mixer[1].effects[0].plugin;
- }, instrument });
- owner.reset();
- step ("window_open=" + juce::String ((int) lynx::PluginWindows::isOpen (*instance)));
- phase = 1;
- ticks = 0;
- return;
- }
- if (phase == 1 && ticks == 20 && checked != nullptr)
- step ("param_after_1s=" + juce::String (checked->getValue(), 4));
- if (phase == 1 && ticks >= seconds * 20) // remove the plugin from the song
- {
- engine->editSong ([this] (lynx::Song& song) {
- if (instrument)
- song.channels.clear();
- else
- song.mixer[1].effects.clear();
- });
- step ("removed");
- phase = 2;
- ticks = 0;
- return;
- }
- if (phase == 2 && ticks >= 40)
- {
- const auto open = lynx::PluginWindows::isOpen (*instance);
- step ("window_open_after_remove=" + juce::String ((int) open));
- step (open ? "result=FAILED" : "result=OK");
- stopTimer();
- lynx::PluginWindows::closeAll();
- done (! open);
- }
- }
- };
- auto* test = new Test();
- test->reportPath = reportPath;
- test->seconds = seconds;
- test->done = [this, test] (bool ok) {
- setApplicationReturnValue (ok ? 0 : 1);
- juce::MessageManager::callAsync ([this, test] {
- lynx::setMainWindowForOwnership (nullptr);
- test->mainWindow = nullptr;
- test->engine = nullptr;
- delete test;
- quit();
- });
- };
- test->engine = std::make_unique<lynx::AudioEngine> (false);
- test->mainWindow = std::make_unique<juce::DocumentWindow> ("LYNX test main window", juce::Colours::darkgrey, 0);
- test->mainWindow->setBounds (20, 20, 300, 200);
- test->mainWindow->setVisible (true);
- lynx::setMainWindowForOwnership (test->mainWindow.get());
- auto& host = test->engine->getPluginHost();
- test->step ("plugins_in_file=" + juce::String (host.addPluginFile (juce::File (pluginPath))));
- std::optional<juce::PluginDescription> chosen;
- for (const auto& type : host.getKnownPlugins().getTypes())
- if ((juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginPath).getFileName() || type.fileOrIdentifier == pluginPath)
- && (only.isEmpty() || type.name == only))
- {
- chosen = type;
- break;
- }
- if (! chosen)
- {
- test->step ("result=FAILED (no plugin)");
- test->done (false);
- return;
- }
- test->instrument = chosen->isInstrument;
- lynx::PluginRef ref;
- ref.id = chosen->createIdentifierString().toStdString();
- ref.name = chosen->name.toStdString();
- test->engine->editSong ([&] (lynx::Song& song) {
- if (test->instrument)
- {
- lynx::ChannelDef c;
- c.name = ref.name;
- c.instrument = lynx::InstrumentKind::plugin;
- c.plugin = ref;
- song.channels.push_back (c);
- }
- else
- {
- while (song.mixer.size() < 2)
- song.mixer.emplace_back();
- lynx::EffectSlot slot;
- slot.kind = lynx::EffectKind::plugin;
- slot.plugin = ref;
- song.mixer[1].effects.push_back (slot);
- }
- });
- test->step ("plugin=" + chosen->name + " instrument=" + juce::String ((int) test->instrument));
- test->startTimerHz (20);
- }
- void runEditorCrashTest (const juce::String& pluginPath, const juce::String& reportPath)
- {
- struct CrashTest final : juce::Timer
- {
- juce::String reportPath, report;
- std::unique_ptr<lynx::PluginHost> host;
- juce::AudioPluginInstance* plugin = nullptr;
- std::shared_ptr<juce::AudioPluginInstance> keep; // a window whose plugin nobody else holds is closed as orphaned
- std::function<void (bool)> done;
- int ticks = 0, crashesBefore = 0;
- void step (const juce::String& line)
- {
- report << line << "\n";
- juce::File (reportPath).replaceWithText (report); // at each step: a crash leaves the last one
- }
- void timerCallback() override
- {
- ++ticks;
- const auto crashes = lynx::PluginWindows::editorCrashCount() - crashesBefore;
- const auto open = lynx::PluginWindows::isOpen (*plugin);
- if ((crashes > 0 && ! open) || ticks >= 50) // 100 ms ticks: up to 5 s
- {
- stopTimer();
- step ("editor_crashes=" + juce::String (crashes) + " window_open=" + juce::String ((int) open) + " ticks=" + juce::String (ticks));
- bool traced = false;
- if (crashes > 0)
- {
- const auto last = lynx::PluginWindows::editorCrashes().back();
- traced = last.traceFile.existsAsFile() && last.traceFile.loadFileAsString().contains ("LYNX Test Crash");
- step ("plugin=" + last.plugin + " detail=" + last.detail + " trace=" + last.traceFile.getFileName() + " traced="
- + juce::String ((int) traced));
- last.traceFile.deleteFile();
- }
- // still alive: one more message through the loop after the fault
- juce::MessageManager::callAsync ([this, ok = crashes == 1 && ! open && traced] {
- step ("message_loop_after_fault=1");
- step (juce::String ("result=") + (ok ? "OK" : "FAILED"));
- done (ok);
- });
- }
- }
- };
- auto* test = new CrashTest();
- test->reportPath = reportPath;
- test->done = [this, test] (bool ok)
- {
- setApplicationReturnValue (ok ? 0 : 1);
- juce::MessageManager::callAsync ([this, test] { lynx::PluginWindows::closeAll(); delete test; quit(); });
- };
- #if ! JUCE_WINDOWS
- test->step ("result=SKIPPED (Windows only: on macOS / Linux a plugin fault is a signal, see docs/analise/REA_rodada174a.md)");
- test->done (true);
- return;
- #else
- _putenv_s ("LYNX_TEST_CRASH", "editor");
- test->host = std::make_unique<lynx::PluginHost> (false);
- test->step ("plugins_in_file=" + juce::String (test->host->addPluginFile (juce::File (pluginPath))));
- std::shared_ptr<juce::AudioPluginInstance> instance;
- for (const auto& type : test->host->getKnownPlugins().getTypes())
- {
- if (juce::File (type.fileOrIdentifier).getFileName() != juce::File (pluginPath).getFileName())
- continue;
- juce::String error;
- instance = std::shared_ptr<juce::AudioPluginInstance> (lynx::createRightInstance (test->host->getFormats(), type, 48000.0, 512, error).release());
- test->step ("plugin=" + type.name + (instance == nullptr ? " error=" + error : juce::String()));
- break;
- }
- if (instance == nullptr || ! instance->hasEditor())
- {
- test->step ("result=FAILED (no plugin with an editor)");
- test->done (false);
- return;
- }
- lynx::preparePlugin (*instance, 48000.0, 512);
- test->plugin = instance.get();
- test->keep = instance;
- test->crashesBefore = lynx::PluginWindows::editorCrashCount();
- lynx::PluginWindows::open (instance, *instance, instance->getName()); // (the window keeps the plugin alive)
- test->step ("window_open=" + juce::String ((int) lynx::PluginWindows::isOpen (*instance)));
- test->startTimer (100);
- #endif
- }
- void runEditorTest (const juce::String& pluginPath, const juce::String& reportPath, const juce::String& only)
- {
- struct EditorTest final : juce::Timer
- {
- juce::String reportPath, report;
- std::unique_ptr<lynx::PluginHost> host;
- std::unique_ptr<juce::AudioPluginInstance> plugin;
- std::unique_ptr<juce::DocumentWindow> window;
- std::function<void (bool)> done;
- void step (const juce::String& line)
- {
- report << line << "\n";
- juce::File (reportPath).replaceWithText (report); // written at each step: a crash leaves the last one
- }
- void timerCallback() override
- {
- stopTimer();
- window = nullptr;
- step ("step=closed");
- plugin = nullptr;
- step ("result=OK");
- done (true);
- }
- };
- auto* test = new EditorTest();
- test->reportPath = reportPath;
- test->done = [this, test] (bool ok)
- {
- setApplicationReturnValue (ok ? 0 : 1);
- juce::MessageManager::callAsync ([this, test] { delete test; quit(); });
- };
- test->host = std::make_unique<lynx::PluginHost> (false);
- test->step ("plugins_in_file=" + juce::String (test->host->addPluginFile (juce::File (pluginPath))));
- test->step ("exe=" + juce::File::getSpecialLocation (juce::File::currentExecutableFile).getFullPathName());
- for (const auto& type : test->host->getKnownPlugins().getTypes())
- {
- if (juce::File (type.fileOrIdentifier).getFileName() != juce::File (pluginPath).getFileName()
- || (only.isNotEmpty() && type.name != only))
- continue;
- juce::String error;
- test->plugin = lynx::createRightInstance (test->host->getFormats(), type, 48000.0, 512, error);
- test->step ("plugin=" + type.name + (test->plugin == nullptr ? " error=" + error : juce::String()));
- break;
- }
- if (test->plugin == nullptr)
- {
- test->step ("result=FAILED");
- test->done (false);
- return;
- }
- lynx::preparePlugin (*test->plugin, 48000.0, 512);
- test->step ("step=create_editor");
- test->window = std::make_unique<juce::DocumentWindow> (test->plugin->getName(), juce::Colours::black, juce::DocumentWindow::closeButton);
- test->window->setUsingNativeTitleBar (true);
- if (auto* editor = test->plugin->createEditorIfNeeded())
- test->window->setContentOwned (editor, true);
- else
- test->step ("no_editor");
- test->step ("step=show");
- test->window->centreWithSize (test->window->getWidth(), test->window->getHeight());
- test->window->setVisible (true);
- test->step ("step=shown");
- test->startTimer (4000);
- }
- void runFitTest (const juce::String& reportPath, int percent)
- {
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- struct FitTest final : juce::Timer
- {
- juce::String path, report;
- bool ok = true;
- int step = 0, percent = 150;
- std::unique_ptr<juce::DocumentWindow> tall, big;
- std::function<void()> done;
- // `whole`: the window must fit entirely (a resizable one); else its title bar and close button must be on the screen
- void check (const juce::String& what, juce::Component& w, bool whole)
- {
- juce::BorderSize<int> frame;
- if (auto* peer = w.getPeer())
- if (const auto f = peer->getFrameSizeIfPresent())
- frame = *f;
- auto outer = frame.addedTo (w.getBounds());
- const auto* display = juce::Desktop::getInstance().getDisplays().getDisplayForRect (outer);
- const auto area = display != nullptr ? display->userArea : outer;
- #if JUCE_LINUX
- // round 164: a compositor that draws the frame itself (WSLg's Weston) reports its invisible shadow in
- // the frame (59 px on top, 38 around at 100%): only what is visible is checked, give or take 4 px
- const auto shadow = frame.getLeft() >= 16 ? frame.getLeft() : 0;
- outer = outer.reduced (shadow);
- const auto slack = shadow > 0 ? 4 : 0;
- #else
- const auto slack = 0;
- #endif
- const auto passed = outer.getY() >= area.getY() - slack && outer.getRight() <= area.getRight() + slack && outer.getX() >= area.getX() - slack
- && (! whole || outer.getBottom() <= area.getBottom() + 1 + slack);
- report << (passed ? "ok " : "FAIL ") << what << " window=" << outer.toString() << " (frame " << frame.getTop() << ","
- << frame.getLeft() << ") screen=" << area.toString() << "\n";
- ok = ok && passed;
- }
- void start()
- {
- report << "scale=" << percent << "%\n";
- juce::Desktop::getInstance().setGlobalScaleFactor ((float) percent / 100.0f);
- // a tool window taller than the screen, centred (its title bar would be above the screen)
- tall = std::make_unique<juce::DocumentWindow> ("LYNX fit test - tall", lynx::theme::colour::bg2, juce::DocumentWindow::closeButton);
- tall->setUsingNativeTitleBar (true);
- auto* content = new juce::Component();
- const auto area = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea;
- content->setSize (500, area.getHeight() + 200);
- tall->setContentOwned (content, true);
- tall->setCentrePosition (area.getCentre());
- tall->setVisible (true);
- lynx::keepAboveMainWindow (*tall);
- // LYNX_FITTEST_MS: how long each window stays (default 700 ms; longer to take screenshots of them)
- startTimer (juce::jlimit (300, 60000, juce::SystemStats::getEnvironmentVariable ("LYNX_FITTEST_MS", "700").getIntValue()));
- }
- void timerCallback() override
- {
- ++step;
- if (step == 1)
- {
- check ("tall tool window: title bar and close button on the screen", *tall, false);
- tall.reset();
- // round 164: a fixed-size LYNX tool window whose content is taller than the screen: it scrolls
- auto content = std::make_unique<juce::Component>();
- const auto screen = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea;
- content->setSize (520, screen.getHeight() + 300);
- lynx::openToolWindow (std::move (content), "LYNX fit test - fixed size", "fittest-fixed");
- return;
- }
- if (step == 2)
- {
- if (auto* w = lynx::findToolWindow ("fittest-fixed"))
- {
- check ("fixed-size tool window taller than the screen: fits (its content scrolls)", *w, true);
- const auto scrolls = w->getContentComponent() != nullptr && w->getContentComponent()->getNumChildComponents() > 0
- && dynamic_cast<juce::Viewport*> (w->getContentComponent()->getChildComponent (0)) != nullptr;
- report << (scrolls ? "ok " : "FAIL ") << "its content is in a scrolling viewport\n";
- ok = ok && scrolls;
- }
- else
- {
- report << "FAIL fixed-size tool window not found\n";
- ok = false;
- }
- lynx::closeAllToolWindows();
- // a resizable window that fits at 100%, then the zoom goes up (the main window's case)
- juce::Desktop::getInstance().setGlobalScaleFactor (1.0f);
- big = std::make_unique<juce::DocumentWindow> ("LYNX fit test - zoom", lynx::theme::colour::bg2, juce::DocumentWindow::allButtons);
- big->setUsingNativeTitleBar (true);
- big->setResizable (true, false);
- big->setResizeLimits (400, 300, 10000, 10000);
- const auto area = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea;
- big->setBounds (area.getX() + 40, area.getY() + 60, area.getWidth() * 9 / 10 - 40, area.getHeight() * 9 / 10 - 60);
- big->setVisible (true);
- return;
- }
- if (step == 3)
- {
- juce::Desktop::getInstance().setGlobalScaleFactor ((float) percent / 100.0f);
- juce::Timer::callAfterDelay (200, [] { lynx::fitAllWindowsOnScreen(); });
- return;
- }
- if (step == 4)
- {
- check ("resizable window after the zoom change: fits the screen", *big, true);
- big.reset();
- report << "result=" << (ok ? "OK" : "FAILED") << "\n";
- juce::File (path).replaceWithText (report);
- stopTimer();
- if (done)
- done();
- }
- }
- };
- static std::unique_ptr<FitTest> test;
- test = std::make_unique<FitTest>();
- test->path = reportPath;
- test->percent = juce::jlimit (50, 300, percent);
- test->done = [this] { juce::MessageManager::callAsync ([this] { test.reset(); quit(); }); };
- test->start();
- }
- void runWindowTest (const juce::String& reportPath)
- {
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- struct WindowTest final : juce::Timer
- {
- juce::String reportPath, report;
- bool ok = true;
- int stepIndex = 0;
- std::unique_ptr<lynx::AudioEngine> engine;
- lynx::MainComponent* ui = nullptr;
- std::unique_ptr<juce::DocumentWindow> main, pluginLike;
- juce::TextEditor* pluginField = nullptr;
- std::unique_ptr<juce::AlertWindow> nameDialog;
- std::function<void()> done;
- void line (const juce::String& text)
- {
- report << text << "\n";
- juce::File (reportPath).replaceWithText (report);
- }
- void check (const juce::String& what, bool passed)
- {
- line ((passed ? "ok " : "FAIL ") + what);
- ok = ok && passed;
- }
- bool isAbove (juce::Component* w) { return w != nullptr && lynx::isAboveMainWindow (*w); }
- bool focusIn (juce::Component* w)
- {
- auto* f = juce::Component::getCurrentlyFocusedComponent();
- return w != nullptr && f != nullptr && (f == w || w->isParentOf (f));
- }
- void timerCallback() override
- {
- switch (stepIndex++)
- {
- case 0:
- line ("foreground=" + juce::String (juce::Process::isForegroundProcess() ? 1 : 0));
- ui->openQuickAddForTest();
- break;
- case 1:
- {
- auto* w = lynx::findToolWindow ("quickadd");
- check ("quick-add palette open", w != nullptr);
- check ("quick-add palette active", w != nullptr && w->isActiveWindow());
- check ("quick-add palette owned by the main window", w != nullptr && lynx::isOwnedByMainWindow (*w));
- check ("quick-add palette above the main window", isAbove (w));
- auto* f = juce::Component::getCurrentlyFocusedComponent();
- check ("quick-add search box has the keyboard focus", focusIn (w) && dynamic_cast<juce::TextEditor*> (f) != nullptr && f->hasKeyboardFocus (false) && w->isActiveWindow());
- lynx::closeAllToolWindows();
- lynx::openAudioEditor (*engine);
- break;
- }
- case 2:
- {
- auto* w = lynx::findToolWindow ("audioeditor");
- check ("audio editor open", w != nullptr);
- check ("audio editor active", w != nullptr && w->isActiveWindow());
- check ("audio editor owned by the main window", w != nullptr && lynx::isOwnedByMainWindow (*w));
- check ("audio editor above the main window", isAbove (w));
- lynx::forceForegroundForTest (*main); // the user clicks the main window
- break;
- }
- case 3:
- {
- auto* w = lynx::findToolWindow ("audioeditor");
- check ("audio editor stays above the main window after clicking it", isAbove (w));
- lynx::closeAllToolWindows();
- // a plugin editor's window: its own controls keep the keyboard focus
- pluginLike = std::make_unique<juce::DocumentWindow> ("Plugin", juce::Colours::black, juce::DocumentWindow::closeButton);
- pluginLike->setUsingNativeTitleBar (true);
- auto* field = new juce::TextEditor();
- field->setSize (300, 120);
- pluginLike->setContentOwned (field, true);
- pluginLike->centreWithSize (300, 120);
- pluginLike->setVisible (true);
- lynx::keepAboveMainWindow (*pluginLike);
- pluginLike->toFront (true);
- field->grabKeyboardFocus();
- pluginField = field;
- break;
- }
- case 4:
- check ("plugin window active", pluginLike->isActiveWindow());
- check ("plugin window keeps the keyboard focus", pluginField->hasKeyboardFocus (false) && pluginLike->isActiveWindow());
- check ("plugin window above the main window", isAbove (pluginLike.get()));
- pluginLike = nullptr;
- lynx::forceForegroundForTest (*main);
- juce::Component::unfocusAllComponents();
- break;
- case 5:
- check ("main window takes the keyboard focus back when it is active", ui->hasKeyboardFocus (true));
- // round 165q: a name dialog (F4's next empty pattern, Rename and color...) opens ready to type
- nameDialog = lynx::makeNameAndColourDialog ("Rename pattern", "Pattern 2", 0xff808080u);
- nameDialog->enterModalState (true, nullptr, false);
- lynx::keepAboveMainWindow (*nameDialog);
- break;
- case 6:
- {
- auto* f = juce::Component::getCurrentlyFocusedComponent();
- auto* field = dynamic_cast<juce::TextEditor*> (f);
- check ("name dialog: its text field has the keyboard focus", field != nullptr && focusIn (nameDialog.get()));
- if (field != nullptr)
- field->keyPressed (juce::KeyPress ('x', {}, 'x'));
- check ("name dialog: typing replaces the name", nameDialog->getTextEditorContents ("name") == "x");
- nameDialog->exitModalState (0);
- nameDialog = nullptr;
- line (ok ? "result=OK" : "result=FAILED");
- stopTimer();
- done();
- break;
- }
- default:
- break;
- }
- }
- };
- auto* test = new WindowTest();
- test->reportPath = reportPath;
- test->engine = std::make_unique<lynx::AudioEngine> (false);
- test->main = std::make_unique<juce::DocumentWindow> ("LYNX window test", lynx::theme::window, juce::DocumentWindow::allButtons);
- test->main->setUsingNativeTitleBar (true);
- test->ui = new lynx::MainComponent (*test->engine, false);
- test->main->setContentOwned (test->ui, true);
- test->main->setResizable (true, true);
- test->main->centreWithSize (1280, 760);
- test->main->setVisible (true);
- lynx::setMainWindowForOwnership (test->main.get());
- lynx::forceForegroundForTest (*test->main);
- test->main->toFront (true);
- test->done = [this, test] {
- setApplicationReturnValue (test->ok ? 0 : 1);
- juce::MessageManager::callAsync ([this, test] {
- lynx::closeAllToolWindows();
- lynx::setMainWindowForOwnership (nullptr);
- test->main = nullptr;
- delete test;
- quit();
- });
- };
- test->startTimer (1500);
- }
- // LYNX.exe --plugintest plugin.vst3 report.txt ["name"]: loads the plugin (or the one named in a shell), plays notes if it is an
- // instrument (and runs audio through it if it is an effect) and measures the audio.
- void runPluginTest (const juce::String& pluginPath, const juce::String& reportPath, const juce::String& only = {})
- {
- juce::String report;
- bool ok = false;
- {
- lynx::AudioEngine offline (false);
- auto& host = offline.getPluginHost();
- const auto added = host.addPluginFile (juce::File (pluginPath));
- report << "plugins_in_file=" << added << "\n";
- juce::PluginDescription instrument, effect;
- bool hasInstrument = false, hasEffect = false;
- for (const auto& type : host.getKnownPlugins().getTypes())
- {
- if (juce::File (type.fileOrIdentifier).getFileName() != juce::File (pluginPath).getFileName()
- || (only.isNotEmpty() && type.name != only))
- continue;
- report << " " << (type.isInstrument ? "instrument: " : "effect: ") << type.name << " (" << type.manufacturerName
- << ") in " << type.fileOrIdentifier << "\n";
- if (type.isInstrument && ! hasInstrument) { instrument = type; hasInstrument = true; }
- if (! type.isInstrument && ! hasEffect) { effect = type; hasEffect = true; }
- }
- auto song = lynx::Song::makeDefault();
- if (hasInstrument)
- {
- auto& c = song.channels[4]; // the "Synth" channel becomes the plugin
- c.instrument = lynx::InstrumentKind::plugin;
- c.plugin.id = instrument.createIdentifierString().toStdString();
- c.plugin.name = instrument.name.toStdString();
- c.volume = 1.0f;
- for (int i = 0; i < 4; ++i) // one chord per beat
- for (int key : { 60, 64, 67 })
- song.patterns[0].notes.push_back ({ (std::int64_t) i * lynx::ppq, lynx::ppq / 2, 4, key, 0.9f });
- song.patterns[0].sortNotes();
- }
- if (hasEffect)
- {
- lynx::EffectSlot slot;
- slot.kind = lynx::EffectKind::plugin;
- slot.plugin.id = effect.createIdentifierString().toStdString();
- slot.plugin.name = effect.name.toStdString();
- song.mixer[0].effects.push_back (slot);
- }
- const auto effectSlot = (int) song.mixer[0].effects.size() - 1; // (the default master may hold effects already)
- offline.setSong (song);
- // after a render: the rack (and its plugins) is built when the engine is prepared
- const auto peak = offline.renderOffline (3.0, 48000.0);
- const auto* loadedInstrument = dynamic_cast<lynx::PluginInstrument*> (offline.getChannelInstrument (4).get());
- const auto* loadedEffect = dynamic_cast<lynx::PluginEffect*> (offline.getEffect (0, effectSlot).get());
- report << "instrument_loaded=" << (loadedInstrument != nullptr ? "yes" : "no") << "\n"
- << "effect_loaded=" << (loadedEffect != nullptr ? "yes" : "no") << "\n";
- if (host.getLoadFailures().size() > 0) // why: the host's own message (license, missing file, load failure)
- report << "load_failures=" << host.getLoadFailures().joinIntoString (" | ") << "\n";
- report << "peak=" << peak << "\n";
- // plugins that crashed inside a call, were caught and switched off (round 111)
- report << "plugin_crashes=" << lynx::pluginCrashCount() << "\n";
- for (const auto& c : lynx::pluginCrashes())
- report << " crashed: " << c.plugin << " (" << lynx::crashguard::describe (c.code) << ")\n";
- offline.capturePluginStates();
- const auto stateSize = hasInstrument ? offline.getSong().channels[4].plugin.state.size() : (size_t) 0;
- report << "state_bytes_base64=" << (int) stateSize << "\n";
- ok = (hasInstrument || hasEffect) && (! hasInstrument || loadedInstrument != nullptr)
- && (! hasEffect || loadedEffect != nullptr) && peak > 0.001f && peak < 10.0f;
- }
- report << "result=" << (ok ? "OK" : "FAILED") << "\n";
- juce::File (reportPath).replaceWithText (report);
- setApplicationReturnValue (ok ? 0 : 1);
- quit();
- }
- // LYNX.exe --claprestarttest "LYNX Test Restart.clap" report.txt (tools/testplugin/lynx_test_restart.c, PR #29): a
- // CLAP effect on the Master that asks for a restart every 8 blocks while an export renders on a thread of its own
- // (the message thread is free to run the restarts, as with the Export window). The plugin aborts the process when
- // start / stop_processing run off the audio thread or activate / deactivate off the main thread (issue #46, as u-he
- // Presswerk does; an export at 44.1 kHz and prepare calls from the export's thread check the latter) and counts deactivations that
- // landed inside its process() call (must be none), the restarts must happen, and the delay compensation must end on
- // the latency the plugin reports after its last restart.
- void runClapRestartTest (const juce::String& pluginPath, const juce::String& reportPath)
- {
- struct Run
- {
- std::unique_ptr<lynx::AudioEngine> engine;
- juce::String report;
- int slot = -1;
- std::thread render;
- std::atomic<bool> done { false };
- double renderSeconds = 0.0;
- };
- auto run = std::make_shared<Run>();
- const auto counters = juce::File (reportPath).getSiblingFile (juce::File (reportPath).getFileNameWithoutExtension() + "-plugin.txt");
- counters.deleteFile();
- #if JUCE_WINDOWS
- _putenv_s ("LYNX_TEST_RESTART_REPORT", counters.getFullPathName().toRawUTF8());
- #else
- setenv ("LYNX_TEST_RESTART_REPORT", counters.getFullPathName().toRawUTF8(), 1);
- #endif
- const auto fail = [this, reportPath] (juce::String report) {
- report << "result=FAILED\n";
- juce::File (reportPath).replaceWithText (report);
- setApplicationReturnValue (1);
- quit();
- };
- run->engine = std::make_unique<lynx::AudioEngine> (false);
- auto& host = run->engine->getPluginHost();
- run->report << "plugins_in_file=" << host.addPluginFile (juce::File (pluginPath)) << "\n";
- std::optional<juce::PluginDescription> clap;
- for (const auto& type : host.getKnownPlugins().getTypes())
- if (type.pluginFormatName == "CLAP" && juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginPath).getFileName())
- clap = type;
- if (! clap)
- {
- fail (run->report + "no CLAP plugin in the file\n");
- return;
- }
- auto song = lynx::Song::makeDefault();
- lynx::EffectSlot slot;
- slot.kind = lynx::EffectKind::plugin;
- slot.plugin.id = clap->createIdentifierString().toStdString();
- slot.plugin.name = clap->name.toStdString();
- slot.smartDisable = false; // (processed every block, as with music playing: the export itself is silent)
- song.mixer[0].effects = { slot }; // alone on the Master: the delay compensation is the plugin's latency
- run->slot = (int) song.mixer[0].effects.size() - 1;
- run->engine->setSong (song);
- run->engine->renderOffline (0.1, 48000.0); // builds the rack (and the plugin) on the message thread
- if (dynamic_cast<lynx::PluginEffect*> (run->engine->getEffect (0, run->slot).get()) == nullptr)
- {
- fail (run->report + "effect_loaded=no\n");
- return;
- }
- auto effect = std::dynamic_pointer_cast<lynx::PluginEffect> (run->engine->getEffect (0, run->slot));
- run->render = std::thread ([run, effect] {
- const auto start = juce::Time::getMillisecondCounterHiRes();
- run->engine->renderOffline (30.0, 48000.0);
- run->renderSeconds = (juce::Time::getMillisecondCounterHiRes() - start) * 0.001;
- // issue #46: an export at another rate / block size prepares the plugin from the export's thread; the
- // plugin aborts unless activate / deactivate reach the main thread
- auto& instance = effect->getInstance();
- instance.prepareToPlay (44100.0, 1024);
- instance.releaseResources();
- instance.prepareToPlay (48000.0, 512);
- run->engine->renderOffline (3.0, 44100.0); // (the engine rebuilds its rack at that rate)
- run->done = true;
- });
- // after the render: a second for the restarts still queued and the engine's timer (the new PDC plan)
- auto finish = std::make_shared<std::function<void()>>();
- *finish = [this, run, counters, reportPath, fail, finish] {
- if (! run->done)
- {
- juce::Timer::callAfterDelay (50, *finish);
- return;
- }
- run->render.join();
- juce::Timer::callAfterDelay (1000, [this, run, counters, reportPath, fail] {
- auto report = run->report;
- int pluginLatency = -1;
- if (const auto effect = run->engine->getEffect (0, run->slot)) // (not held past the engine's reset)
- pluginLatency = effect->latencySamples();
- const auto pdc = run->engine->getLatencySamples();
- report << "render_seconds=" << juce::String (run->renderSeconds, 2) << "\n"
- << "plugin_latency=" << pluginLatency << "\npdc_total=" << pdc << "\n"
- << "plugin_crashes=" << lynx::pluginCrashCount() << "\n";
- run->engine.reset(); // destroys the plugin: it writes its counters
- // one line per plugin instance (the engine may have made more than one): none may have been
- // deactivated inside process(), and the one that rendered must have restarted
- int overlapped = 0, inactive = 0, requests = 0, activations = 0, lines = 0, wrongThread = 0, misordered = 0, unstopped = 0;
- bool otherRate = false;
- for (const auto& line : juce::StringArray::fromLines (counters.loadFileAsString()))
- {
- juce::StringPairArray values;
- for (const auto& token : juce::StringArray::fromTokens (line, " ", ""))
- if (token.contains ("="))
- values.set (token.upToFirstOccurrenceOf ("=", false, false), token.fromFirstOccurrenceOf ("=", false, false));
- if (values.size() == 0)
- continue;
- ++lines;
- report << "instance: " << line << "\n";
- overlapped += values["overlapped"].getIntValue();
- inactive += values["inactive_blocks"].getIntValue();
- // issue #46: activate / deactivate on the main thread, start / stop_processing on the audio thread
- // (the plugin aborts the process otherwise, as u-he's do), in order, every start stopped
- wrongThread += values["wrong_thread"].getIntValue();
- misordered += values["misordered"].getIntValue();
- unstopped += values["starts"].getIntValue() - values["stops"].getIntValue();
- otherRate = otherRate || values["last_rate"].getIntValue() == 44100;
- if (values["requests"].getIntValue() > requests)
- {
- requests = values["requests"].getIntValue();
- activations = values["activations"].getIntValue();
- }
- }
- report << "wrong_thread=" << wrongThread << "\nmisordered=" << misordered << "\nunstopped=" << unstopped
- << "\nactivated_at_44100=" << (otherRate ? "yes" : "no") << "\n";
- const auto ok = lines > 0 && requests > 0 && activations > requests / 2 && overlapped == 0 && inactive == 0
- && wrongThread == 0 && misordered == 0 && unstopped == 0 && otherRate
- && pluginLatency > 0 && pdc == pluginLatency && lynx::pluginCrashCount() == 0;
- if (! ok)
- {
- fail (report);
- return;
- }
- report << "result=OK\n";
- juce::File (reportPath).replaceWithText (report);
- setApplicationReturnValue (0);
- quit();
- });
- };
- juce::Timer::callAfterDelay (50, *finish);
- }
- // LYNX.exe --vst2test "LYNX Test Synth.dll" report.txt (tools/testplugin/lynx_test_vst2.c): LYNX's own VST2 host.
- // Scans the DLL, imports it the way an .flp holds it (Fruity Wrapper VST2 state with a chunk, REA_rodada89 §2),
- // renders with two saved gains (the level must follow the restored state) and checks the plugin saw the song tempo.
- void runVst2Test (const juce::String& pluginPath, const juce::String& reportPath)
- {
- juce::String report;
- bool ok = false;
- {
- lynx::AudioEngine offline (false);
- auto& host = offline.getPluginHost();
- report << "plugins_in_file=" << host.addPluginFile (juce::File (pluginPath)) << "\n";
- std::optional<juce::PluginDescription> vst2;
- for (const auto& type : host.getKnownPlugins().getTypes())
- if (type.pluginFormatName == "VST")
- vst2 = type;
- auto render = [&] (float gain, float& tempoSeen, int& adopted) {
- lynx::FlVst2State state;
- state.flags = 8;
- state.chunk = { 'L', 'X', 'V', '2', 0, 0, 0, 0 };
- std::memcpy (state.chunk.data() + 4, &gain, 4);
- auto song = lynx::Song::makeDefault();
- song.bpm = 137.0;
- auto& f = song.channels[4].plugin.foreign;
- f.format = lynx::ForeignPlugin::Format::vst2;
- f.vst2Id = (std::uint32_t) vst2->uniqueId;
- f.name = "Some other name"; // found by the VST2 ID
- f.state = lynx::writeFlVst2State (state);
- song.channels[4].volume = 1.0f;
- song.patterns[0].notes.clear();
- song.patterns[0].notes.push_back ({ 0, 4 * lynx::ppq, 4, 69, 1.0f });
- for (std::size_t c = 0; c < song.channels.size(); ++c)
- if (c != 4)
- song.channels[c].muted = true;
- adopted = host.adoptFlPlugins (song);
- offline.setSong (song);
- const auto peak = offline.renderOffline (1.0, 48000.0);
- offline.capturePluginStates();
- juce::MemoryBlock saved;
- saved.fromBase64Encoding (juce::String (offline.getSong().channels[4].plugin.state));
- lynx::FlVst2State back;
- tempoSeen = 0.0f;
- if (lynx::parseFlVst2State (std::vector<std::uint8_t> ((const std::uint8_t*) saved.getData(), (const std::uint8_t*) saved.getData() + saved.getSize()), back)
- && back.chunk.size() >= 12)
- std::memcpy (&tempoSeen, back.chunk.data() + 8, 4);
- return peak;
- };
- if (vst2)
- {
- report << "plugin=" << vst2->name << " id=" << vst2->uniqueId << " instrument=" << (int) vst2->isInstrument << "\n";
- float tempoA = 0, tempoB = 0;
- int adoptedA = 0, adoptedB = 0;
- const auto quiet = render (0.1f, tempoA, adoptedA);
- const auto loud = render (0.4f, tempoB, adoptedB);
- report << "adopted=" << adoptedA << "," << adoptedB << " peak_gain_0.1=" << quiet << " peak_gain_0.4=" << loud
- << " tempo_seen=" << tempoB * 1000.0f << "\n";
- ok = adoptedA == 1 && adoptedB == 1 && quiet > 0.01f && std::abs (loud / quiet - 4.0f) < 0.2f
- && std::abs (tempoB * 1000.0f - 137.0f) < 0.01f;
- }
- }
- report << "result=" << (ok ? "OK" : "FAILED") << "\n";
- juce::File (reportPath).replaceWithText (report);
- setApplicationReturnValue (ok ? 0 : 1);
- quit();
- }
- // LYNX.exe --wrappertest plugin.vst3 report.txt: builds a VST3 state the way FL's Fruity
- // Wrapper stores it (REA_rodada5 §3.2), runs it through the import (adoptFlPlugins) and checks
- // that the plugin comes back with the changed parameter.
- void runWrapperTest (const juce::String& pluginPath, const juce::String& reportPath)
- {
- juce::String report;
- bool ok = false;
- {
- lynx::AudioEngine offline (false);
- auto& host = offline.getPluginHost();
- host.addPluginFile (juce::File (pluginPath));
- const juce::PluginDescription* vst3 = nullptr;
- const auto types = host.getKnownPlugins().getTypes(); // copy: the pointer below points into it
- for (const auto& type : types)
- if (type.pluginFormatName == "VST3" && type.isInstrument)
- vst3 = &type;
- if (vst3 != nullptr)
- {
- juce::String error;
- auto plugin = host.getFormats().createPluginInstance (*vst3, 48000.0, 512, error);
- auto* parameter = plugin != nullptr && ! plugin->getParameters().isEmpty() ? plugin->getParameters()[0] : nullptr;
- if (parameter != nullptr)
- {
- const auto target = parameter->getValue() > 0.5f ? 0.13f : 0.87f;
- parameter->setValueNotifyingHost (target);
- juce::MemoryBlock juceState;
- plugin->getStateInformation (juceState);
- report << "parameter=" << parameter->getName (64) << " target=" << target << "\n";
- // JUCE state -> FL container: u32 1 + records 1 (flags), 3 (component), 2 (controller)
- std::vector<std::uint8_t> flState;
- auto put32 = [&] (std::uint32_t v) { for (int b = 0; b < 4; ++b) flState.push_back ((std::uint8_t) (v >> (8 * b))); };
- auto record = [&] (std::uint32_t id, const juce::MemoryBlock& data) {
- put32 (id);
- put32 ((std::uint32_t) data.getSize());
- put32 (0);
- flState.insert (flState.end(), (const std::uint8_t*) data.getData(), (const std::uint8_t*) data.getData() + data.getSize());
- };
- put32 (1);
- record (1, juce::MemoryBlock (64, true));
- // record 4 (REA_rodada22 §2.3): slots 0/1 hold the ParamIDs of parameters 2 and 0, so FL's
- // automations k = 0, 1, 2 mean positions 2, 0 and 1 (the first parameter without a slot)
- juce::MemoryBlock slots;
- const auto paramId = [&] (int i) {
- const auto* hosted = dynamic_cast<const juce::HostedAudioProcessorParameter*> (plugin->getParameters()[i]);
- return hosted != nullptr ? (std::uint32_t) hosted->getParameterID().getLargeIntValue() : 0u;
- };
- const bool reorder = plugin->getParameters().size() >= 3;
- if (reorder)
- {
- for (auto v : { 2u, paramId (2), paramId (0) })
- slots.append (&v, 4);
- report << "slot_param_ids=" << (juce::int64) paramId (2) << "," << (juce::int64) paramId (0) << "\n";
- }
- if (auto xml = juce::AudioProcessor::getXmlFromBinary (juceState.getData(), (int) juceState.getSize()))
- for (auto [tag, id] : { std::pair { "IComponent", 3u }, { "IEditController", 2u } })
- if (auto* child = xml->getChildByName (tag))
- {
- juce::MemoryBlock data;
- data.fromBase64Encoding (child->getAllSubText());
- record (id, data);
- report << tag << "_bytes=" << (int) data.getSize() << "\n";
- }
- if (reorder)
- record (4, slots);
- plugin.reset();
- auto song = lynx::Song::makeDefault();
- auto& f = song.channels[4].plugin.foreign;
- f.format = lynx::ForeignPlugin::Format::vst3;
- f.name = vst3->name.toStdString(); // no class ID: find it by name (fallback)
- f.state = flState;
- {
- std::vector<std::uint8_t> comp, ctrl;
- report << "split=" << (int) lynx::splitFlVst3State (flState, comp, ctrl) << " component=" << (int) comp.size()
- << " saved_slots=" << (int) lynx::flVst3ParamSlots (flState).size() << "\n";
- }
- for (int k = 0; k < 3; ++k)
- {
- lynx::Automation a;
- a.target = { lynx::AutomationTargetKind::channelParam, 4, 0, k };
- song.automations.push_back (a);
- }
- const auto adopted = host.adoptFlPlugins (song);
- report << "adopted=" << adopted << "\n";
- juce::String mapped;
- for (const auto& a : song.automations)
- if (a.target.kind == lynx::AutomationTargetKind::channelParam && a.target.index == 4)
- mapped << (mapped.isEmpty() ? "" : ",") << a.target.param;
- report << "slot_positions=" << mapped << "\n";
- const auto slotsOk = ! reorder || mapped == "2,0,1";
- offline.setSong (song);
- if (auto* loaded = dynamic_cast<lynx::PluginInstrument*> (offline.getChannelInstrument (4).get()))
- {
- const auto value = loaded->getInstance().getParameters()[0]->getValue();
- report << "restored_value=" << value << "\n";
- ok = adopted == 1 && std::abs (value - target) < 0.02f && slotsOk;
- }
- }
- }
- }
- report << "result=" << (ok ? "OK" : "FAILED") << "\n";
- juce::File (reportPath).replaceWithText (report);
- setApplicationReturnValue (ok ? 0 : 1);
- quit();
- }
- void runShowcase (const juce::String& outputPath, int currentPattern)
- {
- using namespace lynx;
- Song song;
- song.bpm = 124.0;
- song.mixer = Song::defaultMixer();
- const auto presets = synthPresets();
- auto preset = [&] (const char* name) {
- for (const auto& [n, sset] : presets)
- if (n == name)
- return sset;
- return SynthSettings {};
- };
- auto channel = [&] (const char* name, InstrumentKind kind, float volume, int track, std::uint32_t colour) {
- ChannelDef c;
- c.name = name;
- c.instrument = kind;
- c.volume = volume;
- c.mixerTrack = track;
- c.colour = colour;
- song.channels.push_back (c);
- return (int) song.channels.size() - 1;
- };
- const auto kick = channel ("Kick", InstrumentKind::kick, 0.9f, 1, 0xffd9534f);
- const auto clap = channel ("Clap", InstrumentKind::clap, 0.75f, 2, 0xfff0ad4e);
- const auto hat = channel ("Hat", InstrumentKind::hat, 0.6f, 3, 0xfff7d774);
- const auto snare = channel ("Snare", InstrumentKind::snare, 0.7f, 4, 0xffe8835a);
- const auto bass = channel ("Reese Bass", InstrumentKind::synth, 0.8f, 5, 0xff5bc0de);
- song.channels[(std::size_t) bass].synth = preset ("Reese Bass"); // preset name as defined in core/SynthPresets
- const auto pad = channel ("Pad", InstrumentKind::synth, 0.7f, 6, 0xff9b7fd6);
- song.channels[(std::size_t) pad].synth = preset ("Pad");
- const auto pluck = channel ("Pluck", InstrumentKind::synth, 0.72f, 7, 0xff5cb85c);
- song.channels[(std::size_t) pluck].synth = preset ("Pluck");
- const auto lead = channel ("Supersaw", InstrumentKind::synth, 0.6f, 8, 0xff4fc3a1);
- song.channels[(std::size_t) lead].synth = preset ("Supersaw");
- auto addPattern = [&] (const char* name, std::uint32_t colour) {
- auto& p = song.patterns.emplace_back();
- p.name = name;
- p.colour = colour;
- return (int) song.patterns.size() - 1;
- };
- auto note = [&] (int pattern, int ch, double beat, double beats, int key, float velocity = 0.8f) {
- Note n;
- n.channel = ch;
- n.start = (std::int64_t) (beat * ppq);
- n.length = (std::int64_t) (beats * ppq);
- n.key = key;
- n.velocity = velocity;
- song.patterns[(std::size_t) pattern].notes.push_back (n);
- };
- const auto beat = addPattern ("Beat", 0xffd9534f);
- for (int s = 0; s < 16; s += 4)
- song.patterns[(std::size_t) beat].toggleStep (kick, s);
- for (int s : { 4, 12 })
- song.patterns[(std::size_t) beat].toggleStep (clap, s);
- for (int s = 2; s < 16; s += 4)
- song.patterns[(std::size_t) beat].toggleStep (hat, s);
- for (int s : { 7, 15 })
- song.patterns[(std::size_t) beat].toggleStep (snare, s);
- const auto groove = addPattern ("Groove", 0xfff0ad4e);
- for (int s = 0; s < 16; ++s)
- song.patterns[(std::size_t) groove].toggleStep (hat, s);
- for (int s : { 4, 12 })
- song.patterns[(std::size_t) groove].toggleStep (clap, s);
- // Am – F – C – G, one bar each
- const int roots[4] = { 45, 41, 48, 43 };
- const int chords[4][3] = { { 57, 60, 64 }, { 53, 57, 60 }, { 55, 60, 64 }, { 55, 59, 62 } };
- const auto bassline = addPattern ("Bass", 0xff5bc0de);
- for (int bar = 0; bar < 4; ++bar)
- for (int e = 0; e < 8; ++e)
- if (e != 3)
- note (bassline, bass, bar * 4 + e * 0.5, 0.4, roots[bar] - 12 + (e == 6 ? 12 : 0), e % 2 == 0 ? 0.9f : 0.65f);
- const auto chordsPattern = addPattern ("Chords", 0xff9b7fd6);
- for (int bar = 0; bar < 4; ++bar)
- for (int k = 0; k < 3; ++k)
- note (chordsPattern, pad, bar * 4, 3.9, chords[bar][k], 0.7f);
- const auto melody = addPattern ("Melody", 0xff5cb85c);
- const int line[] = { 69, 72, 76, 74, 72, 69, 67, 69, 65, 69, 72, 74, 72, 69, 67, 64,
- 72, 76, 79, 76, 74, 72, 74, 76, 71, 74, 79, 78, 76, 74, 71, 67 };
- for (int k = 0; k < 32; ++k)
- if (k % 8 != 7)
- note (melody, pluck, k * 0.5, k % 4 == 3 ? 0.9 : 0.4, line[k], k % 2 == 0 ? 0.85f : 0.65f);
- const auto hook = addPattern ("Hook", 0xff4fc3a1);
- for (int bar = 0; bar < 4; ++bar)
- for (int k = 0; k < 3; ++k)
- note (hook, lead, bar * 4 + k * 1.5, k == 2 ? 1.0 : 1.4, chords[bar][2] + 12 - k * 3, 0.8f);
- // Playlist: intro, verse, drop, breakdown, final drop
- song.playlistTracks = { { "Drums" }, { "Groove" }, { "Bass" }, { "Chords" }, { "Melody" }, { "Hook" }, { "Automation" } };
- const auto bar = (std::int64_t) ppq * 4;
- auto clip = [&] (int pattern, int track, int fromBar, int bars) {
- const auto length = song.patterns[(std::size_t) pattern].effectiveLength (song.beatsPerBar);
- for (int b = fromBar; b < fromBar + bars;)
- {
- Clip c;
- c.pattern = pattern;
- c.track = track;
- c.start = b * bar;
- c.length = length;
- song.playlist.push_back (c);
- b += (int) std::max<std::int64_t> (1, length / bar);
- }
- };
- clip (chordsPattern, 3, 0, 8);
- clip (melody, 4, 4, 4);
- clip (beat, 0, 8, 16);
- clip (groove, 1, 12, 12);
- clip (bassline, 2, 8, 8);
- clip (melody, 4, 8, 8);
- clip (chordsPattern, 3, 16, 4);
- clip (bassline, 2, 20, 4);
- clip (hook, 5, 20, 4);
- clip (melody, 4, 20, 4);
- song.addMarker ({ 0, "Intro" });
- song.addMarker ({ 8 * bar, "Drop" });
- song.addMarker ({ 16 * bar, "Breakdown" });
- song.addMarker ({ 20 * bar, "Final" });
- // automation: the pad volume opens up during the intro
- Automation a;
- a.name = "Pad Volume";
- a.target = { AutomationTargetKind::mixerVolume, 6, 0, 0 };
- a.points = { { 0, 0.15f, 0.4f }, { 8 * bar, 0.8f, 0.0f } };
- song.automations.push_back (a);
- Clip ac;
- ac.kind = ClipKind::automation;
- ac.automation = 0;
- ac.track = 6;
- ac.start = 0;
- ac.length = 8 * bar;
- song.playlist.push_back (ac);
- // mixer: names, colours and effects (bass compressor sidechained to the kick)
- const char* names[] = { "Master", "Kick", "Clap", "Hat", "Snare", "Bass", "Pad", "Pluck", "Lead" };
- for (int t = 0; t < 9; ++t)
- {
- song.mixer[(std::size_t) t].name = names[t];
- if (t > 0)
- song.mixer[(std::size_t) t].colour = song.channels[(std::size_t) t - 1].colour;
- }
- auto fx = [&] (int track, EffectKind kind) -> EffectSlot& {
- song.mixer[(std::size_t) track].effects.push_back (makeEffectSlot (kind));
- return song.mixer[(std::size_t) track].effects.back();
- };
- {
- // kick EQ: cut below 30 Hz, weight at 60 Hz, remove the "boxiness" at 350 Hz, brightness at 4 kHz
- auto& eq = fx (1, EffectKind::parametricEq);
- auto band = [&] (int b, peq::BandType type, double hz, double db, double q) {
- eq.params[(std::size_t) peq::param (b, 0)] = peq::typeValue (type);
- eq.params[(std::size_t) peq::param (b, 1)] = peq::hzValue (hz);
- eq.params[(std::size_t) peq::param (b, 2)] = peq::gainValue (db);
- eq.params[(std::size_t) peq::param (b, 3)] = peq::qValue (q);
- };
- band (0, peq::BandType::lowCut, 30.0, 0.0, 0.7);
- band (1, peq::BandType::peak, 62.0, 5.0, 1.2);
- band (2, peq::BandType::peak, 350.0, -6.0, 2.0);
- band (3, peq::BandType::peak, 4200.0, 3.5, 1.5);
- band (4, peq::BandType::highCut, 14000.0, 0.0, 0.7);
- for (int b = 5; b < peq::bands; ++b)
- eq.params[(std::size_t) peq::param (b, 0)] = peq::typeValue (peq::BandType::off);
- }
- fx (1, EffectKind::distortion).mix = 0.3f;
- auto& comp = fx (5, EffectKind::compressor);
- comp.params[0] = 0.55f;
- comp.params[1] = 0.8f;
- comp.sidechain = 1;
- fx (5, EffectKind::parametricEq);
- fx (6, EffectKind::chorus);
- fx (6, EffectKind::reverb);
- fx (7, EffectKind::delay);
- fx (7, EffectKind::reverb).mix = 0.4f;
- fx (8, EffectKind::effector);
- fx (8, EffectKind::delay);
- fx (0, EffectKind::parametricEq);
- auto& limiter = fx (0, EffectKind::limiter);
- limiter.params = { 11.7f / 12.0f, 0.1f, 0.5f };
- song.mixer[1].volume = 0.78f;
- song.mixer[5].volume = 0.72f;
- song.mixer[6].volume = 0.6f;
- song.mixer[6].pan = -0.2f;
- song.mixer[7].pan = 0.25f;
- song.mode = PlayMode::song;
- song.currentPattern = std::clamp (currentPattern, 0, (int) song.patterns.size() - 1);
- juce::String error;
- const auto ok = ProjectFile::save (song, juce::File (outputPath), error);
- setApplicationReturnValue (ok ? 0 : 1);
- quit();
- }
- // LYNX.exe --sandboxtest plugin.vst3 report.txt: opens the instrument in a separate process, plays a
- // note, changes a parameter, checks the state (back in an in-process plugin) and makes the child hang
- // to check that LYNX keeps going (silence, without waiting longer than the timeout).
- // --sandboxtest: plays an instrument (a note) or an effect (a 440 Hz tone through it); render() adds into l / r
- struct TestVoice
- {
- explicit TestVoice (std::unique_ptr<juce::AudioPluginInstance> p)
- {
- if (p->acceptsMidi() && p->getTotalNumInputChannels() == 0)
- instrument = std::make_unique<lynx::PluginInstrument> (std::move (p), 512);
- else
- effect = std::move (p);
- }
- void noteOn()
- {
- if (instrument != nullptr)
- instrument->noteOn (60, 0.9f);
- }
- void render (float* l, float* r, int n, float gainLeft, float gainRight)
- {
- if (instrument != nullptr)
- {
- instrument->render (l, r, n, gainLeft, gainRight);
- return;
- }
- const auto channels = juce::jmax (2, effect->getTotalNumInputChannels(), effect->getTotalNumOutputChannels());
- juce::AudioBuffer<float> block (channels, 512);
- juce::MidiBuffer midi;
- for (int done = 0; done < n; done += 512)
- {
- const auto k = juce::jmin (512, n - done);
- block.setSize (channels, k, false, false, true);
- for (int i = 0; i < k; ++i)
- {
- const auto v = 0.25f * (float) std::sin (phase);
- phase += 2.0 * juce::MathConstants<double>::pi * 440.0 / 48000.0;
- for (int c = 0; c < channels; ++c)
- block.setSample (c, i, v);
- }
- effect->processBlock (block, midi);
- for (int i = 0; i < k; ++i)
- {
- l[done + i] += gainLeft * block.getSample (0, i);
- r[done + i] += gainRight * block.getSample (1, i);
- }
- }
- }
- std::unique_ptr<lynx::PluginInstrument> instrument;
- std::unique_ptr<juce::AudioPluginInstance> effect;
- double phase = 0.0;
- };
- void runSandboxTest (const juce::String& pluginPath, const juce::String& reportPath)
- {
- juce::String report;
- bool ok = false;
- lynx::setPluginSandboxAlerts (false);
- const juce::File log (reportPath + ".log");
- auto step = [&] (const char* what) { log.appendText (juce::String (what) + "\n"); };
- log.deleteFile();
- {
- lynx::PluginHost host (false);
- host.addPluginFile (juce::File (pluginPath));
- const auto types = host.getKnownPlugins().getTypes(); // getTypes() returns a copy
- // the file's instrument, else its first effect (round 161: effects too, e.g. a Windows effect through yabridge)
- const juce::PluginDescription* instrument = nullptr;
- for (const auto& type : types)
- if (type.isInstrument)
- instrument = &type;
- for (const auto& type : types)
- if (instrument == nullptr && ! type.isInstrument)
- instrument = &type;
- step ("host");
- juce::String error;
- auto remote = instrument != nullptr ? lynx::createSandboxedPlugin (*instrument, 48000.0, 512, {}, error) : nullptr;
- report << "opened=" << (remote != nullptr ? 1 : 0) << " error=" << error << "\n";
- step ("created");
- if (remote != nullptr)
- {
- auto& proxy = *remote;
- TestVoice voice (std::move (remote));
- std::vector<float> l (48000), r (48000);
- auto peakOf = [&] {
- float peak = 0.0f;
- for (std::size_t k = 0; k < l.size(); ++k)
- peak = std::max ({ peak, std::abs (l[k]), std::abs (r[k]) });
- return peak;
- };
- const auto start = juce::Time::getMillisecondCounterHiRes();
- voice.noteOn();
- voice.render (l.data(), r.data(), 48000, 1.0f, 1.0f);
- const auto renderMs = juce::Time::getMillisecondCounterHiRes() - start;
- const auto peak = peakOf();
- step ("played");
- if (juce::JUCEApplication::getCommandLineParameters().contains ("--expect-crash"))
- {
- // a plugin that crashes while playing (round 161 test plugin): LYNX notices, mutes it and keeps running
- const auto dead = lynx::isSandboxedPluginDead (proxy);
- std::fill (l.begin(), l.end(), 0.0f);
- std::fill (r.begin(), r.end(), 0.0f);
- voice.render (l.data(), r.data(), 4096, 1.0f, 1.0f);
- report << "peak=" << peak << " render_1s_ms=" << renderMs << " dead=" << (dead ? 1 : 0) << " peak_after=" << peakOf() << "\n";
- ok = dead && peak > 1e-4f && renderMs < 2000.0 && peakOf() == 0.0f;
- report << "result=" << (ok ? "OK" : "FAILED") << "\n";
- juce::File (reportPath).replaceWithText (report);
- setApplicationReturnValue (ok ? 0 : 1);
- quit();
- return;
- }
- report << "plugin=" << proxy.getName() << (instrument->isInstrument ? " (instrument)" : " (effect)") << " parameters="
- << proxy.getParameters().size() << " peak=" << peak << " render_1s_ms=" << renderMs << "\n";
- if (juce::JUCEApplication::getCommandLineParameters().contains ("--editor") && proxy.hasEditor())
- {
- // the plugin's own window, opened by the child process (4 s on screen); the child must stay responsive
- std::unique_ptr<juce::AudioProcessorEditor> editor (proxy.createEditorIfNeeded());
- juce::Thread::sleep (4000);
- juce::MemoryBlock state;
- const auto t0 = juce::Time::getMillisecondCounterHiRes();
- proxy.getStateInformation (state);
- report << "editor_shown=1 state_with_editor_ms=" << (juce::Time::getMillisecondCounterHiRes() - t0) << " dead=" << (lynx::isSandboxedPluginDead (proxy) ? 1 : 0) << "\n";
- editor.reset();
- }
- // parameter -> state -> in-process plugin
- bool stateOk = false;
- if (! proxy.getParameters().isEmpty())
- {
- auto* p = proxy.getParameters()[0];
- const auto target = p->getValue() > 0.5f ? 0.13f : 0.87f;
- p->setValue (target);
- std::fill (l.begin(), l.end(), 0.0f);
- voice.render (l.data(), r.data(), 512, 1.0f, 1.0f); // carries the change to the child
- juce::MemoryBlock state;
- proxy.getStateInformation (state);
- if (auto local = host.getFormats().createPluginInstance (*instrument, 48000.0, 512, error))
- {
- local->setStateInformation (state.getData(), (int) state.getSize());
- const auto back = local->getParameters()[0]->getValue();
- // the same steps without the sandbox: some plugins quantise the value or keep it out of their state
- auto control = target;
- if (auto a = host.getFormats().createPluginInstance (*instrument, 48000.0, 512, error))
- {
- a->enableAllBuses();
- a->prepareToPlay (48000.0, 512);
- a->getParameters()[0]->setValue (target);
- juce::AudioBuffer<float> block (juce::jmax (2, a->getTotalNumInputChannels(), a->getTotalNumOutputChannels()), 512);
- block.clear();
- juce::MidiBuffer none;
- a->processBlock (block, none);
- juce::MemoryBlock direct;
- a->getStateInformation (direct);
- if (auto b = host.getFormats().createPluginInstance (*instrument, 48000.0, 512, error))
- {
- b->setStateInformation (direct.getData(), (int) direct.getSize());
- control = b->getParameters()[0]->getValue();
- }
- a->releaseResources();
- }
- report << "state_bytes=" << (int) state.getSize() << " target=" << target << " in_process=" << back << " in_process_control=" << control << "\n";
- stateOk = std::abs (back - control) < 0.02f;
- }
- }
- step ("state");
- // hung child: the block returns in ~0.5 s, muted, and the plugin is marked dead
- lynx::hangSandboxedPluginForTest (proxy);
- juce::Thread::sleep (200);
- std::fill (l.begin(), l.end(), 1.0f);
- std::fill (r.begin(), r.end(), 1.0f);
- const auto hangStart = juce::Time::getMillisecondCounterHiRes();
- voice.render (l.data(), r.data(), 4096, 0.0f, 0.0f);
- std::fill (l.begin(), l.end(), 0.0f);
- std::fill (r.begin(), r.end(), 0.0f);
- voice.render (l.data(), r.data(), 4096, 1.0f, 1.0f);
- const auto hangMs = juce::Time::getMillisecondCounterHiRes() - hangStart;
- const auto dead = lynx::isSandboxedPluginDead (proxy);
- const auto hangPeak = peakOf();
- report << "hung_ms=" << hangMs << " dead=" << (dead ? 1 : 0) << " peak_after=" << hangPeak << "\n";
- // crashed child (round 161): a second instance aborts; LYNX notices, mutes it and keeps running
- bool crashOk = false;
- if (auto second = lynx::createSandboxedPlugin (*instrument, 48000.0, 512, {}, error))
- {
- auto& proxy2 = *second;
- TestVoice voice2 (std::move (second));
- voice2.noteOn();
- voice2.render (l.data(), r.data(), 512, 1.0f, 1.0f);
- lynx::crashSandboxedPluginForTest (proxy2);
- const auto crashStart = juce::Time::getMillisecondCounterHiRes();
- while (! lynx::isSandboxedPluginDead (proxy2) && juce::Time::getMillisecondCounterHiRes() - crashStart < 5000.0)
- {
- voice2.render (l.data(), r.data(), 512, 1.0f, 1.0f);
- juce::Thread::sleep (5);
- }
- const auto crashMs = juce::Time::getMillisecondCounterHiRes() - crashStart;
- std::fill (l.begin(), l.end(), 0.0f);
- std::fill (r.begin(), r.end(), 0.0f);
- voice2.render (l.data(), r.data(), 4096, 1.0f, 1.0f);
- const auto crashDead = lynx::isSandboxedPluginDead (proxy2);
- report << "crash_ms=" << crashMs << " crash_dead=" << (crashDead ? 1 : 0) << " crash_peak_after=" << peakOf() << "\n";
- crashOk = crashDead && crashMs < 3000.0;
- }
- step ("crash");
- ok = peak > 1e-4f && stateOk && dead && hangMs < 1500.0 && hangPeak == 0.0f && crashOk;
- }
- }
- report << "result=" << (ok ? "OK" : "FAILED") << "\n";
- juce::File (reportPath).replaceWithText (report);
- setApplicationReturnValue (ok ? 0 : 1);
- quit();
- }
- // --uiperf (round 161): opens the project in the normal window, plays it, and drives the heavy UI cases of round 151
- // through the window's own event path — the default layout, the Mixer maximised (meters while playing, then
- // scrolled), the Playlist maximised (scroll down, scroll sideways, zoom in and out) and the Channel rack scrolled.
- // Every frame is painted right after its event (ComponentPeer::performAnyPendingRepaintsNow) and timed; the report
- // has, per case, the time to show it and the frames' mean / p95 / max, how many took longer than 16 ms, and the
- // process CPU. The same on every OS, so Linux (X11, XWayland) and Windows numbers can be put side by side.
- void runUiPerf (const juce::File& project, const juce::File& report)
- {
- startupOptions = lynx::StartupOptions::load();
- engine = std::make_unique<lynx::AudioEngine>();
- lynx::videoview::install (*engine); // (Fruity Video Player channels: their sound tracks)
- crashEngine = engine.get();
- createMainWindow();
- mainWindow->reveal();
- juce::String error;
- auto ok = false;
- const auto loadStart = juce::Time::getMillisecondCounterHiRes();
- if (project.hasFileExtension ("flp"))
- ok = engine->importFlpFile (project, error);
- else if (auto song = lynx::ProjectFile::load (project, error))
- {
- engine->setSong (std::move (*song));
- ok = true;
- }
- const auto loadMs = juce::Time::getMillisecondCounterHiRes() - loadStart;
- if (! ok)
- {
- report.replaceWithText ("project: " + project.getFullPathName() + "\nresult=ERROR " + error + "\n");
- setApplicationReturnValue (1);
- quit();
- return;
- }
- // LYNX_UIPERF_MUTE=1: the Master fader down (the meters of the inserts still move): a run on a desktop someone uses
- if (juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_MUTE", {}) == "1")
- engine->editSong ([] (lynx::Song& s) { if (! s.mixer.empty()) s.mixer[0].volume = 0.0f; }, false);
- struct Step
- {
- juce::String name;
- std::function<void()> setup;
- std::function<void (int)> action; // per frame; none: the step watches the window for `frames` ms
- int frames;
- std::function<juce::String()> finish = {}; // round 173f: after the step, its own lines for the report
- };
- struct UiPerf final : juce::Timer
- {
- LynxApplication& app;
- juce::File report;
- juce::String text;
- std::vector<Step> steps;
- std::size_t step = 0;
- int frame = -1;
- std::vector<double> times, rendered; // whole frames (event + paint + blit, when this timer paints) / the window's paints
- std::vector<double> frames; // round 173f: the time of every frame the window painted (ui/FrameProbe.h)
- double setupMs = 0.0, wallStart = 0.0;
- double cpuStart = 0.0; // process CPU seconds (std::clock is wall time on Windows)
- double messageCpuStart = 0.0; // the message thread's CPU seconds
- double audioLoadSum = 0.0; // the device's CPU use (AudioDeviceManager::getCpuUsage), summed per tick
- int audioLoadTicks = 0;
- UiPerf (LynxApplication& a, juce::File r) : app (a), report (std::move (r)) {}
- juce::ComponentPeer* peer() const { return app.mainWindow != nullptr ? app.mainWindow->getPeer() : nullptr; }
- double paintNow() const
- {
- const auto t0 = juce::Time::getMillisecondCounterHiRes();
- if (auto* p = peer())
- p->performAnyPendingRepaintsNow();
- return juce::Time::getMillisecondCounterHiRes() - t0;
- }
- void timerCallback() override
- {
- if (step >= steps.size())
- {
- stopTimer();
- finish();
- return;
- }
- auto& s = steps[step];
- if (frame < 0)
- {
- const auto t0 = juce::Time::getMillisecondCounterHiRes();
- if (s.setup)
- s.setup();
- paintNow();
- setupMs = juce::Time::getMillisecondCounterHiRes() - t0;
- times.clear();
- rendered.clear();
- frames.clear();
- wallStart = juce::Time::getMillisecondCounterHiRes();
- cpuStart = lynx::processCpuSeconds();
- messageCpuStart = lynx::threadCpuSeconds();
- audioLoadSum = 0.0;
- audioLoadTicks = 0;
- frame = 0;
- return;
- }
- audioLoadSum += app.engine->getDeviceManager().getCpuUsage();
- ++audioLoadTicks;
- if (s.action)
- s.action (frame);
- if (const auto ms = paintNow(); ms > 0.25) // (nothing to paint: not a frame)
- times.push_back (ms);
- ++frame;
- if (s.action ? frame < s.frames : juce::Time::getMillisecondCounterHiRes() - wallStart < (double) s.frames)
- return;
- const auto wall = juce::Time::getMillisecondCounterHiRes() - wallStart;
- const auto cpu = 1000.0 * (lynx::processCpuSeconds() - cpuStart);
- const auto messageCpu = 1000.0 * (lynx::threadCpuSeconds() - messageCpuStart);
- text << s.name << ": show " << juce::String (setupMs, 1) << " ms\n"
- << " painted frames: " << stats (rendered) << "\n"
- << " timed here (event + paint + blit): " << stats (times)
- << "\n window frames (probe): " << lynx::ui::FrameStats::of (frames, wall).describe()
- << "\n CPU " << juce::String (wall > 0.0 ? 100.0 * cpu / wall : 0.0, 0) << "% (process, " << juce::String (wall / 1000.0, 1) << " s), message thread "
- << juce::String (wall > 0.0 ? 100.0 * messageCpu / wall : 0.0, 1) << "%, audio device "
- << juce::String (audioLoadTicks > 0 ? 100.0 * audioLoadSum / audioLoadTicks : 0.0, 1) << "%\n";
- if (s.finish)
- text << s.finish();
- juce::File (report).replaceWithText (text);
- ++step;
- frame = -1;
- }
- static juce::String stats (std::vector<double> sorted)
- {
- std::sort (sorted.begin(), sorted.end());
- 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()))]; };
- double sum = 0.0;
- int over = 0;
- for (auto t : sorted)
- {
- sum += t;
- over += t > 16.0 ? 1 : 0;
- }
- return juce::String ((int) sorted.size()) + ", mean " + juce::String (sorted.empty() ? 0.0 : sum / (double) sorted.size(), 1)
- + " ms, p95 " + juce::String (at (0.95), 1) + " ms, max " + juce::String (sorted.empty() ? 0.0 : sorted.back(), 1)
- + " ms, >16 ms " + juce::String (over);
- }
- void finish()
- {
- // the cost of asking where the mouse is (X11: a round trip to the display server)
- const auto q0 = juce::Time::getMillisecondCounterHiRes();
- for (int i = 0; i < 100; ++i)
- juce::ignoreUnused (juce::Desktop::getInstance().getMainMouseSource().getScreenPosition());
- text << "mouse position query: " << juce::String ((juce::Time::getMillisecondCounterHiRes() - q0) / 100.0, 3) << " ms\n";
- app.mainWindow->onFrame = nullptr;
- app.mainWindow->watchFrames ({});
- app.engine->stop();
- text << "result=OK\n";
- report.replaceWithText (text);
- app.setApplicationReturnValue (0);
- app.quit();
- }
- };
- auto* ui = &mainWindow->getContent();
- auto wheelAt = [this] (juce::Component& target, float dx, float dy, juce::ModifierKeys mods) {
- auto* peer = mainWindow->getPeer();
- if (peer == nullptr || ! target.isShowing())
- return;
- juce::ModifierKeys::currentModifiers = mods;
- const auto local = peer->globalToLocal (target.localPointToGlobal (target.getLocalBounds().getCentre()).toFloat());
- juce::MouseWheelDetails wheel { dx, dy, false, false, false };
- peer->handleMouseWheel (juce::MouseInputSource::InputSourceType::mouse, local, juce::Time::currentTimeMillis(), wheel);
- juce::ModifierKeys::currentModifiers = {};
- };
- auto run = std::make_unique<UiPerf> (*this, report);
- mainWindow->onFrame = [r = run.get()] (double ms) { if (r->frame >= 0) r->rendered.push_back (ms); };
- // round 173f: every frame the window paints; a fader drag's moves count as shown when a frame covers the fader
- auto drag = std::make_shared<UiPerfDrag>();
- mainWindow->watchFrames ([r = run.get(), drag] (double now, juce::Rectangle<int> area) {
- if (r->frame >= 0)
- r->frames.push_back (now);
- drag->framePainted (now, area);
- });
- run->text << "project: " << project.getFullPathName() << "\n"
- << "LYNX " << getApplicationVersion() << ", " << juce::SystemStats::getOperatingSystemName() << ", "
- << juce::SystemStats::getCpuModel() << ", window " << mainWindow->getWidth() << "x" << mainWindow->getHeight()
- << ", scale " << juce::String (juce::Desktop::getInstance().getDisplays().getPrimaryDisplay() != nullptr
- ? juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->scale : 1.0, 2)
- << ", audio device " << (engine->getDeviceManager().getCurrentAudioDevice() != nullptr ? engine->getDeviceManager().getCurrentAudioDevice()->getName() : juce::String ("none")) << "\n"
- << "load " << juce::String (loadMs / 1000.0, 2) << " s\n";
- const auto none = juce::ModifierKeys();
- // discussion #10 (round 173f): the reporter's screen — the Channel Rack and the Mixer open, the pattern playing —
- // watched as it is, then insert 3's fader dragged up and down with the mouse (125 moves a second through the
- // window's own mouse path, the frames painted as the window paints them)
- const auto dragTrack = engine->getSong().mixer.size() > 3 ? 3 : 1;
- run->steps.push_back ({ "rack + mixer, pattern playing", [this, ui] {
- ui->showPanelsForSnapshot ({ lynx::workspace::Panel::channelRack, lynx::workspace::Panel::mixer });
- engine->getTransport().songMode = false;
- engine->rewind();
- engine->play();
- }, {}, 4000 });
- run->steps.push_back ({ "fader drag by mouse, rack + mixer, pattern playing", [this, ui, drag, dragTrack] {
- auto& strips = ui->getMixerForSnapshot().getStripsForSnapshot();
- const auto rail = strips.faderRailForSnapshot (dragTrack);
- drag->start (*mainWindow, strips, rail, engine.get(), dragTrack);
- }, {}, 3000, [drag] { return drag->stop(); } });
- run->steps.push_back ({ "song stopped during the drag", {}, {}, 500, [drag] { return drag->release(); } });
- run->steps.push_back ({ "after the drag (released)", {}, {}, 600, [drag] { return drag->released(); } });
- run->steps.push_back ({ "desktop, playing", [this, ui] { ui->showDesktopForSnapshot (false); engine->rewind(); engine->play(); }, {}, 3000 });
- run->steps.push_back ({ "mixer maximised, playing", [ui] { ui->selectTabForSnapshot (3); }, {}, 3000 });
- run->steps.push_back ({ "mixer scroll", {}, [wheelAt, ui, none] (int f) { wheelAt (ui->getMixerForSnapshot(), 0.0f, f < 30 ? -0.25f : 0.25f, none); }, 60 });
- // a fader dragged while the song plays (round 171c, discussion #10): 4 mouse moves per frame on insert 1's fader,
- // through the old path (a whole snapshot per move) and through editLevels
- auto faderMove = [this] (bool levels, int f) {
- for (int k = 0; k < 4; ++k)
- {
- const auto v = 0.5f + 0.3f * std::sin ((float) (f * 4 + k) * 0.05f);
- const auto edit = [v] (lynx::Song& s) { if (s.mixer.size() > 1) s.mixer[1].volume = v; };
- if (levels)
- engine->editLevels (edit, false); // (no undo step: in a real drag only the press saves one)
- else
- engine->editSong (edit, false);
- }
- };
- run->steps.push_back ({ "mixer fader drag, playing, rebuild per move (before 171c)", {}, [faderMove] (int f) { faderMove (false, f); }, 60 });
- run->steps.push_back ({ "mixer fader drag, playing, live levels (171c)", {}, [faderMove, this] (int f) { faderMove (true, f); if (f == 59) engine->flushLevels(); }, 60 });
- // F8's Plugin picker (round 171c): opening it (the "show" time = building it + its first paint), its pictures
- // loading while it stays open, pointing at the tiles, then closing it
- run->steps.push_back ({ "plugin picker open (F8)", [ui] { ui->togglePluginPickerForSnapshot(); }, {}, 2500 });
- run->steps.push_back ({ "plugin picker, pointing at tiles", {}, [ui] (int f) {
- // (round 175b: the picker is its own window)
- if (auto* picker = ui->pluginPickerForSnapshot(); picker != nullptr && picker->getPeer() != nullptr)
- {
- const auto p = picker->localPointToGlobal (juce::Point<int> (60 + (f * 37) % juce::jmax (1, picker->getWidth() - 120),
- 90 + (f * 53) % juce::jmax (1, picker->getHeight() - 200)));
- const auto local = picker->getPeer()->globalToLocal (p.toFloat());
- picker->getPeer()->handleMouseEvent (juce::MouseInputSource::InputSourceType::mouse, local, {}, 0.0f, 0.0f,
- juce::Time::currentTimeMillis());
- }
- }, 60 });
- run->steps.push_back ({ "plugin picker close", [ui] { ui->togglePluginPickerForSnapshot(); }, {}, 300 });
- run->steps.push_back ({ "playlist maximised, playing", [ui] { ui->selectTabForSnapshot (2); }, {}, 3000 });
- run->steps.push_back ({ "playlist scroll down/up", [this] { engine->stop(); },
- [wheelAt, ui, none] (int f) { wheelAt (ui->getPlaylistForSnapshot(), 0.0f, f < 40 ? -0.15f : 0.15f, none); }, 80 });
- run->steps.push_back ({ "playlist scroll sideways", {},
- [wheelAt, ui, none] (int f) { wheelAt (ui->getPlaylistForSnapshot(), f < 40 ? -0.15f : 0.15f, 0.0f, none); }, 80 });
- run->steps.push_back ({ "whole window repainted", {}, [this] (int) { mainWindow->repaint(); }, 40 });
- run->steps.push_back ({ "channel rack scroll", [ui] { ui->selectTabForSnapshot (0); },
- [wheelAt, ui, none] (int f) { wheelAt (ui->getRackViewportForSnapshot(), 0.0f, f < 30 ? -0.25f : 0.25f, none); }, 60 });
- // let the window draw the project first
- perf = std::move (run);
- juce::Timer::callAfterDelay (1500, [this] { if (perf != nullptr) perf->startTimer (16); });
- }
- // --rtstress: opens the project in the normal window with the saved audio device, plays it from the start for
- // `seconds` and writes the real-time statistics (deadline misses, late device calls, load histogram, heaviest units)
- void runRealtimeStress (const juce::File& project, const juce::File& report, double seconds, int bufferSize,
- const juce::String& deviceType, const juce::String& deviceName, const juce::String& recordTo = {})
- {
- startupOptions = lynx::StartupOptions::load();
- engine = std::make_unique<lynx::AudioEngine>();
- lynx::videoview::install (*engine); // (Fruity Video Player channels: their sound tracks)
- crashEngine = engine.get();
- // the user's saved device stays as it was: this run's choices are undone before quitting
- savedDeviceState = engine->getDeviceManager().createStateXml();
- auto& devices = engine->getDeviceManager();
- const auto driverFile = addDriverFileDeviceType();
- const auto type = deviceType.isEmpty() && driverFile ? juce::String (lynx::dllAsioTypeName) : deviceType;
- if (type.isNotEmpty() && devices.getCurrentAudioDeviceType() != type)
- devices.setCurrentAudioDeviceType (type, true);
- if (bufferSize > 0 || deviceName.isNotEmpty())
- {
- auto setup = devices.getAudioDeviceSetup();
- if (bufferSize > 0)
- setup.bufferSize = bufferSize;
- if (deviceName.isNotEmpty())
- setup.outputDeviceName = deviceName;
- const auto error = devices.setAudioDeviceSetup (setup, true);
- if (error.isNotEmpty())
- report.replaceWithText ("device error: " + error + "\n");
- }
- createMainWindow();
- if (! juce::JUCEApplication::getCommandLineParameters().contains ("--no-window")) // --no-window: is it the UI?
- mainWindow->reveal();
- juce::String error;
- auto ok = false;
- const auto loadStart = juce::Time::getMillisecondCounterHiRes();
- if (project.hasFileExtension ("flp"))
- ok = engine->importFlpFile (project, error);
- else if (auto song = lynx::ProjectFile::load (project, error))
- {
- engine->setSong (std::move (*song));
- ok = true;
- }
- const auto loadMs = juce::Time::getMillisecondCounterHiRes() - loadStart;
- if (! ok)
- {
- report.replaceWithText ("project: " + project.getFullPathName() + "\nresult=ERROR " + error + "\n");
- restoreSavedDeviceState();
- setApplicationReturnValue (1);
- quit();
- return;
- }
- if (recordTo.isNotEmpty())
- engine->setAudioRecordingArmed (true); // opens the input of the driver
- // let the window draw the project, then play from the start with fresh statistics
- juce::Timer::callAfterDelay (1500, [this, project, report, seconds, loadMs, recordTo] {
- if (engine == nullptr)
- return;
- engine->stop();
- engine->rewind();
- engine->getRtStats().reset();
- engine->takeUiPulse();
- if (recordTo.isNotEmpty())
- engine->setRecording (true);
- // --log folder: the audio logger records what the Master plays during the run (realtime vs export checks)
- const auto& cli = juce::JUCEApplication::getCommandLineParameterArray();
- if (const auto at = cli.indexOf ("--log"); at >= 0 && at + 1 < cli.size())
- engine->getAudioLogger().start (juce::File (cli[at + 1].unquoted()), engine->getDeviceManager().getCurrentAudioDevice() != nullptr
- ? engine->getDeviceManager().getCurrentAudioDevice()->getCurrentSampleRate() : 44100.0);
- engine->play();
- juce::Timer::callAfterDelay ((int) (seconds * 1000.0), [this, project, report, seconds, loadMs, recordTo] {
- if (engine == nullptr)
- return;
- engine->stop();
- juce::String recording;
- if (engine->getAudioLogger().isLogging())
- {
- recording << " logged: " << engine->getAudioLogger().currentFile().getFullPathName() << "\n";
- engine->getAudioLogger().stop();
- }
- if (recordTo.isNotEmpty())
- recording = finishStressTake (juce::File (recordTo), seconds);
- const auto& cli = juce::JUCEApplication::getCommandLineParameterArray();
- const auto s = engine->getRtStats().snapshot();
- juce::String text;
- text << "project: " << project.getFullPathName() << "\n"
- << "LYNX " << getApplicationVersion() << ", " << juce::SystemStats::getOperatingSystemName() << ", "
- << juce::SystemStats::getNumCpus() << " logical CPUs (" << juce::SystemStats::getNumPhysicalCpus() << " cores), "
- << juce::SystemStats::getCpuModel() << "\n"
- << "load " << juce::String (loadMs / 1000.0, 1) << " s, played " << juce::String (seconds, 0) << " s\n"
- << engine->describeRealtime();
- const auto pulse = engine->takeUiPulse();
- text << " UI: the 30 Hz engine timer ran " << pulse.calls << " times (" << juce::String (pulse.calls / seconds, 1)
- << "/s), longest gap " << juce::String (pulse.maxGapMs, 0) << " ms" << (mainWindow == nullptr || ! mainWindow->isVisible() ? " (window hidden)" : "") << "\n";
- text << " load histogram (share of the deadline: callbacks):";
- for (std::size_t b = 0; b < s.histogram.size(); ++b)
- if (s.histogram[b] > 0)
- text << " " << (int) (b * 10) << (b + 1 == s.histogram.size() ? juce::String ("+") : "-" + juce::String ((int) (b * 10 + 10))) << "%:" << (juce::int64) s.histogram[b];
- text << "\n";
- text << recording;
- // --settingsshot file.png (round 161): Options > Audio settings of this run's device, as a picture
- if (const auto at = cli.indexOf ("--settingsshot"); at >= 0 && at + 1 < cli.size())
- {
- auto page = lynx::makeSettingsPanel (*engine, lynx::SettingsPage::audio);
- juce::Image image (juce::Image::ARGB, page->getWidth(), page->getHeight(), true);
- {
- juce::Graphics g (image);
- g.fillAll (lynx::theme::panel);
- page->paintEntireComponent (g, false);
- }
- const juce::File shot (cli[at + 1].unquoted());
- shot.deleteFile();
- if (auto out = shot.createOutputStream())
- juce::PNGImageFormat().writeImageToStream (image, *out);
- }
- text << "result=" << (s.callbacks == 0 ? "ERROR no audio callbacks" : s.overBudget == 0 && s.lateCalls == 0 ? "OK" : "GLITCHES") << "\n";
- report.replaceWithText (text);
- restoreSavedDeviceState();
- setApplicationReturnValue (s.callbacks == 0 ? 1 : 0);
- quit();
- });
- });
- }
- // --bendrectest (round 167a): see the command line above
- void runBendRecordTest (const juce::File& report, bool songMode)
- {
- engine = std::make_unique<lynx::AudioEngine>();
- auto text = std::make_shared<juce::String>();
- auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
- auto finish = [this] (int code) {
- setApplicationReturnValue (code);
- quit();
- };
- auto* device = engine->getDeviceManager().getCurrentAudioDevice();
- if (device == nullptr)
- {
- step ("result=ERROR no audio device");
- finish (1);
- return;
- }
- step ("device=" + device->getTypeName() + " | " + device->getName() + " | mode " + (songMode ? "song" : "pattern"));
- auto song = lynx::Song::makeDefault();
- song.bpm = 120.0;
- song.mode = songMode ? lynx::PlayMode::song : lynx::PlayMode::pattern;
- engine->setSong (std::move (song));
- auto o = engine->getRecordOptions();
- o.recordNotes = true;
- o.recordAutomation = true;
- o.countInBars = 0;
- o.waitForInput = false;
- o.quantiseAutomation = false;
- o.punchLoopRegion = false;
- o.preRollBars = o.postRollBars = 0;
- engine->setRecordOptions (o);
- engine->stop();
- engine->rewind();
- engine->setRecording (true);
- engine->startPlayback();
- // 2 s of wheel at ~100 messages a second: 0 → +1 (0.5 s), +1 → −1 (1 s), −1 → 0 (0.5 s)
- auto sent = std::make_shared<std::vector<std::pair<double, float>>>();
- auto t0 = std::make_shared<double> (juce::Time::getMillisecondCounterHiRes());
- engine->injectMidiInput (juce::MidiMessage::noteOn (1, 60, (juce::uint8) 100));
- auto tick = std::make_shared<std::function<void()>>();
- *tick = [this, sent, t0, tick, step, finish, songMode] {
- if (engine == nullptr)
- return;
- const auto ms = juce::Time::getMillisecondCounterHiRes() - *t0;
- if (ms < 2000.0)
- {
- const auto x = ms / 1000.0;
- 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);
- const auto wheel = juce::jlimit (0, 16383, 8192 + juce::roundToInt (v * 8191.0f));
- engine->injectMidiInput (juce::MidiMessage::pitchWheel (1, wheel));
- sent->push_back ({ ms, (float) (wheel - 8192) / 8192.0f });
- juce::Timer::callAfterDelay (10, *tick);
- return;
- }
- engine->injectMidiInput (juce::MidiMessage::pitchWheel (1, 8192));
- engine->injectMidiInput (juce::MidiMessage::noteOff (1, 60));
- juce::Timer::callAfterDelay (400, [this, sent, step, finish, songMode] {
- if (engine == nullptr)
- return;
- engine->stop();
- juce::Timer::callAfterDelay (600, [this, sent, step, finish, songMode] {
- if (engine == nullptr)
- return;
- engine->setRecording (false);
- const auto& s = engine->getSong();
- // the channel's pitch bend (MIDI channel 1), recorded as a lane or a clip
- std::vector<std::pair<std::int64_t, float>> got;
- juce::String where = "nothing";
- for (const auto& a : s.automations)
- if (a.target.kind == lynx::AutomationTargetKind::channelParam && lynx::midictl::isPitchBend (a.target.param))
- {
- where = "automation clip \"" + juce::String (a.name) + "\"";
- for (const auto& pt : a.points)
- got.push_back ({ pt.tick, pt.value });
- }
- for (const auto& p : s.patterns)
- for (const auto& lane : p.events)
- if (lane.target.kind == lynx::AutomationTargetKind::channelParam && lynx::midictl::isPitchBend (lane.target.param))
- {
- where = "pattern \"" + juce::String (p.name) + "\" event lane";
- for (const auto& e : lane.events)
- got.push_back ({ e.tick, e.value });
- }
- int notes = 0;
- for (const auto& p : s.patterns)
- notes += (int) p.notes.size();
- float lo = 1.0f, hi = 0.0f;
- for (const auto& [t, v] : got)
- lo = std::min (lo, v), hi = std::max (hi, v);
- // ticks: in order, spread over the ~2 s sweep (8 beats of 96 ticks at 120 bpm ≈ 4 beats)
- const auto span = got.empty() ? 0 : got.back().first - got.front().first;
- const auto sorted = std::is_sorted (got.begin(), got.end(), [] (const auto& a, const auto& b) { return a.first < b.first; });
- step ("sent=" + juce::String ((int) sent->size()) + " wheel messages over 2 s");
- step ("recorded=" + juce::String ((int) got.size()) + " points in " + where + ", value " + juce::String (lo, 3) + " .. "
- + juce::String (hi, 3) + " (0.5 = centre), ticks " + juce::String (span) + " apart, " + (sorted ? "in order" : "OUT OF ORDER")
- + ", notes " + juce::String (notes));
- if (! got.empty())
- step ("last=" + juce::String (got.back().second, 3));
- // song mode: a clip over the take, ending back at the centre. Pattern mode: the take loops the 1-bar pattern
- // (4.6 beats of take), so the lane spans the bar and the last wheel message (the centre) lands inside it
- const auto centred = std::any_of (got.begin(), got.end(), [] (const auto& p) { return std::abs (p.second - 0.5f) < 0.02f; });
- const auto ok = got.size() >= 20 && hi > 0.97f && lo < 0.03f && sorted && notes >= 1
- && (songMode ? span > lynx::ppq * 3 && span < lynx::ppq * 6 && std::abs (got.back().second - 0.5f) < 0.02f
- : span > lynx::ppq * 2 && span <= lynx::ppq * 4 && centred);
- step (ok ? "result=OK" : "result=FAILED");
- finish (ok ? 0 : 1);
- });
- });
- };
- juce::Timer::callAfterDelay (300, *tick);
- }
- // --countinrectest (round 170d): see the command line above.
- void runCountInRecordTest (const juce::File& report)
- {
- engine = std::make_unique<lynx::AudioEngine>();
- engine->getDeviceManager().closeAudioDevice(); // the engine's callback is driven by hand below
- struct StandIn final : juce::AudioIODevice
- {
- StandIn() : juce::AudioIODevice ("countin", "test") {}
- juce::StringArray getOutputChannelNames() override { return { "L", "R" }; }
- juce::StringArray getInputChannelNames() override { return {}; }
- juce::Array<double> getAvailableSampleRates() override { return { 48000.0 }; }
- juce::Array<int> getAvailableBufferSizes() override { return { 512 }; }
- int getDefaultBufferSize() override { return 512; }
- juce::String open (const juce::BigInteger&, const juce::BigInteger&, double, int) override { return {}; }
- void close() override {}
- bool isOpen() override { return true; }
- void start (juce::AudioIODeviceCallback*) override {}
- void stop() override {}
- bool isPlaying() override { return true; }
- juce::String getLastError() override { return {}; }
- int getCurrentBufferSizeSamples() override { return 512; }
- double getCurrentSampleRate() override { return 48000.0; }
- int getCurrentBitDepth() override { return 32; }
- juce::BigInteger getActiveOutputChannels() const override
- {
- juce::BigInteger b;
- b.setRange (0, 2, true);
- return b;
- }
- juce::BigInteger getActiveInputChannels() const override { return {}; }
- int getOutputLatencyInSamples() override { return 256; }
- int getInputLatencyInSamples() override { return 0; }
- };
- auto device = std::make_shared<StandIn>();
- auto text = std::make_shared<juce::String>();
- auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
- auto finish = [this] (int code) {
- setApplicationReturnValue (code);
- quit();
- };
- constexpr std::int64_t bar = 4 * lynx::ppq; // 120 BPM, 4/4
- lynx::Song song; // (as --cliplooptest: one synth channel on insert 1, an empty pattern)
- song.bpm = 120.0;
- song.mixer = lynx::Song::defaultMixer (2);
- song.channels.resize (1);
- song.channels[0].mixerTrack = 1;
- song.patterns.emplace_back();
- song.mode = lynx::PlayMode::song;
- song.currentPattern = 0;
- engine->setSong (song);
- engine->getTransport().metronome.store (true);
- auto o = engine->getRecordOptions();
- o.countInBars = 1;
- o.catchWindow = lynx::ppq / 4;
- o.compensateOutput = true;
- o.recordNotes = true;
- o.recordAudio = false;
- o.recordAutomation = false;
- o.waitForInput = false;
- o.quantise = 0;
- o.placeSongClip = true;
- o.recordingMarkers = false;
- o.punchLoopRegion = false;
- o.preRollBars = o.postRollBars = 0;
- engine->setRecordOptions (o);
- engine->deviceCallback().audioDeviceAboutToStart (device.get());
- 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");
- // an event heard at output sample `heard` (counted from the first block after Play), sent as MIDI input
- struct Event
- {
- std::int64_t heard;
- juce::MidiMessage message;
- };
- struct Pass
- {
- std::vector<float> out;
- std::vector<Event> events;
- std::int64_t playingAt = -1; // the first sample of the block the song started in
- int block = 0, blocks = 0;
- std::function<void()> done;
- };
- constexpr int n = 512;
- constexpr double rate = 48000.0;
- // one pass: the take recorded from bar 3, `blocks` blocks driven by hand, 8 at a time between the engine's timer
- // ticks (the take is committed there); then stopped and its results left to the timer
- auto runPass = std::make_shared<std::function<void (std::shared_ptr<Pass>)>>();
- *runPass = [this] (std::shared_ptr<Pass> pass) {
- auto& cb = engine->deviceCallback();
- std::vector<float> l (n), r (n);
- float* outs[] = { l.data(), r.data() };
- juce::AudioIODeviceCallbackContext context;
- if (pass->block == 0)
- {
- engine->stop();
- engine->seek ((double) (2 * bar));
- cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, n, context); // (the seek, stopped)
- engine->setRecording (true);
- engine->startPlayback(); // the count-in starts
- }
- for (int k = 0; k < 8 && pass->block < pass->blocks; ++k, ++pass->block)
- {
- // the events heard in this block: stamped the way the engine's clock maps time to heard samples
- const auto blockStart = (std::int64_t) pass->block * n;
- const auto clock = engine->liveClock();
- const auto compMs = 1000.0 * (n + 256) / rate;
- for (auto& e : pass->events)
- if (e.heard >= blockStart && e.heard < blockStart + n)
- {
- auto m = e.message;
- m.setTimeStamp ((clock.timeMs + compMs + (double) (e.heard - blockStart) * 1000.0 / rate) * 0.001);
- engine->injectMidiInput (m);
- }
- cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, n, context);
- pass->out.insert (pass->out.end(), l.begin(), l.end());
- if (pass->playingAt < 0 && engine->getTransport().playing.load())
- pass->playingAt = blockStart;
- }
- };
- // (the recursion through the message loop; written out so each step lets the engine's timer run)
- auto drive = std::make_shared<std::function<void (std::shared_ptr<Pass>)>>();
- *drive = [this, runPass, drive, device] (std::shared_ptr<Pass> pass) { // (the stand-in lives while the passes run)
- if (engine == nullptr)
- return;
- (*runPass) (pass);
- if (pass->block < pass->blocks)
- {
- juce::Timer::callAfterDelay (40, [pass, drive] { (*drive) (pass); });
- return;
- }
- engine->stop();
- juce::Timer::callAfterDelay (300, [this, pass] {
- if (engine == nullptr)
- return;
- engine->setRecording (false);
- juce::Timer::callAfterDelay (200, [pass] { pass->done(); });
- });
- };
- auto onsets = [] (const std::vector<float>& out) {
- std::vector<std::int64_t> at;
- std::int64_t last = -100000;
- for (std::size_t i = 0; i < out.size(); ++i)
- if (std::abs (out[i]) > 0.02f && (std::int64_t) i - last > 4000)
- {
- at.push_back ((std::int64_t) i);
- last = (std::int64_t) i;
- }
- else if (std::abs (out[i]) > 0.02f)
- last = (std::int64_t) i;
- return at;
- };
- // the graph is (re)built on the message thread: start once it has settled
- juce::Timer::callAfterDelay (1500, [this, step, finish, drive, onsets] {
- if (engine == nullptr)
- return;
- auto first = std::make_shared<Pass>();
- first->blocks = (int) (rate * 18.0 / n); // count-in + 8 bars
- first->done = [this, first, step, finish, drive, onsets] {
- const auto clicks = onsets (first->out);
- juce::String list;
- for (std::size_t i = 0; i < std::min<std::size_t> (clicks.size(), 8); ++i)
- list << clicks[i] << " ";
- step ("pass 1: clicks heard at samples " + list + "…, the song started in the block at " + juce::String (first->playingAt));
- // the bar-3 downbeat: the click at the block the song started in
- std::int64_t down = -1;
- for (auto c : clicks)
- if (std::abs (c - first->playingAt) < n)
- down = c;
- if (down < 0 || engine->getSong().patterns[0].notes.size() != 0)
- {
- step ("result=FAILED no downbeat click found (or notes recorded without input)");
- finish (1);
- return;
- }
- const auto ms = [down] (double t) { return down + (std::int64_t) std::llround (t * rate / 1000.0); };
- auto second = std::make_shared<Pass>();
- second->blocks = first->blocks;
- auto add = [&second] (std::int64_t at, int key, bool on) {
- second->events.push_back ({ at, on ? juce::MidiMessage::noteOn (1, key, (juce::uint8) 100) : juce::MidiMessage::noteOff (1, key) });
- };
- for (int key : { 60, 64, 67 }) // the chord, 15 ms early, held half a second
- {
- add (ms (-15.0), key, true);
- add (ms (500.0), key, false);
- }
- add (ms (-1500.0), 62, true); // beat 2 of the count-in bar (bar 2)
- add (ms (-1250.0), 62, false);
- add (ms (503.0), 77, true); // 3 ms after beat 2
- add (ms (603.0), 77, false);
- for (int b = 1; b <= 6; ++b) // a note a bar ("it stopped after two bars")
- {
- add (ms (b * 2000.0), 70 + b, true);
- add (ms (b * 2000.0 + 250.0), 70 + b, false);
- }
- second->done = [this, step, finish] {
- const auto& s = engine->getSong();
- const auto& p = s.patterns[0];
- const lynx::Clip* clip = nullptr;
- for (const auto& c : s.playlist)
- if (c.kind == lynx::ClipKind::pattern && c.pattern == 0)
- clip = &c;
- const auto origin = clip != nullptr ? clip->start - clip->offset : -1;
- step ("pass 2: " + juce::String ((int) p.notes.size()) + " notes recorded, clip at " + juce::String (clip != nullptr ? clip->start : -1));
- auto ok = clip != nullptr && origin == bar && p.notes.size() == 11;
- // where each one was heard (song ticks): 0.5 ms = ~1 tick
- const std::vector<std::pair<int, double>> want = { { 60, 2.0 * bar }, { 64, 2.0 * bar }, { 67, 2.0 * bar },
- { 62, 2.0 * bar - 3 * lynx::ppq }, { 77, 2.0 * bar + lynx::ppq + 3.0 * 1.92 },
- { 71, 3.0 * bar }, { 72, 4.0 * bar }, { 73, 5.0 * bar },
- { 74, 6.0 * bar }, { 75, 7.0 * bar }, { 76, 8.0 * bar } };
- for (const auto& [key, tick] : want)
- {
- const lynx::Note* found = nullptr;
- for (const auto& note : p.notes)
- if (note.key == key)
- found = ¬e;
- const auto at = found != nullptr ? (double) (origin + found->start) : -1.0;
- const auto good = found != nullptr && std::abs (at - tick) <= 2.0;
- ok = ok && good;
- step ("key " + juce::String (key) + ": heard at tick " + juce::String (tick, 2) + ", recorded at " + juce::String (at, 0)
- + (good ? " ok" : " WRONG"));
- }
- const auto* chord = [&p] () -> const lynx::Note* {
- for (const auto& note : p.notes)
- if (note.key == 60)
- return ¬e;
- return nullptr;
- }();
- if (chord != nullptr)
- step ("chord length " + juce::String (chord->length) + " ticks (caught 15 ms early, released 500 ms after bar 3: 960)");
- step (ok ? "result=OK" : "result=FAILED");
- finish (ok ? 0 : 1);
- };
- (*drive) (second);
- };
- (*drive) (first);
- });
- }
- // --cliplooptest (round 167q): see the command line above.
- void runClipLoopTest (const juce::File& report, const juce::File& wavFile)
- {
- engine = std::make_unique<lynx::AudioEngine>();
- engine->getDeviceManager().closeAudioDevice(); // the engine's callback is driven by hand below
- struct StandIn final : juce::AudioIODevice
- {
- StandIn() : juce::AudioIODevice ("cliploop", "test") {}
- juce::StringArray getOutputChannelNames() override { return { "L", "R" }; }
- juce::StringArray getInputChannelNames() override { return {}; }
- juce::Array<double> getAvailableSampleRates() override { return { 48000.0 }; }
- juce::Array<int> getAvailableBufferSizes() override { return { 512 }; }
- int getDefaultBufferSize() override { return 512; }
- juce::String open (const juce::BigInteger&, const juce::BigInteger&, double, int) override { return {}; }
- void close() override {}
- bool isOpen() override { return true; }
- void start (juce::AudioIODeviceCallback*) override {}
- void stop() override {}
- bool isPlaying() override { return true; }
- juce::String getLastError() override { return {}; }
- int getCurrentBufferSizeSamples() override { return 512; }
- double getCurrentSampleRate() override { return 48000.0; }
- int getCurrentBitDepth() override { return 32; }
- juce::BigInteger getActiveOutputChannels() const override
- {
- juce::BigInteger b;
- b.setRange (0, 2, true);
- return b;
- }
- juce::BigInteger getActiveInputChannels() const override { return {}; }
- int getOutputLatencyInSamples() override { return 0; }
- int getInputLatencyInSamples() override { return 0; }
- };
- auto device = std::make_shared<StandIn>();
- auto text = std::make_shared<juce::String>();
- auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
- constexpr int bar = 96000, beat = bar / 4; // 120 BPM, 48 kHz
- const auto ppq = (double) lynx::ppq;
- lynx::Song song;
- song.bpm = 120.0;
- song.mixer = lynx::Song::defaultMixer (2);
- song.channels.resize (1); // the synth of a new channel: deterministic
- song.channels[0].mixerTrack = 1;
- auto& pattern = song.patterns.emplace_back(); // 1 bar: C5 on beat 0, C6 on beat 2
- for (auto [b, key] : { std::pair { 0, 60 }, std::pair { 2, 72 } })
- {
- lynx::Note n;
- n.start = b * lynx::ppq;
- n.length = lynx::ppq / 4;
- n.key = key;
- pattern.notes.push_back (n);
- }
- lynx::Clip clip;
- clip.pattern = 0;
- clip.length = 16 * lynx::ppq; // stretched to 4 bars
- song.playlist.push_back (clip);
- song.mode = lynx::PlayMode::song;
- {
- // the Windows GUI check's project: the same song with a 1-bar clip, to stretch with the mouse
- auto gui = song;
- gui.playlist[0].length = 4 * lynx::ppq;
- juce::String error;
- lynx::ProjectFile::save (gui, report.getSiblingFile ("cliploop-gui.lynx"), error);
- }
- engine->setSong (song);
- auto& callback = engine->deviceCallback();
- callback.audioDeviceAboutToStart (device.get());
- step ("song=1-bar synth pattern, clip stretched to 4 bars, 120 BPM, 48 kHz, blocks of 512");
- // the graph is (re)built on the message thread: the scenarios run once it has settled
- juce::Timer::callAfterDelay (1500, [this, device, step, wavFile, ppq] {
- if (engine == nullptr)
- return;
- auto& cb = engine->deviceCallback();
- // plays `samples` from tick `from` through the device callback; `between` runs after each block (block index)
- auto play = [this, &cb] (double from, int samples, const std::function<void (int)>& between = {}) {
- engine->stop();
- engine->seek (from);
- std::vector<float> l (512), r (512), out;
- float* outs[] = { l.data(), r.data() };
- juce::AudioIODeviceCallbackContext context;
- cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, 512, context); // (the seek, stopped)
- engine->play();
- for (int k = 0; (int) out.size() < samples; ++k)
- {
- cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, 512, context);
- out.insert (out.end(), l.begin(), l.end());
- if (between)
- between (k);
- }
- engine->stop();
- for (int k = 0; k < 400; ++k) // the tails of the scenario die out
- cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, 512, context);
- out.resize ((std::size_t) samples);
- return out;
- };
- auto rms = [] (const std::vector<float>& x, int from, int count) {
- double sum = 0.0;
- for (int i = from; i < from + count && i < (int) x.size(); ++i)
- sum += (double) x[(std::size_t) i] * x[(std::size_t) i];
- return std::sqrt (sum / juce::jmax (1, count));
- };
- auto diff = [] (const std::vector<float>& a, int aFrom, const std::vector<float>& b, int bFrom, int count) {
- double m = 0.0;
- for (int i = 0; i < count && aFrom + i < (int) a.size() && bFrom + i < (int) b.size(); ++i)
- m = juce::jmax (m, (double) std::abs (a[(std::size_t) (aFrom + i)] - b[(std::size_t) (bFrom + i)]));
- return m;
- };
- auto num = [] (double v) { return juce::String (v, 6); };
- bool ok = true;
- auto check = [&ok, step] (bool good, const juce::String& what) {
- ok = ok && good;
- step ((good ? "ok " : "FAIL ") + what);
- };
- lynx::setStretchedClipsLoop (true);
- const auto a = play (0.0, 4 * bar);
- const auto bar1 = rms (a, 0, bar);
- check (bar1 > 0.01, "play from the start: bar 1 RMS " + num (bar1));
- for (int k = 1; k < 4; ++k)
- {
- const auto rk = rms (a, k * bar, bar), d = diff (a, k * bar, a, 0, bar);
- check (std::abs (rk / bar1 - 1.0) < 1.0e-3 && d < 1.0e-4,
- "bar " + juce::String (k + 1) + " RMS " + num (rk) + " (x" + num (rk / bar1) + " of bar 1), max |bar - bar 1| " + juce::String (d, 9));
- }
- {
- const auto x = play (10 * ppq, bar + bar / 2);
- const auto d = juce::jmax (diff (x, 0, a, 2 * beat, bar / 2), diff (x, bar / 2, a, 0, bar));
- check (rms (x, 0, bar / 2) > 0.01 && d < 1.0e-4,
- "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));
- }
- {
- // a seek while playing, after 6.99 beats, to bar 4 beat 3 (a ruler click)
- const auto jumpBlock = 7 * beat / 512 - 1;
- const auto x = play (0.0, 2 * bar, [this, jumpBlock, ppq] (int k) {
- if (k == jumpBlock)
- engine->seek (14 * ppq);
- });
- // (the best of 0-2 samples late: anything but 0 fails)
- const auto at = (jumpBlock + 1) * 512;
- int lag = 0;
- auto d = 1.0e9;
- for (int l = 0; l <= 2; ++l)
- if (const auto dl = diff (x, at + l, a, 2 * beat, beat - 2); dl < d)
- d = dl, lag = l;
- d = lag == 0 ? d : 1.0;
- const auto ratio = rms (x, at, beat) / rms (a, 2 * beat, beat);
- check (std::abs (ratio - 1.0) < 1.0e-3 && d < 1.0e-4,
- "jump mid-clip to bar 4 beat 3: RMS " + num (rms (x, at, beat)) + " (x" + num (ratio) + " of bar 1 beat 3), max diff "
- + juce::String (d, 9) + " (" + juce::String (lag) + " sample(s) late)");
- }
- {
- engine->editSong ([ppq] (lynx::Song& s) {
- s.loopStart = (std::int64_t) (4 * ppq);
- s.loopEnd = (std::int64_t) (12 * ppq);
- }, false);
- const auto x = play (0.0, 7 * bar);
- double d = 0.0;
- juce::String lags;
- for (int k = 1; k < 7; ++k) // (the best of 0-2 samples late after a wrap, as after a jump)
- {
- auto best = 1.0e9;
- int lag = 0;
- for (int l = 0; l <= 2; ++l)
- if (const auto dl = diff (x, k * bar + l, a, 0, bar - 2); dl < best)
- best = dl, lag = l;
- d = juce::jmax (d, lag == 0 ? best : 1.0); // a sample gained at a wrap fails (round 167q loopwrap)
- lags << (k > 1 ? "," : "") << lag;
- }
- const auto r = rms (x, bar, 6 * bar);
- check (std::abs (r / bar1 - 1.0) < 1.0e-3 && d < 1.0e-4,
- "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)
- + " (samples late, bars 2-7: " + lags + ")");
- engine->editSong ([] (lynx::Song& s) { s.loopStart = s.loopEnd = 0; }, false);
- }
- {
- // 100 wraps of a 1-bar loop region (bar 2): every pass on its sample, none gained (round 167q loopwrap: each
- // wrap used to play one sample more)
- engine->editSong ([ppq] (lynx::Song& s) {
- s.loopStart = (std::int64_t) (4 * ppq);
- s.loopEnd = (std::int64_t) (8 * ppq);
- }, false);
- const auto x = play (0.0, 101 * bar);
- double d = 0.0;
- int worst = 0;
- for (int k = 1; k <= 100; ++k)
- if (const auto dk = diff (x, k * bar, a, 0, bar); dk > d)
- d = dk, worst = k + 1;
- check (d < 1.0e-4, "loop region bar 2, 100 wraps: max diff of every pass vs bar 1 " + juce::String (d, 9)
- + (d < 1.0e-4 ? juce::String() : " (worst: bar " + juce::String (worst) + ")"));
- engine->editSong ([] (lynx::Song& s) { s.loopStart = s.loopEnd = 0; }, false);
- }
- lynx::setStretchedClipsLoop (false);
- {
- const auto x = play (0.0, 4 * bar);
- const auto r = juce::jmax (rms (x, bar, bar), juce::jmax (rms (x, 2 * bar, bar), rms (x, 3 * bar, bar)));
- 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));
- }
- lynx::setStretchedClipsLoop (true);
- cb.audioDeviceStopped();
- // the export: a WAV of the 4 bars, read back from the file
- if (wavFile != juce::File())
- {
- for (const auto loops : { true, false })
- {
- lynx::setStretchedClipsLoop (loops);
- const auto file = loops ? wavFile : wavFile.getSiblingFile (wavFile.getFileNameWithoutExtension() + "-off.wav");
- file.deleteFile();
- {
- juce::WavAudioFormat wav;
- std::unique_ptr<juce::AudioFormatWriter> writer (wav.createWriterFor (file.createOutputStream().release(), 48000.0, 2, 32, {}, 0));
- engine->stop();
- engine->seek (0.0);
- lynx::AudioEngine::RenderOptions o;
- o.seconds = 8.0;
- o.sampleRate = 48000.0;
- o.output = writer.get();
- engine->renderOffline (o);
- }
- juce::WavAudioFormat wav;
- std::unique_ptr<juce::AudioFormatReader> reader (wav.createReaderFor (file.createInputStream().release(), true));
- std::vector<float> x;
- if (reader != nullptr)
- {
- juce::AudioBuffer<float> buffer (2, (int) reader->lengthInSamples);
- reader->read (&buffer, 0, (int) reader->lengthInSamples, 0, true, true);
- x.assign (buffer.getReadPointer (0), buffer.getReadPointer (0) + buffer.getNumSamples());
- }
- const auto b1 = rms (x, 0, bar);
- juce::String line = juce::String (loops ? "export" : "export, option off") + " (" + file.getFileName() + ", " + juce::String ((int) x.size()) + " samples): bar 1 RMS " + num (b1);
- bool good = x.size() >= (std::size_t) 4 * bar && b1 > 0.01;
- for (int k = 1; k < 4; ++k)
- {
- const auto rk = rms (x, k * bar, bar);
- line << ", bar " << (k + 1) << " " << num (rk);
- 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);
- }
- if (loops)
- 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);
- check (good, line);
- }
- lynx::setStretchedClipsLoop (true);
- }
- step (ok ? "result=OK" : "result=FAILED");
- setApplicationReturnValue (ok ? 0 : 1);
- quit();
- });
- }
- // --rectest (round 163): see the command line above. Writes report lines step by step (a driver that ends the
- // process leaves what was done).
- void runRecordTest (const juce::File& report, double seconds, const juce::String& deviceType, const juce::String& deviceName,
- const juce::String& inputName, int mode, int pdcSamples, int bufferSize)
- {
- engine = std::make_unique<lynx::AudioEngine>();
- lynx::videoview::install (*engine); // (Fruity Video Player channels: their sound tracks)
- savedDeviceState = engine->getDeviceManager().createStateXml();
- auto text = std::make_shared<juce::String>();
- auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
- auto finish = [this, step] (int code) {
- restoreSavedDeviceState();
- setApplicationReturnValue (code);
- quit();
- };
- auto& devices = engine->getDeviceManager();
- if (deviceType.isNotEmpty() && devices.getCurrentAudioDeviceType() != deviceType)
- devices.setCurrentAudioDeviceType (deviceType, true);
- {
- auto setup = devices.getAudioDeviceSetup();
- if (deviceName.isNotEmpty())
- setup.outputDeviceName = deviceName;
- if (bufferSize > 0)
- setup.bufferSize = bufferSize;
- if (const auto error = devices.setAudioDeviceSetup (setup, true); error.isNotEmpty())
- step ("device_error=" + error);
- }
- if (const auto r = engine->openAudioInput (inputName.isNotEmpty() ? inputName : deviceName); r.issue != lynx::AudioEngine::InputIssue::none)
- step ("input_error=" + juce::String ((int) r.issue) + " " + r.detail);
- // takes go next to the report, not into the user's recordings folder
- engine->setRecordingTarget (report.getSiblingFile (report.getFileNameWithoutExtension() + "-takes"), {});
- auto* device = devices.getCurrentAudioDevice();
- if (device == nullptr || engine->getInputChannelNames().empty())
- {
- step ("result=ERROR no device / no input");
- finish (1);
- return;
- }
- const auto rate = device->getCurrentSampleRate();
- step ("device=" + device->getTypeName() + " | " + device->getName() + " | " + juce::String (rate) + " Hz | block " + juce::String (device->getCurrentBufferSizeSamples())
- + " | driver latency in " + juce::String (device->getInputLatencyInSamples()) + " out " + juce::String (device->getOutputLatencyInSamples()));
- // a click (the ping's pulse) on every beat at 120 bpm: beat k at sample k * rate / 2
- const auto beats = (int) std::ceil (seconds * 2.0) + 8;
- const auto clickFile = report.getSiblingFile (report.getFileNameWithoutExtension() + "-clicks.wav");
- {
- lynx::takes::WavTakeWriter w;
- w.open (clickFile.getFullPathName().toStdString(), rate, 1, lynx::takes::SampleFormat::float32);
- const auto total = (juce::int64) std::llround ((double) beats * rate / 2.0);
- std::vector<float> block (4096);
- for (juce::int64 at = 0; at < total; at += (juce::int64) block.size())
- {
- std::fill (block.begin(), block.end(), 0.0f);
- for (int k = 0; k < (int) block.size(); ++k)
- {
- const auto f = at + k;
- const auto beat = (juce::int64) std::floor ((double) f / (rate / 2.0));
- const auto rel = f - (juce::int64) std::llround ((double) beat * rate / 2.0);
- static constexpr float shape[] { 0.25f, 0.75f, 1.0f, 0.75f, 0.25f };
- if (rel >= 0 && rel < 5)
- block[(std::size_t) k] = 0.5f * shape[rel];
- }
- const float* d[] { block.data() };
- w.write (d, (int) std::min<juce::int64> ((juce::int64) block.size(), total - at));
- }
- w.close();
- }
- lynx::Song song = lynx::Song::makeDefault();
- song.bpm = 120.0;
- song.mode = lynx::PlayMode::song;
- song.playlist.clear();
- lynx::ChannelDef c;
- c.name = "Clicks";
- c.instrument = lynx::InstrumentKind::audioClip;
- c.samplePath = clickFile.getFullPathName().toStdString();
- c.mixerTrack = 0;
- c.volume = 1.0f;
- song.channels.push_back (c);
- lynx::Clip clip;
- clip.kind = lynx::ClipKind::audio;
- clip.channel = (int) song.channels.size() - 1;
- clip.track = 0;
- clip.start = 0;
- clip.length = (std::int64_t) beats * lynx::ppq;
- song.playlist.push_back (clip);
- if (mode == 1) // loop recording, bars 2-4
- {
- song.loopStart = 4 * lynx::ppq;
- song.loopEnd = 16 * lynx::ppq;
- }
- else if (mode == 2) // punch in/out, bars 3-4
- {
- song.loopStart = 8 * lynx::ppq;
- song.loopEnd = 16 * lynx::ppq;
- }
- if (song.mixer.size() > 1)
- {
- song.mixer[1].name = "Loop In";
- song.mixer[1].monitor = lynx::InputMonitor::off; // (the loopback must not hear itself)
- }
- engine->setSong (std::move (song));
- engine->setInsertInput (1, 0, false);
- juce::ignoreUnused (pdcSamples);
- // 1) the ping
- if (const auto error = engine->startLatencyPing(); error.isNotEmpty())
- step ("ping_error=" + error);
- juce::Timer::callAfterDelay (3500, [this, step, finish, seconds, rate, report, mode] {
- if (engine == nullptr)
- return;
- if (engine->isPinging())
- engine->cancelLatencyPing();
- const auto r = engine->finishLatencyPing();
- step ("ping=" + juce::String (r.ok ? "ok" : "FAILED " + juce::String (r.problem)) + " samples " + juce::String (r.samples) + " spread " + juce::String (r.spread)
- + " found " + juce::String (r.found) + "/" + juce::String (r.sent) + " peak " + juce::String (juce::Decibels::gainToDecibels (r.peak, -150.0f), 1) + " dB");
- const auto l = engine->currentLatency();
- step ("compensation=" + juce::String (l.total()) + " (round trip " + juce::String (l.roundTrip()) + ", manual " + juce::String (l.manual) + ", pdc " + juce::String (l.pdc) + ")");
- // 2) record
- engine->setInsertArmed (1, true);
- auto o = engine->getRecordOptions();
- o.recordAudio = true;
- o.countInBars = 0;
- o.waitForInput = false;
- o.punchLoopRegion = mode == 2;
- o.preRollBars = mode == 2 ? 1 : 0;
- o.postRollBars = mode == 2 ? 1 : 0;
- engine->setRecordOptions (o);
- engine->stop();
- engine->rewind();
- engine->setRecording (true);
- juce::Timer::callAfterDelay (300, [this, step, finish, seconds, rate, report, mode] {
- if (engine == nullptr)
- return;
- engine->startPlayback(); // (as the Play button: pre-roll / punch)
- juce::Timer::callAfterDelay ((int) (seconds * 1000.0), [this, step, finish, seconds, rate, report, mode] {
- if (engine == nullptr)
- return;
- if (mode == 2)
- step (juce::String ("stopped_by_post_roll=") + (engine->getTransport().playing.load() ? "no" : "yes"));
- engine->stop();
- juce::Timer::callAfterDelay (500, [this, step, finish, seconds, rate, report, mode] {
- if (engine == nullptr)
- return;
- engine->setRecording (false);
- const auto& s = engine->getSong();
- const auto tps = 120.0 * lynx::ppq / (60.0 * rate);
- int take = -1;
- for (int ch = 0; ch < (int) s.channels.size(); ++ch)
- if (s.channels[(std::size_t) ch].instrument == lynx::InstrumentKind::audioClip && s.channels[(std::size_t) ch].name != "Clicks")
- take = ch;
- if (take < 0)
- {
- step ("result=ERROR no take (" + engine->getLastRecordingError() + ")");
- finish (1);
- return;
- }
- std::vector<std::vector<float>> audio;
- double takeRate = 0.0;
- const auto& path = s.channels[(std::size_t) take].samplePath;
- lynx::takes::readWav (path, audio, &takeRate);
- const auto frames = audio.empty() ? (juce::int64) 0 : (juce::int64) audio[0].size();
- step ("take=" + juce::String::fromUTF8 (path.c_str()) + " frames " + juce::String (frames) + " (" + juce::String ((double) frames / rate, 3)
- + " s of " + juce::String (seconds, 1) + " s played) lost " + juce::String (engine->getLostRecordingFrames()));
- // the clicks in the file (peaks above -12 dBFS, one per 1/8 s at most)
- std::vector<juce::int64> peaks;
- if (! audio.empty())
- for (juce::int64 f = 1; f + 1 < frames; ++f)
- {
- const auto x = std::abs (audio[0][(std::size_t) f]);
- if (x > 0.25f && x >= std::abs (audio[0][(std::size_t) f - 1]) && x > std::abs (audio[0][(std::size_t) f + 1])
- && (peaks.empty() || f - peaks.back() > (juce::int64) (rate / 8)))
- peaks.push_back (f);
- }
- // every clip of the take: each click inside it against the nearest beat
- int clips = 0, checked = 0, muted = 0;
- double worst = 0.0, sum = 0.0;
- for (const auto& c : s.playlist)
- {
- if (c.kind != lynx::ClipKind::audio || c.channel != take)
- continue;
- ++clips;
- muted += c.muted ? 1 : 0;
- const auto skip = ((double) c.offset + (double) c.offsetFraction) / tps; // file samples before the clip start
- for (const auto f : peaks)
- {
- const auto intoClip = (double) f - skip;
- if (intoClip < 0.0 || intoClip * tps >= (double) c.length)
- continue;
- const auto songTick = (double) c.start + intoClip * tps - 2.0 * tps; // (the pulse's peak is its 3rd sample)
- const auto beat = std::round (songTick / lynx::ppq) * lynx::ppq;
- const auto error = (songTick - beat) / tps;
- worst = std::max (worst, std::abs (error));
- sum += error;
- ++checked;
- }
- step ("clip track " + juce::String (c.track) + " start " + juce::String ((juce::int64) c.start) + " length " + juce::String ((juce::int64) c.length)
- + " offset " + juce::String ((juce::int64) c.offset) + juce::String (c.offsetFraction >= 0.0f ? "+" : "") + juce::String (c.offsetFraction, 4)
- + (c.muted ? " (muted lane)" : ""));
- }
- step ("clicks_in_file=" + juce::String ((int) peaks.size()) + " checked=" + juce::String (checked) + " clips=" + juce::String (clips)
- + " muted_lanes=" + juce::String (muted));
- step ("placement_error_samples=max " + juce::String (worst, 3) + " mean " + juce::String (checked > 0 ? sum / checked : 0.0, 3));
- auto ok = checked > 0 && worst <= 1.0 && engine->getLostRecordingFrames() == 0;
- if (mode == 2) // one clip, exactly the punch range, its 8 beats
- {
- const auto& sp = engine->getSong();
- bool exact = false;
- for (const auto& c : sp.playlist)
- if (c.kind == lynx::ClipKind::audio && c.channel == take)
- exact = c.start == sp.loopStart && c.start + c.length == sp.loopEnd;
- step (juce::String ("punch_clip_matches_range=") + (exact ? "yes" : "no"));
- ok = ok && clips == 1 && exact && checked == 8;
- }
- step (juce::String ("result=") + (ok ? "OK" : "FAILED"));
- finish (ok ? 0 : 1);
- });
- });
- });
- });
- }
- // --hwinserttest (round 164d): see the command line above.
- void runHwInsertTest (const juce::File& report, double seconds, const juce::String& deviceType, const juce::String& deviceName,
- const juce::String& inputName, int bufferSize, bool inPatcher = false, juce::File bounceFile = {})
- {
- engine = std::make_unique<lynx::AudioEngine>();
- lynx::videoview::install (*engine); // (Fruity Video Player channels: their sound tracks)
- savedDeviceState = engine->getDeviceManager().createStateXml();
- auto text = std::make_shared<juce::String>();
- auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
- auto finish = [this] (int code) {
- if (engine != nullptr)
- engine->getMeters().capture.setSource (lynx::AudioCapture::off);
- restoreSavedDeviceState();
- setApplicationReturnValue (code);
- quit();
- };
- auto& devices = engine->getDeviceManager();
- if (deviceType.isNotEmpty() && devices.getCurrentAudioDeviceType() != deviceType)
- devices.setCurrentAudioDeviceType (deviceType, true);
- {
- auto setup = devices.getAudioDeviceSetup();
- if (deviceName.isNotEmpty())
- setup.outputDeviceName = deviceName;
- if (bufferSize > 0)
- setup.bufferSize = bufferSize;
- if (const auto error = devices.setAudioDeviceSetup (setup, true); error.isNotEmpty())
- step ("device_error=" + error);
- }
- if (const auto r = engine->openAudioInput (inputName.isNotEmpty() ? inputName : deviceName); r.issue != lynx::AudioEngine::InputIssue::none)
- step ("input_error=" + juce::String ((int) r.issue) + " " + r.detail);
- auto* device = devices.getCurrentAudioDevice();
- if (device == nullptr || engine->getInputChannelNames().empty())
- {
- step ("result=ERROR no device / no input");
- finish (1);
- return;
- }
- const auto rate = device->getCurrentSampleRate();
- step ("device=" + device->getTypeName() + " | " + device->getName() + " | " + juce::String (rate) + " Hz | block " + juce::String (device->getCurrentBufferSizeSamples()));
- // the click track: the ping's pulse on every beat at 120 bpm
- const auto beats = (int) std::ceil (seconds * 2.0) + 8;
- const auto clickFile = report.getSiblingFile (report.getFileNameWithoutExtension() + "-clicks.wav");
- {
- lynx::takes::WavTakeWriter w;
- w.open (clickFile.getFullPathName().toStdString(), rate, 1, lynx::takes::SampleFormat::float32);
- const auto total = (juce::int64) std::llround ((double) beats * rate / 2.0);
- std::vector<float> block (4096);
- for (juce::int64 at = 0; at < total; at += (juce::int64) block.size())
- {
- std::fill (block.begin(), block.end(), 0.0f);
- for (int k = 0; k < (int) block.size(); ++k)
- {
- const auto f = at + k;
- const auto beat = (juce::int64) std::floor ((double) f / (rate / 2.0));
- const auto rel = f - (juce::int64) std::llround ((double) beat * rate / 2.0);
- static constexpr float shape[] { 0.25f, 0.75f, 1.0f, 0.75f, 0.25f };
- if (rel >= 0 && rel < 5)
- block[(std::size_t) k] = 0.5f * shape[rel];
- }
- const float* d[] { block.data() };
- w.write (d, (int) std::min<juce::int64> ((juce::int64) block.size(), total - at));
- }
- w.close();
- }
- lynx::Song song = lynx::Song::makeDefault();
- song.bpm = 120.0;
- song.mode = lynx::PlayMode::song;
- song.playlist.clear();
- song.channels.clear();
- for (int k = 0; k < 2; ++k)
- {
- lynx::ChannelDef c;
- c.name = k == 0 ? "Wet" : "Dry";
- c.instrument = lynx::InstrumentKind::audioClip;
- c.samplePath = clickFile.getFullPathName().toStdString();
- c.mixerTrack = k + 1;
- c.volume = 1.0f;
- song.channels.push_back (c);
- lynx::Clip clip;
- clip.kind = lynx::ClipKind::audio;
- clip.channel = k;
- clip.track = k;
- clip.start = 0;
- clip.length = (std::int64_t) beats * lynx::ppq;
- song.playlist.push_back (clip);
- }
- song.mixer[0].outputChannel = lynx::outputNone; // (the cable carries the send only)
- for (auto& fx : song.mixer[0].effects) // (no Master effects: the default limiter's PDC would hide nothing, but keep it plain)
- fx.enabled = false;
- song.mixer[1].pan = -1.0f;
- song.mixer[2].pan = 1.0f;
- auto hw = lynx::makeEffectSlot (lynx::EffectKind::hardwareInsert);
- hw.params[lynx::hwinsert::output] = lynx::hwinsert::channelValue (0);
- hw.params[lynx::hwinsert::input] = lynx::hwinsert::channelValue (0);
- hw.params[lynx::hwinsert::inputStereo] = 1.0f;
- song.mixer[1].effects.clear();
- lynx::AudioEngine::HardwareInsertRef ref { false, 1, 0, {} };
- if (inPatcher) // (round 165c) From LYNX -> Hardware Insert -> To LYNX
- {
- auto slot = lynx::makeEffectSlot (lynx::EffectKind::patcher);
- lynx::PatchNode node;
- node.effect = hw;
- slot.patcher.nodes = { node };
- lynx::PatchWire in, out;
- in.from = lynx::patchFromHost;
- in.to = 0;
- out.from = 0;
- out.to = lynx::patchToHost;
- slot.patcher.wires = { in, out };
- song.mixer[1].effects.push_back (slot);
- ref.nodes = { 0 };
- }
- else
- song.mixer[1].effects.push_back (hw);
- engine->setSong (std::move (song));
- step (juce::String ("insert=") + (inPatcher ? "inside a Patcher on Insert 1" : "Insert 1 slot 1"));
- const auto meter = [this, ref] (int output) {
- const auto fx = engine->runningHardwareInsert (ref);
- return fx != nullptr ? fx->controlOutput (output) : 0.0f;
- };
- // 1) the insert's ping (as its Ping button: a momentary value flipped)
- juce::Timer::callAfterDelay (500, [this, report, step, finish, seconds, rate, meter, ref, inPatcher, bounceFile] {
- if (engine == nullptr)
- return;
- engine->pingHardwareInserts ({ ref });
- juce::Timer::callAfterDelay (3500, [this, report, step, finish, seconds, rate, meter, ref, inPatcher, bounceFile] {
- if (engine == nullptr)
- return;
- // (round 165c) the engine makes a ping's result the slot's round trip with the device setup it belongs to; the
- // new round trip rebuilds the insert (its latency), so the result is read from the slot
- const auto* slot = lynx::AudioEngine::locateHardwareInsert (const_cast<lynx::Song&> (engine->getSong()), ref);
- const auto samples = slot != nullptr ? lynx::hwinsert::roundTripOf (slot->params[lynx::hwinsert::roundTrip]) : 0;
- const auto setup = slot != nullptr ? lynx::hwinsert::measuredSetup (*slot) : std::string();
- const auto state = meter (lynx::hwinsert::pingState);
- const auto ok = samples > 0 && setup == engine->currentSetupKey();
- step ("ping_round_trip=" + juce::String (samples) + " measured_setup=" + juce::String (setup) + (ok ? " (ok)" : " (FAILED)")
- + " live_ping_state=" + juce::String (state, 3) + " status_flags=" + juce::String (juce::roundToInt (meter (lynx::hwinsert::status) * 16.0f)));
- if (! ok)
- {
- step ("result=FAILED ping");
- finish (1);
- return;
- }
- // a stale setup is noticed: another setup key on the slot gives the notice, the real one none
- step ("stale_now=" + juce::String ((int) engine->staleHardwareInserts().size()));
- // 2) play, capturing the Master
- juce::Timer::callAfterDelay (500, [this, report, step, finish, seconds, rate, samples, ref, inPatcher, bounceFile] {
- if (engine == nullptr)
- return;
- step ("pdc_total=" + juce::String (engine->getLatencySamples()) + " (expected " + juce::String (samples) + ")");
- // saved in the project: the slot comes back the same (routing, round trip), and its latency with it — also an
- // odd round trip (12345 samples: the project keeps it to the sample)
- if (! inPatcher)
- {
- auto odd = engine->getSong();
- odd.mixer[1].effects[0].params[lynx::hwinsert::roundTrip] = lynx::hwinsert::roundTripValue (12345);
- juce::String error;
- auto same = true;
- for (const auto* song : { &engine->getSong(), (const lynx::Song*) &odd })
- {
- const auto file = report.getSiblingFile (report.getFileNameWithoutExtension() + (song == &odd ? "-odd.lynx" : ".lynx"));
- const auto saved = lynx::ProjectFile::save (*song, file, error);
- const auto loaded = saved ? lynx::ProjectFile::load (file, error) : std::nullopt;
- same = same && loaded && loaded->mixer.size() > 1 && ! loaded->mixer[1].effects.empty()
- && loaded->mixer[1].effects[0].kind == lynx::EffectKind::hardwareInsert
- && loaded->mixer[1].effects[0].params == song->mixer[1].effects[0].params
- && lynx::makeEffect (loaded->mixer[1].effects[0])->latencySamples() == (song == &odd ? 12345 : samples);
- }
- const auto file = report.getSiblingFile (report.getFileNameWithoutExtension() + ".lynx");
- step (juce::String ("project_round_trip=") + (same ? "same" : "DIFFERENT " + error) + " (" + file.getFileName() + ")");
- if (! same)
- {
- step ("result=FAILED project");
- finish (1);
- return;
- }
- }
- auto left = std::make_shared<std::vector<float>>(), right = std::make_shared<std::vector<float>>();
- engine->stop();
- engine->rewind();
- engine->getMeters().capture.setSource (0);
- engine->play();
- auto pulls = std::make_shared<int> ((int) (seconds * 5.0));
- auto pull = std::make_shared<std::function<void()>>();
- *pull = [this, report, step, finish, seconds, rate, samples, left, right, pulls, pull, ref, inPatcher, bounceFile] {
- if (engine == nullptr)
- return;
- engine->getMeters().capture.pull (*left, *right);
- if (*pulls == 10) // the insert's editor while it plays (next to the report)
- for (const auto scale : { 1.0f, 1.5f })
- {
- auto editor = inPatcher ? lynx::makeNodeEffectEditor (
- *engine, [ref] (lynx::Song& s) { return lynx::AudioEngine::locateHardwareInsert (s, ref); },
- [this, ref] { return engine->runningHardwareInsert (ref); }, "Insert 1 (Patcher)", scale)
- : lynx::makeNativeEffectEditor (*engine, 1, 0, scale, 0);
- juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
- {
- juce::Graphics g (image);
- g.fillAll (lynx::theme::panel);
- editor->paintEntireComponent (g, false);
- }
- const auto file = report.getSiblingFile (report.getFileNameWithoutExtension() + (scale > 1.0f ? "-editor150.png" : "-editor.png"));
- file.deleteFile();
- juce::PNGImageFormat png;
- if (auto stream = file.createOutputStream())
- png.writeImageToStream (image, *stream);
- }
- if (--*pulls > 0)
- {
- juce::Timer::callAfterDelay (200, *pull);
- return;
- }
- engine->stop();
- const auto dropped = engine->getMeters().capture.droppedFrames();
- engine->getMeters().capture.setSource (lynx::AudioCapture::off);
- // the clicks of each side (peaks above -12 dBFS, one per 1/8 s at most)
- auto peaksOf = [rate] (const std::vector<float>& x) {
- std::vector<juce::int64> peaks;
- for (std::size_t f = 1; f + 1 < x.size(); ++f)
- 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])
- && (peaks.empty() || (juce::int64) f - peaks.back() > (juce::int64) (rate / 8)))
- peaks.push_back ((juce::int64) f);
- return peaks;
- };
- const auto wet = peaksOf (*left), dry = peaksOf (*right);
- int pairs = 0;
- juce::int64 worst = 0;
- double gainSum = 0.0, residual = 0.0, energy = 0.0;
- for (const auto w : wet)
- {
- 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); });
- if (best == dry.end() || std::abs (*best - w) > (juce::int64) (rate / 8))
- continue;
- ++pairs;
- worst = std::max (worst, std::abs (*best - w));
- gainSum += (*left)[(std::size_t) w] / (*right)[(std::size_t) *best];
- }
- const auto gain = pairs > 0 ? gainSum / pairs : 1.0;
- // dry clicks with no wet click beside them (a dropout of the cable / device), listed
- juce::String unmatched;
- for (const auto d : dry)
- if (std::none_of (wet.begin(), wet.end(), [d, rate] (juce::int64 w) { return std::abs (w - d) <= (juce::int64) (rate / 8); }))
- unmatched << " " << (juce::int64) d << " (" << juce::String ((*left)[(std::size_t) d], 3) << ")";
- if (unmatched.isNotEmpty())
- step ("dry_clicks_without_wet=" + unmatched);
- // the null test: left − gain · right around each click (both sides aligned → only the cable's colour remains)
- for (const auto w : wet)
- for (juce::int64 f = std::max<juce::int64> (0, w - 16); f < std::min<juce::int64> ((juce::int64) left->size(), w + 16); ++f)
- {
- const auto d = (double) (*left)[(std::size_t) f] - gain * (double) (*right)[(std::size_t) f];
- residual += d * d;
- energy += (double) (*left)[(std::size_t) f] * (*left)[(std::size_t) f];
- }
- const auto nullDb = energy > 0.0 ? 10.0 * std::log10 (std::max (1e-30, residual / energy)) : 0.0;
- step ("captured=" + juce::String ((int) left->size()) + " frames dropped=" + juce::String (dropped) + " wet_clicks=" + juce::String ((int) wet.size())
- + " dry_clicks=" + juce::String ((int) dry.size()) + " pairs=" + juce::String (pairs));
- step ("alignment_error_samples=max " + juce::String ((int) worst) + " cable_gain=" + juce::String (gain, 4) + " null_residual_db=" + juce::String (nullDb, 1));
- auto* dev = engine->getDeviceManager().getCurrentAudioDevice();
- const auto xruns = dev != nullptr ? dev->getXRunCount() : -1;
- step ("device_xruns=" + juce::String (xruns) + " (a dropout loses what was on the cable then: its clicks are excused)");
- const auto excused = xruns > 0 ? 2 * xruns : 0;
- const auto ok = pairs >= (int) (seconds * 2.0) - 2 - excused && worst == 0 && dropped == 0 && engine->getLatencySamples() == samples;
- step (juce::String ("result=") + (ok ? "OK" : "FAILED"));
- // (round 165c) then the re-ping notice after a buffer size change
- auto then = [this, ref, step, finish] (int code) {
- if (code != 0)
- finish (code);
- else
- runRepingCheck (ref, step, finish);
- };
- if (! ok)
- {
- finish (1);
- return;
- }
- if (bounceFile == juce::File())
- then (0);
- else
- runBounceCheck (bounceFile, step, then);
- };
- juce::Timer::callAfterDelay (200, *pull);
- });
- });
- });
- }
- // --hwinserttest --bounce (round 165c): Export › "Render through the hardware in real time" of the test song next to
- // the offline export of the same song. Through the loopback cable (gain 1) the return is the send delayed by the
- // pinged round trip, so the real-time file must equal the offline one (which passes the dry signal at that delay)
- // to float rounding, with the wet clicks (left) on the dry clicks' samples (right).
- // --hwinserttest (round 165c): the buffer size changes (another round trip on the device): the engine notices the
- // insert measured for the old setup (the app's "Ping now?" prompt), "Ping now" measures it again for the new one
- void runRepingCheck (lynx::AudioEngine::HardwareInsertRef ref, std::function<void (const juce::String&)> step, std::function<void (int)> finish)
- {
- auto& devices = engine->getDeviceManager();
- auto setup = devices.getAudioDeviceSetup();
- const auto before = setup.bufferSize;
- setup.bufferSize = before == 512 ? 256 : 512;
- if (const auto error = devices.setAudioDeviceSetup (setup, true); error.isNotEmpty())
- step ("reping_device_error=" + error);
- engine->takeHardwareInsertNotice(); // (whatever was pending before the change)
- juce::Timer::callAfterDelay (1500, [this, ref, step, finish, before] {
- if (engine == nullptr)
- return;
- auto* device = engine->getDeviceManager().getCurrentAudioDevice();
- const auto block = device != nullptr ? device->getCurrentBufferSizeSamples() : 0;
- const auto notice = engine->takeHardwareInsertNotice();
- step ("reping_buffer=" + juce::String (before) + "->" + juce::String (block) + " notice=" + juce::String ((int) notice.size())
- + " stale=" + juce::String ((int) engine->staleHardwareInserts().size()));
- if (notice.size() != 1 || ! (notice[0] == ref))
- {
- step ("result_reping=FAILED (no notice)");
- finish (1);
- return;
- }
- engine->pingHardwareInserts (notice); // ("Ping now")
- juce::Timer::callAfterDelay (3500, [this, ref, step, finish, block] {
- if (engine == nullptr)
- return;
- const auto* slot = lynx::AudioEngine::locateHardwareInsert (const_cast<lynx::Song&> (engine->getSong()), ref);
- const auto samples = slot != nullptr ? lynx::hwinsert::roundTripOf (slot->params[lynx::hwinsert::roundTrip]) : 0;
- const auto stale = (int) engine->staleHardwareInserts().size();
- step ("reping_round_trip=" + juce::String (samples) + " pdc_total=" + juce::String (engine->getLatencySamples()) + " stale=" + juce::String (stale));
- const auto ok = stale == 0 && samples > 0 && engine->getLatencySamples() == samples;
- step (juce::String ("result_reping=") + (ok ? "OK" : "FAILED") + " (device block " + juce::String (block) + ")");
- finish (ok ? 0 : 1);
- });
- });
- }
- void runBounceCheck (const juce::File& bounceFile, std::function<void (const juce::String&)> step, std::function<void (int)> finish)
- {
- // the Export window as the user sees it with the real-time option ticked (next to the report)
- lynx::showExportDialog (*engine, bounceFile.getParentDirectory(), "bounce", 0);
- for (int k = 0; k < juce::TopLevelWindow::getNumTopLevelWindows(); ++k)
- if (auto* w = juce::TopLevelWindow::getTopLevelWindow (k))
- {
- std::function<juce::ToggleButton* (juce::Component&)> find = [&find] (juce::Component& c) -> juce::ToggleButton* {
- if (auto* t = dynamic_cast<juce::ToggleButton*> (&c); t != nullptr && t->getButtonText() == lynx::tr ("Render through the hardware in real time"))
- return t;
- for (auto* child : c.getChildren())
- if (auto* t = find (*child))
- return t;
- return nullptr;
- };
- if (auto* toggle = find (*w))
- {
- step (juce::String ("export_option_visible=") + (toggle->isVisible() ? "yes" : "NO"));
- toggle->setToggleState (true, juce::sendNotificationSync); // (calls its onClick, as a click)
- auto* c = dynamic_cast<juce::DocumentWindow*> (w) != nullptr ? static_cast<juce::DocumentWindow*> (w)->getContentComponent() : w;
- if (c != nullptr)
- {
- const auto file = bounceFile.getSiblingFile (bounceFile.getFileNameWithoutExtension() + "-export.png");
- file.deleteFile();
- juce::FileOutputStream out (file);
- juce::PNGImageFormat png;
- if (out.openedOk())
- png.writeImageToStream (c->createComponentSnapshot (c->getLocalBounds()), out);
- }
- delete w;
- break;
- }
- }
- lynx::exportopts::Options o;
- o.format = lynx::exportopts::Format::wav;
- o.wavBits = 32;
- o.dither = lynx::exportopts::DitherMode::none;
- o.tail = lynx::exportopts::TailMode::cut;
- o.range = lynx::exportopts::Range::song;
- o.trimPdc = true;
- o.hqAllPlugins = false;
- o.pluginWarmUp = false;
- const auto offlineFile = bounceFile.getSiblingFile (bounceFile.getFileNameWithoutExtension() + "-offline.wav");
- auto realtimeJob = std::make_shared<lynx::ExportJob> (*engine, o, bounceFile);
- o.sampleRate = engine->getTransport().sampleRate.load();
- auto offlineJob = std::make_shared<lynx::ExportJob> (engine->getSong(), o, offlineFile);
- struct Shared
- {
- std::atomic<int> done { 0 };
- bool okRealtime = false, okOffline = false;
- juce::String errorRealtime, errorOffline;
- double lastProgress = 0.0;
- double started = juce::Time::getMillisecondCounterHiRes();
- };
- auto shared = std::make_shared<Shared>();
- // (the jobs stay owned by the message thread's poll below: they are destroyed there)
- juce::Thread::launch ([rt = realtimeJob.get(), off = offlineJob.get(), shared] {
- shared->okRealtime = rt->run ([shared] (double p) { shared->lastProgress = p; return true; }, shared->errorRealtime);
- shared->okOffline = off->run ({}, shared->errorOffline);
- shared->done.store (1);
- });
- auto poll = std::make_shared<std::function<void()>>();
- *poll = [this, poll, shared, realtimeJob, offlineJob, bounceFile, offlineFile, step, finish] {
- if (shared->done.load() == 0)
- {
- juce::Timer::callAfterDelay (100, *poll);
- return;
- }
- const auto seconds = (juce::Time::getMillisecondCounterHiRes() - shared->started) / 1000.0;
- step ("bounce_realtime=" + juce::String (shared->okRealtime ? "ok" : "FAILED " + shared->errorRealtime) + " offline="
- + juce::String (shared->okOffline ? "ok" : "FAILED " + shared->errorOffline) + " took=" + juce::String (seconds, 1) + " s (music "
- + juce::String (realtimeJob->getMusicSeconds(), 1) + " s)" + (realtimeJob->getNotice().isNotEmpty() ? " notice=" + realtimeJob->getNotice() : juce::String()));
- juce::AudioFormatManager formats;
- formats.registerBasicFormats();
- std::unique_ptr<juce::AudioFormatReader> a (formats.createReaderFor (bounceFile)), b (formats.createReaderFor (offlineFile));
- if (! shared->okRealtime || ! shared->okOffline || a == nullptr || b == nullptr)
- {
- step ("result=FAILED bounce");
- finish (1);
- return;
- }
- const auto frames = (int) std::min (a->lengthInSamples, b->lengthInSamples);
- juce::AudioBuffer<float> x (2, frames), y (2, frames);
- a->read (&x, 0, frames, 0, true, true);
- b->read (&y, 0, frames, 0, true, true);
- double residual = 0.0, energy = 0.0, wetDry = 0.0;
- for (int ch = 0; ch < 2; ++ch)
- for (int i = 0; i < frames; ++i)
- {
- const double d = x.getSample (ch, i) - y.getSample (ch, i);
- residual += d * d;
- energy += (double) y.getSample (ch, i) * y.getSample (ch, i);
- }
- for (int i = 0; i < frames; ++i) // the wet side against the dry side of the real-time file
- wetDry += std::pow ((double) x.getSample (0, i) - x.getSample (1, i), 2.0);
- const auto db = [energy] (double r) { return energy > 0.0 ? 10.0 * std::log10 (std::max (1e-30, r / energy)) : 0.0; };
- step ("bounce_frames=" + juce::String ((juce::int64) a->lengthInSamples) + " offline_frames=" + juce::String ((juce::int64) b->lengthInSamples)
- + " rate=" + juce::String (a->sampleRate) + " bounce_vs_offline_db=" + juce::String (db (residual), 1)
- + " wet_vs_dry_db=" + juce::String (db (2.0 * wetDry), 1) + " peak=" + juce::String (realtimeJob->getPeak(), 3));
- const auto ok = std::abs (a->lengthInSamples - b->lengthInSamples) <= 1 && db (residual) < -100.0 && realtimeJob->getPeak() > 0.1f;
- step (juce::String ("result_bounce=") + (ok ? "OK" : "FAILED"));
- finish (ok ? 0 : 1);
- };
- juce::Timer::callAfterDelay (100, *poll);
- }
- // --rtstress --record: stops recording (the take becomes a clip of the song, as in the app), moves the take's WAV to
- // `target` and describes it: length against the time played, channels, peak, the latencies the driver reported.
- juce::String finishStressTake (const juce::File& target, double seconds)
- {
- juce::String text;
- auto* device = engine->getDeviceManager().getCurrentAudioDevice();
- text << " recording: input " << (device != nullptr ? device->getActiveInputChannels().countNumberOfSetBits() : 0) << " channel(s)";
- if (device != nullptr)
- text << ", input latency " << device->getInputLatencyInSamples() << " + output latency " << device->getOutputLatencyInSamples() << " samples";
- engine->setRecording (false); // closes the take: a clip of the song
- juce::File take;
- for (const auto& c : engine->getSong().channels)
- if (c.instrument == lynx::InstrumentKind::audioClip)
- take = juce::File (juce::String::fromUTF8 (c.samplePath.c_str()));
- if (! take.existsAsFile())
- return text + "\n recording: no take (" + engine->getLastRecordingError() + ")\n";
- target.deleteFile();
- if (! take.moveFileTo (target))
- take.copyFileTo (target);
- juce::AudioFormatManager formats;
- formats.registerBasicFormats();
- if (std::unique_ptr<juce::AudioFormatReader> reader (formats.createReaderFor (target)); reader != nullptr)
- {
- juce::AudioBuffer<float> audio ((int) reader->numChannels, (int) reader->lengthInSamples);
- reader->read (&audio, 0, (int) reader->lengthInSamples, 0, true, true);
- const auto peak = audio.getMagnitude (0, audio.getNumSamples());
- const auto length = (double) reader->lengthInSamples / reader->sampleRate;
- text << "\n recording: take " << juce::String (length, 3) << " s of " << juce::String (seconds, 0) << " s played, "
- << (int) reader->numChannels << " ch @ " << (int) reader->sampleRate << " Hz, peak "
- << juce::String (juce::Decibels::gainToDecibels (peak, -150.0f), 1) << " dBFS -> " << target.getFullPathName() << "\n";
- }
- else
- text << "\n recording: take unreadable (" << target.getFullPathName() << ")\n";
- return text;
- }
- // LYNX.exe --render project.(flp|lynx) output.wav [seconds]
- // Exports the current pattern to 24-bit WAV (for an imported .flp, the one with the most notes).
- void runRender (const juce::String& inputPath, const juce::String& outputPath, double seconds)
- {
- lynx::AudioEngine offline (false);
- const juce::File input (inputPath);
- juce::String error, report;
- bool ok = false;
- if (input.hasFileExtension ("flp;als"))
- ok = offline.importFlpFile (input, error);
- else if (auto song = lynx::ProjectFile::load (input, error))
- {
- offline.setSong (std::move (*song));
- ok = true;
- }
- int samplers = 0, samplersLoaded = 0;
- if (ok)
- {
- for (const auto& c : offline.getSong().channels)
- if (c.instrument == lynx::InstrumentKind::sampler || c.instrument == lynx::InstrumentKind::audioClip)
- {
- ++samplers;
- samplersLoaded += offline.getSampleLibrary().load (juce::String::fromUTF8 (c.samplePath.c_str())) != nullptr;
- }
- const juce::File output (outputPath);
- output.deleteFile();
- juce::WavAudioFormat wav;
- std::unique_ptr<juce::AudioFormatWriter> writer (
- wav.createWriterFor (output.createOutputStream().release(), 44100.0, 2, 24, {}, 0));
- if (writer == nullptr)
- {
- ok = false;
- error = lynx::utf8 ("could not create ") + outputPath;
- }
- else
- {
- const auto peak = offline.renderOffline (seconds > 0.0 ? seconds : 10.0, 44100.0, writer.get());
- report << "peak=" << peak << "\n";
- ok = peak > 0.001f;
- }
- }
- report << "samples=" << samplersLoaded << "/" << samplers << "\n"
- << "result=" << (ok ? "OK" : "ERROR " + error) << "\n";
- juce::File (outputPath + ".txt").replaceWithText (report);
- setApplicationReturnValue (ok ? 0 : 1);
- quit();
- }
- // LYNX.exe --export-flp project.(lynx|flp) output.(flp|zip) [--substitute] (round 171e): File › Export › FL Studio
- // project without the window (option A unless --substitute; the renders next to a .flp in "<name> audio"); the
- // report goes to output.txt
- void runFlExport (const juce::String& inputPath, const juce::String& outputPath, bool substitute)
- {
- juce::String error;
- bool ok = false;
- lynx::flstudio::Written written;
- {
- lynx::AudioEngine loader (false);
- const juce::File input (inputPath);
- if (input.hasFileExtension ("flp"))
- ok = loader.importFlpFile (input, error);
- else if (auto song = lynx::ProjectFile::load (input, error))
- {
- loader.setSong (std::move (*song));
- ok = true;
- }
- if (ok)
- {
- const juce::File output (outputPath);
- const auto zip = output.hasFileExtension ("zip");
- const auto mode = substitute ? lynx::flpexport::LynxOnly::substitute : lynx::flpexport::LynxOnly::renderAudio;
- loader.capturePluginStates();
- auto options = lynx::flstudio::optionsFor (&loader.getPluginHost(), mode, loader.getSong());
- // --flp-ppq N: the file's PPQ (tests; default: 96 when the notes and clips fit it)
- if (const auto args = juce::JUCEApplication::getCommandLineParameterArray(); args.contains ("--flp-ppq"))
- options.ppq = juce::jlimit (0, 960, args[args.indexOf ("--flp-ppq") + 1].getIntValue());
- const auto renderDir = zip ? juce::File::getSpecialLocation (juce::File::tempDirectory).getNonexistentChildFile ("LYNX FL export", {}, false)
- : output.getSiblingFile (output.getFileNameWithoutExtension() + " audio");
- ok = lynx::flstudio::exportProject (loader.getSong(), options, output, zip, renderDir, 44100.0,
- [] (const lynx::Song& s, const lynx::ExportSettings& settings, const juce::File& wav,
- const std::function<bool (double)>& progress, juce::String& err) {
- lynx::ExportJob job (s, settings, wav);
- return job.run (progress, err);
- },
- {}, written, error);
- if (zip)
- renderDir.deleteRecursively();
- }
- }
- juce::String report;
- report << (ok ? "ok" : "error=" + error) << "\n"
- << "exact=" << (int) written.report.exact.size() << " rendered=" << (int) written.report.rendered.size()
- << " substituted=" << (int) written.report.substituted.size() << " dropped=" << (int) written.report.dropped.size()
- << " samples=" << written.samples << "\n\n"
- << lynx::flstudio::reportText (written) << "\n";
- juce::File (outputPath + ".txt").replaceWithText (report);
- setApplicationReturnValue (ok ? 0 : 1);
- quit();
- }
- // LYNX.exe --export project.(flp|lynx) output.(wav|flac|ogg|mp3) [--pattern] [--insert N] [--rate N]
- // Same path as "Export" in the UI: the whole song (or the current pattern) with its tail.
- void runExport (const juce::String& inputPath, const juce::String& outputPath, bool patternOnly, int insert)
- {
- juce::String error, report;
- bool ok = false;
- const auto started = juce::Time::getMillisecondCounterHiRes();
- lynx::loadtrace::begin (inputPath.toStdString()); // phase times (round 112): report lines + load.log
- {
- lynx::AudioEngine loader (false);
- const juce::File input (inputPath);
- // --find-plugins: first the targeted scan opening the project in the app runs (its plugins not known yet)
- if (input.hasFileExtension ("flp") && juce::JUCEApplication::getCommandLineParameters().contains ("--find-plugins"))
- {
- juce::MemoryBlock data;
- if (input.loadFileAsData (data))
- try
- {
- const auto uses = lynx::flpForeignPlugins (flp::parseProject ({ static_cast<const std::uint8_t*> (data.getData()), data.getSize() }));
- auto& host = loader.getPluginHost();
- const auto listed = std::chrono::steady_clock::now();
- const auto files = host.filesToScanFor (uses);
- lynx::loadtrace::add ("plugin_scan_list", lynx::loadtrace::msSince (listed));
- report << "scanned=" << files.joinIntoString (";") << "\n";
- const auto scanned = std::chrono::steady_clock::now();
- host.scanFiles (files, {});
- lynx::loadtrace::add ("plugin_scan", lynx::loadtrace::msSince (scanned), files.size());
- }
- catch (const flp::Error&)
- {
- }
- }
- if (input.hasFileExtension ("flp"))
- ok = loader.importFlpFile (input, error);
- else if (auto song = lynx::ProjectFile::load (input, error))
- {
- loader.setSong (std::move (*song));
- ok = true;
- }
- if (ok)
- {
- const juce::File output (outputPath);
- lynx::ExportSettings settings;
- settings.wholeSong = ! patternOnly;
- settings.format = output.hasFileExtension ("flac") ? lynx::ExportSettings::Format::flac24
- : output.hasFileExtension ("ogg") ? lynx::ExportSettings::Format::ogg
- : lynx::ExportSettings::Format::wav24;
- // --insert N: only that insert's output (what "Render to audio" records)
- if (juce::JUCEApplication::getCommandLineParameters().contains ("--no-effects")
- || juce::JUCEApplication::getCommandLineParameters().contains ("--sem-efeitos")) // performance diagnostics; --sem-efeitos: legacy alias
- loader.editSong ([] (lynx::Song& s) {
- for (auto& t : s.mixer)
- t.effects.clear();
- }, false);
- if (juce::JUCEApplication::getCommandLineParameters().contains ("--no-automation")
- || juce::JUCEApplication::getCommandLineParameters().contains ("--sem-automacao")) // --sem-automacao: legacy alias
- loader.editSong ([] (lynx::Song& s) { s.automations.clear(); }, false);
- const auto loaded = juce::Time::getMillisecondCounterHiRes();
- // .mp3: the Export window's MP3 (320 kbps); everything else as before
- auto options = settings.toOptions();
- // --save-tempo: FL's "Tempo information" (acid chunk) on (round 167l: compare with FL's AcidBox render; --export)
- if (juce::JUCEApplication::getCommandLineParameters().contains ("--save-tempo"))
- options.saveTempo = true;
- // --no-warmup: the export's plugin warm-up off (round 155: compare the start of the file)
- if (juce::JUCEApplication::getCommandLineParameters().contains ("--no-warmup"))
- options.pluginWarmUp = false;
- // --rate N: render at another sample rate (round 157b: samples resampled as at a 48 kHz device)
- if (const auto args = juce::JUCEApplication::getCommandLineParameterArray(); args.contains ("--rate"))
- if (const auto rate = args[args.indexOf ("--rate") + 1].getDoubleValue(); rate >= 8000.0 && rate <= 384000.0)
- options.sampleRate = rate;
- if (output.hasFileExtension ("mp3"))
- {
- options.format = lynx::exportopts::Format::mp3;
- options.mp3Kbps = 320;
- }
- lynx::ExportJob job (insert > 0 ? lynx::makeBounceSong (loader.getSong(), insert) : loader.getSong(), options, output);
- job.setExtraData (true);
- const auto prepared = juce::Time::getMillisecondCounterHiRes();
- lynx::loadtrace::end();
- int lastPercent = -1;
- ok = job.run ([&lastPercent] (double p) {
- lastPercent = (int) (p * 100.0);
- return true;
- }, error);
- auto joined = [] (const std::map<std::string, int>& items) {
- juce::StringArray names;
- for (const auto& [name, count] : items)
- names.add (juce::String::fromUTF8 (name.c_str()) + "x" + juce::String (count));
- return names.joinIntoString (", ");
- };
- const auto& importReport = loader.getImportReport();
- report << "converted=" << joined (importReport.converted) << "\n"
- << "approximated=" << joined (importReport.approximated) << "\n"
- << "unsupported=" << joined (importReport.unsupported) << "\n"
- << "dropped_effects=" << joined (importReport.droppedEffects) << "\n"
- << "partial_effects=" << joined (importReport.partialEffects) << "\n"
- << "missing_samples=" << importReport.missingSamples << "\n";
- // third-party plugins: how each was found, or what plays in its place (diagnostics for level differences)
- for (const auto& line : loader.getMatchedPlugins())
- report << "plugin_found=" << line << "\n";
- for (const auto& m : loader.getMissingPluginDetails())
- report << "plugin_missing=" << juce::String::fromUTF8 (m.name.c_str()) << " -> "
- << juce::String::fromUTF8 (m.replacement.c_str()).replace ("{0}", juce::String::fromUTF8 (m.replacementArg.c_str())) << "\n";
- {
- const auto& song = loader.getSong();
- for (std::size_t t = 0; t < song.mixer.size(); ++t)
- {
- const auto& track = song.mixer[t];
- if (track.effects.empty() && track.sends.empty())
- continue;
- report << "insert " << (int) t << " vol=" << juce::String (track.volume / lynx::unityFader, 3)
- << (track.muted ? " muted" : "") << (track.toMaster ? "" : " noMaster");
- for (const auto& s : track.sends)
- report << " send>" << s.target << "@" << juce::String (s.level, 3);
- report << " |";
- for (const auto& fx : track.effects)
- report << " [" << (fx.kind == lynx::EffectKind::plugin ? juce::String::fromUTF8 (fx.plugin.name.c_str())
- : juce::String::fromUTF8 (lynx::effectInfo (fx.kind).name))
- << (fx.isSubstitute() ? " (substitute)" : "") << (fx.enabled ? "" : " off")
- << (fx.mix < 0.999f ? " mix=" + juce::String (fx.mix, 2) : juce::String()) << "]";
- report << "\n";
- }
- }
- report << juce::String (lynx::loadtrace::reportLines());
- lynx::PluginHost::settingsFolder().getChildFile ("load.log").replaceWithText (juce::String (lynx::loadtrace::table()));
- report << "open_ms=" << juce::roundToInt (loaded - started) << "\n"
- << "prepare_ms=" << juce::roundToInt (prepared - loaded) << "\n"
- << "render_ms=" << juce::roundToInt (juce::Time::getMillisecondCounterHiRes() - prepared) << "\n"
- << "graph_ms=" << juce::roundToInt (job.getEngine().getLastRenderStats().graphMs) << "\n"
- << "write_ms=" << juce::roundToInt (job.getEngine().getLastRenderStats().writeMs) << "\n"
- << "warmup_blocks=" << job.getEngine().getLastRenderStats().warmUp.blocks << "\n"
- << "warmup_ms=" << juce::roundToInt (job.getEngine().getLastRenderStats().warmUp.wallSeconds * 1000.0) << "\n"
- << "warmup_changes=" << job.getEngine().getLastRenderStats().warmUp.signatureChanges << "\n"
- << "warmup_timed_out=" << (job.getEngine().getLastRenderStats().warmUp.timedOut ? 1 : 0) << "\n"
- << "pdc_trim=" << job.getEngine().getLastRenderStats().trimmedSamples << "\n"
- << "song_seconds=" << job.getMusicSeconds() << "\n"
- << "peak=" << job.getPeak() << "\n"
- << "final_progress=" << lastPercent << "\n"
- << "bytes=" << output.getSize() << "\n";
- ok = ok && job.getPeak() > 0.001f;
- }
- }
- report << "result=" << (ok ? "OK" : "ERROR " + error) << "\n";
- juce::File (outputPath + ".txt").replaceWithText (report);
- setApplicationReturnValue (ok ? 0 : 1);
- quit();
- }
- // LYNX.exe --snapshot prefix [project]: draws the window off-screen and writes
- // prefix-rack.png, -pianoroll.png and -playlist.png (to check the UI without touching the screen).
- // --editorcpu: one editor after another; each phase runs 2 s to settle and 8 s measured
- struct EditorCpuRun final : juce::Timer
- {
- struct Case { lynx::EffectKind kind; const char* name; int type; bool demo; }; // type 0 native, 1 display-first, 2 Facet EQ
- std::vector<Case> cases;
- std::size_t at = 0;
- int phase = 0;
- double t0 = 0.0, c0 = 0.0;
- juce::String report;
- juce::File out;
- std::unique_ptr<lynx::AudioEngine> engine;
- std::unique_ptr<juce::DocumentWindow> window;
- std::function<void()> done;
- void start()
- {
- engine = std::make_unique<lynx::AudioEngine> (false);
- report << "editor\tmode\tcpu % of one core\n";
- open();
- startTimer (250);
- }
- void open()
- {
- window.reset();
- if (at >= cases.size()) { out.replaceWithText (report); stopTimer(); if (done) done(); return; }
- const auto& c = cases[at];
- lynx::Song song;
- song.mixer.resize (2);
- song.mixer[0].name = "Master";
- song.mixer[1].name = "Insert 1";
- song.mixer[1].effects.push_back (lynx::makeEffectSlot (c.kind));
- engine->setSong (std::move (song));
- engine->dispatchPendingMessages();
- lynx::setNativeEditorDemo (c.demo);
- auto editor = c.type == 1 ? lynx::makeProEditor (*engine, 1, 0, c.demo) : c.type == 2 ? lynx::makeFacetEqEditor (*engine, 1, 0, c.demo)
- : lynx::makeNativeEffectEditor (*engine, 1, 0, 1.0f, 0);
- window = std::make_unique<juce::DocumentWindow> (juce::String ("LYNX editor CPU - ") + c.name, lynx::theme::colour::bg1, 0);
- window->setUsingNativeTitleBar (true);
- window->setContentOwned (editor.release(), true);
- const auto area = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea;
- window->setTopLeftPosition (area.getRight() - window->getWidth() - 8, area.getBottom() - window->getHeight() - 8);
- window->setVisible (true);
- phase = 0;
- t0 = juce::Time::getMillisecondCounterHiRes();
- }
- void timerCallback() override
- {
- const auto now = juce::Time::getMillisecondCounterHiRes();
- if (phase == 0 && now - t0 > 2000.0) { phase = 1; t0 = now; c0 = lynx::processCpuSeconds(); return; }
- if (phase == 1 && now - t0 > 8000.0)
- {
- const auto cpu = (lynx::processCpuSeconds() - c0) / ((now - t0) * 0.001) * 100.0;
- const auto& c = cases[at];
- report << c.name << "\t" << (c.demo ? "animating" : "idle") << "\t" << juce::String (cpu, 2) << "\n";
- ++at;
- open();
- }
- }
- };
- std::unique_ptr<EditorCpuRun> editorCpu;
- void runEditorCpu (const juce::String& path)
- {
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- editorCpu = std::make_unique<EditorCpuRun>();
- editorCpu->out = juce::File (path);
- using K = lynx::EffectKind;
- for (const auto demo : { false, true })
- for (const auto& c : std::vector<EditorCpuRun::Case> { { K::facetEq, "Facet EQ", 2, demo }, { K::crestCompressor, "Crest Compressor", 1, demo },
- { K::apexLimiter, "Apex Limiter", 1, demo }, { K::prismMultiband, "Prism Multiband", 1, demo },
- { K::epochVerb, "Epoch Verb", 0, demo }, { K::glowLeveler, "Glow Leveler", 0, demo },
- { K::fruityLimiter, "Fruity Limiter", 0, demo }, { K::lynxTune, "LYNX Tune", 0, demo } })
- editorCpu->cases.push_back (c);
- editorCpu->done = [this] { juce::MessageManager::callAsync ([this] { editorCpu.reset(); quit(); }); };
- editorCpu->start();
- }
- void runParityShot (const juce::String& path, const juce::String& effectName, const juce::String& paramsFile)
- {
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- int kindIndex = -1;
- for (int k = 0; k <= (int) lynx::lastEffectKind; ++k)
- if (juce::String::fromUTF8 (lynx::effectInfo ((lynx::EffectKind) k).name).equalsIgnoreCase (effectName))
- kindIndex = k;
- if (kindIndex < 0)
- return;
- const auto kind = (lynx::EffectKind) kindIndex;
- auto fx = lynx::makeEffectSlot (kind);
- if (paramsFile.isNotEmpty())
- for (const auto& line : juce::StringArray::fromLines (juce::File (paramsFile).loadFileAsString()))
- {
- const auto t = juce::StringArray::fromTokens (line, " \t", "");
- const auto index = t.size() >= 2 ? t[0].getIntValue() : -1;
- if (index >= 0 && index < lynx::maxEffectParams)
- fx.params[(std::size_t) index] = t[1].getFloatValue();
- }
- lynx::AudioEngine offline (false);
- auto song = lynx::Song::makeDefault();
- song.mixer.resize (2);
- song.mixer[0].name = "Master";
- song.mixer[1].name = "Insert 1";
- song.mixer[1].effects.assign (1, fx);
- for (auto& c : song.channels)
- c.mixerTrack = 1;
- offline.setSong (std::move (song));
- offline.dispatchPendingMessages();
- const bool facet = kind == lynx::EffectKind::facetEq;
- // round tp172b4: the originals are pictured idle (nothing playing), so the display-first editors are too: no demo
- // history unless LYNX_PARITYSHOT_DEMO=1 asks for the running display
- const bool demoDisplay = juce::SystemStats::getEnvironmentVariable ("LYNX_PARITYSHOT_DEMO", {}) == "1";
- // (Ember in its Classic voicing: the Classic panel, as the mixer opens it)
- const bool pro = lynx::ProEditorWindows::handles (kind)
- && ! (kind == lynx::EffectKind::ember && fx.params[(std::size_t) lynx::mixsuite::ember::voicing] > 0.5f);
- auto editor = facet ? lynx::makeFacetEqEditor (offline, 1, 0, false)
- : pro ? lynx::makeProEditor (offline, 1, 0, demoDisplay) : lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
- if (editor == nullptr)
- return;
- if (! pro) // the demo song through the effect, the editor ticked 30 times a second of audio as its timer would
- {
- lynx::AudioEngine::RenderOptions o;
- o.seconds = 3.0;
- o.sampleRate = 48000.0;
- o.pluginWarmUp = false;
- int sinceTick = 0;
- o.capture = [&] (const float*, const float*, int n) {
- sinceTick += n;
- if (sinceTick < 1600) return;
- sinceTick = 0;
- if (facet) lynx::tickFacetEqEditor (*editor);
- else lynx::tickNativeEffectEditor (*editor);
- };
- offline.renderOffline (o);
- }
- juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
- {
- juce::Graphics g (image);
- g.fillAll (lynx::theme::panel);
- editor->paintEntireComponent (g, false);
- }
- const juce::File file (path);
- file.deleteFile();
- juce::PNGImageFormat png;
- if (auto stream = file.createOutputStream())
- png.writeImageToStream (image, *stream);
- }
- void runEq166fShots (const juce::String& folder)
- {
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- const juce::File out (folder);
- out.createDirectory();
- lynx::AudioEngine offline (false);
- auto save = [&] (juce::Component& editor, const juce::String& name) {
- juce::Image image (juce::Image::ARGB, editor.getWidth(), editor.getHeight(), true);
- {
- juce::Graphics g (image);
- g.fillAll (lynx::theme::panel);
- editor.paintEntireComponent (g, false);
- }
- const auto f = out.getChildFile (name);
- f.deleteFile();
- juce::PNGImageFormat png;
- if (auto stream = f.createOutputStream())
- png.writeImageToStream (image, *stream);
- };
- // a song whose demo beat plays into insert 1 (the source) and, for Facet's target, its other half into insert 2
- auto songWith = [] (const lynx::EffectSlot& fx, bool split) {
- auto song = lynx::Song::makeDefault();
- song.mixer.resize (3);
- song.mixer[0].name = "Master";
- song.mixer[1].name = "Vocal";
- song.mixer[2].name = "Reference mix";
- song.mixer[1].effects.assign (1, fx);
- for (std::size_t c = 0; c < song.channels.size(); ++c)
- song.channels[c].mixerTrack = split && c % 2 == 1 ? 2 : 1;
- return song;
- };
- auto feed = [&] (juce::Component& editor, bool facet, int frames) {
- // one continuous render of the song, the editor ticked 30 times a second of audio, as its timer would
- lynx::AudioEngine::RenderOptions o;
- o.seconds = frames / 30.0;
- o.sampleRate = 48000.0;
- o.pluginWarmUp = false;
- int sinceTick = 0;
- o.capture = [&] (const float*, const float*, int n) {
- sinceTick += n;
- if (sinceTick < 1600) return;
- sinceTick = 0;
- if (facet) lynx::tickFacetEqEditor (editor);
- else lynx::tickNativeEffectEditor (editor);
- };
- offline.renderOffline (o);
- if (facet) lynx::tickFacetEqEditor (editor);
- else lynx::tickNativeEffectEditor (editor);
- };
- // Parametric EQ 2: spectrum + heatmap (Full), flat / band 4 +12 dB / band 4 -12 dB, then the Top position
- auto& display = lynx::peqview::displaySettings();
- const auto kept = display;
- display.spectrum = display.heatmap = true;
- display.position = 0;
- 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" },
- { 0.0, "peq2-heatmap-top.png" } })
- {
- auto eq = lynx::makeEffectSlot (lynx::EffectKind::parametricEq);
- eq.params[(std::size_t) lynx::peq::param (3, 2)] = lynx::peq::gainValue (gain);
- eq.params[(std::size_t) lynx::peq::param (3, 1)] = lynx::peq::hzValue (900.0);
- display.position = juce::String (name).contains ("top") ? 1 : 0;
- offline.setSong (songWith (eq, false));
- offline.dispatchPendingMessages();
- auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.25f, 0);
- feed (*editor, false, 120);
- save (*editor, name);
- }
- display = kept;
- // Facet EQ's comparative EQ: listening to the target (insert 2) with its spectrum over the source's
- {
- using namespace lynx::facet;
- auto eq = lynx::makeEffectSlot (lynx::EffectKind::facetEq);
- eq.params[(std::size_t) param (0, 0)] = shapeValue (Shape::bell);
- eq.params[(std::size_t) param (0, 1)] = hzValue (250.0);
- eq.params[(std::size_t) param (0, 2)] = gainValue (-4.0);
- eq.params[(std::size_t) param (1, 0)] = shapeValue (Shape::highShelf);
- eq.params[(std::size_t) param (1, 1)] = hzValue (6000.0);
- eq.params[(std::size_t) param (1, 2)] = gainValue (3.0);
- eq.params[(std::size_t) analyzerParam] = analyzerValue (Analyzer::both);
- eq.sidechain = 2;
- for (const auto& [l, name] : { std::pair { Listen::target, "facet-compare-target.png" }, { Listen::eq, "facet-compare-eq.png" } })
- {
- eq.params[(std::size_t) listenParam] = listenValue (l);
- offline.setSong (songWith (eq, true));
- offline.dispatchPendingMessages();
- auto editor = lynx::makeFacetEqEditor (offline, 1, 0, false);
- feed (*editor, true, 90);
- save (*editor, name);
- }
- }
- }
- void runDesign168rShots (const juce::String& folder)
- {
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- const juce::File out (folder);
- out.createDirectory();
- lynx::AudioEngine offline (false);
- using K = lynx::EffectKind;
- for (const auto kind : { K::pitchCorrect, K::lovePhilter, K::peakController, K::spreader, K::fruityFastLP, K::flFrequencyShifter,
- K::flLowLifter, K::distructor, K::flBassBoost, K::flDelay1, K::fl7BandEq, K::flCenter, K::flPhaseInverter,
- K::eq, K::delay, K::reverb, K::limiter, K::filter, K::distortion, K::chorus, K::utility, K::lofi,
- K::crossover, K::pitchShift, K::freqShift, K::rhythmGain, K::volumeGate })
- {
- const auto& bank = lynx::presets::factory (kind);
- // Love Philter / Distructor play FL's state: their second picture is FL's default preset (when installed)
- std::optional<lynx::EffectSlot> flPreset;
- if (kind == K::lovePhilter || kind == K::distructor)
- {
- const auto roots = lynx::findFlStudioRoots();
- const auto file = juce::File (juce::String::fromUTF8 (roots.data.c_str()))
- .getChildFile ("Patches/Plugin presets/Effects")
- .getChildFile (kind == K::lovePhilter ? "Fruity Love Philter/Default.fst" : "Distructor/Default.fst");
- juce::MemoryBlock bytes;
- if (file.loadFileAsData (bytes))
- flPreset = lynx::effectFromFlPreset (std::vector<std::uint8_t> ((const std::uint8_t*) bytes.getData(),
- (const std::uint8_t*) bytes.getData() + bytes.getSize()));
- }
- for (int pass = 0; pass < (bank.empty() && ! flPreset ? 1 : 2); ++pass)
- {
- auto fx = lynx::makeEffectSlot (kind);
- if (pass == 1 && flPreset)
- fx = *flPreset;
- else if (pass == 1)
- {
- fx.params = lynx::presets::apply (kind, bank.front(), 120.0);
- fx.presetName = bank.front().name;
- }
- lynx::Song song;
- song.mixer.resize (2);
- song.mixer[0].name = "Master";
- song.mixer[1].name = "Insert 1";
- song.mixer[1].effects.push_back (fx);
- offline.setSong (std::move (song));
- offline.dispatchPendingMessages();
- const auto pages = juce::jmax (1, (int) lynx::plugui::layoutFor (kind).pages.size());
- for (const auto scale : { 1.0f, 2.0f })
- for (int page = 0; page < pages; ++page)
- {
- auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, scale, page);
- if (editor == nullptr)
- continue;
- juce::Image image (juce::Image::ARGB, juce::jmax (1, editor->getWidth()), juce::jmax (1, editor->getHeight()), true);
- {
- juce::Graphics g (image);
- g.fillAll (lynx::theme::panel);
- editor->paintEntireComponent (g, false);
- }
- // (FL's "Frequency Shifter" and LYNX's "Frequency shifter" differ only in case: FL editors get "FL ")
- const auto file = out.getChildFile ((lynx::plugui::hasFlLayout (kind) ? "FL " : "")
- + juce::String (lynx::effectInfo (kind).name).replaceCharacters ("/\\:", "---")
- + (pass == 1 ? "-preset" : "") + (page > 0 ? "-p" + juce::String (page + 1) : juce::String())
- + (scale > 1.5f ? "-200" : "-100") + ".png");
- file.deleteFile();
- juce::PNGImageFormat png;
- if (auto stream = file.createOutputStream())
- png.writeImageToStream (image, *stream);
- }
- }
- }
- }
- bool runInstrumentShots (const juce::File& folder, const juce::String& which, const juce::String& source)
- {
- folder.createDirectory();
- auto key = [] (juce::String n) { return n.toLowerCase().removeCharacters (" -!._"); };
- juce::StringArray wanted;
- wanted.addTokens (which, ",", "");
- auto ok = true;
- struct Shot
- {
- juce::String name;
- std::optional<lynx::ChannelDef> channel;
- };
- std::vector<Shot> shots;
- for (const auto& e : lynx::natives::instrumentEngines())
- {
- const auto name = key (e.name);
- const auto banked = which == "banks" && lynx::banks::hasBank (e.kind);
- if (! banked && ! wanted.contains (name))
- continue;
- auto channel = source == "fl" ? lynx::natives::makeChannel (e.kind, lynx::flStudioAccess())
- : lynx::banks::defaultChannel (e.kind, e.name);
- if (! channel)
- {
- std::fprintf (stderr, "%s: no %s channel\n", e.name, source.toRawUTF8());
- ok = false;
- continue;
- }
- shots.push_back ({ name, std::move (channel) });
- }
- // Autogun (round 169h): not in the Add menus (no preset files); FL's own render-test channel, either source
- if (wanted.contains ("autogun"))
- {
- if (auto channel = lynx::natives::autogunShotChannel (lynx::flStudioAccess()))
- shots.push_back ({ "autogun", std::move (channel) });
- else
- {
- std::fprintf (stderr, "Autogun: no channel (FL Studio's Render tests\\Autogun.flp)\n");
- ok = false;
- }
- }
- for (auto& shot : shots)
- {
- const auto& name = shot.name;
- auto& channel = shot.channel;
- lynx::AudioEngine offline (false);
- lynx::Song song;
- song.mixer = lynx::Song::defaultMixer (2);
- song.channels.push_back (*channel);
- song.patterns.emplace_back();
- {
- juce::String error; // the project too, so an older build can picture the same channel (--snapshot)
- lynx::ProjectFile::save (song, folder.getChildFile (name + "-" + source + ".lynx"), error);
- }
- offline.setSong (std::move (song));
- offline.dispatchPendingMessages();
- auto frame = lynx::makeChannelFrame (offline, 0, 0);
- if (frame == nullptr || frame->getWidth() <= 0)
- {
- ok = false;
- continue;
- }
- for (const auto scale : { 1.0f, 1.5f, 2.0f })
- {
- const auto file = folder.getChildFile (name + "-" + source + "-" + juce::String (juce::roundToInt (scale * 100)) + ".png");
- savePng (frame->createComponentSnapshot (frame->getLocalBounds(), true, scale), file.getFullPathName());
- std::printf ("%s %dx%d\n", file.getFullPathName().toRawUTF8(), frame->getWidth(), frame->getHeight());
- }
- // round 169h: the layout's other pages (Toxic's MIDI / Seq …), one shot each at 1.5×
- for (int page = 1; page < lynx::showChannelLayoutPage (*frame, -1); ++page)
- {
- lynx::showChannelLayoutPage (*frame, page);
- const auto file = folder.getChildFile (name + "-" + source + "-page" + juce::String (page) + "-150.png");
- savePng (frame->createComponentSnapshot (frame->getLocalBounds(), true, 1.5f), file.getFullPathName());
- std::printf ("%s\n", file.getFullPathName().toRawUTF8());
- }
- }
- return ok;
- }
- // --- round 170j: the pilot editors with their own art -------------------------------------------------
- struct ArtPilot
- {
- std::string file; // the art's name as a file name: "toxic-biohazard"
- bool instrument;
- lynx::InstrumentKind instrumentKind;
- lynx::EffectKind effectKind;
- lynx::skin::Style before; // the automatic style it had before the Themed style
- };
- static juce::StringArray& artOnly() // --artshot / --artgui: only these (file names), all when empty
- {
- static juce::StringArray only;
- return only;
- }
- // every plugin with art of its own (round 170j/170k): generators first, then effects; built from the art
- // registries, so a new theme is shot without touching this list
- static const std::vector<ArtPilot>& artPilots()
- {
- using I = lynx::InstrumentKind;
- using E = lynx::EffectKind;
- static const std::vector<ArtPilot> list = [] {
- std::vector<ArtPilot> all;
- auto slug = [] (lynx::skin::Art a) {
- return juce::String (lynx::skin::artName (a)).toLowerCase().replaceCharacters (" ", "-").removeCharacters ("!.()'").toStdString();
- };
- for (const auto& e : lynx::natives::instrumentEngines()) // (the engines' order first)
- if (const auto a = lynx::skin::artForInstrument (e.kind); a != lynx::skin::Art::none)
- all.push_back ({ slug (a), true, e.kind, E::reverb, lynx::skin::Style::neon });
- for (int k = 0; k <= (int) I::wavetraveller; ++k) // then every other kind with art (DrumSynth, Autogun, Wasp...)
- if (const auto a = lynx::skin::artForInstrument ((I) k); a != lynx::skin::Art::none)
- all.push_back ({ slug (a), true, (I) k, E::reverb, lynx::skin::Style::neon });
- for (int k = 0; k <= (int) lynx::lastEffectKind; ++k)
- if (const auto a = lynx::skin::artForEffect ((E) k); a != lynx::skin::Art::none)
- all.push_back ({ slug (a), false, I::synth, (E) k, lynx::skin::plainStyleFor (k) });
- std::vector<ArtPilot> kept;
- for (auto& p : all)
- if (artOnly().isEmpty() || artOnly().contains (juce::String (p.file)))
- if (std::none_of (kept.begin(), kept.end(), [&] (const ArtPilot& q) { return q.file == p.file; }))
- kept.push_back (p);
- return kept;
- }();
- return list;
- }
- // the song and the editor of a pilot (an instrument: the channel window on its Plugin tab)
- static std::unique_ptr<juce::Component> makeArtPilot (lynx::AudioEngine& engine, const ArtPilot& p)
- {
- lynx::Song song;
- song.mixer = lynx::Song::defaultMixer (2);
- if (p.instrument)
- {
- for (const auto& e : lynx::natives::instrumentEngines())
- if (e.kind == p.instrumentKind)
- {
- auto channel = lynx::natives::makeChannel (e.kind, lynx::flStudioAccess());
- if (! channel) channel = lynx::banks::defaultChannel (e.kind, e.name);
- if (! channel) return nullptr;
- song.channels.push_back (*channel);
- break;
- }
- if (song.channels.empty()) // a kind without an engine entry: its LYNX default, else an empty channel of that kind
- {
- const std::string name = lynx::skin::artName (lynx::skin::artForInstrument (p.instrumentKind));
- auto channel = lynx::banks::defaultChannel (p.instrumentKind, name);
- if (! channel)
- {
- channel = lynx::ChannelDef {};
- channel->instrument = p.instrumentKind;
- channel->name = name;
- }
- song.channels.push_back (*channel);
- }
- song.patterns.emplace_back();
- }
- else
- {
- song.mixer[1].effects.push_back (lynx::makeEffectSlot (p.effectKind));
- }
- engine.setSong (std::move (song));
- engine.dispatchPendingMessages();
- if (p.instrument) return lynx::makeChannelFrame (engine, 0, 0);
- if (p.effectKind == lynx::EffectKind::facetEq) return lynx::makeFacetEqEditor (engine, 1, 0, true);
- if (lynx::ProEditorWindows::handles (p.effectKind)) return lynx::makeProEditor (engine, 1, 0, true); // display-first editors, demo signal
- return lynx::makeNativeEffectEditor (engine, 1, 0, 1.0f, 0);
- }
- // "before": the style each pilot had (forced for its run); "after": automatic (the pilots are Themed)
- static void artPilotStyle (const ArtPilot& p, const juce::String& mode)
- {
- lynx::skin::setForcedStyle (mode == "before" ? (int) p.before : -1);
- lynx::skin::setArtMotion (mode != "still");
- }
- bool runArtShots (const juce::File& folder, bool before)
- {
- folder.createDirectory();
- auto ok = true;
- juce::String titles ("editor\tsize\twidth\tname width at the style's size\tbox\tsize used\tlines\tresult\n");
- for (const auto& p : artPilots())
- {
- artPilotStyle (p, before ? "before" : "after");
- lynx::AudioEngine offline (false);
- auto editor = makeArtPilot (offline, p);
- if (editor == nullptr || editor->getWidth() <= 0)
- {
- std::fprintf (stderr, "%s: no editor\n", p.file.c_str());
- ok = false;
- continue;
- }
- if (p.effectKind == lynx::EffectKind::facetEq) lynx::tickFacetEqEditor (*editor);
- // round 170k2: titles.tsv, how the header's name fitted (its width at the style's size, the box, the size used)
- auto fit = [&] (const juce::String& at) {
- const auto f = lynx::skin::lastTitleFit();
- if (f.have <= 0.0f) return; // no plugin header drawn (a generator's channel window)
- titles << juce::String (p.file) << "\t" << at << "\t" << editor->getWidth() << "\t" << juce::String (f.need, 1) << "\t" << juce::String (f.have, 1)
- << "\t" << juce::String (f.size, 1) << "\t" << f.lines << "\t" << (f.clipped ? "ELLIPSIS" : "full") << "\n";
- };
- for (const auto scale : { 1.0f, 2.0f })
- {
- const auto file = folder.getChildFile (juce::String (p.file) + "-" + (before ? "before" : "after") + "-" + juce::String (juce::roundToInt (scale * 100)) + ".png");
- lynx::skin::resetTitleFit();
- savePng (editor->createComponentSnapshot (editor->getLocalBounds(), true, scale), file.getFullPathName());
- std::printf ("%s %dx%d\n", file.getFullPathName().toRawUTF8(), editor->getWidth(), editor->getHeight());
- if (scale == 1.0f) fit ("100");
- }
- // ... and at the smallest size its window allows (effect panels; the Pro editors scale as a whole)
- if (const auto smallest = lynx::nativeEditorMinimumSize (*editor); smallest.x > 0)
- {
- editor->setSize (smallest.x, smallest.y);
- const auto file = folder.getChildFile (juce::String (p.file) + "-" + (before ? "before" : "after") + "-min.png");
- lynx::skin::resetTitleFit();
- savePng (editor->createComponentSnapshot (editor->getLocalBounds(), true, 1.0f), file.getFullPathName());
- fit ("min");
- }
- }
- folder.getChildFile (juce::String ("titles-") + (before ? "before" : "after") + ".tsv").replaceWithText (titles);
- lynx::skin::setForcedStyle (-1);
- return ok;
- }
- struct ArtGuiRun final : juce::Timer
- {
- juce::File folder;
- juce::String mode, report;
- std::size_t at = 0;
- int phase = 0;
- double t0 = 0.0, c0 = 0.0;
- std::unique_ptr<lynx::AudioEngine> engine;
- std::unique_ptr<juce::DocumentWindow> window;
- std::function<void()> done;
- void start()
- {
- engine = std::make_unique<lynx::AudioEngine> (false);
- report << "editor\tmode\tcpu % of one core\tart layer animating\n";
- open();
- startTimer (100);
- }
- void open()
- {
- window.reset();
- const auto& pilots = artPilots();
- if (at >= pilots.size())
- {
- folder.getChildFile ("cpu-" + mode + ".txt").replaceWithText (report);
- stopTimer();
- lynx::skin::setForcedStyle (-1);
- lynx::skin::setArtMotion (true);
- if (done) done();
- return;
- }
- const auto& p = pilots[at];
- artPilotStyle (p, mode);
- auto editor = makeArtPilot (*engine, p);
- if (editor == nullptr) { ++at; open(); return; }
- window = std::make_unique<juce::DocumentWindow> (juce::String ("LYNX art - ") + juce::String (p.file), lynx::theme::colour::bg1, 0);
- window->setUsingNativeTitleBar (true);
- window->setContentOwned (editor.release(), true);
- const auto area = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea;
- window->setTopLeftPosition (area.getX() + 24, area.getY() + 24);
- window->setAlwaysOnTop (true);
- window->setVisible (true);
- phase = 0;
- t0 = juce::Time::getMillisecondCounterHiRes();
- }
- bool animating() const
- {
- if (window == nullptr || window->getContentComponent() == nullptr) return false;
- std::function<bool (juce::Component&)> find = [&] (juce::Component& c) {
- if (auto* l = dynamic_cast<lynx::skin::ArtLayer*> (&c); l != nullptr && l->animating()) return true;
- for (auto* child : c.getChildren())
- if (find (*child)) return true;
- return false;
- };
- return find (*window->getContentComponent());
- }
- void timerCallback() override
- {
- const auto now = juce::Time::getMillisecondCounterHiRes();
- const auto& p = artPilots()[at];
- const auto ready = folder.getChildFile (juce::String (p.file) + "-" + mode + ".ready");
- const auto shotDone = folder.getChildFile (juce::String (p.file) + "-" + mode + ".done");
- if (phase == 0 && now - t0 > 1500.0)
- {
- // the window's content on screen, in physical pixels, for the outside screenshot to crop
- auto* c = window->getContentComponent();
- const auto scale = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->scale;
- const auto b = c->getScreenBounds();
- shotDone.deleteFile();
- ready.replaceWithText (juce::String (juce::roundToInt (b.getX() * scale)) + " " + juce::String (juce::roundToInt (b.getY() * scale)) + " "
- + juce::String (juce::roundToInt (b.getWidth() * scale)) + " " + juce::String (juce::roundToInt (b.getHeight() * scale)));
- phase = 1;
- t0 = now;
- return;
- }
- if (phase == 1 && (shotDone.existsAsFile() || now - t0 > 10000.0))
- {
- ready.deleteFile();
- shotDone.deleteFile();
- phase = 2;
- t0 = now;
- c0 = lynx::processCpuSeconds();
- return;
- }
- if (phase == 2 && now - t0 > 6000.0)
- {
- const auto cpu = (lynx::processCpuSeconds() - c0) / ((now - t0) * 0.001) * 100.0;
- report << juce::String (p.file) << "\t" << mode << "\t" << juce::String (cpu, 2) << "\t" << (animating() ? "yes" : "no") << "\n";
- ++at;
- open();
- }
- }
- };
- std::unique_ptr<ArtGuiRun> artGui;
- void runArtGui (const juce::File& folder, const juce::String& mode)
- {
- folder.createDirectory();
- artGui = std::make_unique<ArtGuiRun>();
- artGui->folder = folder;
- artGui->mode = mode;
- artGui->done = [this] { juce::MessageManager::callAsync ([this] { artGui.reset(); quit(); }); };
- artGui->start();
- }
- void runPluginEditorSnapshots (const juce::String& folder)
- {
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- {
- const juce::File out (folder);
- out.createDirectory();
- lynx::AudioEngine offline (false);
- const auto roots = lynx::findFlStudioRoots();
- const auto presets = juce::File (juce::String::fromUTF8 (roots.data.c_str())).getChildFile ("Patches/Plugin presets/Effects");
- auto kinds = lynx::plugui::flLayoutKinds();
- kinds.push_back (lynx::EffectKind::maximus); // Soundgoodizer (below)
- for (const auto own : lynx::plugui::ownLayoutKinds()) // LYNX's own panels (mixing suite, round 96)
- kinds.push_back (own);
- kinds.push_back (lynx::EffectKind::apexLimiter); // round 114: display-first editor
- kinds.push_back (lynx::EffectKind::ridgeStrip); // round 145: the second pass shows the Vocal strip voicing
- kinds.push_back (lynx::EffectKind::ridgeStrip); // round 165: the third pass shows the E console voicing
- kinds.push_back (lynx::EffectKind::compressor); // round 152: the RComp role's panel (vintage voicing, RComp ranges)
- const auto database = juce::File (juce::String::fromUTF8 (roots.data.c_str())).getChildFile ("Patches/Plugin database/Effects");
- auto maximusPasses = 0; // Maximus has its own page (first pass); the second pass shows Soundgoodizer
- auto ridgePasses = 0;
- for (const auto kind : kinds)
- {
- auto fx = lynx::makeEffectSlot (kind);
- juce::String name (lynx::effectInfo (kind).name);
- for (const auto& plugin : lynx::flPluginsForEffect (kind))
- {
- const auto dir = presets.getChildFile (juce::String::fromUTF8 (plugin.c_str()));
- auto file = dir.getChildFile ("Default.fst");
- if (! file.existsAsFile()) // plugins without presets: their entry of FL's plugin database
- for (const auto& f : database.findChildFiles (juce::File::findFiles, true, juce::String::fromUTF8 (plugin.c_str()) + ".fst"))
- file = f;
- if (! file.existsAsFile())
- {
- auto files = dir.findChildFiles (juce::File::findFiles, true, "*.fst");
- std::sort (files.begin(), files.end(), [] (const juce::File& a, const juce::File& b) { return a.getFullPathName().compareNatural (b.getFullPathName()) < 0; });
- file = files.isEmpty() ? juce::File() : files[0];
- }
- juce::MemoryBlock data;
- if (file.existsAsFile() && file.loadFileAsData (data))
- {
- const auto* bytes = static_cast<const std::uint8_t*> (data.getData());
- if (auto loaded = lynx::effectFromFlPreset (std::vector<std::uint8_t> (bytes, bytes + data.getSize()), 130.0); loaded && loaded->kind == kind)
- fx = *loaded;
- }
- name = juce::String::fromUTF8 (plugin.c_str());
- break;
- }
- if (kind == lynx::EffectKind::maximus && ++maximusPasses == 2) // Soundgoodizer: preset A of the installation, Amount 60 %
- {
- juce::MemoryBlock data;
- juce::File (juce::String::fromUTF8 (roots.factoryData.c_str())).getChildFile ("Plugins/Fruity/Effects/Soundgoodizer/Data/Presets/a.dat").loadFileAsData (data);
- lynx::maximusfx::Blob blob;
- blob.build = lynx::hlfx::MaximusBuild::soundgoodizer;
- blob.mix = 600;
- const auto* b = static_cast<const std::uint8_t*> (data.getData());
- blob.state.assign (b, b + data.getSize());
- fx = lynx::makeEffectSlot (kind);
- fx.state = lynx::maximusfx::pack (blob);
- name = "Soundgoodizer";
- }
- if (kind == lynx::EffectKind::ridgeStrip && ++ridgePasses == 2) // round 145: her Vocalstrip 2 setting
- {
- for (const auto& [param, value] : { std::pair<const char*, float> { "Vocal strip", 1.0f }, { "Compander", 1.0f },
- { "Compander threshold", 0.3083f }, { "Compander ratio", 0.6929f }, { "Compander attack", 0.2543f },
- { "Compander release", 0.5316f }, { "Make-up", 0.2917f }, { "Soft knee", 1.0f },
- { "Expander threshold", 0.2198f }, { "Vocal input", 0.6792f }, { "Vocal output", 0.3938f },
- { "Process order", 0.4783f }, { "De-esser", 1.0f } })
- fx.params[(std::size_t) lynx::plugui::paramIndex (kind, param)] = value;
- name = "Ridge Strip (Vocal strip)";
- }
- else if (kind == lynx::EffectKind::ridgeStrip && ridgePasses == 3) // round 165: the E console, EQ to the side chain
- {
- for (const auto& [param, value] : { std::pair<const char*, float> { "Voicing", 1.0f }, { "HPF", 0.3f }, { "HF gain", 0.8f },
- { "HF bell", 1.0f }, { "Ratio", 0.5f }, { "Comp. threshold", 0.4f }, { "EQ to SC", 1.0f },
- { "Filter split", 1.0f }, { "Expander", 1.0f } })
- fx.params[(std::size_t) lynx::plugui::paramIndex (kind, param)] = value;
- name = "Ridge Strip (E console)";
- }
- else if (kind == lynx::EffectKind::ridgeStrip) // a vocal setting, so the graphs show something
- for (const auto& [param, value] : { std::pair<const char*, float> { "HPF", 0.3f }, { "LMF gain", 0.35f }, { "HF gain", 0.7f },
- { "Ratio", 0.3f }, { "Comp. threshold", 0.55f } })
- fx.params[(std::size_t) lynx::plugui::paramIndex (kind, param)] = value;
- if (kind == lynx::EffectKind::compressor) // round 152: the vintage voicing with the reference's ranges and meter
- {
- for (const auto& [param, value] : { std::pair<const char*, float> { "Voicing", 1.0f }, { "Ranges", 1.0f }, { "Limiter", 1.0f },
- { "Threshold", 0.6f }, { "RC ratio", 0.4f } })
- fx.params[(std::size_t) lynx::plugui::paramIndex (kind, param)] = value;
- name = "Compressor (RComp role)";
- }
- if (kind == lynx::EffectKind::apexLimiter) // round 114: gain into the ceiling, so the display shows reduction
- fx.params[0] = 0.33f;
- if (kind == lynx::EffectKind::ember)
- {
- fx.params[(std::size_t) lynx::plugui::paramIndex (kind, "Drive")] = 0.5f;
- fx.params[(std::size_t) lynx::plugui::paramIndex (kind, "Bands")] = 1.0f; // round 108: the band rows
- fx.params[(std::size_t) lynx::plugui::paramIndex (kind, "B3 drive")] = 0.6f;
- }
- if (kind == lynx::EffectKind::crestCompressor) // round 108: a curve with a knee and a side-chain low cut
- for (const auto& [param, value] : { std::pair<const char*, float> { "Threshold", 0.55f }, { "Knee", 0.15f },
- { "SC1 shape", 0.5f }, { "SC1 freq.", 0.3f } })
- fx.params[(std::size_t) lynx::plugui::paramIndex (kind, param)] = value;
- lynx::Song song;
- song.mixer.resize (2);
- song.mixer[0].name = "Master";
- song.mixer[1].name = "Insert 1";
- song.mixer[1].effects.push_back (fx);
- offline.setSong (std::move (song));
- offline.dispatchPendingMessages();
- if (lynx::ProEditorWindows::handles (kind)) // round 114: the display-first editors, with a demo signal
- {
- auto editor = lynx::makeProEditor (offline, 1, 0, true);
- juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
- {
- juce::Graphics g (image);
- editor->paintEntireComponent (g, false);
- }
- const auto file = out.getChildFile (name + ".png");
- file.deleteFile();
- juce::PNGImageFormat png;
- if (auto stream = file.createOutputStream())
- png.writeImageToStream (image, *stream);
- continue;
- }
- const auto pages = name == "Soundgoodizer" ? 1 : juce::jmax (1, (int) lynx::plugui::layoutFor (kind).pages.size());
- for (int page = 0; page < pages; ++page)
- {
- auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, page);
- juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
- {
- juce::Graphics g (image);
- g.fillAll (lynx::theme::panel);
- editor->paintEntireComponent (g, false);
- }
- const auto file = out.getChildFile (name + (page > 0 ? "-p" + juce::String (page + 1) : juce::String()) + ".png");
- file.deleteFile();
- juce::PNGImageFormat png;
- if (auto stream = file.createOutputStream())
- png.writeImageToStream (image, *stream);
- }
- }
- // round 137: Echoform in its Rhythm mode (EchoBoy's role) with the Present era
- {
- namespace ef = lynx::echosuite::echoform;
- auto fx = lynx::makeEffectSlot (lynx::EffectKind::echoform);
- fx.params[ef::rhythm] = 1.0f;
- fx.params[ef::rhythmRepeats] = 5.0f / 15.0f;
- fx.params[ef::rhythmDecay] = 0.25f;
- fx.params[ef::rhythmTap1 + 2] = 0.45f;
- fx.params[ef::feedback] = 0.25f;
- fx.params[ef::era] = 0.5f;
- for (const auto& [param, value] : ef::rhythmPresetEdits (0)) // round 144: a pattern in the rhythm editor (Grid)
- fx.params[(std::size_t) param] = value;
- fx.params[ef::rhythmShape] = 0.5f; // swell
- lynx::Song song;
- song.mixer.resize (2);
- song.mixer[0].name = "Master";
- song.mixer[1].name = "Insert 1";
- song.mixer[1].effects.push_back (fx);
- offline.setSong (std::move (song));
- offline.dispatchPendingMessages();
- auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
- juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
- {
- juce::Graphics g (image);
- g.fillAll (lynx::theme::panel);
- editor->paintEntireComponent (g, false);
- }
- const auto file = out.getChildFile ("Echoform-rhythm.png");
- file.deleteFile();
- juce::PNGImageFormat png;
- if (auto stream = file.createOutputStream())
- png.writeImageToStream (image, *stream);
- }
- // round 150: Echoform with a voicing (the Stereo / L/R offset controls on the Rhythm row)
- {
- namespace ef = lynx::echosuite::echoform;
- auto fx = lynx::makeEffectSlot (lynx::EffectKind::echoform);
- fx.params[ef::voicing] = ef::voicingValue (ef::voicingForEchoBoyStyle (19));
- fx.params[ef::style] = ef::styleValue (ef::Style::dual);
- lynx::Song song;
- song.mixer.resize (2);
- song.mixer[0].name = "Master";
- song.mixer[1].name = "Insert 1";
- song.mixer[1].effects.push_back (fx);
- offline.setSong (std::move (song));
- offline.dispatchPendingMessages();
- auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
- juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
- {
- juce::Graphics g (image);
- g.fillAll (lynx::theme::panel);
- editor->paintEntireComponent (g, false);
- }
- const auto file = out.getChildFile ("Echoform-voicing.png");
- file.deleteFile();
- juce::PNGImageFormat png;
- if (auto stream = file.createOutputStream())
- png.writeImageToStream (image, *stream);
- }
- // round 150: Auto-pan's Rhythm voicing with its Tweak row (PanMan's role)
- {
- auto fx = lynx::makeEffectSlot (lynx::EffectKind::autoPan);
- fx.params[lynx::autopan::count] = 1.0f; // the Rhythm voicing
- fx.params[lynx::autopan::count + 13] = 0.75f; // offset mod +90°
- lynx::Song song;
- song.mixer.resize (2);
- song.mixer[0].name = "Master";
- song.mixer[1].name = "Insert 1";
- song.mixer[1].effects.push_back (fx);
- offline.setSong (std::move (song));
- offline.dispatchPendingMessages();
- auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
- juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
- {
- juce::Graphics g (image);
- g.fillAll (lynx::theme::panel);
- editor->paintEntireComponent (g, false);
- }
- const auto file = out.getChildFile ("Auto-pan-tweak.png");
- file.deleteFile();
- juce::PNGImageFormat png;
- if (auto stream = file.createOutputStream())
- png.writeImageToStream (image, *stream);
- }
- // round 165: Ember's Classic voicing (the Decapitator role) in its one-screen panel
- {
- namespace em = lynx::mixsuite::ember;
- auto fx = lynx::makeEffectSlot (lynx::EffectKind::ember);
- fx.params[em::voicing] = 1.0f;
- fx.params[em::classicDrive] = 0.35f;
- lynx::Song song;
- song.mixer.resize (2);
- song.mixer[0].name = "Master";
- song.mixer[1].name = "Insert 1";
- song.mixer[1].effects.push_back (fx);
- offline.setSong (std::move (song));
- offline.dispatchPendingMessages();
- auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
- juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
- {
- juce::Graphics g (image);
- g.fillAll (lynx::theme::panel);
- editor->paintEntireComponent (g, false);
- }
- const auto file = out.getChildFile ("Ember Saturator-classic.png");
- file.deleteFile();
- juce::PNGImageFormat png;
- if (auto stream = file.createOutputStream())
- png.writeImageToStream (image, *stream);
- }
- // round 152: Foil Plate's one-knob Plate view (the Little Plate role)
- {
- auto fx = lynx::makeEffectSlot (lynx::EffectKind::foilPlate);
- fx.params[14] = 1.0f; // the measured plate voicing
- fx.params[15] = 1.0f; // View = Plate
- lynx::Song song;
- song.mixer.resize (2);
- song.mixer[0].name = "Master";
- song.mixer[1].name = "Insert 1";
- song.mixer[1].effects.push_back (fx);
- offline.setSong (std::move (song));
- offline.dispatchPendingMessages();
- auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
- juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
- {
- juce::Graphics g (image);
- g.fillAll (lynx::theme::panel);
- editor->paintEntireComponent (g, false);
- }
- const auto file = out.getChildFile ("Foil Plate-plate.png");
- file.deleteFile();
- juce::PNGImageFormat png;
- if (auto stream = file.createOutputStream())
- png.writeImageToStream (image, *stream);
- }
- // LYNX's own editors with live displays (round 103): Facet EQ (a mixing curve, one dynamic band, demo analyser)
- // and LYNX Tune (demo pitch phrase)
- {
- lynx::setNativeEditorDemo (true);
- using namespace lynx::facet;
- auto eq = lynx::makeEffectSlot (lynx::EffectKind::facetEq);
- const struct { Shape s; double f, g, q; int slope; double range; } bandsDemo[] = {
- { Shape::lowCut, 32, 0, 1, 24, 0 }, { Shape::bell, 110, 3, 1.2, 12, 0 }, { Shape::bell, 380, -3.5, 1.6, 12, 0 },
- { Shape::bell, 3200, 0, 2.5, 12, -6 }, { Shape::highShelf, 9000, 2.5, 0.8, 12, 0 }
- };
- for (int b = 0; b < 5; ++b)
- {
- eq.params[(std::size_t) param (b, 0)] = shapeValue (bandsDemo[b].s);
- eq.params[(std::size_t) param (b, 1)] = hzValue (bandsDemo[b].f);
- eq.params[(std::size_t) param (b, 2)] = gainValue (bandsDemo[b].g);
- eq.params[(std::size_t) param (b, 3)] = qValue (bandsDemo[b].q);
- eq.params[(std::size_t) param (b, 4)] = slopeValue (bandsDemo[b].slope);
- eq.params[(std::size_t) (rangeParam0 + b)] = rangeValue (bandsDemo[b].range);
- }
- eq.params[(std::size_t) phaseParam] = phaseValue (Phase::natural);
- const auto own = [&] (const lynx::EffectSlot& fx, const juce::String& file, bool facetEditor, int page = 0) {
- lynx::Song song;
- song.mixer.resize (2);
- song.mixer[0].name = "Master";
- song.mixer[1].name = "Vocal";
- song.mixer[1].effects.push_back (fx);
- offline.setSong (std::move (song));
- offline.dispatchPendingMessages();
- auto editor = facetEditor ? lynx::makeFacetEqEditor (offline, 1, 0, true) : lynx::makeNativeEffectEditor (offline, 1, 0, 1.25f, page);
- juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
- {
- juce::Graphics g (image);
- g.fillAll (lynx::theme::panel);
- editor->paintEntireComponent (g, false);
- }
- const auto f = out.getChildFile (file);
- f.deleteFile();
- juce::PNGImageFormat png;
- if (auto stream = f.createOutputStream())
- png.writeImageToStream (image, *stream);
- };
- own (eq, "Facet EQ.png", true);
- own (lynx::makeEffectSlot (lynx::EffectKind::lynxTune), "LYNX Tune.png", false);
- {
- // round 128: the ADVANCED page, with E bypassed and A removed on the keyboard and a created vibrato
- auto tune = lynx::makeEffectSlot (lynx::EffectKind::lynxTune);
- tune.params[(std::size_t) (lynx::lynxtune::bypassC + 4)] = 1.0f;
- tune.params[(std::size_t) (lynx::lynxtune::noteC + 9)] = 0.0f;
- tune.params[lynx::lynxtune::vibratoShape] = 1.0f / 3.0f;
- // round 166c: the created vibrato's amplitude / formant / variation, a short throat, In scale +2
- tune.params[lynx::lynxtune::vibratoAmplitude] = 1.0f / 3.0f;
- tune.params[lynx::lynxtune::vibratoFormant] = 0.7f;
- tune.params[lynx::lynxtune::vibratoVariation] = 0.2f;
- tune.params[lynx::lynxtune::throatLength] = lynx::lynxtune::throatValue (80.0);
- tune.params[lynx::lynxtune::transposeInScale] = 1.0f;
- tune.params[lynx::lynxtune::scaleTranspose] = lynx::lynxtune::scaleTransposeValue (2);
- own (tune, "LYNX Tune-p2.png", false, 1);
- }
- own (lynx::makeEffectSlot (lynx::EffectKind::lynxTune), "LYNX Tune-p3.png", false, 2); // round 135w: Real-time
- lynx::setNativeEditorDemo (false);
- }
- // generators in FL's arrangement: the channel's plugin page with the FL preset's settings
- const auto generators = juce::File (juce::String::fromUTF8 (roots.data.c_str())).getChildFile ("Patches/Plugin presets/Generators");
- 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" } })
- {
- juce::MemoryBlock data;
- if (juce::String (folder) == "Harmor") // the first preset whose state the engine reads
- {
- auto files = generators.getChildFile (folder).findChildFiles (juce::File::findFiles, true, "*.fst");
- files.sort();
- for (const auto& f : files)
- {
- juce::MemoryBlock block;
- if (! f.loadFileAsData (block))
- continue;
- const auto* b = static_cast<const std::uint8_t*> (block.getData());
- try
- {
- const auto p = flp::parseProject (std::vector<std::uint8_t> (b, b + block.getSize()), true);
- if (! p.channels.empty() && lynx::harmorStateUsable (p.channels.front().pluginState))
- {
- preset = nullptr;
- data = block;
- break;
- }
- }
- catch (const std::exception&)
- {
- }
- }
- }
- auto file = preset == nullptr ? juce::File() : juce::String (preset).isEmpty() ? database.getSiblingFile ("Generators").getChildFile ("Misc").getChildFile (juce::String (folder) + ".fst")
- : generators.getChildFile (folder).getChildFile (preset);
- if (! file.existsAsFile())
- {
- auto files = generators.getChildFile (folder).findChildFiles (juce::File::findFiles, true, "*.fst");
- files.sort();
- file = files.isEmpty() ? juce::File() : files[0];
- }
- if (data.isEmpty() && ! file.loadFileAsData (data))
- continue;
- try
- {
- const auto* bytes = static_cast<const std::uint8_t*> (data.getData());
- auto project = flp::parseProject (std::vector<std::uint8_t> (bytes, bytes + data.getSize()), true);
- if (project.channels.empty())
- continue;
- project.channels.front().type = flp::ChannelType::native;
- lynx::FlpImportOptions options;
- options.roots = roots;
- options.fileExists = [] (const std::string& path) { return lynx::platform::localFile (path).existsAsFile(); };
- options.readFile = [] (const std::string& path) {
- juce::MemoryBlock block;
- lynx::platform::localFile (path).loadFileAsData (block);
- const auto* b = static_cast<const std::uint8_t*> (block.getData());
- return std::vector<std::uint8_t> (b, b + block.getSize());
- };
- options.saveEmbedded = [out] (const std::vector<std::uint8_t>& wav, const std::string& name) {
- const auto f = out.getChildFile ("samples").getNonexistentChildFile (juce::String::fromUTF8 (name.c_str()), ".wav");
- f.getParentDirectory().createDirectory();
- f.replaceWithData (wav.data(), wav.size());
- return f.getFullPathName().toStdString();
- };
- auto song = lynx::importFlp (project, options);
- // the page only needs the plugin's saved state (FL Keys' sample zones need the installed wavetables)
- if (! song.channels.empty() && project.channels.front().pluginName == "BooBass" && song.channels.front().instrument != lynx::InstrumentKind::boobass)
- {
- song.channels.front().instrument = lynx::InstrumentKind::boobass; // (its sound needs the engine DLL; the page does not)
- song.channels.front().modelParams.assign (3, 32768.0f);
- }
- if (! song.channels.empty() && project.channels.front().pluginName == "FL Keys")
- {
- song.channels.front().instrument = lynx::InstrumentKind::flkeys;
- song.channels.front().pluginState = project.channels.front().pluginState;
- }
- offline.setSong (std::move (song));
- offline.dispatchPendingMessages();
- if (offline.getSong().channels.empty())
- continue;
- auto panel = lynx::makeChannelSettingsPanel (offline, 0);
- juce::Image image (juce::Image::ARGB, panel->getWidth(), panel->getHeight(), true);
- {
- juce::Graphics g (image);
- g.fillAll (lynx::theme::panel);
- panel->paintEntireComponent (g, false);
- }
- const auto out2 = out.getChildFile (juce::String (folder) + ".png");
- out2.deleteFile();
- juce::PNGImageFormat png;
- if (auto stream = out2.createOutputStream())
- png.writeImageToStream (image, *stream);
- }
- catch (const std::exception&)
- {
- }
- }
- }
- quit();
- }
- void runVideoShot (const juce::String& prefix, const juce::String& videoPath)
- {
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- // the message loop runs while the frames decode (modal loops are off): a timer takes one snapshot per step
- struct VideoShot final : juce::Timer
- {
- lynx::AudioEngine offline { false };
- std::unique_ptr<juce::Component> editor;
- juce::String prefix, report;
- int step = 0;
- std::function<void()> done;
- void moveTo (double seconds)
- {
- offline.getTransport().positionTicks.store (seconds * offline.getSong().bpm / 60.0 * lynx::ppq);
- }
- void timerCallback() override
- {
- static constexpr double times[] = { 0.0, 1.5, 3.25 };
- if (step > 0 && editor != nullptr)
- savePng (editor->createComponentSnapshot (editor->getLocalBounds()), prefix + "-" + juce::String (step - 1) + ".png");
- if (editor == nullptr || step >= (int) std::size (times))
- {
- stopTimer();
- juce::File (prefix + "-report.txt").replaceWithText (report);
- if (done)
- done();
- return;
- }
- moveTo (times[step++]);
- }
- };
- static std::unique_ptr<VideoShot> shot;
- shot = std::make_unique<VideoShot>();
- shot->prefix = prefix;
- auto& offline = shot->offline;
- lynx::videoview::install (offline);
- lynx::Song song;
- song.mixer = lynx::Song::defaultMixer (2);
- lynx::ChannelDef c;
- c.name = "Fruity Video Player";
- c.instrument = lynx::InstrumentKind::videoplayer;
- lynx::video::Settings vs;
- vs.path = juce::File (videoPath).getFullPathName().toStdString();
- vs.delay = lynx::video::unitsPerSecond / 2; // the video starts at 0.5 s
- c.pluginState = lynx::video::write (vs);
- song.channels.push_back (c);
- song.patterns.emplace_back();
- offline.setSong (std::move (song));
- offline.dispatchPendingMessages();
- auto& report = shot->report;
- report << "ffmpeg: " << lynx::findFfmpeg().getFullPathName() << "\n";
- report << lynx::videoview::report (vs.path).fromFirstOccurrenceOf ("Input #0", true, false).upToFirstOccurrenceOf ("At least", false, false) << "\n";
- shot->editor = lynx::makeChannelSettingsPanel (offline, 0);
- if (shot->editor != nullptr)
- shot->editor->setVisible (true);
- shot->done = [this] { juce::MessageManager::callAsync ([this] { shot.reset(); quit(); }); };
- shot->startTimer (1500);
- }
- void runDanceShot (const juce::String& prefix)
- {
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- // the moves: one row each, eight moments of a cycle (both facings for Spinning; Pose ends the sheet)
- {
- constexpr int cell = 120, cols = 8;
- juce::Image sheet (juce::Image::ARGB, 130 + cols * cell, lynx::dance::moveCount * cell + 10, true);
- juce::Graphics g (sheet);
- g.fillAll (lynx::theme::colour::bg0);
- for (int m = 0; m < lynx::dance::moveCount; ++m)
- {
- g.setColour (lynx::theme::colour::textSecondary);
- g.setFont (14.0f);
- g.drawText (lynx::dance::moveName (m), 8, m * cell + 5, 118, cell, juce::Justification::centredLeft);
- for (int k = 0; k < cols; ++k)
- {
- const auto pose = lynx::dance::pose (m, k / (double) cols + (m == lynx::dance::freestyle ? k * 2 : 0), 1);
- lynx::dancer::draw (g, { 130.0f + (k + 0.5f) * cell, (float) (m + 1) * cell - 6.0f }, 92.0f, pose, false, juce::Colour (0xffff3048));
- }
- }
- savePng (sheet, prefix + "-moves.png");
- }
- lynx::AudioEngine offline (false);
- lynx::Song song;
- song.mixer = lynx::Song::defaultMixer (2);
- for (int d = 0; d < 2; ++d)
- {
- lynx::ChannelDef c;
- c.name = d == 0 ? "Fruity Dance" : "Fruity Dance #2";
- c.instrument = lynx::InstrumentKind::fruitydance;
- lynx::dance::Settings s;
- s.move = d == 0 ? lynx::dance::stepping : lynx::dance::waving;
- s.x = d == 0 ? 520 : 760;
- s.y = 560;
- s.colour = d == 0 ? 0xffff3048 : 0xff30a8ff;
- s.mirrored = d == 1;
- c.pluginState = lynx::dance::toState (s);
- song.channels.push_back (c);
- }
- song.patterns.emplace_back();
- {
- const juce::File demo (prefix + "-demo.lynx");
- juce::String error;
- lynx::ProjectFile::save (song, demo, error);
- }
- offline.setSong (std::move (song));
- offline.dispatchPendingMessages();
- if (auto editor = lynx::makeChannelSettingsPanel (offline, 0))
- savePng (editor->createComponentSnapshot (editor->getLocalBounds()), prefix + "-editor.png");
- if (auto frame = lynx::makeChannelFrame (offline, 1, 0))
- savePng (frame->createComponentSnapshot (frame->getLocalBounds()), prefix + "-frame.png");
- }
- void runControllerShot (const juce::String& prefix)
- {
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- lynx::AudioEngine offline (false);
- lynx::Song song;
- song.mixer = lynx::Song::defaultMixer (2);
- song.mixer[1].name = "Insert 1";
- auto fx = lynx::makeEffectSlot (lynx::EffectKind::formulaController);
- lynx::formula::State formula;
- formula.formula = "a*Sin(SongTime*Pi*b*4)+c";
- fx.state = lynx::formula::writeState (formula);
- fx.params[0] = 0.5f;
- fx.params[1] = 0.25f;
- fx.params[2] = 0.5f;
- song.mixer[1].effects.push_back (fx);
- // round 164: X-Y (slot 2), X-Y-Z (slot 3) and a Control Surface (slot 4)
- {
- auto xyFx = lynx::makeEffectSlot (lynx::EffectKind::xyController);
- xyFx.params[(std::size_t) lynx::xy::level (0)] = 0.3f;
- xyFx.params[(std::size_t) lynx::xy::level (1)] = 0.7f;
- xyFx.params[(std::size_t) lynx::xy::tension (0)] = 0.8f;
- song.mixer[1].effects.push_back (xyFx);
- auto xyzFx = lynx::makeEffectSlot (lynx::EffectKind::xyzController);
- xyzFx.params[(std::size_t) lynx::xy::level (2)] = 0.8f;
- song.mixer[1].effects.push_back (xyzFx);
- // round 165: an X-Y-Z whose X curve is FL's "Stairs" (tension +40 %) and Y a bent single curve
- xyzFx.params[(std::size_t) lynx::xy::curveMode (0)] = lynx::xy::curveModeValue (lynx::flcurve::stairs);
- xyzFx.params[(std::size_t) lynx::xy::tension (0)] = 0.7f;
- xyzFx.params[(std::size_t) lynx::xy::level (0)] = 0.62f;
- xyzFx.params[(std::size_t) lynx::xy::tension (1)] = 0.825f;
- song.mixer[1].effects.push_back (xyzFx);
- auto panel = lynx::makeEffectSlot (lynx::EffectKind::controlSurface);
- lynx::SurfaceControl c;
- for (const auto& [kind, name, v, x, y] : std::vector<std::tuple<lynx::SurfaceControl::Kind, const char*, float, float, float>> {
- { lynx::SurfaceControl::Kind::knob, "Cutoff", 0.65f, 20.0f, 20.0f },
- { lynx::SurfaceControl::Kind::knob, "Reso", 0.3f, 90.0f, 20.0f },
- { lynx::SurfaceControl::Kind::slider, "Mix", 0.8f, 170.0f, 20.0f },
- { lynx::SurfaceControl::Kind::xy, "Space", 0.4f, 230.0f, 20.0f },
- { lynx::SurfaceControl::Kind::button, "Drop", 0.0f, 20.0f, 110.0f },
- { lynx::SurfaceControl::Kind::checkBox, "Bypass", 1.0f, 20.0f, 160.0f } })
- {
- c.kind = kind;
- c.name = name;
- c.value = v;
- c.valueY = 0.6f;
- c.x = x;
- c.y = y;
- lynx::surface::add (panel, c);
- }
- song.mixer[1].effects.push_back (panel);
- }
- lynx::ChannelDef env;
- env.name = "Envelope Controller";
- env.instrument = lynx::InstrumentKind::controller;
- auto ecData = lynx::defaultEnvelopeController();
- ecData[0].lfoOn = true;
- ecData[0].lfoTempo = true;
- ecData[0].lfoSpeed = 40898;
- ecData[0].maps[lynx::mapKeyboard].count = 2;
- ecData[0].maps[lynx::mapKeyboard].time = { 0.2f, 0.8f };
- ecData[0].maps[lynx::mapKeyboard].level = { 0.0f, 1.0f };
- ecData[0].maps[lynx::mapModX] = ecData[0].maps[lynx::mapKeyboard];
- env.controllerState = lynx::writeEnvelopeController (ecData);
- song.channels.push_back (env);
- lynx::ChannelDef out;
- out.name = "MIDI Out";
- out.instrument = lynx::InstrumentKind::midiOut;
- lynx::midictl::MidiOutSettings settings;
- settings.port = 1;
- lynx::midictl::writeMidiOut (out.pluginState, settings);
- song.channels.push_back (out);
- // a Layer (round 164) over three synths split across the keyboard, crossfading
- for (const auto* name : { "Bass", "Pad", "Lead" })
- {
- lynx::ChannelDef c;
- c.name = name;
- c.instrument = lynx::InstrumentKind::synth;
- song.channels.push_back (c);
- }
- {
- lynx::ChannelDef layer;
- layer.name = "Layer";
- layer.instrument = lynx::InstrumentKind::layer;
- song.channels.push_back (layer);
- const auto self = (int) song.channels.size() - 1;
- lynx::layer::setChildren (song, self, { 2, 3, 4 });
- song.channels[2].keyLow = 0, song.channels[2].keyHigh = 47;
- song.channels[3].keyLow = 36, song.channels[3].keyHigh = 83;
- song.channels[4].keyLow = 72, song.channels[4].keyHigh = 127;
- song.channels[(std::size_t) self].layer.crossfade = true;
- song.channels[(std::size_t) self].layer.fade = 0.35f;
- }
- {
- lynx::ChannelDef dash; // channel 6
- dash.name = "Dashboard";
- dash.instrument = lynx::InstrumentKind::dashboard;
- dash.patcher.surface = lynx::surface::starterControls();
- song.channels.push_back (dash);
- }
- {
- lynx::ChannelDef volt; // channel 7: FL's render-test settings (main L pitch, R gate × 0.5) with Out 2 on insert 3
- volt.name = "Voltage Controller";
- volt.instrument = lynx::InstrumentKind::voltage;
- lynx::voltage::Settings v;
- v.enabled = true;
- v.params[9] = 49152;
- v.unipolar[2] = true;
- v.tracks = { 3, 0, 0 };
- v.source[6] = lynx::voltage::Source::clock;
- volt.pluginState = lynx::voltage::write (v);
- song.channels.push_back (volt);
- }
- song.patterns.emplace_back();
- offline.setSong (std::move (song));
- offline.dispatchPendingMessages();
- auto shoot = [&] (std::unique_ptr<juce::Component> c, const juce::String& name) {
- if (c == nullptr)
- return;
- savePng (c->createComponentSnapshot (c->getLocalBounds()), prefix + name);
- };
- shoot (lynx::makeChannelSettingsPanel (offline, 0), "-envelope-controller.png");
- shoot (lynx::makeChannelSettingsPanel (offline, 1), "-midi-out.png");
- shoot (lynx::makeChannelSettingsPanel (offline, 5), "-layer.png");
- shoot (lynx::makeChannelFrame (offline, 3, -1), "-layer-child-misc.png"); // (the key-region ruler over the root keyboard)
- {
- const auto slotOf = [] (int k) -> lynx::SlotLocator {
- return [k] (lynx::Song& s) { return &s.mixer[1].effects[(std::size_t) k]; };
- };
- const lynx::AutomationTarget target { lynx::AutomationTargetKind::effectParam, 1, 1, 0 };
- shoot (lynx::makeXyControllerEditor (offline, slotOf (1), nullptr, target), "-xy-controller.png");
- shoot (lynx::makeXyControllerEditor (offline, slotOf (2), nullptr, target), "-xyz-controller.png");
- shoot (lynx::makeXyControllerEditor (offline, slotOf (3), nullptr, target), "-xyz-controller-stairs.png");
- shoot (lynx::makeControlSurfaceEditor (offline, slotOf (4), target), "-control-surface.png");
- shoot (lynx::makeChannelSettingsPanel (offline, 6), "-dashboard.png");
- shoot (lynx::makeChannelSettingsPanel (offline, 7), "-voltage-controller.png");
- }
- // FL's Dashboard presets of this PC's FL Studio, imported (round 164f): one PNG each
- if (const auto fl = lynx::findFlStudio(); fl.installDir.isDirectory())
- for (const auto& file : fl.installDir.getChildFile ("Data/Patches/Plugin presets/Generators/Dashboard").findChildFiles (juce::File::findFiles, false, "*.fst"))
- {
- juce::MemoryBlock bytes;
- if (! file.loadFileAsData (bytes))
- continue;
- const auto preset = flp::parseProject ({ (const std::uint8_t*) bytes.getData(), bytes.getSize() }, true);
- const auto dash = preset.channels.empty() ? std::nullopt : lynx::surface::parseFlDashboard (preset.channels[0].pluginState);
- if (! dash || dash->controls.empty())
- continue;
- offline.editSong ([&] (lynx::Song& s) {
- s.channels[6].name = file.getFileNameWithoutExtension().toStdString();
- s.channels[6].patcher.surface = dash->controls;
- s.channels[6].pluginState = preset.channels[0].pluginState; // (its MIDI port, channel, program)
- });
- offline.dispatchPendingMessages();
- const auto name = file.getFileNameWithoutExtension().replaceCharacter (' ', '-');
- shoot (lynx::makeChannelSettingsPanel (offline, 6), "-dashboard-fl-" + name + ".png");
- // edit mode (round 165): each control's output number and the MIDI it sends ("1 CC74")
- if (auto panel = lynx::makeChannelSettingsPanel (offline, 6))
- {
- std::function<void (juce::Component&)> pressEdit = [&] (juce::Component& c) {
- for (auto* child : c.getChildren())
- {
- if (auto* b = dynamic_cast<juce::TextButton*> (child); b != nullptr && b->getButtonText() == lynx::tr ("Edit"))
- b->setToggleState (true, juce::sendNotificationSync);
- pressEdit (*child);
- }
- };
- pressEdit (*panel);
- shoot (std::move (panel), "-dashboard-fl-" + name + "-edit.png");
- }
- }
- // the Envelope Controller's pages (issue #7): one PNG per part of the dropdown
- if (auto ec = lynx::makeEnvelopeControllerEditor (offline, 0))
- for (int part = 0; part < 7; ++part)
- {
- for (auto* child : ec->getChildren())
- if (auto* box = dynamic_cast<juce::ComboBox*> (child))
- box->setSelectedItemIndex (part, juce::sendNotificationSync);
- savePng (ec->createComponentSnapshot (ec->getLocalBounds()), prefix + "-ec-part" + juce::String (part) + ".png");
- }
- lynx::FormulaControllerWindows::open (offline, 1, 0);
- for (int k = 0; k < juce::TopLevelWindow::getNumTopLevelWindows(); ++k)
- if (auto* w = dynamic_cast<juce::DocumentWindow*> (juce::TopLevelWindow::getTopLevelWindow (k)))
- if (w->getName().startsWith ("Formula") && w->getContentComponent() != nullptr)
- savePng (w->getContentComponent()->createComponentSnapshot (w->getContentComponent()->getLocalBounds()), prefix + "-formula-controller.png");
- lynx::FormulaControllerWindows::closeAll();
- }
- void runEdisonShot (const juce::String& prefix, const juce::String& file)
- {
- namespace ae = lynx::audioedit;
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- lynx::AudioEngine offline (false);
- ae::Document d;
- if (file.isNotEmpty())
- {
- juce::MemoryBlock bytes;
- if (! juce::File (file).loadFileAsData (bytes) || ! ae::decodeWav (static_cast<const std::uint8_t*> (bytes.getData()), bytes.getSize(), d))
- {
- std::fprintf (stderr, "edisonshot: cannot read %s\n", file.toRawUTF8());
- return;
- }
- }
- else
- {
- // a drum loop with a hum and hiss under it (something for the denoiser and the EQ to show)
- d.title = "Drum loop";
- d.audio.sampleRate = 44100.0;
- const auto frames = (std::size_t) (44100 * 2);
- d.audio.channels.assign (2, std::vector<float> (frames, 0.0f));
- std::uint32_t seed = 7;
- for (std::size_t i = 0; i < frames; ++i)
- {
- seed = seed * 1664525u + 1013904223u;
- const auto hiss = ((float) (seed >> 8) / 16777216.0f - 0.5f) * 0.02f;
- const auto hum = 0.01f * (float) std::sin (2.0 * 3.141592653589793 * 50.0 * (double) i / 44100.0);
- d.audio.channels[0][i] = hiss + hum;
- d.audio.channels[1][i] = hiss * 0.9f + hum;
- }
- for (int hit = 0; hit < 8; ++hit)
- {
- const auto at = (std::size_t) hit * frames / 8;
- const auto kick = hit % 2 == 0;
- double phase = 0.0;
- for (std::size_t i = 0; i < 12000 && at + i < frames; ++i)
- {
- seed = seed * 1664525u + 1013904223u;
- const auto noise = (float) (seed >> 8) / 16777216.0f - 0.5f;
- const auto t = (double) i / 44100.0;
- phase += 2.0 * 3.141592653589793 * (kick ? 45.0 + 160.0 * std::exp (-t * 30.0) : 190.0) / 44100.0;
- const auto body = (float) std::sin (phase) * (float) std::exp (-t * (kick ? 9.0 : 22.0));
- const auto v = kick ? 0.85f * body : 0.35f * body + 0.6f * noise * (float) std::exp (-t * 18.0);
- d.audio.channels[0][at + i] += v;
- d.audio.channels[1][at + i] += kick ? v : v * 0.8f;
- }
- }
- for (int hit = 1; hit < 8; ++hit)
- ae::addMarker (d, (std::int64_t) (hit * frames / 8));
- ae::setLoop (d, { 0, (std::int64_t) frames });
- }
- // a volume envelope (a fade-in and a dip) to show the envelope mode and the envelope tools
- 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 } };
- auto editor = lynx::makeAudioEditorForSnapshot (offline, d, false);
- auto shot = [&prefix] (juce::Component& c, const juce::String& name) {
- juce::Image image (juce::Image::ARGB, c.getWidth(), c.getHeight(), true);
- {
- juce::Graphics g (image);
- g.fillAll (lynx::theme::panel);
- c.paintEntireComponent (g, false);
- }
- savePng (image, prefix + name);
- };
- editor->setSize (1120, 600);
- lynx::setAudioEditorEnvelopeModeForSnapshot (*editor, 1);
- shot (*editor, "-editor-volume-envelope.png");
- lynx::setAudioEditorEnvelopeModeForSnapshot (*editor, 0);
- juce::File (prefix + "-menu.txt").replaceWithText (lynx::audioEditorMenuForSnapshot (*editor).joinIntoString ("\n") + "\n");
- for (int t = 0; lynx::audioToolNameForSnapshot (t) != nullptr; ++t)
- {
- const auto envelopeTool = t >= 10 && t <= 14; // Scale levels .. Create sequence work on the volume envelope
- if (auto panel = lynx::makeAudioToolPanelForSnapshot (*editor, t, envelopeTool ? 1 : 0))
- {
- offline.dispatchPendingMessages();
- const auto name = juce::String (lynx::audioToolNameForSnapshot (t)).toLowerCase().retainCharacters ("abcdefghijklmnopqrstuvwxyz ").trim().replaceCharacter (' ', '-');
- shot (*panel, "-tool-" + juce::String (t).paddedLeft ('0', 2) + "-" + name + ".png");
- if (envelopeTool)
- shot (*editor, "-tool-" + juce::String (t).paddedLeft ('0', 2) + "-" + name + "-editor.png");
- panel.reset(); // (puts the envelope back)
- }
- }
- }
- static juce::TextButton* findButton (juce::Component& root, const juce::String& text)
- {
- if (auto* b = dynamic_cast<juce::TextButton*> (&root); b != nullptr && b->getButtonText() == text)
- return b;
- for (auto* child : root.getChildren())
- if (auto* b = findButton (*child, text))
- return b;
- return nullptr;
- }
- // a VFX Script editor's Script / Log / API reference tabs, then the Script tab of a script with an error
- void shootScriptTabs (juce::Component& panel, lynx::AudioEngine& engine, int index, const juce::String& name)
- {
- const std::pair<const char*, const char*> tabs[] = { { "Script", "script" }, { "Log", "log" }, { "API reference", "api" } };
- for (const auto& [tab, file] : tabs)
- if (auto* b = findButton (panel, lynx::tr (tab)); b != nullptr && b->onClick)
- {
- b->onClick();
- savePng (panel.createComponentSnapshot (panel.getLocalBounds()), name + "-tab-" + file + ".png");
- }
- engine.editSong ([&] (lynx::Song& s) {
- auto st = *lynx::vfx::readState (s.channels[(std::size_t) index].pluginState);
- auto settings = lynx::vfx::parseScript (st.fl).value_or (lynx::vfx::defaultScript());
- settings.setSource ("import flvfx as vfx\n\ndef onTriggerVoice(incomingVoice):\n v = vfx.Voice(incomingVoice)\n"
- " v.note += 7\n v.trigger(\n\ndef onReleaseVoice(incomingVoice):\n pass\n");
- st.fl = lynx::vfx::writeScript (settings);
- s.channels[(std::size_t) index].pluginState = lynx::vfx::writeState (st);
- });
- engine.dispatchPendingMessages();
- if (auto broken = lynx::makeChannelSettingsPanel (engine, index))
- {
- engine.dispatchPendingMessages();
- if (auto* b = findButton (*broken, lynx::tr ("Script")); b != nullptr && b->onClick)
- b->onClick();
- savePng (broken->createComponentSnapshot (broken->getLocalBounds()), name + "-error.png");
- }
- }
- void runVfxShot (const juce::String& prefix)
- {
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- lynx::AudioEngine offline (false);
- lynx::MainComponent ui (offline, false);
- ui.setSize (1280, 720);
- auto song = lynx::Song::makeDefault();
- song.channels.clear();
- for (const auto kind : lynx::vfx::allKinds)
- {
- lynx::ChannelDef c;
- lynx::vfx::makeChannel (c, kind);
- if (kind == lynx::vfx::Kind::keyMapper) // a chord on every key: something to see in the grid
- for (const auto& p : lynx::vfx::builtInPresets (kind))
- if (p.name == "Major triad")
- {
- auto st = *lynx::vfx::readState (c.pluginState);
- st.fl = p.fl;
- c.pluginState = lynx::vfx::writeState (st);
- }
- song.channels.push_back (c);
- }
- // a Patcher: its notes through a Color Mapper to three synths
- lynx::ChannelDef patcher;
- patcher.name = "Patcher";
- patcher.instrument = lynx::InstrumentKind::patcher;
- lynx::PatchNode mapper;
- mapper.generator = true;
- lynx::vfx::makeChannel (mapper.channel, lynx::vfx::Kind::colorMapper);
- mapper.x = 260.0f;
- patcher.patcher.nodes.push_back (mapper);
- lynx::PatchWire notes;
- notes.kind = lynx::PatchWire::Kind::midi, notes.to = 0;
- patcher.patcher.wires.push_back (notes);
- for (int k = 0; k < 3; ++k)
- {
- lynx::PatchNode synth;
- synth.generator = true;
- synth.channel.instrument = lynx::InstrumentKind::synth;
- synth.channel.name = "Synth " + std::to_string (k + 1);
- synth.x = 520.0f, synth.y = (float) k * 90.0f;
- patcher.patcher.nodes.push_back (synth);
- lynx::PatchWire in, out;
- in.kind = lynx::PatchWire::Kind::midi, in.from = 0, in.fromPort = k, in.to = 1 + k;
- out.from = 1 + k, out.to = lynx::patchToHost;
- patcher.patcher.wires.push_back (in);
- patcher.patcher.wires.push_back (out);
- }
- patcher.patcher.outputX = 760.0f;
- song.channels.push_back (patcher);
- offline.setSong (std::move (song));
- offline.dispatchPendingMessages();
- for (int c = 0; c < lynx::vfx::kindCount; ++c)
- if (auto panel = lynx::makeChannelSettingsPanel (offline, c))
- {
- offline.dispatchPendingMessages();
- savePng (panel->createComponentSnapshot (panel->getLocalBounds()),
- prefix + "-" + juce::String (lynx::vfx::flName (*lynx::vfx::kindOf (offline.getSong().channels[(std::size_t) c]))).replaceCharacter (' ', '-').toLowerCase() + ".png");
- }
- // with FL Studio installed: the Sequencer with FL's factory bank (to compare with FL's own editor) and
- // a Script with FL's "Snap To Scale"
- if (const auto roots = lynx::findFlStudioRoots(); ! roots.data.empty())
- {
- const auto data = juce::File (juce::String::fromUTF8 (roots.data.c_str()));
- const std::pair<lynx::vfx::Kind, juce::String> extra[] = {
- { lynx::vfx::Kind::sequencer, "Patches/Plugin database/Effects/Patcher/VFX Sequencer.fst" },
- { lynx::vfx::Kind::script, "Patches/Plugin presets/Effects/VFX Script/Snap To Scale.fst" },
- };
- for (const auto& [kind, path] : extra)
- {
- juce::MemoryBlock bytes;
- if (! data.getChildFile (path).loadFileAsData (bytes))
- continue;
- const auto* b = static_cast<const std::uint8_t*> (bytes.getData());
- const auto fl = lynx::vfx::stateFromFlPreset (std::vector<std::uint8_t> (b, b + bytes.getSize()), kind);
- int index = -1;
- for (int c = 0; c < lynx::vfx::kindCount; ++c)
- if (lynx::vfx::kindOf (offline.getSong().channels[(std::size_t) c]) == kind)
- index = c;
- if (! fl || index < 0)
- continue;
- offline.editSong ([&] (lynx::Song& s) {
- auto st = *lynx::vfx::readState (s.channels[(std::size_t) index].pluginState);
- st.fl = *fl;
- s.channels[(std::size_t) index].pluginState = lynx::vfx::writeState (st);
- });
- offline.dispatchPendingMessages();
- if (auto panel = lynx::makeChannelSettingsPanel (offline, index))
- {
- offline.dispatchPendingMessages();
- const auto name = prefix + "-" + juce::String (lynx::vfx::flName (kind)).replaceCharacter (' ', '-').toLowerCase();
- savePng (panel->createComponentSnapshot (panel->getLocalBounds()), name + "-fl.png");
- if (kind == lynx::vfx::Kind::script) // the editor's other tabs (round 165d)
- shootScriptTabs (*panel, offline, index, name);
- }
- }
- }
- lynx::PatcherWindows::openChannel (offline, lynx::vfx::kindCount);
- for (int k = 0; k < juce::TopLevelWindow::getNumTopLevelWindows(); ++k)
- if (auto* w = dynamic_cast<juce::DocumentWindow*> (juce::TopLevelWindow::getTopLevelWindow (k)))
- if (w->getName().startsWith (lynx::tr ("Patcher")) && w->getContentComponent() != nullptr)
- {
- auto* content = w->getContentComponent();
- savePng (content->createComponentSnapshot (content->getLocalBounds()), prefix + "-patcher.png");
- delete w;
- break;
- }
- lynx::PatcherWindows::shootMenus (offline, true, lynx::vfx::kindCount, 0, [&] (const juce::Image& image, const juce::String& name) {
- savePng (image, prefix + "-patcher-menu-" + name + ".png");
- });
- // a plugin renamed in the Plugin database ("1_EQ", FL): the Quick-add palette and the mixer slot show the new name
- if (juce::SystemStats::getEnvironmentVariable ("LYNX_TEST_MODE", {}).isNotEmpty())
- {
- const auto key = std::string ("lynx:fx:") + lynx::effectInfo (lynx::EffectKind::parametricEq).name;
- offline.getPluginHost().setPluginName (key, "1_EQ");
- offline.editSong ([] (lynx::Song& s) {
- if (s.mixer.size() > 1)
- {
- lynx::EffectSlot slot;
- slot.kind = lynx::EffectKind::parametricEq;
- s.mixer[1].effects.push_back (slot);
- }
- });
- offline.dispatchPendingMessages();
- {
- lynx::QuickAddTargets targets;
- targets.addInstrument = [] (lynx::ChannelDef) {};
- targets.addEffect = [] (lynx::EffectSlot) {};
- auto palette = lynx::makeQuickAddPalette (offline, std::move (targets));
- savePng (palette->createComponentSnapshot (palette->getLocalBounds()), prefix + "-quickadd-renamed.png");
- }
- ui.selectTabForSnapshot (3);
- ui.getMixerForSnapshot().selectTrack (1);
- offline.dispatchPendingMessages();
- savePng (ui.createComponentSnapshot (ui.getLocalBounds()), prefix + "-mixer-renamed.png");
- offline.getPluginHost().setPluginName (key, "");
- }
- }
- void runFeat166Shot (const juce::String& prefix, const juce::String& projectPath)
- {
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- lynx::AudioEngine offline (false);
- {
- lynx::MainComponent ui (offline, false);
- const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
- ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
- if (projectPath.isNotEmpty())
- ui.openFile (juce::File (projectPath));
- offline.dispatchPendingMessages();
- ui.selectTabForSnapshot (1); // the Piano Roll, on the channel with the most notes
- offline.dispatchPendingMessages();
- // the scale the pattern's notes fit best (major / minor, any root)
- const auto& song = offline.getSong();
- const auto& notes = song.patterns[(std::size_t) song.currentPattern].notes;
- int bestRoot = 0, bestScale = 1, bestHits = -1;
- for (int sc = 1; sc < (int) lynx::notetools::scales().size(); ++sc)
- {
- const juce::String name (lynx::notetools::scales()[(std::size_t) sc].name);
- if (name != "Major" && name != "Minor")
- continue;
- for (int root = 0; root < 12; ++root)
- {
- int hits = 0;
- for (const auto& n : notes)
- hits += lynx::notetools::inScale (n.key, root, sc) ? 1 : 0;
- if (hits > bestHits)
- bestHits = hits, bestRoot = root, bestScale = sc;
- }
- }
- auto& roll = ui.getPianoRollForSnapshot();
- roll.setScaleForSnapshot (bestRoot, bestScale);
- roll.scrollToNotes();
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-pr-scale.png");
- roll.setFoldToScale (true);
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-pr-folded.png");
- roll.setFoldToScale (false);
- // ghost channels: only the first other channel with notes stays a ghost
- const auto selected = offline.getSelectedChannel();
- int keep = -1;
- for (const auto& n : notes)
- if (n.channel != selected && keep < 0)
- keep = n.channel;
- offline.editSong ([keep] (lynx::Song& s) {
- for (int c = 0; c < (int) s.channels.size(); ++c)
- s.channels[(std::size_t) c].ghostHidden = c != keep;
- }, false);
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-pr-ghost-one.png");
- saveMenus (juce::StringArray { "Ghost channels" }, { roll.ghostChannelsMenu() }, prefix + "-ghostmenu.png");
- offline.editSong ([] (lynx::Song& s) {
- for (auto& c : s.channels)
- c.ghostHidden = false;
- }, false);
- // the Mixer at 500 inserts
- const auto t0 = juce::Time::getMillisecondCounterHiRes();
- offline.editSong ([] (lynx::Song& s) { lynx::mixerops::insertTracks (s, (int) s.mixer.size(), lynx::mixerops::roomForInserts (s)); }, false);
- const auto t1 = juce::Time::getMillisecondCounterHiRes();
- offline.dispatchPendingMessages();
- ui.selectTabForSnapshot (3);
- offline.dispatchPendingMessages();
- auto& mixer = ui.getMixerForSnapshot();
- const auto t2 = juce::Time::getMillisecondCounterHiRes();
- saveSnapshot (ui, prefix + "-mixer500-start.png");
- const auto t3 = juce::Time::getMillisecondCounterHiRes();
- mixer.selectTrack ((int) offline.getSong().mixer.size() - 1);
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-mixer500-end.png");
- juce::File (prefix + "-mixer500.txt")
- .replaceWithText ("inserts=" + juce::String ((int) offline.getSong().mixer.size() - 1) + "\nfill_ms=" + juce::String (t1 - t0, 2)
- + "\nsnapshot_ms=" + juce::String (t3 - t2, 2) + "\n");
- }
- }
- void runPerfShot (const juce::String& prefix, const juce::String& projectPath)
- {
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- lynx::AudioEngine offline (false);
- {
- lynx::MainComponent ui (offline, false);
- const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
- ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
- if (projectPath.isNotEmpty())
- ui.openFile (juce::File (projectPath));
- offline.dispatchPendingMessages();
- // LYNX_PERFSHOT_PREPARE=1: Tools › Macros › Prepare for performance mode first (16 one-bar columns)
- if (juce::SystemStats::getEnvironmentVariable ("LYNX_PERFSHOT_PREPARE", {}) == "1")
- offline.editSong ([] (lynx::Song& s) { lynx::perf::prepareForPerformance (s, 16, 4 * lynx::ppq); }, false);
- offline.editSong ([] (lynx::Song& s) { s.performanceMode = true; s.mode = lynx::PlayMode::song; }, false);
- offline.dispatchPendingMessages();
- // what the Player would publish: on each of the first tracks with zone clips, one clip playing (part way)
- // and on every other one the next clip waiting for its sync point
- const auto& song = offline.getSong();
- auto& live = offline.performanceStateForSnapshot();
- const auto zone = lynx::perf::zoneClips (song);
- int lastTrack = -1, launched = 0;
- for (const auto index : zone)
- {
- const auto& c = song.playlist[(std::size_t) index];
- if (c.track == lastTrack || c.track >= lynx::perf::maxTracks)
- continue;
- lastTrack = c.track;
- std::int64_t clips[64];
- const auto n = lynx::perf::trackZoneClips (song, zone, c.track, clips, 64);
- auto& view = live.tracks[(std::size_t) c.track];
- view.playing.store (clips[(std::size_t) ((launched % 3) % n)]);
- view.progress.store (0.2f + 0.15f * (float) (launched % 5));
- if (launched % 2 == 1 && n > 1)
- view.pending.store (clips[(std::size_t) ((launched % 3 + 1) % n)]);
- ++launched;
- }
- live.anyPlaying.store (launched > 0);
- ui.selectTabForSnapshot (2);
- offline.dispatchPendingMessages();
- auto& playlist = ui.getPlaylistForSnapshot();
- savePng (playlist.createComponentSnapshot (playlist.getLocalBounds()), prefix + "-playlist-song.png");
- playlist.runAction ("playlist.zoomPerformance"); // as FL opens these demos: the zone fills the view
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-playlist.png");
- savePng (playlist.createComponentSnapshot (playlist.getLocalBounds()), prefix + "-playlist-only.png");
- // patcherize: the first insert with effects (all of them) and the first channel that can be
- auto patched = offline.getSong();
- for (int t = 0; t < (int) patched.mixer.size(); ++t)
- if (lynx::patcherize::slotsForAll (patched, t).size() > 1)
- {
- lynx::patcherize::patcherizeSlots (patched, t, 0, true);
- break;
- }
- for (int c = 0; c < (int) patched.channels.size(); ++c)
- if (lynx::patcherize::patcherizeChannel (patched, c))
- break;
- juce::String error;
- lynx::ProjectFile::save (patched, juce::File (prefix + "-patcherized.lynx"), error);
- }
- }
- void runPatcherShot (const juce::String& prefix, const juce::String& projectPath)
- {
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- lynx::AudioEngine offline (false);
- {
- lynx::MainComponent ui (offline, false);
- ui.setSize (1280, 720);
- if (projectPath.isNotEmpty())
- ui.openFile (juce::File (projectPath));
- else
- {
- auto song = lynx::Song::makeDefault();
- song.mixer.resize (4);
- auto slot = lynx::makeEffectSlot (lynx::EffectKind::patcher);
- slot.patcher.wires.clear();
- for (auto [kind, x, y] : { std::tuple { lynx::EffectKind::frequencySplitter, 200.0f, 60.0f }, { lynx::EffectKind::reverb, 420.0f, 0.0f },
- { lynx::EffectKind::fruityDelay3, 420.0f, 120.0f }, { lynx::EffectKind::peakController, 200.0f, 260.0f } })
- {
- lynx::PatchNode n;
- n.effect = lynx::makeEffectSlot (kind);
- n.x = x;
- n.y = y;
- slot.patcher.nodes.push_back (n);
- }
- { // round 165c: a Hardware Insert node (its editor opens from the node)
- lynx::PatchNode n;
- n.effect = lynx::makeEffectSlot (lynx::EffectKind::hardwareInsert);
- n.x = 420.0f, n.y = 260.0f;
- slot.patcher.nodes.push_back (n);
- }
- auto wire = [&] (int from, int fromPort, int to, int toPort, float gain = 1.0f, lynx::PatchWire::Kind kind = lynx::PatchWire::Kind::audio) {
- lynx::PatchWire w;
- w.kind = kind;
- w.from = from, w.fromPort = fromPort, w.to = to, w.toPort = toPort, w.gain = gain;
- slot.patcher.wires.push_back (w);
- };
- wire (lynx::patchFromHost, 0, 0, 0);
- wire (0, 1, 1, 0);
- wire (0, 3, 2, 0, 0.5f);
- wire (1, 0, lynx::patchToHost, 0);
- wire (2, 0, lynx::patchToHost, 0);
- wire (lynx::patchFromHost, 1, 3, 0);
- wire (3, 1, 2, 2, 1.0f, lynx::PatchWire::Kind::control);
- wire (0, 2, lynx::patchToHost, 1, 0.7f);
- // round 171b (issue #65): a Surface knob on the reverb's parameter input 1, the reverb's parameter 0 out to
- // the delay's parameter input 2 (FL's Inputs / Outputs › Parameters)
- {
- lynx::SurfaceControl knob;
- knob.name = "Knob 1";
- knob.value = 0.6f;
- slot.patcher.surface = { knob };
- slot.patcher.surfaceX = 200.0f, slot.patcher.surfaceY = 380.0f;
- lynx::patcher::setParamInput (slot.patcher, 1, 1, true, "Reverb - 2");
- lynx::patcher::setParamOutput (slot.patcher, 1, 0, true);
- lynx::patcher::setParamInput (slot.patcher, 2, 2, true, "Delay - 3");
- wire (lynx::patchSurface, 0, 1, 1, 1.0f, lynx::PatchWire::Kind::control);
- wire (1, lynx::patchParamOutput (0), 2, 2, 1.0f, lynx::PatchWire::Kind::control);
- }
- slot.patcher.outputTracks = { 3 };
- slot.patcher.inputX = -20.0f;
- slot.patcher.outputX = 660.0f;
- song.mixer[1].effects = { slot };
- lynx::ChannelDef ch;
- ch.name = "Patcher";
- ch.instrument = lynx::InstrumentKind::patcher;
- lynx::PatchNode synth, chorus;
- synth.generator = true;
- synth.channel.instrument = lynx::InstrumentKind::synth;
- synth.channel.name = "Synth";
- synth.x = 220.0f;
- chorus.effect = lynx::makeEffectSlot (lynx::EffectKind::chorus);
- chorus.x = 420.0f;
- // round 162: a MIDI Out node between the "MIDI port 5" pin and "To LYNX" MIDI port 3, an Envelope Controller
- // on the notes moving the chorus
- lynx::PatchNode midiOut, envelope;
- midiOut.generator = envelope.generator = true;
- midiOut.channel.instrument = lynx::InstrumentKind::midiOut;
- midiOut.channel.name = "MIDI Out";
- lynx::midictl::writeMidiOut (midiOut.channel.pluginState, { 3, 0, 0, -1, -1 });
- midiOut.x = 220.0f, midiOut.y = 160.0f;
- envelope.channel.instrument = lynx::InstrumentKind::controller;
- envelope.channel.name = "Envelope Controller";
- envelope.channel.controllerState = lynx::writeEnvelopeController (lynx::defaultEnvelopeController());
- envelope.x = 220.0f, envelope.y = 260.0f;
- lynx::PatchNode osc; // round 164f: an FL engine node (its editor opens from the node)
- osc.generator = true;
- osc.channel = lynx::natives::makeChannel (lynx::InstrumentKind::threeosc, lynx::flStudioAccess()).value_or (lynx::ChannelDef {});
- osc.channel.instrument = lynx::InstrumentKind::threeosc;
- osc.channel.name = "3x Osc";
- osc.x = 420.0f, osc.y = 260.0f;
- // round 165c: Keyboard Controller, SoundFont player, Granulizer and Dashboard nodes (their editors open from the node)
- lynx::PatchNode keys, soundfont, granulizer, dashboard;
- keys.generator = soundfont.generator = granulizer.generator = dashboard.generator = true;
- keys.channel.instrument = lynx::InstrumentKind::controller;
- keys.channel.name = "Keyboard Controller";
- {
- lynx::KeyboardControllerData ramp;
- for (std::size_t k = 0; k < ramp.keys.size(); ++k)
- ramp.keys[k] = (float) k / (float) (ramp.keys.size() - 1);
- lynx::writeKeyboardController (ramp, keys.channel.controllerState);
- }
- soundfont.channel = lynx::sf::makeChannel();
- granulizer.channel = lynx::natives::makeChannel (lynx::InstrumentKind::granulizer, lynx::flStudioAccess()).value_or (lynx::ChannelDef {});
- granulizer.channel.instrument = lynx::InstrumentKind::granulizer;
- granulizer.channel.name = "Fruity Granulizer";
- dashboard.channel.instrument = lynx::InstrumentKind::dashboard;
- dashboard.channel.name = "Dashboard";
- dashboard.channel.patcher.surface = lynx::surface::starterControls();
- keys.x = 20.0f, keys.y = 440.0f;
- soundfont.x = 220.0f, soundfont.y = 440.0f;
- granulizer.x = 420.0f, granulizer.y = 440.0f;
- dashboard.x = 20.0f, dashboard.y = 540.0f;
- // and a Layer node playing the SoundFont and Granulizer nodes on its Children pin (crossfaded)
- lynx::PatchNode layerNode;
- layerNode.generator = true;
- layerNode.channel.instrument = lynx::InstrumentKind::layer;
- layerNode.channel.name = "Layer";
- layerNode.channel.layer.crossfade = true;
- layerNode.channel.layer.fade = 0.35f;
- layerNode.x = 220.0f, layerNode.y = 540.0f;
- ch.patcher.nodes = { synth, chorus, midiOut, envelope, osc, keys, soundfont, granulizer, dashboard, layerNode };
- lynx::PatchWire notes, a, b, portIn, portOut, envNotes, envControl;
- notes.kind = lynx::PatchWire::Kind::midi, notes.to = 0;
- a.from = 0, a.to = 1;
- b.from = 1;
- portIn.kind = lynx::PatchWire::Kind::midi, portIn.fromPort = lynx::patchMidiPortPin (5), portIn.to = 2;
- portOut.kind = lynx::PatchWire::Kind::midi, portOut.from = 2, portOut.to = lynx::patchToHost, portOut.toPort = 3;
- envNotes.kind = lynx::PatchWire::Kind::midi, envNotes.to = 3;
- envControl.kind = lynx::PatchWire::Kind::control, envControl.from = 3, envControl.to = 1, envControl.toPort = 0;
- lynx::PatchWire oscNotes, oscOut;
- oscNotes.kind = lynx::PatchWire::Kind::midi, oscNotes.to = 4;
- oscOut.from = 4;
- lynx::PatchWire layerNotes, layerToFont, layerToGrains, fontOut, grainsOut;
- layerNotes.kind = layerToFont.kind = layerToGrains.kind = lynx::PatchWire::Kind::midi;
- layerNotes.to = 9;
- layerToFont.from = 9, layerToFont.to = 6;
- layerToGrains.from = 9, layerToGrains.to = 7;
- fontOut.from = 6;
- grainsOut.from = 7;
- ch.patcher.wires = { notes, a, b, portIn, portOut, envNotes, envControl, oscNotes, oscOut, layerNotes, layerToFont, layerToGrains, fontOut, grainsOut };
- ch.patcher.fromMidiPorts = { 1, 5 };
- ch.patcher.toMidiPorts = { 3 };
- ch.patcher.outputX = 640.0f;
- song.channels.push_back (ch);
- // LYNX_PATCHERSHOT_SAVE=file.lynx: the demo as a project (a GUI check of the same Patchers, round 164f)
- if (const auto save = juce::SystemStats::getEnvironmentVariable ("LYNX_PATCHERSHOT_SAVE", {}); save.isNotEmpty())
- {
- if (! song.patterns.empty())
- for (int k = 0; k < 4; ++k)
- 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 });
- juce::String error;
- lynx::ProjectFile::save (song, juce::File (save), error);
- // round 171b: the saved Patchers come back the same (parameter ports, event cables, published)
- juce::String report;
- if (const auto loaded = lynx::ProjectFile::load (juce::File (save), error))
- {
- const auto same = loaded->mixer.size() > 1 && ! loaded->mixer[1].effects.empty()
- && loaded->mixer[1].effects[0].patcher == song.mixer[1].effects[0].patcher;
- const auto& d = loaded->mixer.size() > 1 && ! loaded->mixer[1].effects.empty() ? loaded->mixer[1].effects[0].patcher : lynx::PatcherDoc {};
- report << "patcher round trip: " << (same ? "OK" : "DIFFERENT") << "\n";
- if (! same && loaded->mixer.size() > 1 && ! loaded->mixer[1].effects.empty())
- {
- const auto& a = song.mixer[1].effects[0].patcher;
- report << "wires " << (a.wires == d.wires ? "same" : "differ") << ", published " << (a.published == d.published ? "same" : "differ")
- << ", surface " << (a.surface == d.surface ? "same" : "differ") << "\n";
- for (std::size_t n = 0; n < std::min (a.nodes.size(), d.nodes.size()); ++n)
- if (! (a.nodes[n] == d.nodes[n]))
- report << "node " << (int) n << " differs: ports " << (a.nodes[n].paramIns == d.nodes[n].paramIns && a.nodes[n].paramOuts == d.nodes[n].paramOuts ? "same" : "differ")
- << ", effect " << (a.nodes[n].effect == d.nodes[n].effect ? "same" : "differ") << ", xy "
- << (a.nodes[n].x == d.nodes[n].x && a.nodes[n].y == d.nodes[n].y ? "same" : "differ") << "\n";
- }
- for (int n = 0; n < (int) d.nodes.size(); ++n)
- report << "node " << n << " paramIns " << (int) d.nodes[(std::size_t) n].paramIns.size() << " paramOuts "
- << (int) d.nodes[(std::size_t) n].paramOuts.size() << "\n";
- for (const auto& w : d.wires)
- if (w.kind == lynx::PatchWire::Kind::control)
- report << "control " << w.from << ":" << w.fromPort << " -> " << w.to << ":" << w.toPort << "\n";
- for (const auto& p : d.published)
- report << "published " << p.node << ":" << p.param << " " << juce::String::fromUTF8 (p.name.c_str()) << "\n";
- }
- else
- report << "patcher round trip: load failed: " << error << "\n";
- juce::File (prefix + "-roundtrip.txt").replaceWithText (report);
- }
- offline.setSong (std::move (song));
- }
- offline.dispatchPendingMessages();
- const auto& song = offline.getSong();
- auto shootOpen = [&] (const juce::String& name) {
- for (int k = 0; k < juce::TopLevelWindow::getNumTopLevelWindows(); ++k)
- if (auto* w = dynamic_cast<juce::DocumentWindow*> (juce::TopLevelWindow::getTopLevelWindow (k)))
- if (w->getName().startsWith (lynx::tr ("Patcher")) && w->getContentComponent() != nullptr)
- {
- auto* c = w->getContentComponent();
- savePng (c->createComponentSnapshot (c->getLocalBounds()), prefix + name);
- delete w;
- return;
- }
- };
- int shots = 0;
- for (int t = 0; t < (int) song.mixer.size() && shots < 12; ++t)
- for (int s = 0; s < (int) song.mixer[(std::size_t) t].effects.size(); ++s)
- if (song.mixer[(std::size_t) t].effects[(std::size_t) s].kind == lynx::EffectKind::patcher)
- {
- lynx::PatcherWindows::openSlot (offline, t, s);
- shootOpen ("-insert" + juce::String (t) + "-slot" + juce::String (s) + ".png");
- // each built-in node's editor, as a double-click opens it (round 165c)
- lynx::PatcherWindows::shootNodeEditors (offline, false, t, s, [&] (const juce::Image& image, int n) {
- savePng (image, prefix + "-insert" + juce::String (t) + "-slot" + juce::String (s) + "-node" + juce::String (n) + ".png");
- });
- ++shots;
- if (shots == 1) // its menus (round 162)
- lynx::PatcherWindows::shootMenus (offline, false, t, s, [&] (const juce::Image& image, const juce::String& name) {
- savePng (image, prefix + "-menu-" + name + ".png");
- });
- }
- for (int c = 0; c < (int) song.channels.size(); ++c)
- if (song.channels[(std::size_t) c].instrument == lynx::InstrumentKind::patcher)
- {
- lynx::PatcherWindows::openChannel (offline, c);
- shootOpen ("-channel" + juce::String (c) + ".png");
- // each node's editor, as a double-click opens it (round 164f; every built-in node since round 165c)
- lynx::PatcherWindows::shootNodeEditors (offline, true, c, 0, [&] (const juce::Image& image, int n) {
- savePng (image, prefix + "-channel" + juce::String (c) + "-node" + juce::String (n) + ".png");
- });
- lynx::PatcherWindows::shootMenus (offline, true, c, 0, [&] (const juce::Image& image, const juce::String& name) {
- savePng (image, prefix + "-channel" + juce::String (c) + "-menu-" + name + ".png");
- });
- }
- }
- }
- // Issue #64: FL's letter keys in a plugin menu (quickpick::showMenu), checked on the real menu windows
- struct TypeAheadTest final : private juce::Timer
- {
- juce::File out;
- juce::StringArray log;
- int step = 0, picked = 0;
- bool ok = true, menuShown = false;
- std::unique_ptr<juce::DocumentWindow> owner;
- juce::PopupMenu pending;
- static juce::String highlighted()
- {
- if (auto* window = juce::Component::getCurrentlyModalComponent())
- for (auto* child : window->getChildren())
- if (auto* h = child->getAccessibilityHandler(); h != nullptr && h->hasFocus (false))
- return h->getTitle();
- return "(none)";
- }
- static void press (const juce::KeyPress& key)
- {
- if (auto* window = juce::Component::getCurrentlyModalComponent())
- if (auto* peer = window->getPeer())
- peer->handleKeyPress (key);
- }
- void expect (const juce::String& what, const juce::String& got, const juce::String& wanted)
- {
- const auto good = got == wanted;
- ok = ok && good;
- log.add ((good ? "ok " : "FAIL ") + what + ": " + got + (good ? juce::String() : " (wanted " + wanted + ")"));
- }
- void start()
- {
- juce::PopupMenu menu, sub;
- auto item = [this] (juce::PopupMenu& m, int id, const char* text, bool enabled = true) {
- m.addItem (text, enabled, false, [this, id] { picked = id; });
- };
- menu.addSectionHeader ("LYNX SHARE");
- item (menu, 1, "Echoform");
- item (menu, 2, "EQ");
- item (menu, 3, "Halo");
- menu.addSectionHeader ("Misc");
- item (menu, 4, "Effector");
- item (menu, 5, "Exciter (unavailable)", false);
- item (sub, 10, "Delay");
- item (sub, 11, "Edison");
- item (sub, 12, "Eventide");
- menu.addSubMenu ("Tree", sub);
- // the menu belongs to a window in the foreground, as when the user right-clicks a mixer slot (JUCE closes a
- // menu of a background process at once)
- owner = std::make_unique<juce::DocumentWindow> ("LYNX type-ahead test", juce::Colours::black, 0);
- owner->setBounds (200, 200, 300, 200);
- owner->setVisible (true);
- lynx::forceForegroundForTest (*owner);
- pending = menu; // shown once the window is up and active (X11 maps and activates it asynchronously)
- startTimer (300);
- }
- void timerCallback() override
- {
- const auto e = juce::KeyPress ('e', {}, 'e');
- if (step == 0 && owner != nullptr && ! menuShown)
- {
- menuShown = true;
- lynx::forceForegroundForTest (*owner);
- lynx::quickpick::showMenu (pending, juce::PopupMenu::Options().withTargetComponent (owner.get()), {});
- return;
- }
- switch (step++)
- {
- case 0: expect ("menu open", juce::String ((int) (juce::Component::getCurrentlyModalComponent() != nullptr)), "1"); break;
- case 1: press (e); expect ("e", highlighted(), "Echoform"); break;
- case 2: press (e); expect ("e again", highlighted(), "EQ"); break;
- case 3: press (juce::KeyPress ('E', juce::ModifierKeys::shiftModifier, 'E')); expect ("E (shift)", highlighted(), "Effector"); break;
- case 4: press (e); expect ("e wraps (skips the disabled one)", highlighted(), "Echoform"); break;
- case 5: press (juce::KeyPress ('m', {}, 'm')); expect ("m (only a heading starts with it: no move)", highlighted(), "Echoform"); break;
- case 6: press (juce::KeyPress (juce::KeyPress::downKey)); expect ("down arrow", highlighted(), "EQ"); break;
- case 7: press (e); expect ("e after the arrow", highlighted(), "Effector"); break;
- case 8: press (juce::KeyPress ('t', {}, 't')); expect ("t", highlighted(), "Tree"); break;
- case 9: press (juce::KeyPress (juce::KeyPress::rightKey)); break; // opens the submenu (it takes the keys)
- case 10: press (e); expect ("e in the submenu", highlighted(), "Edison"); break;
- case 11: press (e); expect ("e again in the submenu", highlighted(), "Eventide"); break;
- case 12: expect ("nothing picked by the letters", juce::String (picked), "0"); press (juce::KeyPress (juce::KeyPress::returnKey)); break;
- case 13: break;
- default:
- expect ("Enter closed the menu", juce::String ((int) (juce::Component::getCurrentlyModalComponent() == nullptr)), "1");
- expect ("Enter picked", juce::String (picked), "12");
- stopTimer();
- owner.reset();
- log.add (ok ? "result=OK" : "result=FAIL");
- out.replaceWithText (log.joinIntoString ("\n") + "\n");
- juce::JUCEApplication::getInstance()->setApplicationReturnValue (ok ? 0 : 1);
- juce::JUCEApplication::quit();
- return;
- }
- }
- };
- std::unique_ptr<TypeAheadTest> typeAheadTest;
- struct ChooserTest final : private juce::Timer
- {
- juce::File out, file;
- juce::StringArray log;
- std::unique_ptr<juce::FileChooser> chooser;
- double started = 0;
- bool shot = false, done = false;
- void start()
- {
- log.add ("LYNX_FILE_DIALOG=" + juce::SystemStats::getEnvironmentVariable ("LYNX_FILE_DIALOG", {}));
- log.add ("native=" + juce::String ((int) lynx::ui::filechooser::nativeDialogs()));
- chooser = lynx::ui::makeFileChooser ("Open audio file", file.getParentDirectory(), "*.wav;*.flac");
- started = juce::Time::getMillisecondCounterHiRes();
- lynx::ui::launchChooser (chooser, juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectFiles,
- [this] (const juce::FileChooser& fc) { finish (fc.getResult()); });
- startTimer (200);
- }
- static juce::FileChooserDialogBox* builtInDialog()
- {
- for (int i = 0; i < juce::Desktop::getInstance().getNumComponents(); ++i)
- if (auto* box = dynamic_cast<juce::FileChooserDialogBox*> (juce::Desktop::getInstance().getComponent (i)); box != nullptr && box->isShowing())
- return box;
- return nullptr;
- }
- static juce::FileBrowserComponent* findBrowser (juce::Component& c)
- {
- if (auto* b = dynamic_cast<juce::FileBrowserComponent*> (&c))
- return b;
- for (auto* child : c.getChildren())
- if (auto* b = findBrowser (*child))
- return b;
- return nullptr;
- }
- void timerCallback() override
- {
- if (done)
- return;
- if (auto* box = builtInDialog(); box != nullptr && ! shot)
- {
- shot = true;
- log.add ("built-in dialog shown after " + juce::String (juce::roundToInt (juce::Time::getMillisecondCounterHiRes() - started)) + " ms");
- const auto image = box->createComponentSnapshot (box->getLocalBounds());
- juce::FileOutputStream png (out.getSiblingFile (out.getFileName() + ".png"));
- if (png.openedOk())
- {
- png.setPosition (0), png.truncate();
- juce::PNGImageFormat().writeImageToStream (image, png);
- }
- if (auto* browser = findBrowser (*box))
- {
- browser->setRoot (file.getParentDirectory());
- browser->setFileName (file.getFileName());
- log.add ("typed " + file.getFileName());
- box->exitModalState (1);
- }
- else
- log.add ("no file browser in the dialog");
- }
- if (juce::Time::getMillisecondCounterHiRes() - started > 30000.0)
- finish ({}, "timeout");
- }
- void finish (const juce::File& result, const juce::String& why = {})
- {
- if (done)
- return;
- done = true;
- stopTimer();
- log.add ("callback after " + juce::String (juce::roundToInt (juce::Time::getMillisecondCounterHiRes() - started)) + " ms: "
- + (why.isNotEmpty() ? why : result.getFullPathName().isEmpty() ? juce::String ("(no file)") : result.getFullPathName()));
- log.add ("native now=" + juce::String ((int) lynx::ui::filechooser::nativeDialogs()));
- const auto ok = result == file && result.existsAsFile();
- log.add (ok ? "result=OK" : "result=FAIL");
- out.replaceWithText (log.joinIntoString ("\n") + "\n");
- juce::JUCEApplication::getInstance()->setApplicationReturnValue (ok ? 0 : 1);
- juce::MessageManager::callAsync ([] { juce::JUCEApplication::quit(); });
- }
- };
- std::unique_ptr<ChooserTest> chooserTest;
- void runChooserTest (const juce::File& out, const juce::File& file)
- {
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- chooserTest = std::make_unique<ChooserTest>();
- chooserTest->out = out;
- chooserTest->file = file;
- chooserTest->start();
- }
- void runTypeAheadTest (const juce::File& out)
- {
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- typeAheadTest = std::make_unique<TypeAheadTest>();
- typeAheadTest->out = out;
- typeAheadTest->start();
- }
- void runSnapshot (const juce::String& prefix, const juce::String& projectPath)
- {
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- // LYNX_SNAPSHOT_THEME=file.lynxtheme: the pictures in that theme (round 162d)
- if (const auto themeFile = juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_THEME", {}); themeFile.isNotEmpty())
- if (const auto spec = lynx::themeui::loadFile (juce::File (themeFile)))
- lynx::themeui::apply (*spec, false);
- {
- lynx::AudioEngine offline (false);
- lynx::MainComponent ui (offline, false); // default layout and keys, nothing saved
- // LYNX_SNAPSHOT_SIZE=WxH (default 1280x720)
- const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1280x720"), "x", "");
- ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
- if (projectPath.isNotEmpty())
- ui.openFile (juce::File (projectPath));
- offline.dispatchPendingMessages(); // change notifications are asynchronous
- ui.waitForBrowserForSnapshot();
- // the workspace desktop: the default layout, then with the Piano Roll and Mixer floating too
- // (and a sample hint in the status strip, as when hovering a knob)
- ui.showDesktopForSnapshot (false);
- ui.setMetersForSnapshot (0.23, (std::int64_t) 412 << 20, 6);
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-desktop.png");
- // the first start: the setup wizard over the main window (round 140), also on a small screen (it scrolls)
- {
- const auto size = ui.getBounds();
- ui.showSetupWizard();
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-desktop-setup.png");
- ui.setSize (1024, 600);
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-desktop-setup-small.png");
- ui.closeSetupWizardForSnapshot();
- ui.setBounds (size);
- offline.dispatchPendingMessages();
- }
- // the start-up desktop and the toolbar at the usual window sizes: the untouched default layout
- // follows the window (default rects, not scaled ones); panels drop from the toolbar by priority
- {
- const auto size = ui.getBounds();
- for (const auto& [w, h] : std::vector<std::pair<int, int>> { { 1280, 720 }, { 1366, 768 }, { 1600, 900 }, { 1920, 1080 }, { 2560, 1440 }, { 3840, 2160 } })
- {
- ui.setSize (w, h);
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-desktop-" + juce::String (w) + ".png");
- saveArea (ui, ui.getToolbarBoundsForSnapshot(), prefix + "-toolbar-" + juce::String (w) + ".png");
- if (w == 1920) // the rack scrolled to its last steps: the controls column stays in view (round 90)
- {
- ui.scrollRackForSnapshot (100000);
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-desktop-rack-scrolled.png");
- ui.scrollRackForSnapshot (0);
- }
- }
- // the toolbar with small and large icons, and a customized one (groups hidden and reordered)
- ui.setSize (1600, 900);
- for (auto [iconSize, name] : { std::pair { lynx::toolbarlayout::IconSize::small, "small" }, { lynx::toolbarlayout::IconSize::large, "large" } })
- {
- auto layout = lynx::toolbarlayout::Layout::makeDefault();
- layout.iconSize = iconSize;
- ui.setToolbarLayoutForSnapshot (layout);
- saveArea (ui, ui.getToolbarBoundsForSnapshot(), prefix + "-toolbar-" + name + "-1600.png");
- }
- {
- auto layout = lynx::toolbarlayout::Layout::makeDefault();
- layout.move (lynx::toolbarlayout::Group::windows, -3);
- layout.setShown (lynx::toolbarlayout::Group::record, false);
- layout.setShown (lynx::toolbarlayout::Group::meters, false);
- ui.setToolbarLayoutForSnapshot (layout);
- saveArea (ui, ui.getToolbarBoundsForSnapshot(), prefix + "-toolbar-custom-1600.png");
- }
- {
- // round 170e: the toolbar after a knob was moved: the last tweaked read-out (its caption) and the snap magnet
- ui.setSize (1920, 1080); // the read-out needs room beside the hint bar
- ui.setToolbarLayoutForSnapshot (lynx::toolbarlayout::Layout::makeDefault());
- lynx::AutomationTarget t;
- t.kind = lynx::AutomationTargetKind::mixerVolume;
- t.index = 0;
- offline.noteTweaked (t);
- ui.refreshTweakReadoutForSnapshot();
- offline.dispatchPendingMessages();
- saveArea (ui, ui.getToolbarBoundsForSnapshot(), prefix + "-toolbar-tweak-1920.png");
- ui.setSize (1600, 900);
- }
- {
- // the toolbar's edit mode (round 115): outlined panels and the tray of panels under it
- ui.setToolbarLayoutForSnapshot (lynx::toolbarlayout::Layout::makeDefault());
- auto layout = lynx::toolbarlayout::Layout::makeDefault();
- layout.setShown (lynx::toolbarlayout::Group::meters, false);
- ui.setToolbarLayoutForSnapshot (layout);
- ui.setToolbarEditingForSnapshot (true);
- offline.dispatchPendingMessages();
- saveArea (ui, ui.getToolbarBoundsForSnapshot().withHeight (ui.getToolbarAndTrayHeightForSnapshot()), prefix + "-toolbar-edit-1600.png");
- ui.setToolbarEditingForSnapshot (false);
- // Ctrl+F11: only the menu and the hint bar
- layout = lynx::toolbarlayout::Layout::makeDefault();
- layout.visible = false;
- ui.setToolbarLayoutForSnapshot (layout);
- saveArea (ui, ui.getLocalBounds().withHeight (120), prefix + "-toolbar-hidden-1600.png");
- }
- ui.setToolbarLayoutForSnapshot (lynx::toolbarlayout::Layout::makeDefault());
- // quick tips: the toolbar and title bars with a few name bubbles, and every tip on one sheet
- offline.dispatchPendingMessages();
- saveQuickTips (ui, prefix);
- ui.setBounds (size);
- offline.dispatchPendingMessages();
- }
- // the hint bar: a value control while it is dragged (live value), a gesture line with mouse and key
- // glyphs, and a text too long for one line (two lines)
- {
- const auto toolbar = ui.getToolbarBoundsForSnapshot().withWidth (juce::jmin (ui.getWidth(), 900));
- const lynx::ui::Hint hints[] = {
- { lynx::tr ("Volume") + " - " + lynx::tr ("drag (Ctrl: fine), wheel, Alt+click resets"), "-3.2 dB", true, true },
- { lynx::tr ("Piano Roll: [LMB] add a note, drag to move [RMB] delete [Ctrl][LMB] drag to select [Ctrl][Wheel] zoom"), {}, false, false },
- { lynx::tr ("Global snap: the grid of the Piano Roll and Playlist (when they follow it) and the quantise of recorded notes "
- "[LMB] choose [Wheel] step [RMB] length of new notes [Backspace] snap on/off [Alt] while dragging: no snap"), {}, false, true },
- };
- for (int i = 0; i < 3; ++i)
- {
- ui.setHintForSnapshot (hints[i], i == 0);
- saveArea (ui, toolbar, prefix + "-hint-" + juce::String (i + 1) + ".png");
- }
- }
- ui.showDesktopForSnapshot (true);
- ui.setHintForSnapshot ({ lynx::tr ("Volume") + " - " + lynx::tr ("drag (Ctrl: fine), wheel, Alt+click resets"), "78%", true, true });
- saveSnapshot (ui, prefix + "-desktop-all.png");
- ui.selectTabForSnapshot (0);
- saveSnapshot (ui, prefix + "-rack.png");
- {
- // a pattern with piano-roll notes: those rows show a miniature instead of steps (round 90)
- int found = -1;
- const auto before = offline.getSong().currentPattern;
- {
- const auto& song = offline.getSong();
- for (int p = 0; p < (int) song.patterns.size() && found < 0; ++p)
- for (int c = 0; c < (int) song.channels.size() && found < 0; ++c)
- if (lynx::showsNotePreview (song.patterns[(std::size_t) p], c))
- found = p;
- }
- if (found >= 0)
- {
- offline.editSong ([found] (lynx::Song& s) { s.currentPattern = found; }, false);
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-rack-preview.png");
- offline.editSong ([before] (lynx::Song& s) { s.currentPattern = before; }, false);
- offline.dispatchPendingMessages();
- }
- }
- ui.selectTabForSnapshot (1);
- saveSnapshot (ui, prefix + "-pianoroll.png");
- if (const auto strip = ui.getToolStripAreaForSnapshot (false); ! strip.isEmpty())
- saveArea (ui, strip, prefix + "-pianoroll-tools.png");
- // the editors' mouse feel: the hovered note / clip edge (grip, outline) and its hint in the hint bar
- ui.setHintForSnapshot (ui.getPianoRollForSnapshot().hoverForSnapshot());
- saveSnapshot (ui, prefix + "-pianoroll-hover.png");
- ui.selectTabForSnapshot (2);
- saveSnapshot (ui, prefix + "-playlist.png");
- if (const auto strip = ui.getToolStripAreaForSnapshot (true); ! strip.isEmpty())
- saveArea (ui, strip, prefix + "-playlist-tools.png");
- ui.setHintForSnapshot (ui.getPlaylistForSnapshot().hoverForSnapshot());
- saveSnapshot (ui, prefix + "-playlist-hover.png");
- ui.setHintForSnapshot ({ lynx::tr ("Volume") + " - " + lynx::tr ("drag (Ctrl: fine), wheel, Alt+click resets"), "78%", true, true });
- // the Playlist with a time selection over bars 2-3 (it selects the clips it touches) and the Knife tool
- ui.getPlaylistForSnapshot().setTimeSelectionForSnapshot (1, 3);
- ui.getPlaylistForSnapshot().setToolForSnapshot (lynx::EditTool::knife);
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-playlist-timesel.png");
- ui.getPlaylistForSnapshot().setToolForSnapshot (lynx::EditTool::pencil);
- // round 104: a folded track group (FL's thin member rows) and the Picker's audio tab
- {
- int header = -1;
- for (int t = 0; t < (int) offline.getSong().playlistTracks.size() && header < 0; ++t)
- if (lynx::noteedit::isGroupHeader (offline.getSong(), t))
- header = t;
- if (header >= 0)
- {
- offline.editSong ([header] (lynx::Song& s) { lynx::noteedit::setGroupCollapsed (s, header, true); }, false);
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-playlist-group-folded.png");
- offline.editSong ([header] (lynx::Song& s) { lynx::noteedit::setGroupCollapsed (s, header, false); }, false);
- }
- ui.getPickerForSnapshot().setView (1);
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-playlist-picker-audio.png");
- ui.getPickerForSnapshot().setView (0);
- }
- // round 104: the Channel Rack filtered to its first filter group
- if (! offline.getSong().channelGroups.empty())
- {
- ui.selectTabForSnapshot (0);
- ui.getRackForSnapshot().setFilterGroup (0);
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-rack-filter.png");
- ui.getRackForSnapshot().setFilterGroup (-1);
- }
- ui.selectTabForSnapshot (3);
- // LYNX_SNAPSHOT_TRACK=n: shows the effects of that mixer track
- if (const auto track = juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_TRACK", {}); track.isNotEmpty())
- {
- ui.selectMixerTrackForSnapshot (track.getIntValue(),
- juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SLOT", "-1").getIntValue());
- offline.dispatchPendingMessages();
- }
- saveSnapshot (ui, prefix + "-mixer.png");
- // round 168h (issue #52): FL's 8 Mixer layouts
- {
- const auto before = lynx::MixerStrips::layout;
- for (int l = 0; l < lynx::mixerlayout::layoutCount; ++l)
- {
- ui.getMixerForSnapshot().getStripsForSnapshot().setLayout ((lynx::mixerlayout::Layout) l);
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-mixer168h-" + juce::String (l) + ".png");
- }
- ui.getMixerForSnapshot().getStripsForSnapshot().setLayout (before);
- offline.dispatchPendingMessages();
- }
- // round 163: the Mixer at short heights (UI zoom 150%+): the EQ folds, then the effects panel scrolls
- {
- const auto size = ui.getBounds();
- for (auto h : { 450, 560, 680, 820 })
- {
- ui.setSize (size.getWidth(), h);
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-mixer163-" + juce::String (h) + ".png");
- }
- ui.setBounds (size);
- offline.dispatchPendingMessages();
- }
- // round 170b (Busy Works Beats' review): inserts 1-3 selected and routed together to insert 4, a single effect
- // moved down into slot 2 (FL's slot places), and the plugin menus grouped by category, LYNX SHARE first
- {
- const auto before = offline.getSong();
- offline.editSong ([] (lynx::Song& s) {
- if (s.mixer.size() < 5)
- return;
- s.mixer[1].effects.clear();
- lynx::EffectSlot fx;
- fx.kind = lynx::EffectKind::compressor;
- s.mixer[1].effects.push_back (fx);
- lynx::mixerops::moveEffectBy (s, 1, 0, 1);
- lynx::mixerops::switchSelectedRoute (s, { 1, 2, 3 }, 4, true);
- });
- ui.selectMixerTrackForSnapshot (1);
- ui.getMixerForSnapshot().getStripsForSnapshot().setSelection ({ 1, 2, 3 }, 1);
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-mixer170b.png");
- juce::PopupMenu effects, generators;
- lynx::quickpick::addFolderGroups (effects, offline, std::function<void (lynx::EffectSlot)> ([] (lynx::EffectSlot) {}));
- lynx::quickpick::addFolderViewItems (effects, offline);
- lynx::quickpick::addGeneratorMenu (generators, offline, [] (lynx::ChannelDef) {}, {}, nullptr, nullptr);
- lynx::quickpick::addFolderViewItems (generators, offline);
- saveMenus (juce::StringArray { "Mixer slot: add an effect", "Channel Rack: add" }, { effects, generators }, prefix + "-menus170b.png");
- offline.setSong (before);
- offline.dispatchPendingMessages();
- }
- // standalone windows, with the theme background
- auto saveWindow = [&prefix] (std::unique_ptr<juce::Component> c, const juce::String& name) {
- juce::Component frame;
- frame.setSize (c->getWidth(), c->getHeight());
- frame.setOpaque (true);
- frame.addAndMakeVisible (*c);
- c->setTopLeftPosition (0, 0);
- checkTextFit (*c, name.fromFirstOccurrenceOf ("-", false, false).upToLastOccurrenceOf (".", false, false));
- juce::Image image (juce::Image::ARGB, frame.getWidth(), frame.getHeight(), true);
- {
- juce::Graphics g (image);
- g.fillAll (lynx::theme::panel);
- frame.paintEntireComponent (g, false);
- }
- const juce::File file (prefix + name);
- file.deleteFile();
- juce::PNGImageFormat png;
- if (auto out = file.createOutputStream())
- png.writeImageToStream (image, *out);
- };
- saveWindow (lynx::makeExportPanel (offline), "-export.png");
- saveWindow (lynx::makeExportPanel (offline, 1), "-export-mp3.png");
- saveWindow (lynx::makeExportPanel (offline, 3), "-export-flac-stems.png");
- {
- // REA round 165f-mixer: the mixer track's Track latency / routing submenus, Disk recording, PDC, and the
- // Export window for "Render selected tracks to wave file(s)"
- const auto before = offline.getSong();
- offline.editSong ([] (lynx::Song& s) {
- if (s.mixer.size() > 3)
- {
- s.mixer[1].latencyMs = 5.0f;
- s.mixer[1].latencyBypass = lynx::LatencyBypass::whenRecordingOrStopped;
- s.mixer[2].latencyMs = -1.5f;
- }
- });
- offline.dispatchPendingMessages();
- auto& strips = ui.getMixerForSnapshot().getStripsForSnapshot();
- strips.setSelection ({ 1, 2, 3 }, 1);
- const auto menu = strips.buildMenu (1);
- juce::StringArray names { "Mixer track" };
- std::vector<juce::PopupMenu> menus { menu };
- const auto latencyPrefix = lynx::tr ("Track latency: {0}", { juce::String() });
- const juce::String wanted[] = { lynx::tr ("Selected tracks ⇄ this track"), lynx::tr ("Disk recording"),
- lynx::tr ("Plugin delay compensation") };
- for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
- {
- const auto& item = it.getItem();
- if (item.subMenu != nullptr && (item.text.startsWith (latencyPrefix) || std::find (std::begin (wanted), std::end (wanted), item.text) != std::end (wanted)))
- {
- names.add (item.text.upToFirstOccurrenceOf (":", false, false));
- menus.push_back (*item.subMenu);
- }
- }
- saveMenus (names, menus, prefix + "-menus165-mixer.png");
- saveWindow (lynx::makeExportPanelForTracks (offline, { 1, 2, 3 }), "-export165-tracks.png");
- offline.setSong (before);
- offline.dispatchPendingMessages();
- }
- saveSplashFrames (prefix);
- saveIconSheet (prefix + "-icons.png", 1.0f);
- saveIconSheet (prefix + "-icons-150.png", 1.5f);
- saveWindow (lynx::MainComponent::makeHelpContent(), "-help.png");
- saveWindow (lynx::ui::makeTrackIconGrid (5, {}), "-trackicons168h.png"); // round 168h: the icon picker
- saveWindow (std::make_unique<lynx::toolbar::CustomizePanel> (lynx::toolbarlayout::Layout::makeDefault()), "-customize-toolbar.png");
- // two moved controls: Tools › Last tweaked and Add › Automation for last tweaked parameter show them (REA round 143)
- offline.noteTweaked ({ lynx::AutomationTargetKind::channelVolume, 0 });
- offline.noteTweaked ({ lynx::AutomationTargetKind::mixerVolume, 0 });
- saveMenus (ui, prefix + "-menus.png");
- {
- // the windows' own menus (title bars) and the toolbar's recording menu
- juce::StringArray names;
- std::vector<juce::PopupMenu> menus;
- for (auto [panel, name] : { std::pair { lynx::workspace::Panel::playlist, "Playlist" }, { lynx::workspace::Panel::channelRack, "Channel Rack" },
- { lynx::workspace::Panel::pianoRoll, "Piano Roll" }, { lynx::workspace::Panel::mixer, "Mixer" },
- { lynx::workspace::Panel::browser, "Browser" } })
- {
- names.add (name);
- menus.push_back (ui.getPanelMenuForSnapshot (panel));
- }
- names.add ("Recording");
- menus.push_back (ui.getRecordMenuForSnapshot());
- names.add ("Toolbar");
- menus.push_back (ui.getToolbarMenuForSnapshot());
- saveMenus (names, menus, prefix + "-panel-menus.png");
- }
- {
- // REA round 143: the piano roll Tools menu, a Playlist track menu and a mixer insert menu (FL's layouts)
- std::vector<juce::PopupMenu> menus { ui.getPianoRollForSnapshot().getToolsMenuForSnapshot(),
- ui.getPlaylistForSnapshot().getTrackMenuForSnapshot (0),
- ui.getMixerForSnapshot().getStripsForSnapshot().buildMenu (1) };
- saveMenus (juce::StringArray { "Piano roll tools", "Playlist track", "Mixer track" }, menus, prefix + "-menus143.png");
- // round 167l: the channel menu ("Lock active/mute state")
- if (! offline.getSong().channels.empty())
- saveMenus (juce::StringArray { "Channel" }, std::vector<juce::PopupMenu> { ui.getRackForSnapshot().getChannelMenuForSnapshot (0) }, prefix + "-channel-menu.png");
- // round 163: menu density, compact (default) and comfortable, on a Browser folder menu
- {
- juce::PopupMenu folder;
- folder.addSectionHeader ("Documents");
- folder.addItem (1, "Expand all");
- folder.addItem (2, "Collapse all");
- folder.addSeparator();
- folder.addItem (3, "Refresh");
- folder.addSectionHeader ("System");
- folder.addItem (4, "Open");
- folder.addItem (5, "Copy the file path");
- folder.addSectionHeader ("Tags");
- folder.addItem (6, "Starred", true, true);
- folder.addSeparator();
- folder.addItem (7, "Add folder...");
- const auto wasCompact = lynx::theme::menus::compact();
- lynx::theme::menus::setCompact (true);
- saveMenus (juce::StringArray { "Compact" }, { folder }, prefix + "-menu163-compact.png");
- lynx::theme::menus::setCompact (false);
- saveMenus (juce::StringArray { "Comfortable" }, { folder }, prefix + "-menu163-comfortable.png");
- lynx::theme::menus::setCompact (wasCompact);
- }
- // and the clip menus of the first pattern, audio and automation clips of the project
- juce::StringArray clipNames;
- std::vector<juce::PopupMenu> clipMenus;
- for (auto [kind, name] : { std::pair { lynx::ClipKind::pattern, "Pattern clip" }, { lynx::ClipKind::audio, "Audio clip" },
- { lynx::ClipKind::automation, "Automation clip" } })
- for (int c = 0; c < (int) offline.getSong().playlist.size(); ++c)
- if (offline.getSong().playlist[(std::size_t) c].kind == kind)
- {
- clipNames.add (name);
- clipMenus.push_back (ui.getPlaylistForSnapshot().getClipMenuForSnapshot (c));
- break;
- }
- if (! clipMenus.empty())
- saveMenus (clipNames, clipMenus, prefix + "-menus143-clips.png");
- }
- auto saveAlert = [&] (std::unique_ptr<juce::AlertWindow> alert, const juce::String& name) {
- alert->setOpaque (true);
- saveWindow (std::move (alert), name);
- };
- saveAlert (ui.makeConfirmDiscardWindow(), "-confirm.png");
- saveAlert (lynx::MainComponent::makeAboutWindow(), "-about.png");
- saveAlert (lynx::makeNameAndColourDialog (lynx::tr ("Rename pattern"), "Pattern 2", lynx::lynxPalette()[6]), "-rename.png");
- saveAlert (lynx::makeRecordChoiceDialog(), "-record-dialog.png");
- saveAlert (lynx::makeSamplePitchDialog (7.25f, true, true), "-sample-pitch.png"); // round 163c
- saveAlert (lynx::makeMidiImportDialog(), "-midi-import-dialog.png"); // File › Import › MIDI file (REA round 143)
- saveWindow (lynx::makeSetupWizardContent (offline, {}, {}), "-setup.png");
- saveWindow (lynx::crashreporter::makeDialogForSnapshot (false), "-crash-report.png"); // round 159
- saveWindow (lynx::crashreporter::makeDialogForSnapshot (true), "-report-problem.png");
- // round 166b: the update bar in its states (available, downloading, failed, ready) and the release notes window
- {
- struct Bars final : juce::Component
- {
- Bars()
- {
- constexpr int h = lynx::updater::UpdateBar::height;
- setSize (1100, 4 * (h + 6));
- for (int state = 0; state < 4; ++state)
- {
- bars[state].setBounds (0, state * (h + 6), getWidth(), h);
- bars[state].showForSnapshot (state);
- addAndMakeVisible (bars[state]);
- }
- }
- lynx::updater::UpdateBar bars[4];
- };
- saveWindow (std::make_unique<Bars>(), "-update-bar.png");
- saveWindow (lynx::updater::makeReleaseNotesForSnapshot(), "-update-notes.png");
- }
- saveWindow (lynx::makeMissingFilesPanel (lynx::missingFilesSnapshotInfo(), 0, 1), "-missing-files.png");
- saveWindow (lynx::makeMissingFilesPanel (lynx::missingFilesSnapshotInfo(), 1), "-missing-plugins.png");
- saveWindow (lynx::makeMissingFilesPanel (lynx::missingFilesSnapshotInfo(), 2), "-missing-found.png");
- {
- // the Settings pages, with credits like a project imported from FL would carry
- offline.editSong ([] (lynx::Song& s) {
- s.info = { "Night Drive", "LYNX SHARE demo", "Synthwave", "https://lynx-share.com",
- "Made with LYNX SHARE.\nDrums and bass from the Channel Rack, pads from the Browser.", false };
- }, false);
- saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::project), "-settings-project.png");
- saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::info), "-settings-info.png");
- saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::files), "-settings-files.png");
- saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::general), "-settings-general.png");
- saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::theme), "-settings-theme.png");
- saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::audio), "-settings-audio.png");
- saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::midi), "-settings-midi.png");
- saveWindow (lynx::makePluginManagerPanel (offline, false), "-plugin-manager.png");
- saveWindow (lynx::makeShortcutManagerPanel (false), "-shortcuts.png");
- }
- {
- // round 84: New project, Clip properties, Arrangements, Plugin performance monitor, Touch keyboard
- saveWindow (lynx::makeNewProjectPanel(), "-new-project.png");
- const auto& clips = offline.getSong().playlist;
- for (int i = 0; i < (int) clips.size(); ++i)
- if (clips[(std::size_t) i].kind == lynx::ClipKind::pattern)
- {
- saveWindow (lynx::makeClipPropertiesPanel (offline, i, { i, (i + 1) % (int) clips.size() }), "-clip-properties.png");
- break;
- }
- for (int i = 0; i < (int) clips.size(); ++i)
- if (clips[(std::size_t) i].kind == lynx::ClipKind::audio)
- {
- saveWindow (lynx::makeClipPropertiesPanel (offline, i, { i }), "-clip-properties-audio.png");
- break;
- }
- if (offline.getSong().arrangements.size() < 2)
- offline.editSong ([] (lynx::Song& s) {
- const auto current = s.currentArrangement;
- s.addArrangement ("Radio edit", true);
- s.addArrangement ("Intro loop");
- s.selectArrangement (current);
- }, false);
- saveWindow (lynx::makeArrangementsPanel (offline), "-arrangements.png");
- saveWindow (lynx::makePluginMonitorPanel (offline), "-plugin-monitor.png");
- saveWindow (lynx::makeTouchKeyboardPanel (offline), "-touch-keyboard.png");
- }
- {
- // round 142: the Newtone / Newtime editors on a synthetic sung line (A3 B3 C4 · E4), one note moved
- const auto wav = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-snapshot-newtone.wav");
- {
- juce::AudioBuffer<float> line (1, 44100 * 2);
- const double hz[] = { 220.0, 246.94, 261.63, 0.0, 329.63 };
- double ph = 0.0;
- for (int i = 0; i < line.getNumSamples(); ++i)
- {
- const auto f0 = hz[std::min (4, i / 17640)];
- 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;
- float v = 0.0f;
- for (int h = 1; f0 > 0.0 && h < 8; ++h)
- v += (float) (0.3 / h * std::sin (h * ph));
- line.setSample (0, i, v);
- }
- wav.deleteFile();
- juce::WavAudioFormat format;
- std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
- if (auto* w = out != nullptr ? format.createWriterFor (out.get(), 44100.0, 1, 16, {}, 0) : nullptr)
- {
- out.release();
- std::unique_ptr<juce::AudioFormatWriter> writer (w);
- writer->writeFromAudioSampleBuffer (line, 0, line.getNumSamples());
- }
- }
- if (const auto sample = offline.getSampleLibrary().load (wav.getFullPathName()))
- {
- auto notes = lynx::newtonefx::analyseNotes (*sample);
- if (notes.pitches.size() > 1)
- notes.pitches[1].shift = 2.0;
- lynx::newtonefx::WarpMap warp;
- warp.frames = (std::int64_t) sample->frames();
- warp.markers = { { 22050, 33075 } };
- int at = 0;
- offline.editSong ([&] (lynx::Song& song) {
- if (song.mixer.size() < 2)
- song.mixer.resize (2);
- auto& fx = song.mixer[1].effects;
- auto tone = lynx::makeEffectSlot (lynx::EffectKind::newtone);
- tone.samplePath = wav.getFullPathName().toStdString();
- tone.state = lynx::newtonefx::writeNative (notes);
- auto time = lynx::makeEffectSlot (lynx::EffectKind::newtime);
- time.samplePath = tone.samplePath;
- time.state = lynx::newtonefx::writeWarp (warp);
- at = (int) fx.size();
- fx.push_back (tone);
- fx.push_back (time);
- }, false);
- saveWindow (lynx::makeNewtoneEditor (offline, 1, at), "-newtone.png");
- saveWindow (lynx::makeNewtoneEditor (offline, 1, at + 1), "-newtime.png");
- offline.editSong ([at] (lynx::Song& song) {
- auto& fx = song.mixer[1].effects;
- fx.erase (fx.begin() + at, fx.begin() + at + 2);
- }, false);
- }
- }
- if (! offline.getSong().automations.empty())
- {
- auto editor = lynx::makeAutomationEditor (offline, 0);
- editor->setSize (760, 300);
- saveWindow (std::move (editor), "-automation.png");
- // round 177b: the same clip in FL's LFO mode (its amplitude points, the played curve, the LFO strip)
- const auto before = offline.getSong().automations[0].lfo;
- offline.editSong ([] (lynx::Song& song) {
- auto& lfo = song.automations[0].lfo;
- lfo.on = true;
- lfo.level = 96;
- lfo.speed = lynx::AutomationLfo::speedForBeats (2.0);
- lfo.tension = 40;
- lfo.amp = { { 0, 0.3f, 0.0f }, { lynx::ppq * 8, 1.0f, 0.0f } };
- }, false);
- auto lfoEditor = lynx::makeAutomationEditor (offline, 0);
- lfoEditor->setSize (760, 330);
- saveWindow (std::move (lfoEditor), "-automation-lfo.png");
- offline.editSong ([before] (lynx::Song& song) { song.automations[0].lfo = before; }, false);
- }
- // round 177b: LYNX's modulators window, with one routed modulator
- {
- offline.editSong ([] (lynx::Song& song) {
- lynx::Modulator m;
- m.name = "LFO 1";
- m.shape = lynx::ModShape::triangle;
- m.routes = { { { lynx::AutomationTargetKind::mixerVolume, 1, 0, 0 }, 0.25f }, { { lynx::AutomationTargetKind::mixerPan, 1, 0, 0 }, -0.5f } };
- song.modulators.push_back (m);
- lynx::Modulator r;
- r.name = "LFO 2";
- r.shape = lynx::ModShape::smoothRandom;
- r.sync = false;
- r.hz = 0.5;
- song.modulators.push_back (r);
- }, false);
- auto mods = lynx::makeModulatorsPanel (offline);
- mods->setSize (720, 360);
- saveWindow (std::move (mods), "-modulators.png");
- offline.editSong ([] (lynx::Song& song) { song.modulators.clear(); }, false);
- }
- saveWindow (lynx::makeChannelSettingsPanel (offline, 0), "-sampler.png");
- // the channel window frame (REA round 143b): header strip + tabs; the Misc tab of the first channel and of a synth
- saveWindow (lynx::makeChannelFrame (offline, 0), "-channel-frame.png");
- saveWindow (lynx::makeChannelFrame (offline, 0, -1), "-channel-misc.png");
- for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
- if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::synth)
- {
- saveWindow (lynx::makeChannelSettingsPanel (offline, c), "-synth.png");
- saveWindow (lynx::makeChannelModulationPanel (offline, c), "-modulation.png");
- break;
- }
- for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
- if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::controller)
- {
- saveWindow (lynx::makeChannelSettingsPanel (offline, c), "-controller.png");
- break;
- }
- for (const auto kind : { lynx::InstrumentKind::sakura, lynx::InstrumentKind::drumpad })
- for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
- if (offline.getSong().channels[(std::size_t) c].instrument == kind)
- {
- saveWindow (lynx::makeChannelSettingsPanel (offline, c), kind == lynx::InstrumentKind::sakura ? "-sakura.png" : "-drumpad.png");
- break;
- }
- // parametric EQ: the one with the most pronounced curve (in an imported .flp, with FL's settings)
- {
- int bestTrack = -1, bestSlot = -1;
- double bestShape = -1.0;
- const auto& mixer = offline.getSong().mixer;
- for (int t = 0; t < (int) mixer.size(); ++t)
- for (int s = 0; s < (int) mixer[(std::size_t) t].effects.size(); ++s)
- if (const auto& fx = mixer[(std::size_t) t].effects[(std::size_t) s]; fx.kind == lynx::EffectKind::parametricEq)
- {
- double shape = 0.0;
- for (double hz = 30.0; hz < 18000.0; hz *= 1.5)
- shape += std::abs (lynx::peq::responseDb (fx.params, 48000.0, hz));
- if (shape > bestShape)
- {
- bestShape = shape;
- bestTrack = t;
- bestSlot = s;
- }
- }
- if (bestTrack >= 0)
- saveWindow (lynx::makeParametricEqEditor (offline, bestTrack, bestSlot), "-peq.png");
- }
- // Note inspector for the Piano Roll's notes (its selection, or all of the channel's notes)
- if (auto inspector = ui.getPianoRollForSnapshot().makeNoteInspectorForSnapshot())
- saveWindow (std::move (inspector), "-noteinspector.png");
- if (auto inspector = ui.getPianoRollForSnapshot().makeNoteInspectorForSnapshot (true))
- saveWindow (std::move (inspector), "-noteinspector-one.png");
- // workflow P2: note tool dialogs (they preview on the pattern; each one puts the notes back when destroyed)
- {
- auto& roll = ui.getPianoRollForSnapshot();
- const std::pair<lynx::NoteTool, const char*> tools[] = { { lynx::NoteTool::strum, "-tool-strum.png" },
- { lynx::NoteTool::arpeggiate, "-tool-arpeggiate.png" },
- { lynx::NoteTool::flip, "-tool-flip.png" },
- { lynx::NoteTool::randomise, "-tool-randomise.png" },
- { lynx::NoteTool::scaleLevels, "-tool-scalelevels.png" },
- { lynx::NoteTool::limit, "-tool-limit.png" },
- { lynx::NoteTool::quantize, "-tool-quantize.png" },
- { lynx::NoteTool::chop, "-tool-chop.png" },
- { lynx::NoteTool::flam, "-tool-flam.png" },
- { lynx::NoteTool::lfo, "-tool-lfo.png" },
- { lynx::NoteTool::claw, "-tool-claw.png" },
- { lynx::NoteTool::articulate, "-tool-articulate.png" },
- { lynx::NoteTool::riffMachine, "-tool-riff.png" },
- { lynx::NoteTool::chordProgression, "-tool-chords.png" } };
- for (const auto& [tool, name] : tools)
- saveWindow (lynx::makeNoteToolPanel (offline, tool, roll.noteIndicesForSnapshot(), roll.gridForSnapshot()), name);
- }
- // round 83: the event editor, with sample events on the selected channel's volume (removed afterwards)
- {
- const lynx::AutomationTarget volume { lynx::AutomationTargetKind::channelVolume, offline.getSelectedChannel() };
- const auto before = offline.getSong().patterns[(std::size_t) offline.getSong().currentPattern].events;
- offline.editSong ([&] (lynx::Song& s) {
- auto& lane = lynx::eventedit::laneFor (s.patterns[(std::size_t) s.currentPattern], volume);
- lynx::eventedit::line (lane, 0, lynx::ppq * 2, 0.2f, 0.9f, lynx::ticksPerStep);
- lynx::prtools::LfoOptions lfo;
- lfo.startSpeed = 7 * 4096; // one beat
- lynx::eventedit::applyLfo (lane, lynx::ppq * 2, lynx::ppq * 4, lfo, lynx::ticksPerStep);
- }, false);
- saveWindow (lynx::makeEventEditor (offline, volume), "-eventeditor.png");
- offline.editSong ([&] (lynx::Song& s) { s.patterns[(std::size_t) s.currentPattern].events = before; }, false);
- }
- // round 86: the audio editor with a synthetic drum loop (markers, a region, a loop), waveform and spectrogram,
- // and its menu items (-audioeditor-menu.txt)
- {
- namespace ae = lynx::audioedit;
- ae::Document d;
- d.title = "Drum loop";
- d.audio.sampleRate = 44100.0;
- const auto frames = (std::size_t) (44100 * 2);
- d.audio.channels.assign (2, std::vector<float> (frames, 0.0f));
- std::uint32_t seed = 7;
- for (int hit = 0; hit < 8; ++hit)
- {
- const auto at = (std::size_t) hit * frames / 8;
- const auto kick = hit % 2 == 0;
- double phase = 0.0;
- for (std::size_t i = 0; i < 12000 && at + i < frames; ++i)
- {
- seed = seed * 1664525u + 1013904223u;
- const auto noise = (float) (seed >> 8) / 16777216.0f - 0.5f;
- const auto t = (double) i / 44100.0;
- phase += 2.0 * 3.141592653589793 * (kick ? 45.0 + 160.0 * std::exp (-t * 30.0) : 190.0) / 44100.0;
- const auto body = (float) std::sin (phase) * (float) std::exp (-t * (kick ? 9.0 : 22.0));
- const auto v = kick ? 0.85f * body : 0.35f * body + 0.6f * noise * (float) std::exp (-t * 18.0);
- d.audio.channels[0][at + i] += v;
- d.audio.channels[1][at + i] += kick ? v : v * 0.8f + 0.1f * noise * (float) std::exp (-t * 30.0);
- }
- }
- ae::addMarker (d, (std::int64_t) frames / 8, "Snare");
- ae::addRegion (d, { (std::int64_t) frames / 2, (std::int64_t) frames * 3 / 4 }, "Fill");
- ae::setLoop (d, { 0, (std::int64_t) frames });
- auto wave = lynx::makeAudioEditorForSnapshot (offline, d, false);
- juce::File (prefix + "-audioeditor-menu.txt").replaceWithText (lynx::audioEditorMenuForSnapshot (*wave).joinIntoString ("\n") + "\n");
- saveWindow (std::move (wave), "-audioeditor.png");
- saveWindow (lynx::makeAudioEditorForSnapshot (offline, d, true), "-audioeditor-spectrum.png");
- }
- // the tempo tapper after five steady taps (round 132)
- saveWindow (lynx::makeTempoTapperForSnapshot (offline, 5, 128.0), "-tempotapper.png");
- // the Channel Rack's piano-roll view (round 132)
- ui.selectTabForSnapshot (0);
- ui.getRackForSnapshot().setPianoRollView (true);
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-rack-pianoroll-view.png");
- ui.getRackForSnapshot().setPianoRollView (false);
- // the Channel Rack with the step graph lane (velocity), and the Euclidean fill window
- ui.selectTabForSnapshot (0);
- ui.getRackForSnapshot().setGraphLevelForSnapshot (0);
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-rack-graph.png");
- ui.getRackForSnapshot().setGraphLevelForSnapshot (1);
- saveSnapshot (ui, prefix + "-rack-graph-pan.png");
- ui.getRackForSnapshot().toggleGraphLanes();
- saveWindow (ui.getRackForSnapshot().makeEuclideanPanel (0), "-euclidean.png");
- // the Mixer with three inserts selected and one armed for recording
- ui.selectTabForSnapshot (3);
- if (offline.getSong().mixer.size() > 4)
- {
- ui.getMixerForSnapshot().getStripsForSnapshot().setSelection ({ 1, 2, 3 }, 2);
- offline.setInsertArmed (3, true);
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-mixer-multi.png");
- // the armed insert with an audio input (its input row in the side panel, the level bar on the strip)
- offline.editSong ([] (lynx::Song& s) { s.mixer[3].inputChannel = 0; });
- ui.getMixerForSnapshot().selectTrack (3);
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-mixer-input.png");
- offline.undo();
- offline.setInsertArmed (3, false);
- ui.getMixerForSnapshot().getStripsForSnapshot().setSelection ({}, 0);
- }
- // the Mixer's routing lane: an insert with sends selected (send knobs and wires)
- if (offline.getSong().mixer.size() > 6)
- {
- int source = -1;
- for (int t = 1; t < (int) offline.getSong().mixer.size() && source < 0; ++t)
- if (! offline.getSong().mixer[(std::size_t) t].sends.empty())
- source = t;
- const auto temporary = source < 0;
- if (temporary) // the demo has no sends: add two for the picture
- {
- source = 1;
- 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); });
- }
- ui.getMixerForSnapshot().selectTrack (source);
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-mixer-sends.png");
- if (temporary)
- offline.editSong ([] (lynx::Song& s) { s.setRoute (1, 5, false); s.setRoute (1, 6, false); s.setRoute (4, 1, false); });
- ui.getMixerForSnapshot().selectTrack (0);
- }
- // the Playlist with ripple editing on
- ui.selectTabForSnapshot (2);
- ui.getPlaylistForSnapshot().setRipple (true);
- saveSnapshot (ui, prefix + "-playlist-ripple.png");
- ui.getPlaylistForSnapshot().setRipple (false);
- // FL's legacy Pattern Blocks (round 170f, issue #60): the section under the clip tracks, a row per pattern
- {
- const auto saved = offline.getSong();
- offline.editSong ([] (lynx::Song& s) {
- s.patternBlocksOn = true;
- while (s.patterns.size() < 5) // a few rows to show (Drums, Bass...: copies of the demo's pattern)
- lynx::clonePattern (s, (int) s.patterns.size() - 1);
- const auto rows = juce::jmin (6, (int) s.patterns.size());
- for (int r = 0; r < rows; ++r)
- lynx::patternblocks::paintRange (s, r, (std::int64_t) (r % 3) * 4 * lynx::ppq * 2,
- (std::int64_t) (8 + r * 2) * 4 * lynx::ppq);
- }, false);
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-playlist-blocks.png");
- offline.editSong ([saved] (lynx::Song& s) { s = saved; }, false);
- offline.dispatchPendingMessages();
- }
- // quick-add palette, and the Browser searching
- saveWindow (ui.makeQuickAddForSnapshot(), "-quickadd.png");
- ui.showDesktopForSnapshot (false);
- ui.getBrowserForSnapshot().setSearchForSnapshot ("kick");
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-browser-search.png");
- ui.getBrowserForSnapshot().setSearchForSnapshot ({});
- ui.getBrowserForSnapshot().selectFirstSampleForSnapshot(); // the tree with a sample selected and its waveform
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-browser-tree.png");
- // the Browser's PROJECT tab: the patterns, generators and audio files of the project in their colours
- ui.getBrowserForSnapshot().showProjectForSnapshot();
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-browser-project.png");
- ui.getBrowserForSnapshot().showPluginDatabaseForSnapshot(); // round 142: the Plugin database's FL engines
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-browser-plugins.png");
- ui.getBrowserForSnapshot().setTab (lynx::BrowserComponent::allTab);
- saveWindow (ui.getBrowserForSnapshot().makeFoldersPanelForSnapshot(), "-browser-folders.png"); // round 164
- {
- // round 164: the content filter leaves out the folders with nothing to list (a small library)
- const auto lib = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-snapshot-library");
- lib.deleteRecursively();
- for (const auto* path : { "Drums/Kicks/kick 1.wav", "Drums/Kicks/kick 2.wav", "Drums/snare.wav", "Keys/pad.sf2", "Presets/Synth/lead.fst",
- "Projects/beat.flp", "Projects/MIDI/chords.mid", "Notes/readme.txt", "Empty/Nothing/.keep" })
- lib.getChildFile (path).create();
- ui.showDesktopForSnapshot (false);
- ui.getBrowserForSnapshot().showFilterForSnapshot (lib, lynx::browserview::ContentFilter::all);
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-browser164-all.png");
- ui.getBrowserForSnapshot().showFilterForSnapshot (lib, lynx::browserview::ContentFilter::samples);
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-browser164-samples.png");
- ui.getBrowserForSnapshot().showFilterForSnapshot (lib, lynx::browserview::ContentFilter::projects);
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-browser164-projects.png");
- lib.deleteRecursively();
- ui.getBrowserForSnapshot().resetViewForSnapshot();
- }
- // the undo history after a few edits
- offline.editSong ([] (lynx::Song& s) { s.bpm += 1.0; });
- offline.editSong ([] (lynx::Song& s) { if (! s.channels.empty()) s.channels[0].muted = ! s.channels[0].muted; });
- offline.editSong ([] (lynx::Song& s) { if (! s.patterns.empty()) s.patterns[(std::size_t) s.currentPattern].notes.push_back ({}); });
- offline.undo();
- saveWindow (lynx::makeHistoryPanel (offline), "-history.png");
- // spectral waveforms: a synthetic beat (kick, hats, a chord, a noise riser) as audio clips in spectral
- // colours, zoomed in, classic and stereo; the same file in the Sampler editor and the Browser preview
- {
- const juce::File wav (prefix + "-wavedemo.wav");
- writeWaveDemo (wav, offline.getSong().bpm);
- const auto path = wav.getFullPathName();
- const auto pathUtf8 = path.toStdString();
- int samplerChannel = -1, firstTrack = 0;
- offline.editSong ([&] (lynx::Song& s) {
- for (const auto& clip : s.playlist)
- firstTrack = std::max (firstTrack, clip.track + 1);
- lynx::ChannelDef audio;
- audio.name = "Beat (audio)";
- audio.instrument = lynx::InstrumentKind::audioClip;
- audio.samplePath = pathUtf8;
- s.channels.push_back (audio);
- const auto audioChannel = (int) s.channels.size() - 1;
- lynx::ChannelDef sampler = audio;
- sampler.name = "Beat (sampler)";
- sampler.instrument = lynx::InstrumentKind::sampler;
- sampler.sampler.regionStart = 0.06f;
- sampler.sampler.regionEnd = 0.94f;
- s.channels.push_back (sampler);
- samplerChannel = (int) s.channels.size() - 1;
- const auto bar = (std::int64_t) lynx::ppq * std::max (1, s.beatsPerBar);
- const auto whole = (std::int64_t) std::llround (8.0 * s.bpm / 60.0 * lynx::ppq);
- lynx::Clip clip;
- clip.kind = lynx::ClipKind::audio;
- clip.channel = audioChannel;
- clip.track = firstTrack;
- clip.length = whole;
- s.playlist.push_back (clip);
- clip.track = firstTrack + 1; // a slice of it, later in the song
- clip.start = bar;
- clip.offset = bar;
- clip.length = 2 * bar;
- s.playlist.push_back (clip);
- // taller rows for the audio (tracks can be resized: P18)
- if ((int) s.playlistTracks.size() < firstTrack + 2)
- s.playlistTracks.resize ((std::size_t) firstTrack + 2);
- s.playlistTracks[(std::size_t) firstTrack].height = 80;
- s.playlistTracks[(std::size_t) firstTrack + 1].height = 60;
- });
- offline.dispatchPendingMessages();
- auto& cache = *lynx::ui::WaveformCache::getInstance();
- cache.find (path, [&offline, path] { return offline.getSampleLibrary().load (path); });
- cache.waitUntilIdle (30000);
- ui.selectTabForSnapshot (2);
- auto& playlist = ui.getPlaylistForSnapshot();
- playlist.setTimeSelectionForSnapshot (0, 0);
- {
- // the Playlist alone (the floating Channel Rack would cover the clips)
- auto saveSnapshot = [&playlist] (juce::Component&, const juce::String& file) { saveArea (playlist, playlist.getLocalBounds(), file); };
- playlist.setViewForSnapshot (180.0, 0, std::max (0, firstTrack - 3));
- saveSnapshot (ui, prefix + "-playlist-audio.png");
- playlist.setViewForSnapshot (1400.0, 0, std::max (0, firstTrack - 3));
- saveSnapshot (ui, prefix + "-playlist-audio-zoom.png");
- lynx::ui::WaveformCache::stereo = true;
- saveSnapshot (ui, prefix + "-playlist-audio-stereo.png");
- lynx::ui::WaveformCache::stereo = false;
- lynx::ui::WaveformCache::spectral = true;
- playlist.setViewForSnapshot (180.0, 0, std::max (0, firstTrack - 3));
- saveSnapshot (ui, prefix + "-playlist-audio-spectral.png");
- lynx::ui::WaveformCache::spectral = false;
- playlist.setViewForSnapshot (40.0, 0, 0);
- saveSnapshot (ui, prefix + "-playlist-audio-far.png");
- // LYNX_SNAPSHOT_AUDIO=a.wav;b.wav...: real audio as clips (default-height tracks, one tall,
- // a fade, a reversed copy), at three zoom levels
- if (const auto files = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_AUDIO", {}), ";", "");
- ! files.isEmpty())
- {
- const auto realTrack = firstTrack + 2;
- std::vector<juce::String> paths;
- for (const auto& f : files)
- if (juce::File (f.trim()).existsAsFile())
- paths.push_back (f.trim());
- offline.editSong ([&] (lynx::Song& s) {
- const auto bar = (std::int64_t) lynx::ppq * std::max (1, s.beatsPerBar);
- const std::uint32_t colours[] = { 0, 0xffd9a441, 0xff6fb36a, 0xffb06fd0, 0xff5fb7c9, 0xffd06f6f };
- for (std::size_t i = 0; i < paths.size(); ++i)
- {
- lynx::ChannelDef audio;
- audio.name = juce::File (paths[i]).getFileNameWithoutExtension().toStdString();
- audio.instrument = lynx::InstrumentKind::audioClip;
- audio.samplePath = paths[i].toStdString();
- audio.colour = colours[i % 6];
- audio.sampler.stretchBeats = i % 2 == 0 ? 16.0f : 0.0f; // fitted to 4 bars, or as recorded
- audio.sampler.keepPitch = true;
- s.channels.push_back (audio);
- lynx::Clip clip;
- clip.kind = lynx::ClipKind::audio;
- clip.channel = (int) s.channels.size() - 1;
- clip.track = realTrack + (int) i;
- clip.length = 4 * bar;
- clip.fadeIn = i == 1 ? bar / 2 : 0;
- s.playlist.push_back (clip);
- clip.start = 4 * bar;
- clip.fadeIn = 0;
- clip.fadeOut = i == 0 ? bar : 0;
- s.playlist.push_back (clip);
- }
- if ((int) s.playlistTracks.size() < realTrack + (int) paths.size())
- s.playlistTracks.resize ((std::size_t) realTrack + paths.size());
- if (! paths.empty())
- s.playlistTracks[(std::size_t) realTrack].height = 90;
- });
- offline.dispatchPendingMessages();
- for (const auto& path2 : paths)
- cache.find (path2, [&offline, path2] { return offline.getSampleLibrary().load (path2); });
- cache.waitUntilIdle (60000);
- playlist.setViewForSnapshot (160.0, 0, std::max (0, realTrack - 4));
- saveSnapshot (ui, prefix + "-playlist-real.png");
- playlist.setViewForSnapshot (700.0, 0, std::max (0, realTrack - 1));
- saveSnapshot (ui, prefix + "-playlist-real-zoom.png");
- playlist.setViewForSnapshot (2400.0, 0, std::max (0, realTrack - 1));
- saveSnapshot (ui, prefix + "-playlist-real-close.png");
- playlist.setViewForSnapshot (50.0, 0, std::max (0, realTrack - 4));
- saveSnapshot (ui, prefix + "-playlist-real-far.png");
- // the clip menu of the first real clip
- if (const auto menu = playlist.getClipMenuForSnapshot ((int) offline.getSong().playlist.size() - (int) paths.size() * 2); menu.getNumItems() > 0)
- saveMenus (juce::StringArray { "Audio clip" }, std::vector<juce::PopupMenu> { menu }, prefix + "-clip-menu-audio.png");
- if (const auto menu = playlist.getClipMenuForSnapshot (0); menu.getNumItems() > 0)
- saveMenus (juce::StringArray { "Pattern clip" }, std::vector<juce::PopupMenu> { menu }, prefix + "-clip-menu-pattern.png");
- // the clip menu's actions, run through the menu itself; results in -clip-actions.txt
- {
- juce::StringArray log;
- auto clipOf = [&offline] (const std::string& channelName, int nth) {
- const auto& sg = offline.getSong();
- for (int i = 0; i < (int) sg.playlist.size(); ++i)
- {
- const auto& c = sg.playlist[(std::size_t) i];
- if (c.kind == lynx::ClipKind::audio && c.channel >= 0 && sg.channels[(std::size_t) c.channel].name == channelName && nth-- == 0)
- return i;
- }
- return -1;
- };
- std::function<bool (const juce::PopupMenu&, const juce::String&)> run = [&run] (const juce::PopupMenu& m, const juce::String& text) {
- for (juce::PopupMenu::MenuItemIterator it (m); it.next();)
- {
- auto& item = it.getItem();
- if (item.subMenu != nullptr && run (*item.subMenu, text))
- return true;
- if (item.text.startsWith (text) && item.isEnabled && item.action)
- {
- item.action();
- return true;
- }
- }
- return false;
- };
- auto act = [&] (const std::string& name, int nth, const juce::String& text) {
- const auto clip = clipOf (name, nth);
- const auto ok = clip >= 0 && run (playlist.getClipMenuForSnapshot (clip), text);
- offline.dispatchPendingMessages();
- return ok;
- };
- auto channelOf = [&] (const std::string& name) -> const lynx::ChannelDef* {
- for (const auto& c : offline.getSong().channels)
- if (c.name == name)
- return &c;
- return nullptr;
- };
- auto check = [&log] (const juce::String& what, bool ok) { log.add ((ok ? "OK " : "FAIL ") + what); };
- const auto names = [&] { std::vector<std::string> n; for (auto& p2 : paths) n.push_back (juce::File (p2).getFileNameWithoutExtension().toStdString()); return n; }();
- if (names.size() >= 4)
- {
- const auto channelsBefore = offline.getSong().channels.size();
- check ("Reverse", act (names[2], 0, lynx::tr ("Reverse")) && channelOf (names[2])->sampler.reverse);
- offline.undo();
- offline.dispatchPendingMessages();
- check ("Reverse undone", ! channelOf (names[2])->sampler.reverse);
- act (names[2], 0, lynx::tr ("Reverse"));
- check ("Make unique", act (names[3], 1, lynx::tr ("Make unique")) && offline.getSong().channels.size() == channelsBefore + 1
- && channelOf (names[3] + " #2") != nullptr);
- check ("Fit to tempo, resample", act (names[1], 0, lynx::tr ("Fit to tempo, resample ({0})", { juce::String() }).upToFirstOccurrenceOf ("(", false, false))
- && channelOf (names[1])->sampler.stretchBeats > 0.0f && ! channelOf (names[1])->sampler.keepPitch);
- const auto gainBefore = offline.getSong().playlist[(std::size_t) clipOf (names[0], 1)].gain;
- check ("Normalize", act (names[0], 1, lynx::tr ("Normalize"))
- && offline.getSong().playlist[(std::size_t) clipOf (names[0], 1)].gain != gainBefore);
- const auto clipsBefore = offline.getSong().playlist.size();
- check ("Split here", act (names[3], 0, lynx::tr ("Split here")) && offline.getSong().playlist.size() == clipsBefore + 1);
- check ("Mute", act (names[0], 0, lynx::tr ("Mute")) && offline.getSong().playlist[(std::size_t) clipOf (names[0], 0)].muted);
- check ("Copy + Paste here", act (names[0], 0, lynx::tr ("Copy")) && act (names[0], 1, lynx::tr ("Paste here"))
- && offline.getSong().playlist.size() == clipsBefore + 2);
- check ("Delete", act (names[0], 2, lynx::tr ("Delete")) && offline.getSong().playlist.size() == clipsBefore + 1);
- check ("Chop to grid", act (names[3], 0, lynx::tr ("Chop to grid")) && offline.getSong().playlist.size() > clipsBefore + 1);
- }
- playlist.setViewForSnapshot (160.0, 0, std::max (0, realTrack - 4));
- saveSnapshot (ui, prefix + "-playlist-real-actions.png");
- juce::File (prefix + "-clip-actions.txt").replaceWithText (log.joinIntoString ("\n") + "\n");
- }
- }
- }
- saveWindow (lynx::makeChannelSettingsPanel (offline, samplerChannel), "-sampler-wave.png");
- ui.showDesktopForSnapshot (false);
- ui.getBrowserForSnapshot().showPreviewForSnapshot (wav);
- saveSnapshot (ui, prefix + "-browser-preview.png");
- }
- }
- // round 165o: every Label / button / tick box whose text the drawing squeezes below its minimum scale or cuts
- // (an ellipsis), per language: `LYNX --lang de --snapshot shots/de` -> shots/de-textfit.txt
- juce::File (prefix + "-textfit.txt").replaceWithText (textFitLog().joinIntoString ("\n") + "\n");
- juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
- quit();
- }
- // --snapshot: 8 s of a synthetic stereo beat whose parts sit in different bands (kick = low, chord = mid,
- // hats and the noise riser = high), to show the spectral waveform colours
- static void writeWaveDemo (const juce::File& file, double bpm)
- {
- constexpr double rate = 44100.0;
- const auto frames = (int) (8.0 * rate);
- juce::AudioBuffer<float> buffer (2, frames);
- buffer.clear();
- auto* l = buffer.getWritePointer (0);
- auto* r = buffer.getWritePointer (1);
- const auto beat = 60.0 / juce::jlimit (40.0, 300.0, bpm);
- std::uint32_t noise = 0x9e3779b9u;
- auto white = [&noise] {
- noise ^= noise << 13;
- noise ^= noise >> 17;
- noise ^= noise << 5;
- return (float) (noise & 0xffffff) / (float) 0x800000 - 1.0f;
- };
- float previous = 0.0f;
- for (int i = 0; i < frames; ++i)
- {
- const auto t = i / rate;
- const auto inBeat = std::fmod (t, beat);
- const auto bar = (int) (t / (beat * 4.0));
- float left = 0.0f, right = 0.0f;
- // kick on every beat: a falling sine
- {
- const auto phase = 2.0 * juce::MathConstants<double>::pi * (48.0 * inBeat + 4.0 * (1.0 - std::exp (-inBeat * 30.0)));
- const auto k = (float) (std::sin (phase) * std::exp (-inBeat * 7.0)) * 0.85f;
- left += k;
- right += k;
- }
- // hats on the off-beats: high-passed noise bursts, a little to the right
- {
- const auto h = std::fmod (t + beat * 0.5, beat);
- const auto n = white();
- const auto hp = (n - previous) * 0.5f;
- previous = n;
- const auto hat = hp * (float) std::exp (-h * 45.0) * 0.55f;
- left += hat * 0.6f;
- right += hat;
- }
- // a chord in the second and third bars (mid band)
- if (bar == 1 || bar == 2)
- {
- const auto env = (float) std::min (1.0, std::min (t - beat * 4.0, beat * 12.0 - t) * 8.0);
- float chord = 0.0f;
- for (const auto hz : { 523.25, 659.25, 783.99 })
- chord += (float) (std::sin (2.0 * juce::MathConstants<double>::pi * hz * t) + 0.3 * std::sin (4.0 * juce::MathConstants<double>::pi * hz * t));
- left += chord * 0.09f * std::max (0.0f, env);
- right += chord * 0.09f * std::max (0.0f, env);
- }
- // a white-noise riser over the last two seconds (high band)
- if (t > 6.0)
- {
- const auto rise = (float) ((t - 6.0) / 2.0);
- left += white() * 0.4f * rise * rise;
- right += white() * 0.4f * rise * rise;
- }
- l[i] = left;
- r[i] = right;
- }
- buffer.applyGain (0.9f / juce::jmax (1.0e-6f, buffer.getMagnitude (0, frames)));
- file.deleteFile();
- juce::WavAudioFormat wav;
- if (std::unique_ptr<juce::AudioFormatWriter> writer { wav.createWriterFor (file.createOutputStream().release(), rate, 2, 24, {}, 0) })
- writer->writeFromAudioSampleBuffer (buffer, 0, frames);
- }
- // the menu bar's menus side by side, drawn with the LookAndFeel as they appear when opened
- static void saveMenus (lynx::MainComponent& ui, const juce::String& path)
- {
- const auto names = ui.getMenuNamesForSnapshot();
- std::vector<juce::PopupMenu> source;
- for (int m = 0; m < names.size(); ++m)
- source.push_back (ui.getMenuForSnapshot (m));
- saveMenus (names, source, path);
- }
- // menus side by side, each under its name
- static void saveMenus (const juce::StringArray& names, const std::vector<juce::PopupMenu>& source, const juce::String& path)
- {
- auto& lf = juce::LookAndFeel::getDefaultLookAndFeel();
- struct Laid
- {
- juce::PopupMenu menu;
- int width = 0, height = 0;
- };
- std::vector<Laid> menus;
- const auto border = lf.getPopupMenuBorderSize();
- for (int m = 0; m < names.size(); ++m)
- {
- Laid laid { source[(std::size_t) m] };
- int width = 160, height = 2 * border;
- for (juce::PopupMenu::MenuItemIterator it (laid.menu); it.next();)
- {
- const auto& item = it.getItem();
- int w = 0, h = 0;
- lf.getIdealPopupMenuItemSize (item.text, item.isSeparator, item.isSectionHeader ? -1 : 0, w, h);
- if (item.isSectionHeader) h += h / 2; // as JUCE does
- if (item.shortcutKeyDescription.isNotEmpty() || item.text.containsChar ('\t'))
- w += 90;
- width = juce::jmax (width, w + 10);
- height += h;
- }
- laid.width = width;
- laid.height = height;
- menus.push_back (std::move (laid));
- }
- int totalWidth = 16, totalHeight = 0;
- for (const auto& l : menus)
- {
- totalWidth += l.width + 16;
- totalHeight = juce::jmax (totalHeight, l.height + 32);
- }
- juce::Image image (juce::Image::ARGB, totalWidth, totalHeight, true);
- {
- juce::Graphics g (image);
- g.fillAll (lynx::theme::colour::bg1);
- int x = 16;
- for (int m = 0; m < (int) menus.size(); ++m)
- {
- const auto& l = menus[(std::size_t) m];
- g.setColour (lynx::theme::colour::textSecondary);
- g.setFont (lynx::theme::font (lynx::theme::type::small, true));
- g.drawText (names[m], x, 0, l.width, 24, juce::Justification::centredLeft);
- {
- juce::Graphics::ScopedSaveState state (g);
- g.reduceClipRegion (x, 24, l.width, l.height);
- g.setOrigin (x, 24);
- lf.drawPopupMenuBackground (g, l.width, l.height);
- int y = border;
- bool first = true;
- for (juce::PopupMenu::MenuItemIterator it (l.menu); it.next();)
- {
- const auto& item = it.getItem();
- int w = 0, h = 0;
- lf.getIdealPopupMenuItemSize (item.text, item.isSeparator, item.isSectionHeader ? -1 : 0, w, h);
- if (item.isSectionHeader) h += h / 2; // as JUCE does
- const juce::Rectangle<int> r (0, y, l.width, h);
- auto text = item.text, shortcut = item.shortcutKeyDescription;
- if (text.containsChar ('\t'))
- {
- shortcut = text.fromFirstOccurrenceOf ("\t", false, false);
- text = text.upToFirstOccurrenceOf ("\t", false, false);
- }
- if (item.isSectionHeader)
- lf.drawPopupMenuSectionHeader (g, r, text);
- else
- lf.drawPopupMenuItem (g, r, item.isSeparator, item.isEnabled, first && ! item.isSeparator && m == 0, item.isTicked,
- item.subMenu != nullptr, text, shortcut, item.image.get(), nullptr);
- first = false;
- y += h;
- }
- }
- x += l.width + 16;
- }
- }
- const juce::File file (path);
- file.deleteFile();
- juce::PNGImageFormat png;
- if (auto out = file.createOutputStream())
- png.writeImageToStream (image, *out);
- }
- static void writePng (const juce::Image& image, const juce::String& path)
- {
- const juce::File file (path);
- file.deleteFile();
- juce::PNGImageFormat png;
- if (auto out = file.createOutputStream())
- png.writeImageToStream (image, *out);
- }
- // the splash screen: one settled frame, and a strip of frames through its animation
- static void saveSplashFrames (const juce::String& prefix)
- {
- lynx::SplashScreen splash;
- splash.setStatus (lynx::tr ("Loading the workspace..."));
- splash.setTimeForSnapshot (1.6);
- writePng (splash.createComponentSnapshot (splash.getLocalBounds()), prefix + "-splash.png");
- const double times[] = { 0.10, 0.22, 0.29, 0.40, 0.58, 0.75, 1.00, 1.30 };
- const auto w = lynx::SplashScreen::width / 2, h = lynx::SplashScreen::height / 2;
- juce::Image strip (juce::Image::ARGB, 4 * (w + 8) + 8, 2 * (h + 8) + 8, true);
- {
- juce::Graphics g (strip);
- g.fillAll (lynx::theme::colour::bg1);
- for (int i = 0; i < 8; ++i)
- {
- splash.setTimeForSnapshot (times[i]);
- const auto frame = splash.createComponentSnapshot (splash.getLocalBounds());
- g.drawImage (frame, 8 + (i % 4) * (w + 8), 8 + (i / 4) * (h + 8), w, h, 0, 0, frame.getWidth(), frame.getHeight());
- }
- }
- writePng (strip, prefix + "-splash-frames.png");
- }
- // every icon at 16, 20 and 24 px (at `scale`, e.g. 1.5 for a 150% display), in the toolbar's
- // colours: at rest, hovered and switched on
- static void saveIconSheet (const juce::String& path, float scale)
- {
- const int sizes[] = { 16, 20, 24 };
- const int cell = 34, columns = 3 * 3, labelWidth = 110;
- const auto w = labelWidth + columns * cell + 16, h = lynx::iconCount * cell + 16;
- juce::Image image (juce::Image::ARGB, juce::roundToInt ((float) w * scale), juce::roundToInt ((float) h * scale), true);
- {
- juce::Graphics g (image); // (drawing is flushed when it goes out of scope)
- g.addTransform (juce::AffineTransform::scale (scale));
- g.fillAll (lynx::theme::colour::bg3);
- g.setFont (lynx::theme::font (lynx::theme::type::small));
- for (int i = 1; i < lynx::iconCount; ++i)
- {
- const auto y = 8 + (i - 1) * cell;
- g.setColour (lynx::theme::colour::textDisabled);
- g.drawText (juce::String (i), 8, y, labelWidth - 8, cell, juce::Justification::centredLeft);
- for (int v = 0; v < 3; ++v)
- for (int s = 0; s < 3; ++s)
- {
- const juce::Rectangle<float> box ((float) (labelWidth + (v * 3 + s) * cell), (float) y, (float) cell, (float) cell);
- const auto bg = v == 2 ? lynx::theme::colour::accent : v == 1 ? lynx::theme::colour::bg5 : lynx::theme::colour::bg3;
- g.setColour (bg);
- g.fillRoundedRectangle (box.reduced (2.0f), 4.0f);
- const auto fg = v == 2 ? lynx::theme::colour::onAccent : v == 1 ? lynx::theme::colour::textPrimary
- : lynx::theme::colour::textSecondary.brighter (0.25f);
- lynx::icons::draw (g, (lynx::Icon) i, box.withSizeKeepingCentre ((float) sizes[s], (float) sizes[s]), fg);
- }
- }
- }
- writePng (image, path);
- }
- // a part of a component (e.g. the main toolbar)
- static void saveArea (juce::Component& c, juce::Rectangle<int> area, const juce::String& path)
- {
- const juce::File file (path);
- file.deleteFile();
- juce::PNGImageFormat png;
- if (auto out = file.createOutputStream())
- png.writeImageToStream (c.createComponentSnapshot (area), *out);
- }
- static void savePng (const juce::Image& image, const juce::String& path)
- {
- const juce::File file (path);
- file.deleteFile();
- juce::PNGImageFormat png;
- if (auto out = file.createOutputStream())
- png.writeImageToStream (image, *out);
- }
- // -toolbar-tips.png: the top of the window with the bubbles of a few controls as they appear under the
- // mouse; -tips-sheet.png: every quick tip of the window, to check names, shortcuts and translations
- static void saveQuickTips (lynx::MainComponent& ui, const juce::String& prefix)
- {
- const auto tips = ui.getQuickTipsForSnapshot();
- const auto top = juce::Rectangle<int> (0, 0, ui.getWidth(), juce::jmin (ui.getHeight(), ui.getToolbarBoundsForSnapshot().getHeight() + 72));
- auto image = ui.createComponentSnapshot (top);
- {
- juce::Graphics g (image);
- const juce::String shown[] = { lynx::tr ("Pattern mode"), lynx::tr ("Play"), lynx::tr ("Metronome"), lynx::tr ("Mixer"), lynx::tr ("Save project"),
- lynx::tr ("Window options"), lynx::tr ("Close") };
- std::vector<juce::Rectangle<int>> used;
- for (const auto& [area, tip] : tips)
- {
- const auto name = tip.upToFirstOccurrenceOf ("\t", false, false);
- if (std::find (std::begin (shown), std::end (shown), name) == std::end (shown))
- continue;
- const auto bubble = lynx::ui::quickTipBounds (tip, area, top);
- if (std::any_of (used.begin(), used.end(), [&] (const auto& r) { return r.intersects (bubble); }))
- continue;
- used.push_back (bubble);
- g.setColour (juce::Colours::white.withAlpha (0.075f)); // the hovered control
- g.fillRoundedRectangle (area.toFloat().reduced (0.5f), lynx::theme::radius::md);
- lynx::ui::paintQuickTip (g, bubble.toFloat(), tip);
- }
- }
- savePng (image, prefix + "-toolbar-tips.png");
- // the sheet: bubbles in rows
- const int width = 900;
- int x = 12, y = 12;
- std::vector<std::pair<juce::Rectangle<int>, juce::String>> placed;
- for (const auto& [area, tip] : tips)
- {
- auto r = lynx::ui::quickTipSize (tip);
- if (x + r.getWidth() > width - 12)
- {
- x = 12;
- y += r.getHeight() + 10;
- }
- placed.emplace_back (r.withPosition (x, y), tip);
- x += r.getWidth() + 10;
- }
- juce::Image sheet (juce::Image::ARGB, width, y + 20 + 12, true);
- {
- juce::Graphics g (sheet);
- g.fillAll (lynx::theme::colour::bg3);
- for (const auto& [r, tip] : placed)
- lynx::ui::paintQuickTip (g, r.toFloat(), tip);
- }
- savePng (sheet, prefix + "-tips-sheet.png");
- }
- static juce::StringArray& textFitLog()
- {
- static juce::StringArray log;
- return log;
- }
- // drawFittedText would shrink `text` below `minScale` or cut it: fewer visible glyphs than the text has
- static bool textIsCut (const juce::Font& font, const juce::String& text, juce::Rectangle<int> area, int maxLines, float minScale)
- {
- if (text.trim().isEmpty() || area.getWidth() <= 4 || area.getHeight() <= 4)
- return false;
- auto visible = [] (juce::GlyphArrangement& ga) {
- int n = 0;
- for (int i = 0; i < ga.getNumGlyphs(); ++i)
- n += ga.getGlyph (i).isWhitespace() ? 0 : 1;
- return n;
- };
- juce::GlyphArrangement fitted, full;
- fitted.addFittedText (font, text, 0.0f, 0.0f, (float) area.getWidth(), (float) area.getHeight(), juce::Justification::centredLeft,
- juce::jmax (1, maxLines), minScale);
- full.addLineOfText (font, text, 0.0f, 0.0f);
- return visible (fitted) < visible (full);
- }
- // walks the visible components under `root` and logs the texts that don't fit (labels, text buttons, tick boxes)
- static void checkTextFit (juce::Component& root, const juce::String& where)
- {
- std::function<void (juce::Component&)> visit = [&] (juce::Component& c) {
- if (! c.isVisible() || c.getWidth() <= 0 || c.getHeight() <= 0)
- return;
- juce::String text;
- bool cut = false;
- if (auto* label = dynamic_cast<juce::Label*> (&c); label != nullptr && ! label->isBeingEdited())
- {
- const auto font = label->getLookAndFeel().getLabelFont (*label);
- const auto area = label->getBorderSize().subtractedFrom (label->getLocalBounds());
- text = label->getText();
- cut = textIsCut (font, text, area, juce::jmax (1, (int) ((float) area.getHeight() / font.getHeight())),
- label->getMinimumHorizontalScale());
- }
- else if (auto* toggle = dynamic_cast<juce::ToggleButton*> (&c))
- {
- const auto tick = juce::jmin (16.0f, (float) c.getHeight() - 4.0f);
- text = toggle->getButtonText();
- cut = textIsCut (juce::Font (lynx::theme::font (juce::jmin ((float) lynx::theme::type::body, (float) c.getHeight() * 0.75f))), text,
- c.getLocalBounds().withTrimmedLeft (juce::roundToInt (tick) + 8).withTrimmedRight (2), 2, 0.85f);
- }
- else if (auto* button = dynamic_cast<juce::TextButton*> (&c);
- button != nullptr && (int) button->getProperties().getWithDefault (lynx::theme::LookAndFeel::iconProperty, 0) == 0)
- {
- text = button->getButtonText();
- cut = textIsCut (button->getLookAndFeel().getTextButtonFont (*button, button->getHeight()), text,
- button->getLocalBounds().reduced (juce::jmin (8, button->getWidth() / 6), 0), 2, 0.85f);
- }
- if (cut)
- {
- juce::String path;
- for (auto* p = &c; p != nullptr && p != &root; p = p->getParentComponent())
- if (p->getName().isNotEmpty())
- path = p->getName() + (path.isEmpty() ? "" : "/") + path;
- const auto line = where + " | " + juce::String (c.getWidth()) + "x" + juce::String (c.getHeight()) + " | " + text.replace ("\n", "\\n")
- + (path.isEmpty() ? juce::String() : " | " + path);
- textFitLog().addIfNotAlreadyThere (line);
- }
- for (auto* child : c.getChildren())
- visit (*child);
- };
- visit (root);
- }
- static void saveSnapshot (juce::Component& c, const juce::String& path)
- {
- checkTextFit (c, juce::File (path).getFileNameWithoutExtension());
- const juce::File file (path);
- file.deleteFile();
- juce::PNGImageFormat png;
- if (auto out = file.createOutputStream())
- png.writeImageToStream (c.createComponentSnapshot (c.getLocalBounds()), *out);
- }
- class MainWindow final : public juce::DocumentWindow
- {
- public:
- MainWindow (const juce::String& name, lynx::AudioEngine& engine)
- : DocumentWindow (name, lynx::theme::window, DocumentWindow::allButtons)
- {
- setUsingNativeTitleBar (true);
- setIcon (lynx::logoImage());
- content = new lynx::MainComponent (engine);
- setContentOwned (content, true);
- setResizable (true, true);
- setResizeLimits (800, 400, 10000, 10000);
- // ~88% of the main display's usable area (at least the UI's design size, but never larger than the
- // display: the AppImage catalog test runs on an 800x600 screen)
- if (const auto* display = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay())
- {
- const auto area = display->userArea;
- const auto fit = [] (int design, int available) {
- return juce::jmin (available, juce::jmax (design, (int) (available * 0.88)));
- };
- setSize (fit (getWidth(), area.getWidth()), fit (getHeight(), area.getHeight()));
- }
- centreWithSize (getWidth(), getHeight());
- // where it was last time (round 167v); the first start opens maximized, the Playlist filling the screen
- // with the Browser at the left and the Channel Rack above it, like FL Studio's first start
- const auto saved = stateFile().loadFileAsString().trim();
- // (LYNX_TEST_MODE keeps the fixed-size window scripted checks expect, unless LYNX_TEST_MAXIMIZE=1)
- const auto firstStart = saved.isEmpty()
- && (! lynx::platform::testMode() || juce::SystemStats::getEnvironmentVariable ("LYNX_TEST_MAXIMIZE", {}) == "1");
- maximiseOnReveal = firstStart || saved.startsWithIgnoreCase ("fs");
- if (saved.isNotEmpty())
- restoreWindowStateFromString (saved.startsWithIgnoreCase ("fs") ? saved.substring (2).trim() : saved);
- }
- // Shows the window (built hidden while the splash screen is up).
- void reveal()
- {
- if (lynx::uitrace::enabled()) // LYNX_TRACE_UI: the frames per second and the longest gap in ui.log (round 173f)
- watchFrames ({});
- setVisible (true);
- lynx::applyWindowChrome (*this);
- lynx::fitWindowOnScreen (*this); // a size saved at another UI zoom still fits (round 163)
- if (maximiseOnReveal)
- setFullScreen (true); // (a title-bar window: maximized, the taskbar stays)
- toFront (true);
- content->grabKeyboardFocus();
- // issue #62: the detached panels restored with the layout (built before this window was shown): their saved
- // place and above it, once the window manager has placed this one
- juce::Timer::callAfterDelay (250, [safe = juce::Component::SafePointer<MainWindow> (this)] {
- if (safe != nullptr)
- safe->content->restoreDetachedWindows();
- });
- }
- // The window's place and maximized state for the next start (main-window.txt in the settings folder).
- void saveState() { stateFile().replaceWithText (getWindowStateAsString()); }
- static juce::File stateFile() { return lynx::PluginHost::settingsFolder().getChildFile ("main-window.txt"); }
- void openFile (const juce::File& file) { content->openFile (file); }
- lynx::MainComponent& getContent() { return *content; }
- void showSetupWizard() { content->showSetupWizard(); }
- void confirmDiscard (std::function<void()> then) { content->confirmDiscard (std::move (then)); }
- void closeButtonPressed() override { JUCEApplication::getInstance()->systemRequestedQuit(); }
- // Every frame the window paints, with its dirty area (ui/FrameProbe.h; --uiperf, LYNX_TRACE_UI). The trace keeps
- // counting when --uiperf watches too.
- void watchFrames (std::function<void (double, juce::Rectangle<int>)> callback)
- {
- if (probe == nullptr)
- {
- probe = std::make_unique<lynx::ui::FrameProbe>();
- Component::addAndMakeVisible (*probe); // (ResizableWindow hides the plain overload)
- probe->setBounds (getLocalBounds());
- }
- probe->onFrame = [callback = std::move (callback)] (double now, juce::Rectangle<int> area) {
- if (lynx::uitrace::enabled())
- lynx::uitrace::frame (now);
- if (callback)
- callback (now, area);
- };
- }
- void resized() override
- {
- DocumentWindow::resized();
- if (probe != nullptr)
- probe->setBounds (getLocalBounds());
- }
- // --uiperf: the time of each frame the window paints (its own paint, then every child's, up to the last)
- std::function<void (double)> onFrame;
- void paint (juce::Graphics& g) override
- {
- if (onFrame)
- frameStart = juce::Time::getMillisecondCounterHiRes();
- DocumentWindow::paint (g);
- }
- void paintOverChildren (juce::Graphics& g) override
- {
- DocumentWindow::paintOverChildren (g);
- if (onFrame && frameStart > 0.0)
- onFrame (juce::Time::getMillisecondCounterHiRes() - frameStart);
- frameStart = 0.0;
- }
- private:
- lynx::MainComponent* content = nullptr; // owned by the window
- std::unique_ptr<lynx::ui::FrameProbe> probe; // (on top of the content; see watchFrames)
- double frameStart = 0.0;
- bool maximiseOnReveal = false;
- JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MainWindow)
- };
- lynx::theme::LookAndFeel lookAndFeel;
- std::unique_ptr<lynx::AudioEngine> engine;
- std::unique_ptr<juce::XmlElement> savedDeviceState; // --rtstress: the user's device before this run's --type/--buffer
- // Hidden test mode --asiodll "<driver.dll>[|{CLSID}]" (REA round 97): an ASIO driver loaded straight from its file,
- // without registering it, listed as the driver type "ASIO driver file". True when one was added.
- bool addDriverFileDeviceType()
- {
- const auto args = juce::JUCEApplication::getCommandLineParameterArray();
- const auto i = args.indexOf ("--asiodll");
- if (i < 0 || i + 1 >= args.size() || engine == nullptr)
- return false;
- auto& devices = engine->getDeviceManager();
- devices.getAvailableDeviceTypes(); // creates the standard types first
- for (auto* t : devices.getAvailableDeviceTypes())
- if (t->getTypeName() == lynx::dllAsioTypeName)
- return true;
- auto type = lynx::makeDllAsioDeviceType (args[i + 1].unquoted());
- if (type == nullptr)
- return false;
- devices.addAudioDeviceType (std::move (type));
- return true;
- }
- void restoreSavedDeviceState()
- {
- if (engine != nullptr)
- engine->restoreAudioDeviceState (savedDeviceState.get());
- }
- std::unique_ptr<MainWindow> mainWindow;
- std::unique_ptr<juce::Timer> perf; // --uiperf
- std::unique_ptr<lynx::SplashScreen> splash;
- double splashDuration = lynx::SplashScreen::minimumDuration; // seconds of its clock (round 121: from the process start)
- lynx::StartupOptions startupOptions;
- juce::File fileToOpen;
- juce::File openTimeReport; // --opentime
- int openTimeIdleSeconds = 10;
- };
- START_JUCE_APPLICATION (LynxApplication)
|